blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
fa1dc640f9fc7aac824733a4952f50795e0db039 | rishitc/PESU-IO-SUMMER | /coding_assignment_module1/program_3.py | 695 | 4.21875 | 4 | #3. Answer for question - 3
num_list = [int(x) for x in input("Enter the sequence of comma separated numbers :\n").split(",")]
num_list = sorted(num_list)
print("The sorted list is :", num_list, "\n")
key = int(input("Enter the number to search for in the sorted list:\n"))
low = 0
flag = False
high = len(num_list) - 1
... |
2567c36aea292c0be402ca28db54bca9731d75e9 | andrei-bolkonsky/programmation_efficace | /src/anagram.py | 719 | 4.125 | 4 | from inputs_utils import read_file
def find_anagrams_of(word):
"""Find all anagrams.
Params
------
word: str
Sequence of characters for which all combinaisons of anagram have to be found.
Returns
-------
list
A list of all anagrams.
"""
outputs = []
if le... |
e8f121bb85df42d7b71c5e277dbcf344256296e4 | adithirgis/DeepLearningFromFirstPrinciples | /Chap1-LogisticRegressionAsNeuralNetwork/DLfunctions1.py | 2,980 | 3.90625 | 4 | # -*- coding: utf-8 -*-
##############################################################################################
#
# Created by: Tinniam V Ganesh
# Date : 4 Jan 2018
# File: DLfunctions1.py
#
##############################################################################################
import numpy as np
import ... |
7aedbc99deb09461fc3e9ba693ab996f0ed879e2 | SandipVyara/Skillsanta-Center | /swap.py | 193 | 3.84375 | 4 | list1= [56,89,12,3,4,2,84]
def swaplist(list1):
first= list1.pop(0)
last= list1.pop(-1)
list1.insert(0,last)
list1.append(first)
return list1
print(swaplist(list1))
|
5013ba70665e272c3998a82e247232f8cbb60094 | Artem-Efremov/CodeWars | /Strings/Sorting Replase Reverse/7kyu_Jaden Casing Strings.py | 577 | 4.03125 | 4 | """
Your task is to convert strings to how they would be written by Jaden Smith.
The strings are actual quotes from Jaden Smith,
but they are not capitalized in the same way he originally typed them.
Example:
Not Jaden-Cased: "How can mirrors be real if our eyes aren't real"
Jaden-Cased: "How Can Mirrors Be Real I... |
7903513da8f065096fb0d6d65f021798e9e04bf8 | gomip/TicTacToe | /TicTacToe.py | 4,078 | 3.796875 | 4 | coord = {'A1': ' ', 'A2': ' ', 'A3': ' ', 'B1': ' ', 'B2': ' ', 'B3': ' ', 'C1': ' ', 'C2': ' ', 'C3': ' '}
#ans=['B2','C3','C1','C5','A3','B3','B1','44','A2','C2','+2','A1']
state=1 #to check whether player put proper position
#count=0
t=0 # count turn
p="O"
Game=0
"""
game state.
Running =0 | Win=1 | Dr... |
53a3217a9f6b547c3c2120e5102321ce6cc465e9 | gauravssnl/Data-Structures-and-Algorithms | /python/Data Structures and Algorithms in Python Book/analysis/prefix_average3.py | 358 | 3.890625 | 4 | # Overall complexity: O(n)
def prefix_average3(S):
n = len(S) # O(1)
A = [0] * n # O(n)
total = 0
for j in range(n): #O(n)
total += S[j] # O(1)
A[j] = total / ( j +1 ) # O(1)
return A
if __name__ == "__main__":
seq = [1, 2, 3, 4, 5, 6]
print("The prefix average for the sequ... |
c997005f9f70aaedf83164dd5f71d8e9ce45f5d6 | ryanmcg86/Euler_Answers | /Important_Functions/tau.py | 478 | 3.625 | 4 | '''This function returns the number of positive divisors of n'''
def pfExps(n):
exps = []
for i in range(2, 4):
if n % i == 0:
exps.append(0)
while n % i == 0:
n /= i
exps[-1] += 1
for i in range(5, int(n**0.5) + 1, 6):
for j in [i, i + 2]:
if n % j == 0:
exps.append(0)
while n % j == 0:... |
1d48966d29551517a3dc023dab9dc6afe57e987e | rajvender/Assignment2_ | /Assignment2_2.py | 213 | 3.6875 | 4 | def main():
print("enter numbre of star")
a=int(input())
for i in range(a):
for j in range(a):
print("*",end=" ")
print("")
if __name__==('__main__'):
main()
|
feb7b43834b37f6356e5d73f7ef6decd79a25341 | nikhiljain9818/Python-Beginners-Tutorial | /Python_Tutorial_7f.py | 262 | 4.03125 | 4 | # wap to tell no. of list inside a list
# ex- input-->[1,2,3, [1,2], [3,4]] output---> 2
num = [1,2,3, [1,2], [3,4],]
def func(l):
count = 0
for i in num:
if type(i) == list:
count += 1
return count
print(func(num))
|
ed9395058e7a27ae519f56a41ed777692f178a97 | boshan/Leetcode | /algorithms/001-Easy-twoSum/twoSum.py | 716 | 3.65625 | 4 | # Source : https://leetcode.com/problems/two-sum/
# Author : Bohan Shan
# Date : 2018-02-22
class Solution(object):
# returns the index of the two numbers that sum to target
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"... |
c86ade298be5aea06c3c2a11d4cb7167f173e8b3 | tiagovla/fdtd.py | /fdtd/utils.py | 2,359 | 3.515625 | 4 | """This module implements the utilities."""
from dataclasses import dataclass
from enum import Enum
import numpy as np
from .exceptions import WrongBounding
class Direction(Enum):
"""Direction of the object."""
X = 0
Y = 1
Z = 2
@dataclass
class BoundingBox:
"""Implement a bounding box that c... |
ba38cd4bfb5e819c9a066bb4c2549920e9a8ea03 | ChristianMRodas/CS101-Python | /Assignment 7 Pair Game/Assignment 7 Pair Game/flip def.py | 2,791 | 4.21875 | 4 |
#Trial 2
game_board_row1 = ['A','B','C','D']
game_board_row2 = ['E','F','F','E']
game_board_row3 = ['D','C','B','A']
main = []
main.append(game_board_row1)
main.append(game_board_row2)
main.append(game_board_row3)
print(main)
# print(main[1][1])
user_board = [['*', '*', '*', '*'], ['*', '*', '*', ... |
b9388136cc3a9efa18863edb872c8000bb7566fd | wesbragagt/Exercism | /python/matrix/matrix.py | 775 | 3.5625 | 4 | class Matrix:
def __init__(self, matrix_string):
self.matrix = list(map(lambda e: e.split(' '),matrix_string.split('\n')))
def row(self, index):
if len(self.matrix) == 1:
return list(map(lambda e: int(e),self.matrix[index - 1]))
else:
return list(map(lambda e: i... |
05c6cf15573cb3a8c7762fc747d0174228d6cecd | zb315044652/python-1000-days | /day-011/dictionary.py | 1,157 | 4.15625 | 4 | # 定义一个字典,并将一定的值赋给变量
MyDog = {'size': 'big', 'color': 'white', 'character': 'gentle'}
# 字典值通过‘键’来访问
print(MyDog['size'])
print('My Dog has ' + MyDog['color'] + ' fur.' + ' and it has a ' + MyDog['character'] + ' character')
# 字典数据类型
MyCon = {12: 'big', 0: 'white', 354: 'gentle', 1: 'good'}
# list 和 dictionary 区别
list... |
5cda27bab5f054d6eab4d1cb3afb72b42e49d7d2 | fabiorfc/Exercicios-Python | /Python-Brasil/1-EstruturaSequencial/exercicio_08.py | 427 | 3.953125 | 4 | # -*- coding: utf-8 -*-
"""
8 - Faça um Programa que pergunte quanto você ganha por hora e o número de
horas trabalhadas no mês. Calcule e mostre o total do seu salário no referido
mês.
"""
valor_hora = float(input('Informe o valor da hora trabalhada: '))
total_horas = float(input('Informe o total de horas trabalhada... |
da2a9ff14e6b62470cc419a89c45659f9d33fe04 | nur3k/Economy_driving | /car.py | 2,037 | 3.875 | 4 | import time
class MyCar:
def __init__(self, position_x):
self.position_x = position_x
self.speed_kmh = 60
def get_gps_position(self):
# symulacja zmiany pozycji x, trzeba bedzie dodać zczytywanie z GPSa
self.position_x += 10
time.sleep(1)
return self.position_x... |
51a700adff1571f3b83ce7ef30cc83772ae8f354 | Ph0en1xGSeek/ACM | /LeetCode/108.py | 1,420 | 3.703125 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def sortedArrayToBST(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
... |
34ace6ca9f44926d66fb0d69aaf638ad8ea0f9d1 | rustyhowell/raytracer_py | /test_vector3.py | 3,217 | 3.6875 | 4 | import unittest
import math
from vector3 import Vec3
class TestVec3(unittest.TestCase):
def test_init(self):
v1 = Vec3(1, 2, 3)
self.assertEqual(v1.r, 1.0)
self.assertEqual(v1.g, 2.0)
self.assertEqual(v1.b, 3.0)
def test_length(self):
v = Vec3(1, 2, 3)
self.ass... |
79c9de60733eb4083a8468d30918d486dbbc9206 | Muhammad-Ramees/Tkinter_Calculator | /calculator.py | 31,233 | 3.859375 | 4 | import math
from tkinter import *
def plus_memory():
global memory, number, is_memory_used, is_memory_clicked
result = float(memory) + float(number)
integer = result.is_integer()
if integer:
memory = str(int(result))
else:
memory = str(result)
memory_store.append("M+ (" + numbe... |
26c8bb5c06065ed5c403751bb5eddf083f083833 | Philipsty/BattleShip | /Ships.py | 2,418 | 3.796875 | 4 | #!/usr/bin/env python
import math
from PointT import*
from InvalidShipException import*
# Tyler Philips
#April 1 the work being submitted is your own individual work
#ASSUME: that start coord will have lower value than end coord. otherwise problems occur in constructor
## @brief
class Ships:
## @brief This is a co... |
5dd3d757ed4fb08d4650346f278929341f20a3ba | Grande-zhu/CSCI1100 | /LEC/lec06/lec6.py | 369 | 4 | 4 | first = input("Enter the first number: ")
print(first)
second= input("Enter the second number: ")
print(second)
first=float(first)
second=float(second)
if (first > 10) and (second> 10):
print("Both are above 10.")
elif (first < 10) and (second < 10):
print("Both are below 10.")
average = round((fi... |
03dd8de45f1790fec147400373271eab537e4203 | RathanakSreang/MyPython | /lessions/looping.py | 323 | 3.609375 | 4 | words = ['rathanak', 'kimly', 'apha', 'akoch']
for w in words:
print(w, len(w))
for w in words[:]:
print(w)
if len(w) > 5:
words.insert(0, w)
print(words)
for i in range(5):
print(i)
def fib(n):
a, b = 0, 1
while a < n:
print(a,end='')
a, b = b, a+b
print()
fib(200... |
a329e63a180e89b80872273387b1449c47a0471e | zzulu/aps-on-programmers | /solutions/py/30-12925.py | 452 | 3.65625 | 4 | # def solution(s):
# return int(s)
# int() 구현하기
def solution(s):
numbers = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
result = 0
for index, char in enumerate(s[::-1]):
if char == '-':
result *= -1
elif char != '+':
result +=... |
939434fef7d0a59fbac2af2f22ed62ac75197e40 | shaymcb/unit3.0 | /fives.py | 135 | 4.15625 | 4 | #Shaylee McBride
#14Feb2018
#fives.py - prints multiples of five
num = int(input('Enter a number: '))
for i in range(5,num+1,5):
print(i)
|
fa432b0345dd32b5737e66d1d5429f94c1dd4519 | LikeLionSCH/Python_Basic_Example | /Quiz/7.py | 60 | 3.5 | 4 | tuple1 = (1, 2, 3, 4)
tuple1 = tuple1 + (5,)
print(tuple1)
|
b9af759a68b33ad888211a42f84dcc4c91f3c21a | szabgab/slides | /python/examples/regex/matching_section_minimal.py | 126 | 3.796875 | 4 | import re
text = "This is <a string> with some <sections> marks."
m = re.search(r'<.*?>', text)
if m:
print(m.group(0))
|
a7f2352d2b740fe86cb462a925a4cb594a206fe9 | rodrigosantosti01/LingProg | /Exercicio6/atv01.py | 279 | 4.125 | 4 | # 1- Defna a função somannat que recebe como argumento um número natural n
# e devolve a soma de todos os números naturais até n.
# Ex: somannat(5) = 15
def soma_nat(n):
return 1 if n == 1 else n + soma_nat(n-1)
print(soma_nat(5))
print(soma_nat(2))
print(soma_nat(1)) |
de2e89cbd202607a672b92e3a710641ba32b438f | sfdye/leetcode | /construct-binary-tree-from-inorder-and-postorder-traversal.py | 534 | 3.859375 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def buildTree(self, inorder: "List[int]", postorder: "List[int]") -> "TreeNode":
if inorder:
root = TreeNode(postord... |
3edeacb635aff16dd512bc80a73dc8f0481d5612 | djs1193/-w3r-esource | /exe7.py | 137 | 4.09375 | 4 | #get extension of any file input from the user
my_file = input("enter the filename: ")
my_list = my_file.split('.')
print (my_list[-1])
|
6ae58d08cb65800361a6985b9195afe29c0e2248 | OriHasin/HasinMyNewProject | /OriHasinDictionaries/Targil7.4.py | 110 | 3.96875 | 4 | keys=int(input("Enter a new number: "))
dic1={}
for i in range(1,keys+1):
dic1.update({i:i*i})
print(dic1) |
13d3ecd578a2654d254ea98c94411ff60e33fb80 | mjhea0/python-basic-examples | /thread/delay_thread.py | 357 | 3.515625 | 4 | #coding:utf-8
import thread
import time
def print_time(threadName, delay):
while 1:
time.sleep(delay)
print "%s: %s" % (threadName, time.ctime(time.time()))
#Start threads to print time at different intervals
thread.start_new_thread(print_time, ("Thread01",2,))
thread.start_new_thread(print_time,... |
91a5c4d5668b1bd8e23c623dc0e99cb2c8091439 | Misk77/DevOps-Programmering-av-Python | /SocketPython/client.py | 2,522 | 4.09375 | 4 | ############################################### A SIMPLE CLIENT ###############################################
# write a simple client program wich open a conneection at given port 12345 and given host
# Once you have the socket open you can read from it like any I/O object
# remember to close then you done, as you... |
f63bafd08a2ab48ec582f16356111fc37124accb | nummy/exec | /mi/program5/program5/ball.py | 724 | 3.984375 | 4 | # A Ball is Prey; it updates by moving in a straight
# line and displays as blue circle with a radius
# of 5 (width/height 10).
import math
import random
from prey import Prey
class Ball(Prey):
radius = 5
def __init__(self,x,y):
angle = 2*math.pi*random.random()
self._color = "#0000ff"
... |
ed32266d96e968ba1aa4caf8e3fe7b7bc15432d8 | sbdzdz/python-katas | /coding_interview/chapter4/test_list_to_bst.py | 556 | 3.5 | 4 | from list_to_bst import *
def test_empty():
assert list_to_bst([]) is None
def test_single():
result = list_to_bst([0])
assert result.value == 0
def test_double():
result = list_to_bst([0, 1])
assert result.value == 1
assert result.left.value == 0
def test_even():
result = list_to_bst([0... |
830f64e3f972382e382f49473da4ad0aadc83118 | LRH733/bj19 | /02类/01多继承.py | 273 | 3.84375 | 4 | # 用类名继承
class Parant(object):
def __init__(self, name):
self.name =name
def show_name(self):
print(self.name)
class Son1(Parant):
def __init__(self, name):
Parant.__init__(self)
self.name = name
print(Son1.__mro__)
|
46e6dcf3e34bb973fc3d36bd65d3257f8abee334 | HumanAcademy-AI-Cource/2021_02Sample | /sample18.py | 409 | 3.828125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*
kekka1 = 5 + 5 # 5+5 の結果をkekka1にコピー
print(kekka1) # kekka1 を表示
for i in range(9): # 9回繰り返す
kekka1 = kekka1 + 10 # kekka1 + 10の結果をkekka1にコピー
print(kekka1) # kekka1を表示
if kekka1 == 100:
print("おわり")
if kekka1 < 100:
prin... |
faa8e175599182e3ba0efd9a44a11cd4c932c974 | SridharanTT3AR/data-structure | /q12 Check Completeness of a Binary Tree.py | 906 | 3.859375 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def isCompleteTree(self, root):
"""
:type root: TreeNode
:r... |
ac9f08a9928d7c7d8842b261102e9d910e50015e | nyukers/APIC-EM | /05_aclNum.py | 261 | 3.984375 | 4 | aclNum = int(input("What is the IPv4 ACL number? "))
if aclNum >= 1 and aclNum <= 99:
print("This is good IPv4 ACL.")
elif aclNum >= 100 and aclNum <= 199:
print("This is extended IPv4 ACL.")
else:
print("This is not good or ext IPv4 ACL.")
|
114d76d12493ce60bc2d1fc6a6b96310c16a420c | Argonauta666/coding-challenges | /interviews.school/02-loops/valid-palindrome.py | 874 | 3.984375 | 4 | # https://leetcode.com/problems/valid-palindrome/
from typing import List
import re
class Solution:
def filterAlphanumeric(self, s: str) -> str:
"""
convert string to lower and filter only alphanumeric characters.
"""
subPattern = re.compile('[^a-zA-Z0-9]')
return subPatter... |
ea37f5570c52bc788bf5003b2c2ed72bb090199f | SSinsa/dataStructure_algorithm | /Chapter16-01.py | 6,261 | 3.5 | 4 | #16강 우선순위 큐(Priority Queue)
# FIFO (First-In First-Out)
# Eq => 6 7 3 2
# Dq => 2 3 6 7 (값이 작은 것이 우선순위가 높을 때)
# Enqueue 할 때 우선순위 순서를 유지하도록
# Dequeue 할 때 우선순위 높은 것을 선택 -> 모든 원소를 다 봐야하기 때문에 불리함
# -> 전자가 더 유리하다
# 선형 배열 이용
# 연결 리스트 이용
# -> 시간적으로 볼 때 연결리스트가 유리함(중간 삽입이 빈번하기 때문)
# -> 메모리 공간 소요에서는 선형 배열이 유리
# -> 그러나 시간적으로 유... |
368ea43ae148707b638a05992378e7f834bc96a1 | ricardoquijas290582/clase_python_1 | /my_name.py | 151 | 4 | 4 | nombre = input('Nombre? ')
print("Me alegro de conocerle " + nombre)
nombre1 = input("¿Cómo se llama? ")
print("Me alegro de conocerle, {nombre1}")
|
21da1f0b98987294b4886eea823834ce7f8431d9 | SowatRafi/My-Python-Journey | /1. Basics/4. Python Data structures/List-Methods.py | 1,721 | 4.46875 | 4 | friends = ['Riyad', 'Afif', 'Faiyaz', 'Rafid', 'Ismam']
travelling = ['Chittagong', 'Sitakundo', 'Chadpur', 'Sonargau']
friends.extend(travelling)
print(f"\nAfter using extend method: \n{friends}")
number1_list = [1, 23, 2, 236, 5, 2354, 24, 65, 234]
number2_list = [123, 152, 524, 521, 347, 74, 746, 432]
number1_lis... |
ab8faebcd96e85dccf64e319bf94006aeb1c1372 | yuqiw4/Othello | /Othello.py | 7,296 | 3.65625 | 4 | #Melody Wang 59907761
'''
Othello game logic
'''
black = 'B'
white = 'W'
none=' '
direction_list = [[-1,-1],[-1,0],[-1,1],
[0,-1], [0,1],
[1,-1], [1,0], [1,1]]
#main part
class Othello_game_state:
def __init__(self,column,row,turn:'B or W',how_to_... |
dc176548035441b31a6cbcc54d7881c5a454d0ed | alu0100773002/prct005 | /src/prct05.py~ | 819 | 3.96875 | 4 | #!/usr/bin/python
#!encoding: UTF-8
import sys
argumentos = sys.argv[1:]#visualiza los parámetros desde la posición 1 en adelante
print argumentos
if (len(argumentos) == 1):
n= int (argumentos[0])
else:
print "Introduzca el nº de intervalos (n>0):"
n = int (raw_input())
if (n>0):
PI35 = 3.1415926535897931159... |
8544e98eaa5f1eaf1676eeba0803baeccfdfd5eb | DaHuO/Supergraph | /codes/CodeJamCrawler/16_1_1_neat/16_1_1_rray_solve.py | 339 | 3.5625 | 4 | def last_word(s):
word = s[0]
for c in s[1:]:
if c >= word[0]:
word = c + word
else:
word = word + c
return word
def main():
t = int(raw_input())
for i in xrange(t):
print "Case #{}: {}".format(i+1, last_word(raw_input().strip()))
if __name__ == '__m... |
ee24eb53b8f03259ea75c558a4e1ded1a48d040c | R11baka/ACME | /python/1079AC.py | 769 | 3.5625 | 4 | import sys
def memorize(function):
memo = {}
def wrapper(*args):
if args in memo:
return memo[args]
else:
rv = function(*args)
memo[args] = rv
return rv
return wrapper
@memorize
def getNumber(i):
"""" Maximum """
if i==0:
return 0
elif i==1:
return 1
elif i%2==0:
retu... |
b6ba08569d686736a49c08721055a80cc243be96 | RobRoger97/test_tomorrowdevs | /cap1/34_Day_Old_Bread.py | 407 | 3.734375 | 4 | #Dati
Pane_prezzo = 3.49
Sconto_old = 0.60
#Chiedi all'utente
n = int(input("Inserire il numero di pane vecchio di un giorno: "))
#Calcoli
prezzo_regolare = n*Pane_prezzo
sconto = prezzo_regolare*Sconto_old
totale = prezzo_regolare-sconto
#Stampa i risultati separatamente
print("Prezzo regolare: %5.2f" % prezzo_rego... |
adc639dbff54a41470bef7afa8df766097879e63 | ferromauro/python3_dojo | /Modulo_5/lezione_5_5_bis.py | 1,009 | 3.53125 | 4 | #! /usr/bin/env python3
#######################################
### COSTRUTTORE DI CLASSE ###
#######################################
class Animale:
def __init__(self,**kwargs):
self._family = kwargs['family'] if 'family' in kwargs else 'felini'
self._name = kwargs['name'] if 'name... |
d83436f72903d296e2d3275c1b9c7db7d3bef994 | prithvi1617/Coding-Questions | /basic question/2.Write a program to check the given string is palindrome or not.py | 291 | 3.5625 | 4 |
def pall(str1,len):
l=0
r=len-1
flag=0
for i in range(len):
if str1[l]!=str1[r]:
flag=1
break
l+=1
r-=1
if flag==1:
return 'no'
else:
return 'yes'
str1='abcdeddcba'
print(pall(list(str1),len(str1))) |
9106dbf5ea4eb5ec01a0490c68a10a86846d2ac8 | alvaro16589/cursopython | /ejercicios/ciclos/tiempodeviaje.py | 190 | 3.515625 | 4 | op = 1
tt = 0
while op!= 0:
op = int(input("Tiempo de tramo(min) = "))
tt = tt + op
print("Tiempo total del viaje es {0}:{1} horas".format(tt//60,int((tt/60-float(tt//60))*60 )))
|
52355a7e15abef3531b7189b8cafbfa8ee384d5d | elhajuojy/exercise-python- | /9.py | 158 | 3.78125 | 4 | TimeInSeconds=int(input("donner le temps :"))
H=TimeInSeconds//3600
Rest=TimeInSeconds%3600
M=Rest//60
Seconds=Rest%60
print(f"Time is :{H}:{M}:{Seconds}")
|
45c9497ba5f16192a96dacd95024c1f80e5c6b82 | Yujunw/leetcode_python | /230_二叉搜索树中第K小的元素.py | 1,335 | 3.734375 | 4 | '''
给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的元素。
说明:
你可以假设 k 总是有效的,1 ≤ k ≤ 二叉搜索树元素个数。
示例 1:
输入: root = [3,1,4,null,2], k = 1
3
/ \
1 4
\
2
输出: 1
示例 2:
输入: root = [5,3,6,2,4,null,null,1], k = 3
5
/ \
3 6
/ \
2 4
/
1
输出: 3
'''
# Definition for a binary tree node.
class Tree... |
d10953c9e23e0ce78f7061f898c57225f1078700 | eronekogin/leetcode | /2020/bulb_switcher.py | 689 | 3.84375 | 4 | """
https://leetcode.com/problems/bulb-switcher/
"""
class Solution:
def bulbSwitch(self, n: int) -> int:
"""
All the bulbs at first are turned on. So a bulb will stay on only
when it is toggled odd times during n rounds. The ith bulb will only
be toggled at the pth round, while p... |
487b7bbb6e1bfa0249f32e5c1b8438b345661618 | AditiGarg09/Python | /find_power_using_recursion.py | 195 | 4.0625 | 4 | def func(num,power):
if power==0:
return 1
else:
return num * (func(num,power-1))
num=int(input("Enter num: "))
power=int(input("Enter power: "))
print(func(num,power))
|
2d775948569cbcf8d1654e9ccc701fc12b390b38 | stanton119/data-analysis | /nlp/nlp_data_loading.py | 4,481 | 3.78125 | 4 |
# %%
"""
# Text classification
TLDR:
* Concat all sentences to single long list with list of starting offsets
* Convert words to tokens
* Tokens + offsets -> nn.EmbeddingBag layer
* which converts to embeddings per token and then aggregates
* Outputs tensor of shape: [No of sentences, embedding size]
Take ... |
49a053bbdeb995c6a3fbf15fd1f96b89de83a595 | Vinicius-Trindade/Python-Project | /index.py | 482 | 3.9375 | 4 | def func1(x, y, z):
print("example")
return x * y * z
print(func1(3, 4, 5))
def convert(miles):
kilometers = miles * 1.60934
return "miles: " + str(miles) + " = " "kilometers: " + str(kilometers)
print(convert(1))
b = [1, 2, 3]
total = 0
for a in b:
total = total + a
print(total)
a = list(range(1... |
37629531ac3cb96ba2a73c5cc5972e1fe97e9108 | 99003734/Project_Python_Learning | /lists.py | 1,032 | 3.890625 | 4 | student_Id = ["Akbar",["basha",21,2654],20,3734]
print(student_Id[0])
print(student_Id[1][0])
student_Id = ["Akbar",["basha",21,2654],20,3734]
print("Akbar" in student_Id)
print("Akbar"not in student_Id )
student_Id = ["Akbar","Basha","Shaik"]
for Akbar in student_Id:
print("yes")
break
num1 = list(range(0... |
0716b8f2e2543fb1a674b8f1a9d2923d0108740e | mdhatmaker/Misc-python | /interview-prep/geeks_for_geeks/google/longest_valid_parens.py | 1,733 | 3.921875 | 4 | import sys
# https://practice.geeksforgeeks.org/problems/longest-valid-parentheses/0
# Given a string S consisting of opening and closing parenthesis '(' and ')'.
# Find length of the longest valid parenthesis substring.
###############################################################################
def longest_va... |
56efb64ac5d524da71bba8e6114d14bdae2786d9 | xia0nan/intent-classification | /spacy_tokenize.py | 707 | 3.703125 | 4 | import string
import spacy
from spacy.lang.en.stop_words import STOP_WORDS
# Creating our tokenizer function
def spacy_tokenizer(sentence):
# Create our list of stopwords
nlp = spacy.load('en')
# Creating our token object, which is used to create documents with linguistic annotations.
mytokens = nlp(s... |
a17d429203952b3527cb184599dee9ea0deaceb1 | rjoshi47/DSmax | /cookOff/DSIMP/+MinJumps.py | 981 | 3.953125 | 4 | '''
Created on 22-Oct-2017
http://www.geeksforgeeks.org/minimum-number-jumps-reach-endset-2on-solution/
@author: rjoshi
'''
def getMinJumps(arr):
n = len(arr)
maxReach = arr[0]
steps = arr[0]
jumps = 1
for i in range(1, n):
if i == n-1:
return jumps
# ... |
b08a99994418f1300b32fe08cfa4e51141d79663 | MikeJay-ctrl/RandomML | /RNN/rnn-layers.py | 8,399 | 3.6875 | 4 | # Vanilla RNN Layers helper module
import numpy as np
def rnn_step_forward(x, prev_h, Wx, Wh, b):
next_h, cache = None, None
intermediate_h = np.dot(x, Wx) + np.dot(prev_h, Wh) + b
next_h = np.tanh(intermediate_h)
cache = (x, Wx, prev_h, Wh, intermediate_h)
return next_h, cache
def rnn_step_back... |
d967bbd5e635763cd772d06f80439608b33cc6ca | martinpeck/random-pi | /matt/pwnict/arrays/what-i-the-punchline.py | 754 | 3.609375 | 4 | import random
jokes = ["Why did the chicken cross the road?",
"What did the cannibal say to the other cannibal whilst eating the clown?",
"What do you get if you cross a kangaroo and a sheep?",
"What did one tomato say to the other tomato?",
"How would you feel if you got covered in perf... |
d1a8fda00ed9198f66b42f5a82af0788e4ed2c34 | jerryfane/dictionaries-implementation | /HashTable.py | 10,224 | 3.96875 | 4 | import hashlib
import struct
import sys
"""
Hash Tables implementations
"""
class HashTable():
def __init__(self, size):
#initiliaze the data array
self.data = [None] * size
# O(1)
def add(self, key, value):
# address: where we want to store the information
# through... |
8b533ad4b9ff753e9e43fcba7506f002883e72ef | katie-ring/hacktoberfest-2021-accepted | /DSA in python/CountingSort.py | 810 | 4 | 4 | def counting_sort(arr):
# Get list size
n = len(arr)
# Array with ordered output numbers
output = [0] * n
# Array of counting numbers and initialized with 0
x = [0] * 256
# Save the amount of each number
for i in range(0, n):
x[arr[i]] += 1
# Getting the position of the numbe... |
efcd327f7a733bd4f95cfd255085d46ad3eb2f13 | Ryan990909/homework | /圓周率.py | 61 | 3.625 | 4 | print('10')
x=int(input())
y=x*2*3.14
print('圓周'(y))
|
d7dd5b6291a4931a90c7e82225446d524492e97c | Lv-474-Python/ngfg | /src/app/helper/answer_validation.py | 355 | 3.765625 | 4 | """
Answer validation functions
"""
from app import LOGGER
def is_numeric(value):
"""
Functions to check whether value is numeric.
:param value:
:return: True if numeric, False else
"""
try:
float(value)
return True
except (ValueError, TypeError) as error:
LOGGER.w... |
3dd7804c78c5dc6b3a74bc3bfcd02ddda2084580 | michaelworkspace/Algorithms | /binary_search.py | 455 | 3.953125 | 4 | """ A function to check if a number is in an array using binary seach algorithm. """
def binary_search(arr, value):
if len(arr) == 0 or (len(arr) == 1 and arr[0] != value):
return False
mid = arr[len(arr) // 2]
# Recursive approach
if value == mid:
return True
if value < mid:
... |
4f8e1b296f5301cfec90626c248a60556212cd59 | fenglihanxiao/Python | /Module01_CZ/day3_loop_func/04-代码/day3/50_break与continue.py | 458 | 3.875 | 4 | """
演示break与continue
break:终止循环
continue:提前结束本轮循环
"""
#演示break功能
# i = 1
# while i <= 10:
# # 如果查到了5,结束循环
# if i == 5 :
# break
# print("查数:%d" % i)
# i += 1
# print("结束")
#演示continue功能
i = 0
while i < 10:
i += 1
# 如果碰到5,则直接跳过,查下面的数字
if i % 2 == 0 :
continue
print("查数:... |
8f08e22a8ee99f91377eb535b136b8104832f68f | BenoitBoucounaud/Terminal-Games | /hangmanGame.py | 3,501 | 3.953125 | 4 | import random
from random import choice
import json
player_score = 0
computer_score = 0
def hangman(hangman):
graphic = [
"""
+-------+
|
|
|
|
|
=============
""",
"""
+-------+
| ... |
0333532a3eb51c684e2947d905528052baa749e6 | htingwang/HandsOnAlgoDS | /LeetCode/0212.Word-Search-II/Word-Search-Ii.py | 1,517 | 4 | 4 | class TrieNode(object):
def __init__(self):
self.children = {}
self.word = ""
class Trie(object):
def __init__(self):
self.root = TrieNode()
self.index = 0
def insert(self, word):
node = self.root
#print("insert " + word)
for c in wor... |
cc51655b48be6bc732f933ae0dc6cd42a94572b5 | LivJH/Leeds_practicals | /practical_3.py | 4,242 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 18 11:00:28 2018
@author: gyojh
"""
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 18 09:42:25 2018
@author: gyojh
"""
# Set up variable
y0 = 50
x0 = 50
## this makes a copy of model.py so it can be used for this prac
# Import random and set a random number between 0-... |
5040c6670baf3236f9bbf9f9eb1d627a32be30da | jjmoo/daily | /leetcode/S0069_Sqrt_x.py | 994 | 3.796875 | 4 | class Solution:
def mySqrt(self, x: int) -> int:
if x < 2: return x
result, value = x, x // 2
while result > value:
result, value = value, (value + x // value) // 2
return result
test = Solution().mySqrt
print(2, test(4))
print(2, test(8))
print(0, test(0))
print(1, tes... |
6715ded4476680cb724bced9920ec6a53c7894b0 | markpbaggett/trace_migrater | /helper_scripts/save_bad_files_to_csv.py | 1,601 | 3.734375 | 4 | # Used in Spring 2019 to build a CSV of bad files.
import csv
def copy_bad_files_to_csv(a_csv, a_new_csv_file):
with open(a_csv, mode='r') as original_csv, open(a_new_csv_file, mode='w') as bad_files, open('list_of_bad_files.txt', 'a') as list_of_files:
bad_file_count = 0
headings = ["title", "DE... |
a7587fddfab133ff7ec77d08408a8f1900541c96 | swanysimon/Baseball-Stat-Scraper | /SQLController.py | 6,565 | 3.640625 | 4 | #!/usr/bin/env python3
"""SQLController.py: provides the framework for storing and retrieving player data from a sqlite database"""
__author__ = "Simon Swanson"
__copyright__ = "Copyright 2015, Simon Swanson"
__license__ = "GPL"
__version__ = "1.0.0"
__maintainer__ = "Simon Swanson"
from Player imp... |
b127993474fecfd029396856eda9f31b24c136b5 | silveira89/CEDERJ-PIG-APX2 | /questao_1.py | 1,682 | 3.796875 | 4 | import sys
import random
class sorter:
@staticmethod
def randomList(k):
lista = []
if (k <= 0):
lista = [9,3,4,10,100,-5,2,1,4,0,-12]
return lista
else:
i = 0
while(i < k):
number = random.randint(10,300)
l... |
a413c8a969ca25a24b619c871784ff8a6b610b15 | arunkumaarr/myfirstproject | /bcp.py | 367 | 3.90625 | 4 | #working of break continue and pass
name = 'Arun Kumar'
for letter in name:
#sampe function to br filled up later but do not want the program to interupt
pass
print('continue in play')
for letter in name:
if letter == 'n':
continue
print(letter)
print('break in play')
for letter in name:
... |
1f36954154304ecd186e59d358b208bfe639f7ac | Sam-Enebi/python_actorsDatabase | /python_actorsDatabase.py | 4,628 | 3.78125 | 4 | import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="root",
database="oscar_nominees"
)
print(mydb)
mycursor = mydb.cursor()
#mycursor.execute("CREATE DATABASE oscar_nominees")
#mycursor.execute("SHOW DATABASES")
#for db in mycursor:
#print(db)
... |
8371093faea7a133884929631233e07e6c8fb84a | Ascarik/Checkio | /home/19.py | 1,272 | 4.0625 | 4 | def date_time(data: str) -> str:
# replace this for solution
date, time = data.split()
day, month, year = date.split(".")
hour, minute = time.split(":")
months = {"01": "January", "02": "February", "03": "March", "04": "April",
"05": "May", "06": "June", "07": "July", "08": "August",
... |
cd3d8b9f4f56725aee17b7dda18af63fadc730c3 | SaulRuizS/pyctice | /classes_exercise.py | 1,084 | 4.1875 | 4 | class Person: #Pascal notation for classes (caps letters at the begining of the name)
def __init__(self, age): #This is the constructor, __init__ means the initialation of the object
self.age = age #"self" represents the object, in this case is taking th... |
c6543a82a8fb78a2f07fe7a86162fd38cbb5555d | Jungeol/algorithm | /leetcode/medium/378_kth_smallest_element_in_a_sorted_matrix/hsh2438.py | 498 | 3.53125 | 4 | """
https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix
Runtime: 176 ms, faster than 99.53% of Python3 online submissions for Kth Smallest Element in a Sorted Matrix.
Memory Usage: 18.6 MB, less than 9.09% of Python3 online submissions for Kth Smallest Element in a Sorted Matrix.
"""
class Solution:... |
63bd208e85e2aa889c46a9326cb39ab81b986878 | kanglicheng/CodeBreakersCode | /Strings/127. Word Ladder(graph - find min path - BFS and memo).py | 1,824 | 3.578125 | 4 | # no solution: return 0
# begin word may not be in the wordList
# transformed word must be in the lsit
# hit -> hot
# hot -> dot, lot
# dot -> dog, lot or lot -> log, dot
# dog -> log, cog or log -> dog, cog -> end
# since this question is a graph, we need a memo for memorizing the result
# if a node can't reach the ... |
de996ee160ae069448d9f209a5fff25fee3435a3 | sunilktm23/Python-Practice | /ch11_args.py | 87 | 3.53125 | 4 | def add_num(*args):
t=0
for i in args:
t += i
return t
print(add_num(1,2,3,4,5,6)) |
96f6c1fe6777177a2b4d493951b5939a8648b792 | albeanth/Fctn_Src | /python/FEM/src/FEM_1D_Mesh.py | 6,534 | 3.515625 | 4 | import sys
from numpy import zeros, arange, int, finfo
class mesh:
"""
- This class defines the characteristics of a 1D mesh. Two options:
1) a continuous finite element (CFEM) mesh
2) a discontinuous finite element (DFEM) mesh
"""
def __init__(self):
"""Default constructor"""
... |
e33ab944efdfea5661f62c044177a9f4d8e5ac4c | SWhale6988/yr10_SummerHW | /HW/2/tables.py | 600 | 4.28125 | 4 | repeat = True
while repeat == True: #Makes sure the loop repeats
table = input("Choose a times table") #Gets user input
try: #Tests if the input is a string or not
table = int(table)
except ValueError: #If the try statement brings up an error
print("Invalid choice")#Outputs invalid choice... |
3a02a30b2325879c9a89725e90ba6f1a84470bd5 | dougshamoo/JennyDataParser | /JennyDataParser.py | 1,165 | 3.515625 | 4 | __author__ = 'dougs_000'
def get_mean(data):
"""
Takes a frequency dictionary
Returns the mean of the data
"""
total = 0
for key in data:
total += (key * data[key])
return float(total) / sum(data.values())
in_downpay = 'downpaymentratio.txt'
in_highestmonth = 'highestmonthlyinst... |
ecc55763860d5d6b67b2af6610dbc8f6cb37d66c | kts1297/Leetcode | /Problem#2.py | 936 | 3.75 | 4 | # https://leetcode.com/problems/add-two-numbers/
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
a, b, x = 0, 0, 1
while... |
9699678d2f56be92ab3a3ba77faae51754de4c05 | sabrinapy/a1033302 | /isPrime.py | 238 | 3.9375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def isPrime(N):
i=2
num=0
while i<N:
if N%i==0:
num=num+1
i=i+1
if num==0:
return 1
else:
return 0
N=2
while N<=1000:
sum=0
x=isPrime(N)
if x==1:
sum=sum+N
N=N+1 |
477bcd525fda943a8f243c4a2c333e57a95748db | timm/15 | /src/settings.py | 2,032 | 3.921875 | 4 | """
Settings idioms
#1) stored in 1 global place (easier to mutate)
#2) source code for making settings can be spread
all over the code
#3) settings have defaults, which can be overridden
#4) when overridden, can be reset to defaults
by calling some function
"""
from __future__ import print_function,division
f... |
10c30ee78d367a56a63bcedbf3e7de0e0a36e52c | shankar7791/MI-10-DevOps | /Personel/Elankavi/python/practice/march25/inheritance_prog5.py | 185 | 3.703125 | 4 | class num():
def add(self,a,b):
return("Addition",a+b)
class num2(num):
def sub(self,a,b):
return("subtraction",a-b)
d=num2()
print(d.add(6,7))
print(d.sub(6,7)) |
bffb55fb50e0e6a7facf4923bd89a003ac97089d | eichitakaya/self_study | /competitive_probramming/AOJ/eratosthenes_sieve.py | 368 | 4.03125 | 4 | import math
def isprime(x):
if x == 2:
return True
if x < 2 or x % 2 == 0:
return False
i = 3
while i <= math.sqrt(x):
if x % i == 0:
return False
i += 2
return True
cnt = 0
n = int(input())
for i in range(n):
x = int(input())
if... |
397c2d7aed9943a1377f3681d33b296dcf08b053 | Parizval/CodeChefCodes | /Python/Beginner/COOMILK.py | 349 | 3.546875 | 4 | for a in range(int(input())):
n = int(input())
val = list(map(str,input().split()))
check = True
for i in range(1,n):
if val[i] == "cookie" and val[i-1] == "cookie":
check = False
break
if val[n-1] == "cookie":
check = False
if check:
print("YES")
... |
641711607a138ce1df44f996bca329d0810f65b8 | syedareehaquasar/python | /encrypting string.py | 1,356 | 3.859375 | 4 | # def generate_encrypted_string (string):
# new = ""
# for x in string:
# if ord(x)>=65 and ord(x)<=90 or ord(x)>=97 and ord(x)<=122:
# if (ord(x)>=65 and ord(x)<=77) or (ord(x)>=97 and ord(x)<=110):
# new += chr(ord(x)+13)
# else:
# new += chr(ord... |
06d2b0535fdb7b2fb0580e8bc7d161ccc2781d70 | jgauth/cis313 | /project1/double_ll.py | 1,192 | 3.875 | 4 | # Author: John Gauthier
# Description: Doubly linked list
class DoubleLL(object):
class LLNode(object):
def __init__(self, data=None):
self.data = data
self.next = None
self.prev = None
def __init__(self):
self.size = 0
self.head = None
sel... |
893542f9315584a11b34c90a9dd4961a0fc0bfac | kuangyu1997/Python | /100sample/kuang/ky006.py | 545 | 3.75 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
#方法一
def fib(n):
a,b = 0,1
for i in range(n):
a,b = b,a+b
return a
print fib(10)
#方法二,使用递归
def fib(n):
if n == 1 or n == 2:
return 1
return fib(n-1) + fib(n-2)
print fib(10)
#方法三(如果你需要输出指定个数的斐波那契数列,可以使用以下代码)
def fib(n):
if n == 1:
return [1... |
cb88c1dae9c14c4621dec660019142aa719352e1 | Spatial-Clusterers/DBSCAN | /rtree-test.py | 855 | 3.609375 | 4 | from random import randrange
from rtree import index
from math import sqrt
# Create a 3D index
p = index.Property()
p.dimension = 3
idx3d = index.Index(properties=p)
# Make and index random data
coords = []
for id in range(13000):
coord = (randrange( 100000, 500000),
randrange(1000000, 5000000),
... |
1f8e645b66aa5508c51310c5d79dfa9a3d5660e4 | baketbek/AlgorithmPractice | /Divide and Conquer/240. Search a 2D Matrix II.py | 1,787 | 4.1875 | 4 | 从左下角开始查找,等于就return,大于就抛弃掉这一行,小于就抛弃掉这一列,不断减小搜索空间,可称为减治
肯定不可能从左上角/右下角开始找,这样的话查找的数必然比当前元素大/小,没有办法缩小搜索的方向
可以用右上角开始,但在col初始化的时候,会出现matrix=[] 导致matrix[0]不存在的情况,要单独return一下
class Solution:
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: b... |
a67552867b9fbc8624c1190cfee236413c3e32f0 | LeynilsonThe1st/python | /cp/primo_rapido.py | 694 | 3.875 | 4 | """ __author__: Leynilson José "Snake" """
# Uri Online Judge | 1221 acepted
from time import sleep
def isPrimo(n):
sieve = [0] * (n+1)
for x in range(2, (n+1)):
if sieve[x]: continue
for y in range(2*x, (n+1), x):
sieve[y] = x
return sieve[n] == 0
def isPrimoRapido(n):
if... |
e952d3d05e8efe0e9f8a565692ee1d780a70c4de | MastersAcademy/Programming-Basics | /homeworks/oleksandr.matskevych_matskevych/homework-2/homework-2.py | 563 | 3.8125 | 4 |
file1= open ('hello.txt','r')
data=file1.read()
print(data)
file1.close()
dict={}
dict['name']=input("Hello, what is you name?")
dict['soname']=input("Hello, what is you soname?")
live=input("We do you live?")
dict['hobby']=input('Talk about your hobby?')
print(dict)
answer=("Hello guy,your name is %s,you soname is... |
d283f1b47151dace731c59ba85d8863ed203ff97 | eMUQI/Python-study | /python_book/basics/chapter08_function/08-10.py | 741 | 4.3125 | 4 | '''
8-10 了不起的魔术师:在你为完成练习 8-9 而编写的程序中,编写一个名为
make_great() 的函数,对魔术师列表进行修改,在每个魔术师的名字中都加入字样“the
Great”。调用函数 show_magicians() ,确认魔术师列表确实变了。
'''
def show_magicians(list_of_magicians):
'''show magicians in list'''
for magician in list_of_magicians:
print(magician)
def make_great(list_of_magicians):
'''... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.