blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
4b642bc44093d6df7d941752ae1c35b3a1d836e8 | bakuganin/python | /Python/Интерестные задачи/9.py | 190 | 3.703125 | 4 | n = int(input())
x = int((n**(0.5)))
y = False
for i in range(2,x):
if n%i == 0:
y = True
if y == True:
print("Cостaвное")
else:
print("Простое")
|
1256a2739b0f8e7c2e0a74c4e78ed1319fcee3fc | Kemin11/basic-python-B4-C | /tugasClass.py | 437 | 3.8125 | 4 | #Membuat class
class data:
def __init__(self):
nama = input("Masukkan nama : ")
jurusan = input("Masukan jurusan : ")
self.nama = nama
self.jurusan = jurusan
def tampil(self):
print("{} jurusan {}".format(self.nama,self.jurusan))
#Input data
mahasiswa1 = data()
mahasiswa... |
af211c4fb797589561c443a8593c3cc3bf122d47 | purnimagupta17/python-excel-func | /string_indexing_slicing_usingpython.py | 967 | 4.65625 | 5 | print('Hello World')
#to shift the 'World' to next line, we can use \n in the symtax as follows:
print('Hello \nWorld')
#to count the number of characters in a string, we use len function as follows:
str1="Hello"
print(len(str1))
#to assign the index number to a string, for example:
ss="Hello World"
print(ss[0])
pri... |
97ada7be28162d75a2a103a5c2dc4153e3aac365 | anonymous14386/Small-coder | /smallcoder.py | 182 | 3.875 | 4 | input = raw_input('Please enter a string: ')
length = len( input )
end = length - 1
count = length
x = 1
while (count > 0):
print (input[x])
count = count - 1
|
9ad7ac02af83c8d2854e57c3d1aa160a3ec6e94e | AabhiShukla/Hackerrank | /day2.py | 371 | 3.8125 | 4 | def solve(meal_cost, tip_percent, tax_percent):
tip=(float(tip_percent)/100)*meal_cost
tax=(float(tax_percent)/100)*meal_cost
total_cost = meal_cost + tip + tax
print (round(total_cost))
if __name__ == '__main__':
meal_cost = float(input())
tip_percent = int(input())
tax_percent = int(input... |
0e8f42a18dee20b84d5d1f009f7881c13da79ad2 | FM2805/Python_Tutorials | /scikit_4.py | 1,076 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Feb 5 14:37:49 2017
@author: FloM
"""
"""
Basic scikit: More cross validation - regression example
"""
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import cross_val_score #CV score
... |
e097b52d96e32a04740a6e1d4a926d3b09233e8c | XeeMpee/DarkestDungeonSavesMenager | /database/Database.py | 589 | 3.921875 | 4 | import sqlite3
class Database():
"""
Class responisble for connection with SQLite database.
Atributes:
--------------
__databaseFile : str - path to file with database.
Methods:
--------------
connect() - connects with database
"""
def __init__(self):
self.__database... |
7a71cc280ae6302fc83eebd003a4693c17f8bc2a | krallnyx/NATO_Alphabet_Translation | /main.py | 527 | 4.1875 | 4 | import pandas
data = pandas.read_csv("nato_phonetic_alphabet.csv")
alphabet = {row.letter: row.code for (index, row) in data.iterrows()}
def generate_phonetic():
to_translate = input("Please enter the word you want to translate into NATO Alphabet.\n").upper()
try:
output = [alphabet[letter] for lette... |
bfc0dbdb10b1c6652000e25acbbbec55f6b93c30 | juanmivy/math_python | /polinomios.py | 6,150 | 3.515625 | 4 |
import math
import numpy as np
import matplotlib.pyplot as plt
class Polinomio():
def __init__(self, coeficientes):
self.coeficientes = coeficientes
#Mostrar el polinomio
def __str__(self):
if (self.coeficientes[0] != 0):
resultado = str(self.coeficientes[0])+'+'
... |
036f82715b0ec2146668a9d8c865ee195c6c3c51 | Vehmeyer/GCA-Problems | /Arrays.py | 1,833 | 4.03125 | 4 | """
Given an array a that contains only numbers in the range from 1 to a.length, find the first duplicate number for which the second occurrence
has the minimal index. In other words, if there are more than 1 duplicated numbers, return the number for which the second occurrence has a
smaller index than the second occ... |
7274d6bfb7fed0ace6b055ff71a5666f288eacce | SergioAlvarezB/ml-numpy | /models/decision_tree.py | 6,972 | 3.671875 | 4 | from __future__ import division
import numpy as np
from collections import namedtuple
Split = namedtuple('Split',
['feature_ix',
'th',
'X_false',
'y_false',
'X_true',
'y_true'])
class TreeNode:
"""DecisionTree Node. If split node, stores the feature index and the
value to make ... |
88d91f9f26529a4063c34f4b7a82d60bd2383b74 | SergioAlvarezB/ml-numpy | /models/k_means.py | 3,902 | 3.671875 | 4 | import numpy as np
from collections import Counter
class KMeans:
"""Implements K-Means. Clustering that fits k clusters by iteratively
assigning points to the cluster represented by the nearest centroid and
moving the centroid to the center of the cluster.
Parameters
----------
k : `int`, opt... |
eb7076d9c7d75d4b0ce59b5a1f74c6cdfe311b7e | jessiecantdoanything/Week10-24 | /CodesAndStrings.py | 1,531 | 4.125 | 4 | # strings
# concatenation
firstName = "Jesus"
lastName = "Monte"
print(firstName + " " + lastName)
name = firstName + " " + lastName
lastFirst = lastName + ", " + firstName
print(lastFirst)
# repition
print("uh "*2 + "AAAAAAAAA")
def imTiredofSchool():
print("me, "*3 + "young Jessie,")
print("is extreme... |
0d8bec6ae5e297d5e4ac2ab4db450276b0fdb869 | zachgood/Artificial-Intelligence-Projects | /Iterative-Deepening Search/EightPuzzleFunctions.py | 3,264 | 3.59375 | 4 | import copy
#Formats 8-puzzle for printing
def printState_8p(state):
state[state.index(0)] = " "
print(state[0], state[1], state[2])
print(state[3], state[4], state[5])
print(state[6], state[7], state[8])
state[state.index(" ")] = 0
#Returns index of blank as tuple
def findBlank_8p(state):
col... |
34d7403016a7a3ffbf262a6c46cedfc61d1919b6 | jeniia/Python_Basic_SoftUni_2021 | /For_loop/Exercise/P02_half_sum_element.py | 354 | 3.703125 | 4 | import math
n = int(input())
max_num = 0
sum_numbers = 0
for i in range(0, n):
num = int(input())
if num > max_num:
max_num = num
sum_numbers += num
sum_numbers -= max_num
if sum_numbers == max_num:
print("Yes")
print(f"Sum = {sum_numbers}")
else:
print("No")
print(f"Diff = {math.... |
e7e961c953f9d55debcf6953aaec5c3648c8d844 | jeniia/Python_Basic_SoftUni_2021 | /Conditional_Statements_Advanced/Exercise/P09Volleyball.py | 269 | 3.65625 | 4 | import math
year = str(input())
p = int(input())
h = int(input())
volleyball_time = 0.0
volleyball_time += (48 - h) * 3.0 / 4
volleyball_time += p * 2.0 / 3
volleyball_time += h
if year == "leap":
volleyball_time *= 1.15
print(f"{math.floor(volleyball_time):.0f}") |
5db3b06b83dfb7075c8343e3d372d8756f0fad61 | jeniia/Python_Basic_SoftUni_2021 | /First_steps_in_coding/Lab/P07Projects_Creation.py | 172 | 3.828125 | 4 | name = input()
countProject = int(input())
neededHours = countProject * 3
print(f'The architect {name} will need {neededHours} hours to complete {countProject} project/s.') |
193b7fca8b000cf0dea0dbf967c1b19898d502e7 | jeniia/Python_Basic_SoftUni_2021 | /Conditional Statements/Exercise/P06Godzilla_vs._Kong.py | 632 | 3.765625 | 4 | budget = float(input())
extras = int(input())
price_for_one_clothing = float(input())
price_decor = (budget * 0.10)
price_for_all_extras = extras * price_for_one_clothing
if extras > 150:
price_for_all_extras= price_for_all_extras * 0.90
total_sum_for_movie = price_decor + price_for_all_extras
left_money = budget ... |
d9c96d43ab6f9b30215f05558df20c10c743601b | Nishu210991/PythonProject | /_list.py | 7,969 | 4.375 | 4 | """The important properties of Python lists are as follows:
Lists are ordered – Lists remember the order of items inserted.
Accessed by index – Items in a list can be accessed using an index.
Lists can contain any sort of object – It can be numbers, strings, tuples and even other lists.
Lists are changeable (mutable) ... |
9962c57cff80a04e501aeec4980ef52ebcec8348 | Nishu210991/PythonProject | /map_filter.py | 985 | 3.859375 | 4 | # numbers=["3","5","4"]
# numbers=list(map(int, numbers))
# for i in range(len(numbers)):
# numbers[i]= int(numbers[i])
# print(numbers[i])
# numbers[2]= numbers[2]+1
# print(numbers[2])
# def sq(a):
# return a*a
#
# num=[2,3,4,5,6,7]
# square=list(map(sq, num))
# print(square)
#Using Lambda Function (o... |
7480d84b24658b9bf5a516f84f141e6767fbdfe5 | Nishu210991/PythonProject | /is_equal.py | 328 | 3.609375 | 4 | """
== - value equality-->Two objects have the same values
is - reference equality -->two refernce refers to the same object
"""
"""
>>> a=[7,8,9]
>>> b=a
>>> b==a
True
>>> b is a
True
>>> c=a[:]
>>> b==c
True
>>> a==c
True
>>> cis a
File "<stdin>", line 1
cis a
^
SyntaxError: invalid syntax
>>> c is a
F... |
b4a49a96845eec86a0aa1053977aac1645f258b3 | Nishu210991/PythonProject | /Filetut.py | 1,552 | 3.984375 | 4 | #f = open("Nishu.txt", "rt")
# content = f.read()
# print(content)
# content = f.read(3)
# print(content) #Starting 3 charcter (Nis)
# content = f.read(3)
# print(content) #next 3 charcter (hu )
# for line in f:
# print(line, end="") #Read code line by line
# Nishu is a good Girl.She is very beautiful an... |
d901f54453c8c11c61f2f93a798a78afe699dd88 | byarustev/iuiu_python_challenge | /question4/addinfinite.py | 153 | 3.59375 | 4 | def sum(*args):
total_sum = 0
for i in args:
total_sum += i
return total_sum
print(sum(1,2,3,4,5))
print(sum(4,5))
print(sum(5))
|
7b1d551e459083b97959a8d4211cfcae675391b5 | lelilia/advent_of_code_2020 | /day18.py | 3,910 | 3.78125 | 4 | ''' advent of code day 18 '''
class Tree:
def __init__(self, value = None):
self.left = None
self.right = None
self.value = value
def append_number(child, root):
q = [root]
while q:
current = q.pop(0)
if isinstance(current.value, str) or current.value is None:
... |
379b827ff69982c0e7e0b7f149d272109584efa7 | lelilia/advent_of_code_2020 | /day9.py | 1,929 | 3.984375 | 4 | ''' ADVENT OF CODE day 9'''
import numpy as np
def check_if_valid(array, preamble_length, index):
'''
check if there are two values in the subarray of length
preamble_length before the index that sum up to the value
of the array at index
'''
for i in range(index-preamble_length, index-1):
... |
16c769b2e4455f2567c22dffe10c8f486756d721 | lelilia/advent_of_code_2020 | /day3.py | 1,135 | 3.671875 | 4 | ''' ADVENT OF CODE day 3'''
def get_tree_for_slope(grid, row_dir, col_dir):
row_pos = 0
col_pos = 0
max_row = len(grid)
max_col = len(grid[0])
tree_count = 0
while row_pos < max_row:
if grid[row_pos][col_pos] == '#':
tree_count += 1
row_pos += row_dir
col_... |
e4e6cc4bfb67e9bf82b00a9f26566fde697f1ad7 | naeidxvTools/xiaojiayu | /sequence/list.py | 139 | 3.6875 | 4 | list1 = [12, 25, 36, 5, 85, 96, 22, 2, 55]
print(list1)
list1.sort()
print(list1)
list1.sort(reverse=True)
print(list1)
print(list1[:6])
|
20ff4c611cd7163e407ba8f8ee8443ca78a1b5f0 | kylefrankovich/problem_solving_with_algorithms_and_data_structures | /chapter_6_trees_and_tree_algorithms.py | 7,035 | 4.15625 | 4 | # notes for Chapter 6 - Lists and List Algorithms
# nodes and references:
# using object-oriented programming representation
# (as opposed to the chapter's first example, using lists of lists)
# create a root node:
class BinaryTree:
def __init__(self,rootObj):
self.key = rootObj
self.leftChild =... |
3f83cc7401b9a812ee78336e2dff6fd3a1a685a4 | jakebarnwell/one-time-chat | /device/storage.py | 874 | 3.6875 | 4 | class Storage(object):
"""Interface to a single file as an addressable byte store."""
def __init__(self, filepath):
self._filepath = filepath
def get(self, start_index, n_bytes):
"""Get bytes from the store.
Args:
start_index: Index of the first byte to get.
... |
e23a61dc3fbd65ab864d781ae45ddd923f3c0284 | CosmicCosmos/SPOJ-1 | /LENGFACT/LENGFACT.py | 199 | 3.515625 | 4 | from math import floor, log, pi, e
t = int(raw_input())
while t:
t-=1
n = int(raw_input())
if n == 0 or n == 1:print "1"
else:print int(floor((log(2*pi*n, e)/2 + n*(log(n, e)-1))/log(10, e))+1)
|
b9258b12f8d41978e920eb2987978a30f05a07ce | nobeans/deep-learning-from-scratch | /ch07/softmax.py | 749 | 3.6875 | 4 | import numpy as np
def softmax(a):
# バッチ処理に対応するため、行列もサポートする必要がある。
if a.ndim == 2:
# 2次元の行列の場合は転置行列を使っていい感じに計算する。
a_T = a.T
c = np.max(a_T, axis=0)
exp_a_T = np.exp(a_T - c) # for avoiding an overflow
sum_exp_a_T = np.sum(exp_a_T, axis=0)
y = exp_a_T / sum_exp_a_T... |
206646486a48a498e8517e709eaa9bea0b5edfa9 | antonaldinho/kiwic | /Input.py | 2,322 | 3.640625 | 4 | import re
import csv
class Input():
def process(self, *args):
#Imprime lineas, pregunta si quiere borrar lineas
if len(args) == 2 and isinstance(args[0], str) and isinstance(args[1], str):
file = open(args[1], "r")
stopWords = []
for w in file:
... |
c0e70fa46c4b3b05c8121c7c23e44f842d40c526 | Peakergzf/the-marvelous-mrs-maths | /number-theory/number_theory.py | 4,046 | 3.75 | 4 | from random import randint
from math import sqrt
def gcd(a, b):
"""
euclidean algorithm
:return: the gcd of a and b
"""
if b == 0:
return a
else:
return gcd(b, a % b)
def ext_euclid(a, b):
"""
extended euclidean algorithm
:return: (g, x, y) s.t. x*a + y*b = gcd(a... |
a521046b13da49dddf70d26ca7ffc7e5abe7ccc0 | iOS-CSPT7/Sprint-Challenge--Computer-Architecture | /cpu.py | 6,468 | 3.546875 | 4 | """CPU functionality."""
import sys
print(sys.argv)
LDI = 0b10000010 # LDI R0,8 130
PRN = 0b01000111 # PRN R0, 71
HLT = 0b00000001 # HLT
MUL = 0b10100010 # Multiply
POP = 0b01000110
PUSH = 0b01000101
CALL = 0b01010000
RET = 0b00010001
ADD = 0b10100000
CMP = 0b10100111
JMP = 0b01010100
JEQ = 0b01010101
JNE = 0b01... |
77ad9ceb099876d89631e11523861624c70696ed | wandyezj/coding_practice | /katamari_words_search/search_helpers.py | 1,523 | 4 | 4 |
import os
import itertools
FILE_WORDS_REAL = "scrabble_words_and_definitions.txt"
FILE_WORDS_TEST = "katamari_test_words.txt"
def unique_permutations(word):
permutations = itertools.permutations(word)
unique_permutations = set(permutations)
return unique_permutations
def print_dictionary(d):
fo... |
c9d46b7acd3ee7edcb44c4febaeb312236252038 | lunar-mycroft/sarcastify | /sarcastify.py | 508 | 3.578125 | 4 | from typing import Iterator
#import click
import sys
from looksRandom import looksRandom
def sarcastify(string : str) -> Iterator[str]:
rng : Iterator[bool] = looksRandom(bias = 0.25)
yield string[0]
for char in string[1:]:
if not char.isalpha():
yield char
continue
... |
5dcecc7721b0e6c4d1df5b83d7bc3911650a8993 | ccstar210/Instrument-Classification | /create_data_file.py | 1,018 | 3.671875 | 4 | #%%
# Creates a list of each filename and instrument and saves it as a csv file
import os
import csv
def detLabel(filename):
#determine the label of the recording
if "cello" in filename:
label = 0
elif "church" in filename:
label = 1
elif "clarinet" in filename:
label = 2
... |
efb19779c940b3f7d1f8999d089c2b2849764f1c | rckc/CoderDojo | /Python-TurtleGraphics/PythonIntro2-1Sequences.py | 1,435 | 4.5625 | 5 | # Author: Robert Cheung
# Date: 29 March 2014
# License: CC BY-SA
# For CoderDojo WA
# Python Intro Turtle Graphics
# Python has a rich "library" of functions.
# We are going to use "turtle" to do some simple graphics.
import turtle
# see https://docs.python.org/2/library/turtle.html#filling
if __name__ ... |
1946511a913c754d2fd3e5398406ea56652bd9da | pugzillo/Exercism | /python/reverse-string/reverse_string.py | 164 | 4.15625 | 4 | def reverse(text):
textlist = list(str(text)) # split text into list of letters
word = "".join(textlist[::-1]) # join the list, in reverse
return(word) |
382e4b8acea53c5ac818a547ed94c5765d2bb149 | pugzillo/Exercism | /python/triangle/triangle.py | 539 | 3.9375 | 4 | def is_valid(sides):
sides.sort()
if sides[0] + sides[1] >= sides[2] and 0 not in sides:
return True
else:
return False
def is_equilateral(sides):
if len(set(sides)) == 1 and set(sides) != {0}:
return True
return False
def is_isosceles(sides):
if is_equilateral(sides):
... |
94e501d87d0d32c19a0f24e1c0033adf3465d2e6 | ortizfer/Software-2016-2017 | /Missions/CenterPath.py | 3,680 | 3.84375 | 4 | from Vision import AngleTest, FrameGrab
from Missions import Movement
''''
CenterPath Mission Logic. The functionality of the CenterPath is to align the submarine to the center of the path by
using different movements like perpendicular, parallel and align Y.
The start of this file is to identify the position of the ... |
51ab48c1613c72737971583d929aaf8a5561266c | JessieSalas/sustainability | /vector2Py.py | 2,492 | 3.546875 | 4 | from pprint import pprint
import pickle
def toDict(filename):
"""
Takes a local txt file output from word2vec
and returns it as a python dictionary
following the convention
{
WORD (str) : Vector (float)
...
}
"""
d = {}
raw = [line for line in ope... |
b624cd173f22aa32496ef9dbfeada0eedb0979f0 | eilyi/IS685_ProblemSet6 | /survival.py | 4,616 | 3.5625 | 4 | #survival.py that bins how many people survive (Survived == 1) for each gender in 10-year blocks
#Count survivors by age and gender in these blocks:
#
import matplotlib.pyplot as plt
import pylab
import pandas as pd
import numpy as np
#setting the dataframe
df = pd.read_csv("train.csv")
#not enough data to be use... |
45d0ffc373ac319b08992388a601a915d1ebf2bb | thaipduong/kernelbasedmap | /astar.py | 1,179 | 3.859375 | 4 | from queue import PriorityQueue
#
# A* implementation.
#
def astar(start, goal, alpha = None, classifier = None):
start.g = 0
start.f = start.g + start.h(goal)
frontier = PriorityQueue()
frontier.put(start)
while not frontier.empty():
current = frontier.get()
if current == goal:
... |
c8229f81d7b415c2eda6c735349980d839782aa2 | OsamaMuharram/problem-solving | /codeforces/118-Div2/A.py | 156 | 3.859375 | 4 | my_word =input().lower()
new_word=''
for i in my_word:
if i not in 'aoieuy':
new_word = new_word+'.'+i
else:
new_word = new_word+''
print(new_word)
|
b9b15eaa64669b4129a9488d4f388543ccaf4a7f | OsamaMuharram/problem-solving | /codeforces/236-Div2/A.py | 158 | 3.65625 | 4 | x=input()
y=""
for i in range(0,len(x)) :
if x[i] in y:
pass
else:
y=y+x[i]
if len(y)%2 ==0:
print("CHAT WITH HER!")
else:
print("IGNORE HIM!")
|
8798dcf0509215f2d48f239a9922c093fa47af95 | greykoshak/patterns | /factorize.py | 1,837 | 3.609375 | 4 | import unittest
def factorize(x):
""" Factorize positive integer and return its factors.
:type x: int,>=0
:rtype: tuple[N],N>0
"""
pass
class TestFactorize(unittest.TestCase):
def test_wrong_types_raise_exception(self):
self.cases = [1.5, "string"]
for val in self.cases... |
1f91ee0d483216db82285df786dc74eea0cfc486 | Tman2111/python-challenge | /PyPoll/PyPoll.py | 2,059 | 3.578125 | 4 | #Grader: I have a syntax error at line 71 which prevents the output
# poll_analysis_code
import os
import csv
#data path
data_csv = os.path.join("Resources", "election_data.csv")
#variables
total_votes = 0
candidates = []
votes_for =[]
percent_of_vote = []
# Read the csv file for the election data
with open('el... |
3165cc41ff47203bab0f439c89f476fd628fc2c8 | conanlhj/2021_python_study | /jan/04/문제풀이/0104-04.py | 232 | 3.640625 | 4 | # Sol 1
list = input().split()
a = int(list[0])
b = int(list[1])
if a > b:
print(">")
elif a == b:
print("==")
else:
print("<")
# Sol 2
a, b = map(int, input().split())
print(">" if a > b else ("<" if a < b else "=="))
|
40802718bf5becc712db853bbd446393c1d530a6 | conanlhj/2021_python_study | /jan/09/평가문제/1427_소트인사이드.py | 151 | 3.515625 | 4 | # Sol 1
a = list(map(int, list(input())))
a.sort(reverse=True)
for i in a:
print(i, end='')
# Sol 2
print(*sorted(input(), reverse=True), sep='')
|
aea723f6f155bd60c9a17a428b16b771eb20f8ed | NataliaWojcik1/Hackathon-2 | /address_book.py | 1,171 | 3.859375 | 4 | import json
def enter_info(new_list):
name = input('Give me name: ')
number = int(input('Give me number: '))
try:
number = int(number)
except ValueError:
print('You gave wrong number')
else:
registration = {'name': name, 'number': number}
new_list.append(registrati... |
dfa00ddee0b6f139f9bf8416743af815f3263a7d | Freeman999/rockpaperscissor | /main.py | 2,227 | 3.5625 | 4 | def on_gesture_screen_down():
basic.show_string("score:" + str(score))
if score >= 0:
basic.show_icon(IconNames.HAPPY)
else:
basic.show_icon(IconNames.CONFUSED)
input.on_gesture(Gesture.SCREEN_DOWN, on_gesture_screen_down)
def on_button_pressed_a():
global score
score += 1
basic... |
0d0b58f109cf85078725e72c9bd0f0ecbcf2942d | LengendsNeverDie/playground-y6kt9gVc | /python-project/transform/scale.py | 598 | 3.59375 | 4 | from PIL import Image, ImageDraw
from math import floor
# Load image:
input_image = Image.open("input.png")
input_pixels = input_image.load()
new_size = (300, 300)
# Create output image
output_image = Image.new("RGB", new_size)
draw = ImageDraw.Draw(output_image)
x_scale = input_image.width / output_image.width
y_s... |
854ba8d463c358965e7d2d8515d7a4e8e4c60337 | willkchan/Torchvision_Example | /main.py | 165 | 3.8125 | 4 |
import time
start = time.time()
tmp = 3
for i in range(9):
tmp = tmp**7
end = time.time()
duration = round(end - start, 2)
print('done', duration, 'seconds')
|
39dc170f8909ee243152d792f94c1023675052e0 | billhong6981/Many-to-Many | /web_flask/4-number_route.py | 1,044 | 3.59375 | 4 | #!/usr/bin/python3
"""
Sript that starts a Flask web application
"""
from flask import Flask
app = Flask(__name__)
@app.route('/', strict_slashes=False)
def hello_bh():
"""
function to return Hello BH!
"""
return "Hello BH!"
@app.route('/bh', strict_slashes=False)
def bh():
"""
funct... |
c5513be63d1ed559b347baeaf78f9a8fe377392f | nrleist/python_games | /two_players/tic_tac_toe.py | 3,666 | 3.78125 | 4 |
def get_selection(p_turn, list, name):
good_sel = False
while(good_sel == False):
try:
sel = int(input(f'{name} please make your selection.\n'))
except:
print("I couldn't understand your selection.\nPlease make a selection from 1 to 9.\n \n")
else:
if(sel < 1 or sel > 9):
print("Your selection ... |
62328a6f11d76d93e9430fca995f88d2eae24b4f | nghiattran/playground | /count_bits.py | 993 | 3.6875 | 4 | import math
# from math import log
def count(num):
list = []
for index in range(num + 1):
if index == 0:
list.append(0)
else:
bits = math.log(index, 2)
if bits % 1 == 0:
bits = int(bits) + 1
else:
bits = math.ceil(b... |
84b7be837f7b8e84bd6e6a0672d3ed4763de9231 | nghiattran/playground | /leetcode/heaters.py | 883 | 3.546875 | 4 | import math
class Solution(object):
def findRadius(self, houses, heaters):
"""
:type houses: List[int]
:type heaters: List[int]
:rtype: int
"""
if len(houses) == 0 or len(heaters) == 0:
return 0
if heaters[0] != 1:
heaters.insert(0, h... |
c154cbfec515efbe0b8124d34af4e7e470dec3ec | nghiattran/playground | /reversed_string.py | 330 | 3.984375 | 4 | def reverse_string(string):
words = string.split(' ')
res = ''
for i in range(len(words)):
res += words[len(words) - 1 - i]
if i != len(words) - 1:
res += ' '
return res
def reverse_word(word):
pass
string = 'Do or do not, there is no try.'
res = reverse_string(string)
... |
fcafc7696cf9cde3e66fbe78f4db84c0eeebb022 | nghiattran/playground | /hackerrank/max-score.py | 855 | 3.578125 | 4 | import itertools
def getMaxScoreTidious(a, n):
print( )
# a = sorted(a, reverse=True)[:n+]
print(a)
# Complete this function
max_total_score = 0
for com in itertools.permutations(a, n):
running_sum = 0
total_score = 0
for i in com:
total_score += running_sum %... |
22e861c2a5adfb0e162ee5ced8c9d1825e5be0cd | nghiattran/playground | /crackingcoding/anagram.py | 357 | 3.921875 | 4 | def is_anagram(first, second):
dict = {}
for char in first:
if char not in dict:
dict[char] = 1
else:
dict[char] += 1
for char in second:
if char in dict and dict[char] > 0:
dict[char] -= 1
else:
return False
return True
p... |
e70241f25156bd8b04e003aa8129950952f24720 | nghiattran/playground | /hackerrank/university_codeprint_2/seperate_the_numbers.py | 719 | 3.546875 | 4 | BASE = ord('0')
def isBeautiful(string, size=1, isFlexible=True):
if len(string) == 1 and isFlexible:
return False, ''
first = int(string[:size])
second = str(first + 1)
nextNumIndex = size + len(second)
if second == string[size:nextNumIndex]:
if nextNumIndex < len(string):
a, b = isBeautiful... |
bb507b15970465843ed3c38122078ecd91790888 | nghiattran/playground | /leetcode/nth_digit.py | 349 | 3.90625 | 4 | import math
def nth_digit(num):
if num <= 9:
return num
base = 9
digit = 1
while base < num:
base *= 10
digit += 1
base /= 10
num -= base + 1
index = num % digit
num = int(math.ceil(num / digit))
num = base + num
return str(num)[int(index)]
print(nth_d... |
84ab6534c6eae23ff75049b2cc1a09701bac82c8 | nghiattran/playground | /hackerrank/palandir-degree/expand_the_acronyms.py | 1,408 | 4.03125 | 4 | dictionary = {}
def parse_abbr(entry, i):
i += 1
abbr = ''
while entry[i] != ')':
abbr += entry[i]
i += 1
return abbr, i
def parse_real(entry, abbr, i):
i -= 2
end_pos = i
stop = False
name = ''
uppercase_cnt = 0
while not stop and i >= 0:
name = entry... |
ecf511f09183776b2bc2076dd458613e7587eaa0 | nghiattran/playground | /leetcode/binary_preorder.py | 708 | 3.703125 | 4 | class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def preorderTraversal(self, root, res=[]):
"""
:type root: TreeNode
:rtype: List[int]
"""
if root is None:
return []
res.append(root.val)
self.preord... |
223e7b9aac61f7e0b89f20cbfb9d4a71c5c0d8aa | nghiattran/playground | /geeksforgeeks/count_negative.py | 471 | 3.671875 | 4 | def count_negative(arr):
row = 0
column = len(arr[0]) -1
count = 0
while row < len(arr) and column >= 0:
if arr[row][column] < 0:
count += column + 1
row +=1
if column != len(arr[0]) -1:
column -= 1
else:
column -= 1
re... |
c9c6d2090a8fb69649721603308245afc377cdd8 | randallale/Ch.08_Lists_Strings | /Secret_Codes.py | 321 | 3.59375 | 4 | secret_message = ""
solved_message = ""
encrypted_text = ""
for c in secret_message:
x = ord(c)
x = x+1
c2 = chr(x)
encrypted_text = encrypted_text + c2
print(encrypted_text)
for c in encrypted_text:
x = ord(c)
x = x-1
c2 = chr(x)
solved_message = solved_message+ c2
print(solved_message... |
c36bbdb48e0af03b51bf5f31c8d2e01d60cba778 | owenparker-utc/CPSC2100 | /Week2_Assignment2/main.py | 497 | 4.09375 | 4 | miles = int(input('Enter number of miles: '))
yards = int(input('Enter number of yards: '))
feet = int(input('Enter number of feet: '))
inches = int(input('Enter number of inches: '))
divider = '--------------------'
totalInches = int((miles * 63360) + (yards * 36) + (feet * 12))
totalMeters = int(totalInches / 39.97)... |
70540875c8211d5433131e881a97d3cf2fb5df07 | sahiljajodia01/Competitive-Programming | /test1.py | 2,160 | 3.5625 | 4 | def get_perm(nums, k):
if k == 1 :
for n in nums:
yield [n]
else:
for i,n in enumerate(nums):
print("i: ", i)
for x in get_perm(nums[i+1:],k-1):
print("Ans: ", [n] + x)
yield [n] + x
def main(nums,k):
if len(nums) < k:
return []
... |
58d47e5841ad8eb04e0a70321c686fb43f966953 | sahiljajodia01/Competitive-Programming | /leet_code/fizz_buzz.py | 1,052 | 3.78125 | 4 | # https://leetcode.com/explore/interview/card/top-interview-questions-easy/102/math/743/
############ Elegant Hasmap solution #############
class Solution:
def fizzBuzz(self, n: int) -> List[str]:
arr = []
d = {3: 'Fizz', 5: 'Buzz'}
for i in range(1, n+1):
ans = ""
f... |
3c4f0fba3fc06f45af839f25dc74624f828b11ae | sahiljajodia01/Competitive-Programming | /leet_code/merge_intervals.py | 2,110 | 3.90625 | 4 | # https://leetcode.com/explore/interview/card/top-interview-questions-medium/110/sorting-and-searching/803/
# My original solution that I attempted. It is correct but overly complicated
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
if len(intervals) == 0:
retur... |
5408a876669c4f3f25f3c603881e94025853171a | sahiljajodia01/Competitive-Programming | /leet_code/reverse_string.py | 356 | 3.734375 | 4 | # https://leetcode.com/explore/interview/card/top-interview-questions-easy/127/strings/879/
# class Solution:
# def reverseString(self, s: List[str]) -> None:
# """
# Do not return anything, modify s in-place instead.
# """
# for i in range(0, len(s)//2):
# s[i], s[len(s... |
d3b4e841be670b5ff23e7d5887b73204046b0a1d | sahiljajodia01/Competitive-Programming | /interview-bit/math/palindrome_integer.py | 250 | 3.953125 | 4 | def palindrome(A):
copy = A
reverse = 0
while copy != 0:
temp = copy % 10
reverse = reverse * 10 + temp
copy = copy//10
if reverse == A:
print("True")
else:
print("False")
palindrome(123) |
06ccf17e2d704e35ae7824739cbfeeb2cdb486ad | sahiljajodia01/Competitive-Programming | /leet_code/container_with_most_water.py | 612 | 3.53125 | 4 | # https://leetcode.com/explore/interview/card/top-interview-questions-hard/116/array-and-strings/830/
###### Two pointer approach #######
class Solution:
def maxArea(self, height: List[int]) -> int:
count1 = 0
count2 = len(height)-1
max_ = 0
while count1 < count2:
area =... |
0b9df4a329c0157bf307f4bdb408699e14a8c5ac | sahiljajodia01/Competitive-Programming | /leet_code/add_two_numbers.py | 2,353 | 3.84375 | 4 | # https://leetcode.com/explore/interview/card/top-interview-questions-medium/107/linked-list/783/
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
######### My solution. Not a very elegant one. Time complexity is O(n) but it still ... |
9e3de24e4fb0ab375da4e8bcf5b12576a4502395 | sahiljajodia01/Competitive-Programming | /leet_code/longest_palindromic_substring.py | 1,793 | 3.875 | 4 | # https://leetcode.com/explore/interview/card/top-interview-questions-medium/103/array-and-strings/780/
######### Recursive solution. Time limit exceeded #########
def longestPalindrome(s: str) -> str:
def solve(s, start, end):
if start > end:
return ""
string = s[start:(end+1)]
... |
086ba3b68b39e3a6c004a9ecbbc603015ebdcf99 | sahiljajodia01/Competitive-Programming | /leet_code/kth_smallest_element_in_a_bst.py | 923 | 3.71875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
####### Similar to inorder traversal and just checking the kth smallest with an if condition #######
class Solution:
def kthSmallest(self, root: TreeNod... |
61768782988d02279ad16bd1be3bf84cab2f402c | sahiljajodia01/Competitive-Programming | /leet_code/flood_fill.py | 1,389 | 3.609375 | 4 | # https://leetcode.com/explore/featured/card/may-leetcoding-challenge/535/week-2-may-8th-may-14th/3328/
###### BFS approach. It can also be done without using visited array ######
from collections import deque
class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[Li... |
09ff2e7ad56291cd38e04e4de3543ffdc80a530d | sahiljajodia01/Competitive-Programming | /leet_code/toeplitz_matrix.py | 444 | 3.65625 | 4 | # https://leetcode.com/problems/toeplitz-matrix/
# Google, Array
def isToeplitzMatrix(matrix: List[List[int]]) -> bool:
row = len(matrix)
column = len(matrix[0])
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if i == 0 or j == 0:
continue
... |
35081bc5325c06ca7a724ff68749902a9af9fc6e | sahiljajodia01/Competitive-Programming | /leet_code/vertical_order_traversal_of_a_binary_tree.py | 1,266 | 3.984375 | 4 | # https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/
###### The problem description was not clear on how to arrange the values for a particular vertical order ######
from collections import defaultdict
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=N... |
8dbfe31a54e5d487cd07735c39ab308d57c3166b | sahiljajodia01/Competitive-Programming | /leet_code/count_primes.py | 686 | 3.65625 | 4 | # https://leetcode.com/explore/interview/card/top-interview-questions-easy/102/math/744/
########### Sieve of Erathosthenes #############
class Solution:
def countPrimes(self, n: int) -> int:
if n == 0:
return 0
arr = [-1] * n
arr[0] = 0
if n > 1:
... |
4e89bd1e087e66d172983f41adb73e57f19e5ce7 | UladzislauVepr/Python-course | /prt.py | 979 | 3.609375 | 4 |
#con=int(1000)
#next_turn='Y'
#while next_turn=='y' or next_turn=='Y':
# n1=int(input('число1: '))
# n2=int(input('число2: '))
# sum_n=n1+n2
# print("Summa: ", sum_n)
# next_turn=input('pass?')
#number=0
#for i in range(0, 1000, 10):
# number=number+10
# print(number)
#number=[]
#i=1
#while i<11... |
98b748d50541ecc27664884452356bd0e1f3380f | kimyh1207/pylib_jump-to-python_lin | /ch17/dataclass_sample.py | 221 | 3.734375 | 4 | from dataclasses import dataclass
@dataclass
class User:
name: str
age: int
married: bool = False
user1 = User("홍길동", 33, True)
user2 = User("홍길동", 33, True)
print(user1)
print(user1 == user2)
|
786073c2e842f81fd71fc391628f6161546b5a9e | yyuuliang/codingchallenges | /hackerrank/Reverse-a-doubly-linked-list.py | 2,556 | 4.15625 | 4 | '''
File: Reverse-a-doubly-linked-list.py
Source: hackerrank
Author: yyuuliang@github
-----
File Created: Thursday, 12th March 2020 4:21:54 pm
Last Modified: Thursday, 12th March 2020 4:21:58 pm
-----
Copyright: MIT
'''
# Reverse a doubly linked list
# https://www.hackerrank.com/challenges/reverse-a-doubly-linked-lis... |
1a384978ed10c489583617fd8e001f22e66fe568 | yashwant-das/BasicPython | /9_RangewWhile.py | 172 | 3.765625 | 4 | #for x in range(5,12):
# print(x)
#for x in range(10):
# print("yash")
# While loop
buttcrack =5
while buttcrack <10:
print(buttcrack)
buttcrack+= 1 |
6c108b714639cdddde4bd4d1e5f37b6efae49a75 | saidsalihefendic/online-programming-school-2021 | /peto_predavanje/zadatak_2.py | 1,064 | 3.515625 | 4 | # Korisnik unosi sljedece brojeve:
# k -> broj bacanja novcica
# l -> broj uzastopnih glava
# Program da kalkulise kolika je vjerovatnoca da se pojavi l uzastopnih glava
# u k bacanja
# Dogadjaj -> k bacanja novcica
# Vjerovatnoca ovog problema
# uspjesan_broj_dogadjaja / ukupan_broj_dogadjaja <= 1
# [0, 1]
# Monte C... |
43f44a00df6ce92ca16250ef02b3a8badd2aec70 | saidsalihefendic/online-programming-school-2021 | /trece_predavanje/sabiranje_prvih_n_brojeva.py | 230 | 3.71875 | 4 | N = int(input("Unesite n: "))
suma = 0
for brojac in range(1, N + 1):
# suma = suma + N # N = 4 -> 4 + 4 + 4 + 4
# N = 5 -> 5 + 5 + 5 + 5 + 5
suma = suma + brojac
print("Suma od 1 do", N, "je:", suma) |
806bb3030c58eab9045cf52724148702f8417313 | RichAguil/Python | /kmToMiles (Assignment 16).py | 200 | 4.3125 | 4 | #Name: Richard Aguilar
#Date: June 11th, 2019
#This program: Converts kilometers to miles
kilometers = float(input("Enter kilometers you wish to convert: "))
miles = 0.621371*kilometers
print(miles) |
1abc43991b2fae468d3130bbc1a4029df4c04127 | pauloadilson/estrutura_de_dados | /python/ex03_class.py | 318 | 3.6875 | 4 | from stack import Pilha
p = Pilha()
NumInt = int(input("Número: "))
Oper = input("OPERAÇÕES: ").upper()
#NumInt = 4
#Oper = "EEEDDEDD"
i = 1
NumResultado = ""
for l in Oper:
if (l == 'E'):
p.Empilha(i)
i += 1
elif (l == 'D'):
NumResultado += str(p.Desempilha())
print(NumResultado) |
2f5772f7295cd2ceea4ec15866ef336440411b91 | pauloadilson/estrutura_de_dados | /python/queueclass.py | 589 | 3.59375 | 4 | class Fila():
def __init__(self, inicio=1, fim=1, max=50):
self.inicio = inicio
self.fim = fim
self.dic = {}
self.max = max
def isEmpty(self):
return self.inicio == self.fim
def isFull(self):
return self.fim == self.max - 1
# Insere um elem... |
18fb84a9659d1e92c4668d241a1c232a8946bcd5 | VOlni/week3 | /kr_5_2.py | 1,609 | 3.75 | 4 | from datetime import date
from datetime import datetime
import csv
class Person(object):
def __init__(self, surname, first_name, birth_date, nickname = None):
self.surname = surname
self.first_name = first_name
if nickname is None:
self.nickname = surname
else:
... |
385f292b49709302ce1a3fe921cec00f7d185f30 | VOlni/week3 | /kr_5_1.py | 947 | 3.6875 | 4 | from datetime import date
from datetime import datetime
class Person(object):
def __init__(self, surname, first_name, birth_date, nickname = None):
self.surname = surname
self.first_name = first_name
if nickname is None:
self.nickname = surname
else:
self.ni... |
d67bca0628f77c94d6e16aaa1230490896e4d19c | 1Amitkumar/Python-Basic | /07Python Lists/05Slicing_List.py | 137 | 3.75 | 4 | list = [11, 33, 44, 66, 788, 1]
print(list[0:5]) # return list starting from index 0 to index 4
print(list[:3])
print(list[2:])
|
94074ac93169161120dfdba5af7a3ada965395a8 | 1Amitkumar/Python-Basic | /08Python Tuples/01Creating_Tuple.py | 193 | 3.625 | 4 | t1 = () # creates an empty tuple
print(t1)
t2 = (11, 22, 33)
print(t2)
t3 = tuple([1, 2, 3, 4, 4]) # tuple from array
print(t3)
t4 = tuple("abc") # tuple from string
print(t4)
|
4943da968d02e24a4528f92ab82523c75dcab75f | shubgene/Assignment4.1 | /question1.py | 512 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Aug 26 19:13:22 2018
@author: shurastogi
"""
import numpy as np
def matrix(vec,dimes,increasing):
list_array=[]
for y in range(dimes):
list_ex=[x**y for x in vec]
list_array.append(list_ex)
if(increasing):
return np.array(l... |
68e32cfe7978ad1ecfd7da2e846f473d0e52c1f3 | Jaybird101/tictactoe_error.py | /Homework 1/question1.py | 1,288 | 4 | 4 | class Hw1q1: # defines Hw1q1 class with the trait of time for the input
def __init__(self, time):
self.time = time
#timeConvert Function#
def timeConvert(self):
days = self.time // 86400; time = self.time % 86400 # floor-divides seconds by number of seconds in a day, saves remainder
... |
7307fdf3b3fed31fcd7523738a9c5aa542228433 | Artix1500/recognition-of-nationality-NLP | /raw_text_processor.py | 1,632 | 3.625 | 4 | import re
def join_hyphenated_words(raw_text):
result = []
previous_word = ''
for raw_word in raw_text.split():
word = previous_word + raw_word.strip()
previous_word = ''
if word[-1] == '-':
previous_word = word[:-1]
continue
result.append(word)
... |
7b04023a27193cf35c7c4db27c72cbb265193ddf | manusoler/code-challenges | /projecteuler/pe_1_multiples_3_and_5.py | 364 | 4.3125 | 4 | """
If we list all the natural numbers below 10 that are multiples of 3 or 5,
we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
def multiples_of(*nums, max=1000):
return [i for i in range(max) if any([i % n == 0 for n in nums])]
if __name__ == "_... |
5edfcb64caffbd7579312220e034c25435350b3f | manusoler/code-challenges | /projecteuler/pe_27_quadratic_primes.py | 1,878 | 3.640625 | 4 | from math import sqrt
from itertools import count
from utils.decorators import timer
"""
Euler discovered the remarkable quadratic formula: n**2 + n + 41
It turns out that the formula will produce 40 primes for the consecutive integer values . However, when is divisible by 41, and certainly when is clearly divisibl... |
7c627aebb0b967337d6d5df9f931e484c99c286b | manusoler/code-challenges | /hackerrank/tutorials/30_days_of_code/day25_running_time_and_complexity.py | 380 | 4.09375 | 4 | from math import sqrt
def is_prime(n):
if n == 2: return True
if n < 2 or n % 2 == 0: return False
for i in range(3,int(sqrt(n))+1,2):
if n % i == 0:
return False
return True
if __name__ == '__main__':
num_tests = [int(input()) for i in range(int(input()))]
for n in num_t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.