blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
bd166d1511218861ec60043fe1a79e4cc6dcc6b3 | jadhavniket/niketrepository | /python/sampleaa.py | 97 | 3.546875 | 4 | num=input()
l=[]
for i in range(num):
u=num%10
l.append(u)
num=str(num//10)
print(l)
|
4c93a21552ad5e93bdb06568a65f6268a375f6d5 | sunchenglong/python-learn | /src/sse/test.py | 125 | 3.84375 | 4 | import re
print re.match("\d-\d-\d","1-2-3")
print re.match("\d-\d-\d","1-22-33")
print re.match("\d+-\d+-\d+","2017-19-10")
|
fff4dfb33e3e51a619568e86740491aefbaf587c | cshintov/connect-four | /closure.py | 850 | 3.828125 | 4 | """ Showcase utility of higher order functions, closure and decorator """
def memoize(func):
results = {}
def inner(*args, debug=False):
if debug:
print(args)
try:
return results[args]
except KeyError:
if debug:
print("Computing new ... |
7de77330283c9352ae4d5eeaf841fd6753ab3791 | YCooE/Python-projects | /Math/poly_fit_cross_val/linreg.py | 2,719 | 3.96875 | 4 | import numpy
class LinearRegression():
"""
Linear regression implementation with
regularization.
"""
def __init__(self, lam=0, solver="inverse"):
""" Constructor for model.
Parameters
----------
lam : float
The regularization parameter
solver : ... |
6c931c1fbaf864db459df52e7def8db9b296d72d | Sinchiguano/codingProblems_Python | /codingProblems/FreeBodyObjects2.py | 3,104 | 4.21875 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2018 CESAR SINCHIGUANO <cesarsinchiguano@hotmail.es>
#
# Distributed under terms of the BSD license.
"""
"""
from math import atan2, degrees, radians, sin, cos
#Last problem, you created a new class called Force. Copy that
#class below:
... |
4f6cb61ee7d16343c8338931f116b0902de966f8 | Algoritm-Study-K/baekjoon | /2주차/7_문자열/1157_yonghee.py | 255 | 3.84375 | 4 | word = input().upper()
letters = list(set(word))
count_letter = []
for c in letters:
count_letter.append(word.count(c))
if count_letter.count(max(count_letter)) >= 2:
print('?')
else:
print(letters[count_letter.index(max(count_letter))]) |
1bb75f9818ffe24971042c3e0e373b33588d6439 | fromradio/ProjectEuler | /src/prime.py | 1,111 | 3.59375 | 4 | import operator
def primeList(num):
#
cons = [True for i in range(0,int(num)+1)]
cons[0] = False
cons[1] = False
p = 2
while p*p <= num:
k = p*p
while k <= num:
cons[k] = False
k += p
i = p+1
while True:
if cons[i]:
p = i
break
i += 1
l = []
for i in range(2,int(num)+1):
if cons[... |
bc8acbd55f0409ddebd416b7f874ebe04ef564d8 | lundbit/PythonBuilding | /ex7.py | 1,835 | 4.125 | 4 | # BREAK:
print("Mary had a little lamb.")
# you can append the function call to the string that contains a {} call
# BREAK:
print("Its fleece was white as {}.".format('snow'))
# BREAK:
print("And everywhere that Mary went.")
# BREAK:
print("." * 10) # what'd that do? It printed the period ten times
# BREAK:... |
8140141f30802a8cc51cf706f2214a4109ef84b1 | FSSlc/AdvancePython | /ch04/class_var.py | 342 | 3.515625 | 4 | #!/usr/bin/env python
# coding: utf-8
class A:
# 类变量
aa = 1
def __init__(self, x, y):
# 这里赋值后是实例的变量
self.x = x
self.y = y
a = A(2, 3)
A.aa = 11 # 修改类属性
a.aa = 100 # 这里会新建属性 aa 到实例中
print(a.x, a.y, a.aa)
print(A.aa)
b = A(3, 5)
print(b.aa)
|
c6606dbdba8b1e22839a8f5b1795fe142cce6b08 | daniel-hampton/computer_vision_scratch | /img_processing01.py | 761 | 4.15625 | 4 | """
First couple exercises/examples in the opencv Python tutorials.
Goals
Here, you will learn how to read an image, how to display it and how to save it back
You will learn these functions : cv2.imread(), cv2.imshow() , cv2.imwrite()
Optionally, you will learn how to display images with Matplotlib
"""
import cv2
# R... |
c3ebbe41e5f1cc01b617d9c85cab580aab6bc3a6 | matheusvictor95/Algoritmos-em-Phyton | /algoritmos/questao01_do_desafio_da_aula07.py | 139 | 3.859375 | 4 | x = int(input('Digite algum número '))
suc= x + 1
ant= x - 1
print(' O sucessor de {} é {} \n e o antecessor é {}\n'.format(x,suc,ant))
|
12f60a66b9b03681a392d47488754fb43ddd1da6 | thouravi/guessgame | /guessgame.py | 512 | 4.0625 | 4 | import random
secretNumber = random.randint(1,10)
print ("I'm taking a guess between 1 to 10.")
for guessTaken in range(1,4):
guess = int(input("Take a guess:"))
if guess < secretNumber:
print ("Your guess is too low.")
elif guess > secretNumber:
print ("Your guess is too high.")
else... |
74c3209e61805591919d290f95976b851a2a8c18 | tqa236/leetcode-solutions | /exercises/0229-MajorityElementII/majority_element_ii.py | 322 | 3.53125 | 4 | from collections import Counter
from typing import List
class Solution(object):
def majorityElement(self, nums: List[int]) -> List[int]:
threshold = len(nums) // 3
counter = Counter(nums)
return [
element for element, count in counter.most_common() if count > threshold
... |
ce3ebe75db318244b793283d642c50ebc6bb6c0e | nehatomar12/Data-structures-and-Algorithms | /Stack_and_Queue/balance_expression.py | 754 | 3.65625 | 4 |
exp = "{([])}"
#exp = "{([])}}"
exp = "{}{(}))}"
def check_exp(exp):
s = []
for i in exp:
if i in ("{", "[", "("):
s.append(i)
else:
if not s:
return False
curr_char = s.pop()
if i == "}":
if curr_char != "{":
... |
19da2a77b1b8c612f2fbe7135d193ea318678b29 | TimothySjiang/leetcodepy | /Solution_1026_2.py | 549 | 3.609375 | 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 maxAncestorDiff(self, root: TreeNode) -> int:
if not root: return 0
return self.dfs(root, high=root.val, low=root.val... |
b0e88810ba0ca7475b35e7ae005d4b363237ba89 | Khalid-Sultan/Section-2 | /radius and area of circle.py | 390 | 4 | 4 | C=eval(input("enter the center point"))
P=eval(input("enter the point on the circumference"))
def distance(C,P):
x=C[0]-P[0]
y=C[1]-P[1]
import math
dis=math.sqrt(x**2+y**2)
return dis
r=distance(C,P)
def area(r):
A=(22*r*r)/7
return A
print('the distance between the center and the point on ... |
4dbaef8f33dfa5755d338c888e5d1bed0869fff7 | Nesquick0/Adventofcode | /2017/07/07.py | 2,632 | 3.65625 | 4 | class Tower(object):
def __init__(self):
self.weight = 0
self.parent = None
self.children = []
def __str__(self):
return "%d, %s, %s" % (self.weight, self.parent, self.children)
def SumOfWeights(towers, name):
sum = towers[name].weight
for childName in towers[name].children:
sum +=... |
8f32ed58d7d769e51b6896c7e4c7fe92e34067c4 | JamesXia23/python | /code/function/内嵌函数以及闭包.py | 1,152 | 4 | 4 | #内嵌函数(函数内部再定义函数)
def fun1():
print("fun1被执行")
def fun2():
print('fun2被执行')
fun2()
fun1()
#闭包
#一个内部函数访问到外部的内容时,该函数称为闭包
def outer(x):
def inner(y):
return x * y
return inner
i = outer(5) #此时i为一个函数变量inner
print(i(6)) #相当于调用了inner,结果为30
#如果在一个内部函数中想要修改外部变量
#那就意味着必须重新定义这个变量,
#则... |
8da56531a3534b02599f13f6bc6e94680d240f9f | TylerBromley/fullstack_python_codeguild | /lab11-simple-calculator_v3.py | 318 | 4.0625 | 4 | # lab11-simple-calculator_v3.py
# get an arithmetic expression from a user
math_todo = input("Please enter an arithmetic expression: ")
# evaluate the expression using built-in eval() function
# and store it in a variable
evaluated = eval(math_todo)
# print the evaluated answer
print(f"Your answer is: {evaluated}") |
61e60ff9c7d80486e2d19183e8242a0ee4d6065e | JoelDavisP/Python-Practice-Book-Solutions | /chapter5/ppbook/2/set7/p26.py | 349 | 3.953125 | 4 | def even(x):
return x%2 == 0
def filter_list_comp(fn,ls):
"""It applies a function to each element of a list and returns items of
the list for which fn(item) is True. Input function name and a list.
output values of list after function applied to be True. """
print [x for x in ls if fn(x)]
filte... |
d4a4ce6f50aec13049b2997d064fd17b8895e3a0 | Joao-paes-oficial/HackerRank | /Python/30 Days of Code/Dia_6.py | 102 | 3.6875 | 4 | n = int(input())
for i in range(0, n):
string = str(input())
print(string[::2], string[1::2]) |
c7951f484d8f7d90bc550cee0d6772af87196266 | Pradeepnitw/tutorials | /cc150/quicksort.py | 1,632 | 3.71875 | 4 | """
Tony Hoare 1980 Turing Award
"""
from random import random
mute = False
def swap(a, i, j):
if i == j:
return
temp = a[i]
a[i] = a[j]
a[j] = temp
def knuth_shuffle(a):
for i in range(len(a)):
ran = int(random()*(i+1))
swap(a, i, ran)
def test_knuth_shuffle():
... |
17bd6a8be0fceb0f9ab865a9d52b69a2bc33c601 | jiting1014/MH8811-G1901803D | /02/program2.py | 60 | 3.59375 | 4 | c=input('Celsius=')
f=float(c)*1.8+32
print('Fahrenheit=',f) |
b02171d6472529aba8a7a1b26552a63d4679330f | ditwoo/centernet-impl | /src/detector/utils/registry.py | 1,573 | 3.5625 | 4 | class Registry:
"""Store classes in one place.
Usage examples:
>>> import torch.optim as optim
>>> my_registry = Registry()
>>> my_registry.add(optim.SGD)
>>> my_registry["SGD"](*args, *kwargs)
Add items using decorator:
>>> my_registry = Registry()
>>> @m... |
de7902f7a84c1a6109a9912f44319f56be9247ff | thomasmcclellan/pythonfundamentals | /00.01_exercise_01-07.py | 1,113 | 4.125 | 4 | # Review of 01-07
############
# Problem 1
############
# Given:
s = 'django'
# Use indexing to print out the following:
# 'd'
s[0]
# 'o'
s[-1]
# 'djan'
s[:4]
# 'jan'
s[1:4]
# 'go'
s[4:]
# Reverse string
s[::-1]
############
# Problem 2
############
# Given:
l = [3,7,[1,4,'hello']]
# Reassign 'hello' to 'go... |
c9cc247125bf28e0895bfa759cd0e8392a9a0039 | smart1004/learn_src | /pso_test/testd10_PyRETIS.py | 11,295 | 3.796875 | 4 | # http://www.pyretis.org/examples/examples-pso.html
'''
PyRETIS1.0.0
Particle Swarm Optimization
In this example, we will perform a task that PyRETIS is NOT intended to do. We will optimize a function using a method called particle swarm optimization and the purpose of this example is to illustrate how the PyRETIS l... |
d956f40fc85da3cfd3e6fe84ad4f015fbcd4c25b | joaoDragado/roulette | /player.py | 9,863 | 3.875 | 4 | import random
from bet import Bet
# this will act as a superclass to individual player types.
class Player(object):
''' Player Class
Places bets on Outcomes, updates the stake with amounts won and lost.
Uses Table to place bets on Outcomes; used by Game to record wins and losses.
'''
def __init__(s... |
dd7835af48650c16611088f3325fe1876dabaeba | Riyer01/SnakeRL | /BFSAgent.py | 3,303 | 3.609375 | 4 | import gym
import gym_snake
from hamilton import Hamilton
from copy import deepcopy
import matplotlib.pyplot as plt
env = gym.make('snake-v0', grid_size = [8, 8])
observation = env.reset()
def generateMoveQueue(path):
move_map = {(-1, 0):3, (1,0):1, (0,1):2, (0,-1):0}
if path:
return [move_map[(y[0]-x... |
683dcb5e7965cc822af8f46881cf7fd5de3be478 | younkyounghwan/python_class | /lab1.py | 574 | 3.765625 | 4 | number="hi"
print(number)
number=10
print(number)
a=5
b=25
c=a+b
# 5+25=30을 출력하라
msg="%d+%d=%d" #출력하고자하는 문자열도 변수로 정의할 수 있다.
print(msg%(a,b,c))
print("%d+%d=%d"%(a,b,c)) # 서식문자를 여러개 이용할 경우 괄호 안에 넣기
#문자열 출력
money=10000
print("나는 현재%d원이 있습니다."%money) #서식문자를 이용할 수 있다.컴마없이 변수이름 앞에 %를 쓴다.
#입력
money = input("얼마를 가지고 게세요?"... |
b4489eb1d4c8623f007d295e174eaddb18a935d1 | misa9999/python | /courses/python3/ch123-unkown/48_lesson/groupby.py | 708 | 3.734375 | 4 | from itertools import groupby, tee
students = [
{'name': 'Misa', 'note': 'A'},
{'name': 'Megumin', 'note': 'B'},
{'name': 'Yuuki', 'note': 'A'},
{'name': 'Mira', 'note': 'A'},
{'name': 'Aqua', 'note': 'C'},
{'name': 'Yui', 'note': 'B'},
{'name': 'Yukinoshita', 'note': 'A'},
{'name': 'Nami', 'note': 'A'},
{'na... |
37f5a6f46ac7bbbccca2c0330eeba92d61113497 | SDRLurker/starbucks | /20170309/20170309_2.py | 1,451 | 3.890625 | 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 findBottomLeftValue(self, root):
"""
:type root: TreeNode
:rtype: int
"""
q = []
... |
49007104a978b21ad305c9ae13413da0dccd7e77 | noy20-meet/meet2018y1lab4 | /sorter.py | 228 | 4.375 | 4 | bin1="apples"
bin2="oranges"
bin3="olives"
new_fruit = input('What fruit am I sorting?')
if new_fruit== bin1:
print('bin 1')
elif new_fruit== bin2:
print('bin 2')
else:
print('Error! I do not recognise this fruit!')
|
25b8d41f93e5396bb53a3cc1db4e8003029e4872 | swell1009/ex | /teach your kids/ch09/DragDots.py | 781 | 3.5625 | 4 | # DragDots.py
# Page 176
import pygame # Setup
pygame.init()
screen = pygame.display.set_mode([800, 600])
pygame.display.set_caption("Click and drag to draw")
keep_going = True
YELLOW = (255, 255, 0) # RGB color triplet for YELLOW
radius = 15
mousedown = False
while keep_going: # Game loop
for event in pygame.e... |
5b21426639e81177c48019719f2ef4e1bead0146 | sug5806/TIL | /Python/data_struct/Tree/prac.py | 4,099 | 4.375 | 4 | # traversal (순회)
# 재방문 없이 어떤 자료구조의 모든 데이터(노드) 방문하는 것
class TreeNode:
def __init__(self, data):
self.data = data
self.left_child = None
self.right_child = None
class Node:
def __init__(self, data):
self.data = data
self.next = None
# 전위 순회
def pre_order(tree_node):
... |
aa1c18a63a45be078098ed43676dbfb94601a0fb | bishii/QA_Scripts | /IoT/RaspberryPi/LED-Matrix/dot.py | 1,771 | 3.6875 | 4 | import time
class Dot:
def __init__(self, settings=("defaultDot",3,10,(0,0))):
"""
Constructor Inputs:
settings: tuple of:
1) descriptive name of instance
2) FALSE interval (seconds)
3) TRUE interval (seconds)
"""
self.creationTime = time.time()
self.dotName = settings[0]
self.IntervalTi... |
35d386bdafd4765e573252bd79b9e2c9191ebd0c | KaushikTK/compiler_design_programs | /exp_4 nfa to dfa/nfa_to_dfa.py | 2,050 | 3.640625 | 4 | from automata.fa.dfa import DFA
from automata.fa.nfa import NFA
states = input('Enter states separated by ",": ')
states = states.split(',')
states = set(states)
symbols = input('Enter symbols separated by ",": ')
symbols = symbols.split(',')
symbols = set(symbols)
transitions = {}
print('Enter the transitions')
w... |
c0ead5646ce7c379bb7d34690cfbb4d8581d30fc | swatia-code/data_structure_and_algorithm | /strings/Count_number_of_words.py | 1,608 | 4.0625 | 4 | """PROBLEM STATEMENT
-----------------
Given a string consisting of spaces,\t,\n and lower case alphabets.Your task is to count the number of words where spaces,\t and \n work as separators.
Input:
The first line of input contains an integer T denoting the number of test cases.Each test case consist of a string.
Out... |
ee7f91fb53b184647e66ee5b4257e7bb84181b18 | whalenmlaura/Python | /2018.10.18 - LandscapingCalculator.py | 1,475 | 4.03125 | 4 | #"""
#Assignment 2 - Landscape Calculator
#October 18, 2018
#Name..: Laura Whalen
#ID....: W0415411
#"""
__AUTHOR__ = "Laura Whalen <W0415411@nscc.ca>"
def main():
# input
address = input("Please enter your house number: ")
length = float(input("Please enter property length in feet: "))
w... |
1838de61b53919a3ef748d0b7ba379397a584efe | eduhmc/CS61A | /Teoria/Class Code/23_ex.py | 3,760 | 3.65625 | 4 | # Morse tree
abcde = {'a': '.-', 'b': '-...', 'c': '-.-.', 'd': '-..', 'e': '.'}
def morse(code):
whole = Tree(None)
for letter, signals in code.items():
t = whole
# YOUR CODE HERE
return whole
def decode(signals, tree):
"""Decode signals into a letter according to tree, assuming sign... |
1289f844eb3b44a008f650f5dcd9ec2871271fc8 | parihar08/PythonJosePortilla | /AdvancedPythonModules/PracticePuzzle.py | 1,150 | 3.53125 | 4 | #There is a zipfile called unzip_me_for_instructions.zip, unzip it and open the .txt file,
#Read out the instructions and figure out what needs to be done
# import shutil
#
# shutil.unpack_archive('ZipPracticePuzzle/unzip_me_for_instructions.zip','ZipPracticePuzzle/','zip')
with open('ZipPracticePuzzle/extracted_cont... |
a4c87052fe39c76051848848d5c75b873f20d0b3 | KoushikGodbole/PythonCodes | /FIleDuplicatesInSystem.py | 1,085 | 3.6875 | 4 | def findDuplicate(paths):
"""
:type paths: List[str]
:rtype: List[List[str]]
"""
fileMap = dict()
temp = ""
duplicates = list()
for s in paths:
tempFile = s.split(" ")
for i in range(len(tempFile)):
if i == 0:
filePath = tempFile[0]
... |
ec870c1989843b7b80cd025976cc45cf1b4672ae | Nachiten/QueueBot-Discord | /tests/tests_all.py | 1,606 | 3.5 | 4 | from unittest import TestCase
from clases.colas import Colas
'''
# Descipcion:
# Estos tests son independientes y prueban
# el funcionamiento del comando All
'''
# Corre antes de iniciar los tests
def setUpModule():
print('[Corriendo tests de all]')
# Corre luego de termianr todos los tests
def tearDownModul... |
2cdf439d63623fb571d7eae7619e3423c71da1a5 | OverCastCN/Python_Learn | /XiaoZzi/Practice100/29IntergerDecopose.py | 434 | 3.953125 | 4 | #coding:utf-8
"""
给一个不多于5位的正整数,要求:一、求它是几位数,二、逆序打印出各位数字。
"""
a = raw_input('请输入一个不多于5位的正整数:')
while len(a) > 5:
print '请输入一个不多于5位的正整数'
a = raw_input('请输入一个不多于5位的正整数:')
print '它是%d位数'%len(a)
def f(a):
if len(a) > 0:
print a[-1]
return f(a[0:-1])
f(a) |
3b7cd24b6884f8e1086f79fb7bbfd232366bd464 | zachjbrowning/cs6441-ciphers | /cmd_control.py | 6,432 | 3.875 | 4 | from cipher_api import encode, decode, methods, overview, method_classes, in_depth
from db_control import load_data, save_data, reset_data
def prompt():
print(' > ', end='')
return input()
def help_cmd():
print("Potential commands:")
commands = ['?', 'q', 'n', 'e', 'd', 's', 'c', 'i', 'r']
docum... |
926c7141c1f6ad007ba57652c1de5c30913d1bbb | chetan1327/Engineering-Practical-Experiments | /Semester 4/Analysis of Algorithm/KMP.py | 1,245 | 3.828125 | 4 | # for proper examples refer https://www.geeksforgeeks.org/kmp-algorithm-for-pattern-searching/
# https://www.youtube.com/watch?v=V5-7GzOfADQ
# uncomment print statements to see how the table is updated
def prefixTable(pattern):
prefix_table = [0]
for i in range(1, len(pattern)):
j = prefix_table[i-1... |
dc46a8bfea15801f06752ddb74bcf0c9369eb82c | heyf/cloaked-octo-adventure | /leetcode/118_pascals-triangle.py | 667 | 3.734375 | 4 | #!/usr/bin/python3
# 118. Pascal's Triangle - LeetCode
# https://leetcode.com/problems/pascals-triangle/description/
class Solution(object):
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
if numRows == 0:
return []
res =... |
3a847330ebcaa1b06ce4d5443c88edd9b4ae9fc8 | rmdimran/Mastering_Python | /Functions.py | 197 | 3.984375 | 4 |
def say_hello(name, age):
print("Hello " + name + " you are " + age + " years old!")
say_hello("John", "35")
"""
x = input("ENter the name")
y = input("enter the age")
say_hello(x,y)
""" |
677eeecdb84f436da5f3864eef89dc451337214c | lingzhi42166/Python | /1_基础/12_循环结构.py | 1,337 | 3.515625 | 4 | # range控制循环次数 提供两个参数 第一个参数 代表从该参数值开始 到参数2-1停止
#条件不成立 或循环结束后 执行else else主要用于 循环体内控制条件为不成立后执行else 比如给你三次登录机会 输入密码错误三次 则把循环条件设为false 被else捕捉执行
#break continue 不会执行else
# python3中range有一个优化 就是每循环一次 就在原本的内存空间中 更新值
# python2中是 range几个数 就开辟几个内存空间
for i in range(1,10): #1~9 不包括10
print(i)
for i in range(10):#0~9
i +=... |
0575793c93bf6ef0c43d53a5c4f58ca3cac6cee0 | kehochman/Python-Challenge | /PyBank/main.py | 2,377 | 3.625 | 4 | import os
import csv
budget = r'C:\Users\kehoc\Documents\GWU-ARL-DATA-PT-12-2019-U-C\02-Homework\03-Python\Instructions\PyBank\Resources\budget_data.csv'
budget_analysis = os.path.join("Analysis", "budget_analysis.txt")
# open and read csv
with open(budget, newline="") as csvfile:
csvreader = csv.reader(csvfile, ... |
53f03b45824b06ecaeaa33885c590c820c287d2f | EarthChen/LeetCode_Record | /easy/excel_sheet_column_title.py | 757 | 3.8125 | 4 | # Given a positive integer,
# return its corresponding column title as appear in an Excel sheet.
#
# For example:
#
# 1 -> A
# 2 -> B
# 3 -> C
# ...
# 26 -> Z
# 27 -> AA
# 28 -> AB
#
class Solution:
def convertToTitle(self, n):
"""
将数字转换为excel的列名
:param n: int
... |
4d0cb08fb2ec76a688dcb16d57b0afc274f55a52 | harsham4026/ds-algo | /python/binary_search/only_once_in_sorted_array.py | 1,807 | 4 | 4 | """
Find the element that appears once in a sorted array, where all others appear twice.
Given a sorted array in which all elements appear twice (one after one)
and one element appears only once. Find that element in O(log n) complexity.
"""
"""
A variant of the non_duplicate_element problem in lists where the list ... |
e11196ff003aa513de2bc01ca0d1a24338917175 | leandrominer85/Data-Analysis-Bitcoin-price-Klines | /python_code/data_visualizator.py | 1,872 | 3.671875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import plotly.graph_objects as go
import pandas as pd
import glob
import os
# In[12]:
def data_vis(path = '..\data\cleaned'):
'''
This function receives a path for the data. First it asks the user wich file(complete path) he wants.
Uses this to... |
920b611d4aea28b23896e6c10b015128d2c002e6 | akcezzz/Learning-the-Snake | /01-Python Object and Data Structures Basics/Data Types/Sets.py | 283 | 4.09375 | 4 | ### Sets ###
#Declaring a set
myset = set({1,2})
#Sets elements are unique (cannot occur twice)
myset.add(3)
print(myset)
#myset.add(3) will do nothing
mylist = [1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,4,4,4,4,4]
myset = set(mylist)
print(myset) #prints 1,2,3,4 only
|
81f575df7a6b1ec9e1e4b6f41e6c64e914188990 | CodeForContribute/Algos-DataStructures | /searching&Sorting/InterPolationSearch.py | 1,311 | 3.96875 | 4 | """
Time Complexity: If elements are uniformly distributed, then O (log log n)). In worst case it can take upto O(n).
Auxiliary Space: O(1)
The Interpolation Search is an improvement over Binary Search for instances, where the values in a sorted array are
uniformly distributed. Binary Search always goes to the middle e... |
85fc1361f6c0ba879f996e367e2b6ddf94d1f6ca | DavidVollendroff/lambdata | /lambdata_davidvollendroff/df_utils.py | 822 | 4.03125 | 4 | """
Utility functions for working with DataFrames
"""
import pandas
import numpy as np
TEST_DF = pandas.DataFrame([1, 2, 3])
def explore_df(dataframe):
"""
Performs basic exploration tasks for a newly created dataframe
"""
print(dataframe.describe())
print('Null Values\n', dataframe.isnull().val... |
23cae418b32e0bd750bfc30745f86fff31ea9eea | DiegoMarulandaB/Curso-python-basico | /7_clase_operadores_logicos_comparacion/operadores_logicos_comparacion.py | 1,087 | 3.75 | 4 | #operadores lógicos y comparación
"""
py = consola interactiva
## Operadores lógicos
## True y False
es_estudiante = True
es_estudiante
True
trabaja= False
trabaja
False
es_estudiante and trabaja
False
## True
es_estudiante = True
es_estudiante
True
trabaja = True
trabaja
True
es_estudiante and traba... |
c011d288c08bac2e19f0e7aec2391c5597430739 | sajjad0057/Practice-Python | /DS and Algorithm/Algorithmic_Tools/Greedy Algorithms/Largest_Number.py | 466 | 4.1875 | 4 | # num = input("Enter the number : ")
# list = []
# for i in num:
# list.append(i)
# list.sort(reverse=True)
# y = ''
# for x in list:
# y +=x
# print("The Bigest Number is : ",y)
num = int(input("Enter the Number of digit : "))
number = []
for i in range(num):
number.append(int(input(f'Enter t... |
5303468ae76f078cad7b8b0bc668ac86b9faf3f4 | Zer0xPoint/Algorithms4_python | /1.Fundamentals/1.Programming Model/14.py | 202 | 3.765625 | 4 | import copy
matrix = [[1,2,3],[4,5,6],[7,8,9]]
temp_matrix = copy.deepcopy(matrix)
for y in range(len(matrix)):
for x in range(len(matrix)):
matrix[y][x] = temp_matrix[x][y]
print(matrix)
|
1d506d329e3a830d7ca1a8bdf3cf1099555cd09f | srinitude/holbertonschool-higher_level_programming | /0x0B-python-input_output/1-number_of_lines.py | 489 | 4.53125 | 5 | #!/usr/bin/python3
"""
This module allows you to count the number of lines
in a text file
"""
def number_of_lines(filename=""):
"""
Returns the number of lines in a text file
Args:
filename (str): The name of the file
"""
if type(filename) is not str:
raise TypeError("filename mus... |
38dbd9e6e194459d02bf5bd09b9bf1ed71a6af2f | jihunchoi/cross-sentence-lvm-public | /scripts/diversity.py | 1,640 | 3.765625 | 4 | """Measures diversity given a text file.
distinct-1 computes the ratio of unique unigrams over the
total number of words.
distinct-2 computes the ratio of unique bigrams.
Reference: A Diversity-Promoting Objective Function for Neural Conversation Models (Li et al. NAACL 2016)
"""
import argparse
import json
from col... |
cc047de320266b8b18e84ea61c119f793a1b521f | westgate458/LeetCode | /P0230.py | 2,247 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Aug 1 20:51:01 2019
@author: Tianqi Guo
"""
# 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 kthSmallest(self, root, k):... |
fcd8bda5e4d8670e14f159fda80d1ca708a75596 | mkobierski/hobby-code | /31/31.py | 5,947 | 3.84375 | 4 | #!/usr/bin/python -tt
from copy import deepcopy
import logging
LOGGER = logging.getLogger(__name__)
AVAILABLE_COINS = (200, 100, 50, 20, 10, 5, 2, 1)
def factorization(sum_, allow_self=False, threshold=None):
"""Given a number of pence, return a list
containing its coin combination using the
least num... |
65b8d79dbff953c0306c4a1a79a771527b0518ac | JoungChanYoung/algorithm | /programmers/자릿수더하기.py | 196 | 3.703125 | 4 | #level1 연습문제
def solution(n):
answer = 0
string = str(n)
answer = sum([int(i) for i in string])
return answer
if __name__ == "__main__":
print(solution(123)) |
6efff7fab9ac39f1bcbaf6b062bace022b8634bc | lemonadegt/PythonPracticeWithMC | /rsp.py | 861 | 3.515625 | 4 | import random
GAWI = "가위"
BAWI = "바위"
BO = "보"
DRAW = "무승부"
WIN = "당신의 승리"
LOSE = "당신의 패배"
rockscissorspaper = [GAWI, BAWI, BO]
states = [DRAW, WIN, LOSE]
result = ''
selectednum = int(input("가위 바위 보 중에서 선택해 주세요\n(가위 = 0, 바위 = 1, 보 = 2) : "))
while (selectednum < 0) or (selectednum > 2):
selectednum = int(input(... |
7770f0ff432d3d4e3a6aefd9e55dfa5db5af4288 | HeGreat/DeepLearning_code | /mutiThreading.py | 1,393 | 4.03125 | 4 | #多线程
import threading,time
def run(num):
print("子线程(%s)开始"%(threading.current_thread().name))
time.sleep(2)
print("打印",num)
time.sleep(2)
print("子线程(%s)结束"%(threading.current_thread().name))
if __name__ == "__main__":
print("主线程(%s)开始"%(threading.current_thread().name))
#target我们这个线程所要执行的函数... |
87f2dcfc5dd7d32665ec92491ffcae31ce994948 | joaoantoniopereira/GitHub | /parse_kibana.py | 271 | 3.59375 | 4 | with open('test_results.json', 'r') as myfile:
data=myfile.read().replace('\n', '')
res=data.split(",")
grade = [k for k in res if 'grade' in k]
if any("FAIL" in s for s in grade):
raise Exception("At least a test has failed")
else:
print "Everything is Ok" |
c8fc1e1caa030003bd863fea4f7dc525f038ae03 | rafaelperazzo/programacao-web | /moodledata/vpl_data/142/usersdata/227/62374/submittedfiles/av2_p3_civil.py | 644 | 3.640625 | 4 | # -*- coding: utf-8 -*-
def media(n):
soma = 0
for i in range(0,len(n),1):
soma = soma + n[i]
media = soma/len(n)
return (media)
#ESCREVA AS DEMAIS FUNÇÕES
def somaA(x,y):
mx=media(x)
my=media(y)
soma=0
for i in range(0,len(x),1):
soma=soma+((x[i]-mx)*(y[i])-my)
ret... |
d6c53a4258a53691fd6df0ddc38f85f51890f1ec | fabiopapais/opencv-essentials | /Basic/transformations.py | 1,507 | 3.59375 | 4 | import cv2 as cv
import numpy as np
img = cv.imread('../Resources/Photos/park.jpg')
cv.imshow('Boston', img)
# Translation
def translate(img, x, y):
translationMatrix = np.float32([[1, 0, x], [0, 1, y]])
dimensions = (img.shape[1], img.shape[0])
return cv.warpAffine(img, translationMatrix, dimensions)
... |
05048b83980de141ee9306506824d569087957de | Viniciusadm/Python | /exerciciosCev/Mundo 1/Aula 9/024.py | 245 | 3.875 | 4 | cidade = str(input('Em qual cidade você nasceu? ')).strip().upper().split()
resposta = cidade[0] == 'SANTO'
if resposta == True:
print('O nome da sua cidade começa com Santo')
else:
print('O nome da sua cidade não começa com Santo')
|
bcc5f5f0189362d6f4fce050501e3a7ba94e3b75 | RedLeaves699/DM-training | /Homework week2/归纳法/1.py | 1,569 | 3.796875 | 4 | #第一题
def power(a, n):
# 请在此添加代码
#-----------Begin----------
if n==0:
return 1
else:
return a*power(a,n-1)
#------------End-----------
#第二题
def fib(n):
# 请在此添加代码
#-----------Begin----------
if n==0 or n==1:
return 1
else:
return fib(n-1)+fib(n-2)
... |
01580d1945c5883ea37f139bec279fe4bef93a59 | strengthen/LeetCode | /Python3/152.py | 3,202 | 3.8125 | 4 | __________________________________________________________________________________________________
sample 48 ms submission
class Solution:
def maxProduct(self, nums: List[int]) -> int:
def split(nums: List[int], n: int):
"""
Split the list at elements equal to n
"""
... |
e38f38e932550d964eb5c320fa3f58ec95b16e7c | arunansu/UdacityML | /TechnicalInterview/TechnicalInterview/Question4.py | 2,173 | 4.15625 | 4 | #Question 4: Find the least common ancestor between two nodes on a binary search tree.
#The least common ancestor is the farthest node from the root that is an ancestor of both nodes.
#For example, the root is a common ancestor of all nodes on the tree,
#but if both nodes are descendents of the root's left child,
#... |
d7e32c5b37ab9e48b54367f8f097d943285f30ef | dankami/StudyPython | /algorithm/Coroutine.py | 625 | 3.90625 | 4 | # 协程demo
# 生产消费者模式
# def foo():
# print("starting...")
# while True:
# res = yield 4
# print("res:",res)
# g = foo()
# print(next(g))
# print("*"*20)
# print(next(g))
# def consume():
# while True:
# number = yield
# print("开始消费", number)
# consumer = consume()
# n... |
ade6364bb0a065c423d748449d41043bf9eefdac | arcaputo3/daily_coding_problem | /arrays/find_elt_rotated_arr.py | 2,575 | 3.953125 | 4 | """ This problem was asked by Amazon.
An sorted array of integers was rotated an unknown number of times.
Given such an array, find the index of the element in the array in faster than linear time.
If the element doesn't exist in the array, return null.
For example, given the array [13, 18, 25, 2, 8, 10] and the ele... |
1f172d54156b2b1cdb3bdba06f8d099d333efb20 | lari5685/nsuts | /number_8.py | 239 | 3.734375 | 4 | max = 10**6
min = 0
while True:
num = min + (max - min )//2
print('? '+ str(num))
inp = input()
if inp == '=':
print('! ' + str(num))
break
if inp == '>':
min = num + 1
elif inp == '<':
max = num - 1
|
e1ac9a49b0a884a64f18a5f454dd33b346f4f580 | navi29/HackerRank-30-Days-of-Code-Python-Solutions | /Day-8.py | 591 | 4.0625 | 4 | #---------------------------------------------
#Problem Statement: https://www.hackerrank.com/challenges/30-dictionaries-and-maps/problem
#---------------------------------------------
#Language: Python
#---------------------------------------------
#Solution:
#---------------------------------------------
n ... |
eb4bc01d7c293d7a109963bb79568df3363866a0 | rrabit42/Python-Programming | /문제해결과SW프로그래밍/Lab7-Turtle graphics&loop statement(break,continue...)/lab7-2.py | 221 | 4 | 4 | """
엘텍공과대학 소프트웨어학부
1871063 김서영
"""
import turtle
t = turtle.Pen()
t.color("blue")
t.begin_fill()
for i in range(5):
t.forward(100)
t.right(144)
t.end_fill()
|
c45347468b74321acc2a553d948cedd59e3e6ed1 | XUAN-CW/python_learning | /sundry/11-循环代码优化测试.py | 452 | 3.5625 | 4 | #循环代码优化测试
import time
start = time.time()
for i in range(1000):
result = []
for m in range(10000):#循环里的东西尽量往外提
result.append(i*1000+m*100)
end = time.time()
print("耗时:{0}".format((end-start)))
start2 = time.time()
for i in range(1000):
result = []
c = i*1000
for m in range(10000):
... |
06363053e61596c338e7a9fc1bd8de614fb1ee25 | Zeisha/Learning | /ListCode/BankFile.py | 2,551 | 4 | 4 | import os.path as record
import random
class Bank:
def __init__(self, accountnumber):
if record.exists(f"{accountnumber}.txt"):
# read data to variables from record
with open(f"{accountnumber}.txt", "r") as reader:
values = reader.readlines()
self.firstname... |
b1c09c0e3a1d3c33559ccb98a3820d3f1b729116 | ryohang/java-basic | /python/DetectLoopInList.py | 514 | 3.875 | 4 | class Node:
def __init__(self, val, nextVal=None):
self.val = val
self.next = nextVal
def detectLoop(head):
p1 = head
p2 = head.next
while p1!=None and p2!=None:
if p1 == p2:
return True
else:
p1 = p1.next
p2 = p2.next
... |
3900b6117c6f69857a7103603db66d76c5b6b42f | Tetfretguru/it_carreer | /Graficado/agrupamiento_jerarquico.py | 2,343 | 3.640625 | 4 | import random
import numpy as np
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def get_coordenadas(self):
return (self.x, self.y)
def __str__(self):
return f'{self.x}#{self.y}'
def generar_vector():
""" Cada vector tiene caracteristicas heredadas de una clase """
vectore... |
bb110c536fc39b10657a159ebd92765994fc2fab | MichSzczep/PythonLab | /zad4d.py | 548 | 3.53125 | 4 | import random
matrix1=[]
matrix2=[]
summed_matrix=[]
for j in range (128):
numbers=[]
for i in range (128):
numbers.append(random.randrange(100))
matrix1.append(numbers)
for j in range (128):
numbers=[]
for i in range (128):
numbers.append(random.randrange(100))
matrix2.ap... |
96c36a3439cdcd702d9c289ab0b6b822d496235a | nagireddy96666/Interview_-python | /nestedif.py | 124 | 4.0625 | 4 | n=input("enter a num")
if n==1:
print n
elif n==2:
print n
elif n==3:
print n
else:
print "enter valid num"
|
488271a8a5285c2f1e7cbbc45f06fc850d02cd94 | pussinboot/euler-solutions | /euler_25.py | 308 | 3.859375 | 4 | def gen_fibb():
""" Generate an infinite sequence of fibonacci numbers.
"""
f1 = 0
f2 = 0
new = 1
while True:
yield new
f1 = f2
f2 = new
new = f1 + f2
g = gen_fibb()
n = next(g)
i = 1
while len(str(n)) < 1000:
i += 1
n = next(g)
print(n)
print(i)
|
3eb7c8b2f97cf53f233e3fff42e65ec40ede9a6d | marcossouz/python-estudos | /arquivos-python/arq.py | 223 | 3.59375 | 4 | #
# Escreve duas linhas no arquivo in.txt
# Uma por vez
#
fout = open('in.txt', 'w')
print (fout)
line1 = 'This here\'s the wattle,\n'
line2 = 'the emblem of our land.\n'
fout.write(line1)
fout.write(line2)
fout.close()
|
89b2f91a52db6dbec0cf2bb7cbabdd039a40d2d7 | porkstoners/LP3THW | /ex3.py | 359 | 3.75 | 4 | # A comment, this is so you can read your program laters.
# Anything after the # is ignored by python
print("I could have a code like this.") # and the comment after is ignored
# You can alos use a comment to "disable" or comment out code:
# print("This will not run")
print("This will run")
print("Well What about t... |
6184c2da91f8ea96c61c17c2e6984c8eb934275c | cappe987/MMA500-project | /Main.py | 2,779 | 3.65625 | 4 |
from AI import AI
import random
import enum
class PlayerType(enum.Enum):
Human = True
AI = False
class Game:
def __init__(self, size, p1, p2):
self.board = []
self.size = size
self.turn = 'X'
self.moves = 0
self.p1 = p1
self.p2 = p2
self.AI1 = AI(size, "X")
self.AI2 = AI(size, ... |
d468ae7b16dca77443c98f75e81022145456ef30 | yahusun/p0427 | /4_dict/dict_age.py | 847 | 4 | 4 | # 請讀取輸入, 建立一個 dictionary 記錄班上的同學名字以及他們對應的歲數.
# 寫一個函數 prAge(name), 如果 name 存在 dictionary, 印出名字和歲數, 否則印出 N/A, 例如: prAge('Bob') 印出 Bob 10, prAge('John') 印出 N/A
ages = {}
def prAge(name):
if ages.get(name):
print(name, ages.get(name))
else:
print("n/a")
def test():
num = int(input())
for ... |
803e18f2c5fb5221d3a729e8d3a7f195bfe64dd1 | vhrehfdl/Algorithm | /Programmers/비밀지도.py | 562 | 3.8125 | 4 | def convert(n, element):
total = ""
for i in range(n):
total += str(element % 2)
element = int(element / 2)
return total[::-1]
def solution(n, arr1, arr2):
answer = []
for i in range(0, n):
arr1_convert = convert(n, arr1[i])
arr2_convert = convert(n, arr2[i])
... |
552ccb7d046975bca1aab2b6c81e65c33816c801 | krishnodey/Python-Tutoral | /decimal_to_binary_conversion_with_recursion.py | 638 | 4.40625 | 4 | '''
let's write a program which will convert a decimal number into a binary number with recursion
logic:
We are not going to use built in functions
base of binary number system is 2
we will write a function and inside that function
if number is grater than 1 we call the function itself... |
f87e40bcb139d988c8762900e4ca93f423ea5fc7 | skinnybeans17/ACS-1100-Intro-to-Programming | /lesson-1/example-1.py | 636 | 3.609375 | 4 | #when you see a hashtag before some text, that means it's a comment
#comments are notes that Python ignores and doesn't run as compile
#line 6 is an example of some code, try running it
#we will explain this code in more depth soon!
print("Your Coding Adventure Begins")
# Challenge: use print() to print the following... |
14448fdf092025b4d05db9bbbe2f9e29b6031a59 | Ian0113/Python-Test | /final_test_20181204/MySQLite.py | 1,818 | 3.578125 | 4 | import sqlite3
class typeForSQL:
CHAR = " char"
TEXT = " text"
AI = " integer primary key autoincrement"
INT = " integer"
NOT_NULL = " not null"
class MySQLite:
def __init__(self, dbName):
self.conn = sqlite3.connect(dbName)
def createTable(self, tableName, dictField):
t... |
c19b193da66226eb40fbe4aef47ee0dd53794286 | James-Oswald/IEEE-Professional-Development-Night | /10-26-20/sumArraySingles.py | 165 | 3.671875 | 4 | #https://www.codewars.com/kata/59f11118a5e129e591000134
def repeats(array):
return sum([i for i in array if array.count(i) == 1])
print(repeats([4,5,7,5,4,8])) |
0d9b597fa4b66aa6508b13e64d17e30ab924f6f7 | touhiduzzaman-tuhin/python-code-university-life | /Anisul/9.py | 259 | 4.21875 | 4 | base = int(input("Enter base : "))
height = int(input("Enter height : "))
area = .5 * base * height
print("Area of Triangle : ", area)
print("\n")
radius = float(input("Enter Radius : "))
area = 3.1415 * radius * radius
print("Area of Circle : ", area) |
91ac89d8b95a2e39a5c6861419c10b759f8d9345 | llondon6/nrutils_dev | /workflows/romspline/example.py | 3,546 | 3.75 | 4 | import numpy as np
################################
# Class for generating some #
# test data for showing how #
# to use the code in the #
# Jupyter/IPython notebooks #
################################
class TestData(object):
"""Generate the test data used as in example IPython notebooks
for de... |
37d18e81c1b88973f3cb34c1d7bee5815959f413 | MansiRaveshia/Data-Structures-and-Algorithms | /datastructure/sumof2lists.py | 723 | 3.515625 | 4 | from singlylinklist import LinkedList,Node
def sumlist(l1,l2):
x=l1.head
y=l2.head
carry=0
s=LinkedList()
while x or y:
if not x:
i=0
else:
i=x.data
if not y:
j=0
else:
j=y.data
z=i+ j + carry
... |
48c11b7574af1174cbad894277dacb3b74bcbfdf | nBidari/Year9DesignCS4-PythonNB | /ProjectEuler/MultiplesOfThreeAndFive.py | 230 | 3.75 | 4 | answerList = []
counter = 0
def multipleOfThree(num):
return num % 3 == 0
def multipleOfFive(num):
return num % 5 == 0
for i in range(1000):
if multipleOfThree(i) or multipleOfFive(i):
counter = counter + i
print(counter) |
4cfbbdfb90d871f5a7b736d60a2f52d0b9bc5f4c | gszlxm/python | /RE/zuoye.py | 546 | 3.703125 | 4 | #作业: 1. 熟记正则表达式元字符
# 2. 使用regex对象复习re模块调用的函数
# 3. 找一个文档, 使用正则表达式匹配:
# [1] 所有以大写字母开头的单词
# [2] 所有的数字, 包含整数, 小数, 负数, 分数, 百分数
import re
pattern = '\b[A-Z]+\w*'
fr= open("day01.txt")
f = fr.read()
regex = re.findall(pattern, f)
print(regex)
#pattern = r'\d+\.\d+|-\d+|\d+/\d+|\d+\%|\d+'
#pattern = r'\d+/\... |
ca88127de765599f2bdd340aa8ce65b0d1acb6a1 | Prashant944/python-class | /year.py | 2,208 | 3.984375 | 4 | #Q1
year = int(input("Please Enter the Year Number you wish:"))
if (year%4 == 0 and year%100!=0 or year%400 ==0):
print("The year is Leap Year!")
else:
print("The year is Not Leap Year")
#Q2
length = int(input("Enter the length: "))
breadth = int(input("Enter the breadth: "))
if length==breadth:
... |
57f09af366f9a65de2dd22babd9517276c81fc02 | cyruskarsan/ProfanityCheck | /tests/sq.py | 1,493 | 3.953125 | 4 | import sqlite3
from sqlite3 import Error
def sql_connection():
try:
con = sqlite3.connect('mydatabase.db')
return con
except Error:
print(Error)
def sql_table(con):
cursorObj = con.cursor()
#cursorObj.execute("CREATE TABLE employees(id integer PRIMARY KEY, name text, salary real, department text, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.