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 |
|---|---|---|---|---|---|---|
fbf415b0ad34eb37cae324a182440fb138019416 | OmarFlow/Python-telegram-bot | /extended_calculator.py | 1,083 | 3.65625 | 4 | from functools import reduce
def calculator(user_expression):
try:
user_expression = user_expression.lower().replace(' ', '')
parts = user_expression.split('+')
for part in range(len(parts)):
if '-' in parts[part]:
parts[part] = parts[part].... |
b50a873c8d0d45fd4ebac22fdeaa92097cdea731 | rakshithsingh55/Clg_project | /FoodSearch/webapp/test.py | 550 | 4.5 | 4 | # Python3 code to demonstrate working of
# Common words among tuple strings
# Using join() + set() + & operator + split()
# Initializing tuple
test_tup = ('gfg is best', 'gfg is for geeks', 'gfg is for all')
# printing original tuple
print("The original tuple is : " + str(test_tup))
# Common words among tuple... |
b74da46a6e90282b87017e9502efa0f1810f0e53 | AJsenpai/PythonCodingBat | /Logic/Logic2.py | 5,232 | 3.921875 | 4 | # lone_sum
# Given 3 int values, a b c, return their sum. However, if one of the values is the same as another of the values,
# it does not count towards the sum.
# lone_sum(1, 2, 3) → 6
# lone_sum(3, 2, 3) → 2
# lone_sum(3, 3, 3) → 0
def lone_sum(a, b, c):
sum=0
sum+=a if a not in [b,c] else 0
sum+=b if b not ... |
0dbec9e9fbd8031de891dd56fca18c640aeb686a | justineclin/dicognito | /src/dicognito/randomizer.py | 1,766 | 3.71875 | 4 | import hashlib
import os
class Randomizer:
def __init__(self, seed):
"""\
Create a new Randomizer.
Parameters
----------
seed
Not intended for general use. Seeds the data randomizer so it
produces consistent results when anonymizing ele... |
9a80520e0e14dc591e9f75714cebf57699ec26a4 | harpiechoise/Machine-Learning-Articulos | /Pandas/Indices.py | 1,677 | 3.640625 | 4 | import numpy as np
import pandas as pd
aleatorio = np.random.randint(low=20, high=100, size=[20, ])
nombre = np.random.choice(['Jaime', 'Sebastian', 'Maximo', 'Claudio'], 20)
numero = np.random.choice([10, 11, 13, 45, 8, 2], 20)
df = pd.DataFrame({'Aleatorio': aleatorio, 'Nombre': nombre, 'Numero': numero})
# Cambiar... |
155fb232c27af4432a0ddf3e89ed929811327125 | harpiechoise/Machine-Learning-Articulos | /Numpy/Operaciones.py | 2,494 | 3.671875 | 4 | import numpy as np # Importamos numpy
a = np.arange(25).reshape(5, 5) # Hacemos una matriz de 5 x 5
print(a > 10)
# [[False False False False False]
# [False False False False False]
# [False True True True True]
# [ True True True True True]
# [ True True True True True]]
# Pasando esta matriz de b... |
3e1026f12332c09eacc9d175bd26681af6716e2d | harpiechoise/Machine-Learning-Articulos | /Numpy Nuevo/4. Indexacion.py | 2,297 | 3.84375 | 4 | import numpy as np # Importamos numpy bajo el seudonimo
a = np.arange(10) + 50 # Creamos un rango y le sumamos 50
print(a[2]) # Si quiero acceder al tercer elemento
print(a[-2]) # Si quiero el penultimo valor de mi Array
# 58
# Seleccionar un rango de elementos
print(a[2:5]) # Seleccionar desde tercer element... |
51626ea331b52740a84c1ce2b74dd0ff50ddfeac | jyoti88/HacktoberFest2020-Contributions | /Algorithms/Binary-search/Binary-Search for N array.py | 610 | 3.90625 | 4 | # Input 2 Arrays
# a = array of elements
# x = array of elements to find from a
def binary_search(a, x):
r = []
for i in x:
left, right = 0, len(a)
if i<a[0] or i>a[len(a)-1]:
r.append(-1)
continue
while left <= right :
mid = (left + (left + right)//2... |
20ce051e440910c78ca5b3c409ff8ebb566520c0 | am3030/IPT | /data/HW5/hw5_182.py | 1,171 | 4.28125 | 4 | def main():
num1 = int(input("Please enter the width of the box: "))
num2 = int(input("Please enter the height of the box: "))
symbol1 = input("Please enter a symbol for the box outline: ")
symbol2 = input("Please enter a symbol for the box fill: ")
boxTop = ""
insideBox = ""
for i in range... |
5de5d8d3bedb628d5dfd81a6d4f1df396678c98c | am3030/IPT | /data/HW5/hw5_453.py | 747 | 4.3125 | 4 |
def main():
width = int(input("Please enter the width of the box: ")) # Prompt user for the width of the box
height = int(input("Please enter the height of the box: ")) # Prompt user for the height of the box
outline = input("Please enter a symbol for the box outline: ") # Prompt user for the symbol that w... |
7c2eb614d8ed545815425e6181dc9b77cd285d16 | am3030/IPT | /data/HW4/hw4_340.py | 451 | 4.21875 | 4 |
flavorText = "Hail is currently at height"
def main():
height = 0 # 0 is not a valid input because it is not "positive"
while height < 1:
height = int(input("Please enter the starting height of the hailstone: "))
while height != 1:
print(flavorText, height)
if (height % 2) == 0:... |
81810e0cf0d99523f5c5e723e1db7d4371415f47 | mderamus19/flower-shop | /flowers/rose.py | 254 | 3.546875 | 4 | from flowers import Flower
class Rose(Flower):
def __init__(self, color):
self.color = color
# self.stem = 7
# if __name__ "__main__":
# for_beth = ValentinesDay()
# red_rose = Rose()
# for_beth.flowers.append(red_rose) |
b666b76adea6300e976c7eca73a0ae081e219c61 | lyb521/algorithm | /interview/lintcode/unique-characters.py | 542 | 3.65625 | 4 | # -*- coding: utf-8 -*-
# @Created by PyCharm Community Edition.
# @User: leiyongbo <lyb19900227@126.com>
# @Date: 2017/7/17
# @Time: 12:19
# @url: http://www.lintcode.com/zh-cn/problem/unique-characters/
# @Description:
class Solution:
# @param s: a string
# @return: a boolean
def isUnique(self, str):
... |
bbd0e1429ddce4dbb4ffa1d07518f63b2cd1797b | lyb521/algorithm | /interview/lintcode/single-number.py | 698 | 3.546875 | 4 | # -*- coding: utf-8 -*-
# @Created by PyCharm Community Edition.
# @User: leiyongbo <lyb19900227@126.com>
# @Date: 2017/7/7
# @Time: 14:04
# @url: http://www.lintcode.com/zh-cn/problem/single-number/
# @Description:给出2*n + 1 个的数字,除其中一个数字之外其他每个数字均出现两次,找到这个数字。
class Solution:
"""
@param A : an integer array
... |
8eb55ff7065d2823318bbde01015c36449c1ab82 | lyb521/algorithm | /interview/lintcode/reverse-words-in-a-string.py | 607 | 3.84375 | 4 | # -*- coding: utf-8 -*-
# @Created by PyCharm Community Edition.
# @User: leiyongbo <lyb19900227@126.com>
# @Date: 2017/7/27
# @Time: 11:45
# @url: http://www.lintcode.com/zh-cn/problem/binary-tree-maximum-node/
# @Description:
class Solution:
# @param s : A string
# @return : A string
def reverseWords(sel... |
2d06682fb0807da61bfc58f44ca0bf24ab329d01 | lyb521/algorithm | /interview/lintcode/maximum-subarray.py | 840 | 3.78125 | 4 | # -*- coding: utf-8 -*-
# @Created by PyCharm Community Edition.
# @User: leiyongbo <lyb19900227@126.com>
# @Date: 2017/7/27
# @Time: 16:11
# @url: http://www.lintcode.com/zh-cn/problem/maximum-subarray/
# @Description:
class Solution:
"""
@param nums: A list of integers
@return: An integer denote the sum ... |
1919999e40e15e3c4901013dad17ac7f25d04bef | lyb521/algorithm | /interview/lintcode/minimum-subarray.py | 828 | 3.84375 | 4 | # -*- coding: utf-8 -*-
# @Created by PyCharm Community Edition.
# @User: leiyongbo <lyb19900227@126.com>
# @Date: 2017/9/5
# @Time: 16:21
# @url: http://www.lintcode.com/zh-cn/problem/minimum-subarray/
# @Description:给定一个整数数组,找到一个具有最小和的子数组。返回其最小和。
class Solution:
"""
@param: nums: a list of integers
@retu... |
079595ae17200a2658afc785af07c1e78568b85b | lyb521/algorithm | /interview/lintcode/hash-function.py | 594 | 3.625 | 4 | # -*- coding: utf-8 -*-
# @Created by PyCharm Community Edition.
# @User: leiyongbo <lyb19900227@126.com>
# @Date: 2017/10/10
# @Time: 15:16
# @url: http://www.lintcode.com/zh-cn/problem/hash-function/
# @Description:
#
class Solution:
"""
@param key: A String you should hash
@param HASH_SIZE: An integer
... |
08db126504efcf5dd81b2024f443075f57f6d993 | matheusb432/hello-world | /Learning Python/ifelse3.py | 363 | 3.546875 | 4 | has_high_income = False
has_good_credit = True
has_criminal_record = True
if has_high_income and has_good_credit: # Mesmo que if x && y
print("Eligible for loan")
if has_high_income or has_good_credit: # Mesmo que if x || y
print("Eligible for loan")
if has_good_credit and not has_criminal_record: # S... |
203e316cac71640f97fb1cc26ecf2eac7d3e76ae | matheusb432/hello-world | /Learning Python/loops2.py | 1,060 | 4.1875 | 4 | car_started = False
while True:
command = input('>')
if command.lower() == 'start': # Utilizando o metodo lower() para tornar o input case insensitive
if car_started: # Mesmo que if car_started == True:
print('The car is already started!')
else:
prin... |
3d89bfc9c2c6d1d81bb595027ce656725a8f666c | matheusb432/hello-world | /Learning Python/math2.py | 298 | 4.0625 | 4 | x = 10 + 3 * 2 ** 2 # As leis aritmeticas se aplicam aqui, a exponenciacao eh executada primeira, e entao a multiplicacao, logo o resultado eh 22.
print(x)
y = (2+3) * 10 - 3 # As parenteses sobescrevem a ordem aritmetica, entao a operacao eh o mesmo que [(2+3) * 10] - 3, Logo, 47
print(y)
|
7218df5d7573e227a65a6a944ab5e20ed8e7148e | ibrahimakhlaq/Cheetay-Assessment- | /Task3.py | 889 | 3.703125 | 4 | # LONGEST PALINDROM OF SUBSTRING
# NOTE THIS TASK COULD HAVE BEEN COMPLETED WITH MANACHAR ALGORITHM(IM WELL AWARE OF IT) WITH THE REQUIRED TIME
# COMPLEXITY BUT ITS A COMPLICATED ALGORITHM.
# HAVING SAID THAT I DIDNT UPLOAD ANY ONLINE PREWRITTEN CODE I DID IT BY MYSELF. BUT THE COMPLEXITY IS COMOPROMISED.
def longe... |
f0be2cee31f19568871bc550619de48a84283445 | abhaydoke09/python-coding | /list_print_recursion.py | 154 | 3.625 | 4 | A = [1,2,3,2,3,4,1,2,3,4,5,6,7,6,5,3,1,2,3,4]
def Print(A,i):
if i==len(A):
return None
else:
print A[i]," ",
Print(A,i+1)
print A
Print(A,0) |
dd471dd810a906b4bfe398773d34235ed011db25 | OnsJannet/holbertonschool-web_back_end | /0x0D-NoSQL/11-schools_by_topic.py | 326 | 3.640625 | 4 | #!/usr/bin/env python3
""" returns the list of school
having a specific topic """
from pymongo import MongoClient
def schools_by_topic(mongo_collection, topic):
""" returns the list of school having a specific topic """
collection = mongo_collection
topic = collection.find({"topics": topic})
return ... |
8cbc562666c92f691094995f0b2d1b6ac1399202 | OnsJannet/holbertonschool-web_back_end | /0x03-caching/3-lru_cache.py | 1,109 | 3.5 | 4 | #!/usr/bin/python3
""" LIFOCache module
"""
from base_caching import BaseCaching
class LRUCache(BaseCaching):
""" BasicCache defines:
- Inherits from BaseCaching
- Cashing System with no limit
- where your data are stored (in a dictionary)
"""
def __init__(self):
""" BaseCaching ... |
2638e991bb136b3fc96cb76121b28a5534e9557d | jooyg62/practice03 | /prob02.py | 585 | 3.96875 | 4 | # 문제2.
# range() 함수와 유사한 frange() 함수를 작성해 보세요. frange() 함수는 실수 리스트를 반환합니다
def frange(val, base=0.0, step=0.1):
if val < base:
start = val
stop = base
else:
start = base
stop = val
start = float(start)
result = []
result.append(start)
while True:
if st... |
054041d8ffe668429fc34a09e13ab85bf4b0d9c9 | HermanYang/C-Minus | /c_minus_utils.py | 299 | 3.578125 | 4 | counter = 0
def printSyntaxTree(node, depth):
if node:
print(' ' * depth + str(node))
nodes = node.children
for child in nodes:
printSyntaxTree(child, depth + 1)
def printTokenList(tokenList):
for token in tokenList:
print(token)
def newAddress():
i = i + 1
return 't' + str(i)
|
3c2ba783748a980db30d573a2bab591365f5246e | armadail/Python-Webscraping | /webscraping/filter1 stopwords.py | 869 | 3.578125 | 4 | import os
import re
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
#word_tokenize accepts a string as an input, not a file.
grade = 8
current_path = os.path.dirname(__file__)
file_path = os.path.join(current_path, "article.txt")
stop_words = set(stopwords.words('english'))
v... |
92a4b9d0d0cc807bb381c036dfe85c8679d9c206 | ihodes/Larder | /src/core.py | 2,024 | 3.78125 | 4 | """
This modules contains methods to manipulate and query the items list.
item = {item:name quantity:quantity unit:unit_of_quantity price:price}
items = [item]
"""
from fractions import Fraction
def traverseWeightedTo(graph, init_weight, in_node, out_node):
"""Returns the the amount multiplied by the weights betw... |
6d89bccc457d3a674f8523436007075f1bf59a45 | mahakal001/algo-panda | /classical-problems/dataStrucutures/disjoint_set.py | 570 | 3.921875 | 4 | class Node(object):
def __init__(self, label):
self.label = label
self.parent = self
def is_root(self):
if self.parent == self:
return True
return False
def set_parent(self, parent):
self.parent = parent
return
def make_set(label):
return ... |
446a465392d039180800fbae569c3ca21b61d644 | Boosya/Hackerrank | /Algorithms/Strings/morgan_and_a_string.py | 4,980 | 3.625 | 4 | from collections import deque
def min_lexographical_string(string1,string2):
min_string = ''
i1 = 0
i2 = 0
len1 = len(string1)
len2 = len(string2)
while i1 < len1 and i2 < len2:
if string1[i1] < string2[i2]:
min_string = min_string + string1[i1]
i1 += 1
e... |
ef7d0676e216756035870fad8cf29c5eb013fe6d | Boosya/Hackerrank | /Algorithms/Dynamic_programming/fibonacci_modified.py | 580 | 3.9375 | 4 | # returns n-th element in modified fibonacci sequence
# f[i] = f[i-2]+f[i-1]ˆ2
# written by Ekaterina Boosya Gasparian
# reading input
t0 = int(t0)
t1 = int(t1)
n = int(n)
elements = [None]*n # will store f[i]
squares = [None]*n # will store f[i]ˆ2
# initializing fisrt 2 items in fibonacci sequence
t0, t1, n = input... |
3c214ff9b2436424ea428ba2c0f5eeed72af81f5 | Junny-cloud/SORO320 | /exercice3_1.py | 144 | 3.75 | 4 | a =float((input("Votre nombre réel a = ")))
h = 0
k = 1
while h < a:
h += 1/k
k += 1
print("Le plus petit entier n ici est n = ", k)
|
307780d1faca934c9556c9bfae32208bbe89a7c2 | sklee16/lexicographic | /problem_set_2.py | 4,850 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 6 07:58:00 2019
Problem Set 2
#1 Lex index as a linear order of input
#2 Weight of a Word
@author: sl288
"""
from nose.tools import ok_
# =============================================================================
# Problem 1
# This program finds ... |
a3ebaec3425ea5f3bcd4d52df4c9c6f79e8962cb | syntomic/interview | /code/2048.py | 661 | 3.546875 | 4 | """2048游戏消除"""
def merge_same_forward(nums):
l = len(nums)
res = []
j = 0
while j < len(nums):
res.append(nums[j])
if j == l - 1:
break
else:
if res[-1] != nums[j+1]:
j += 1
else:
res[-1] = res[-1] * 2
... |
5e28ab74bcbde0b562b05e12949ccc0e498a8d80 | Katyya/1 | /picture.py | 2,019 | 3.734375 | 4 | from graph import *
windowSize(1000,900)
canvasSize(1000,900)
brushColor(101,199,208)
rectangle(0,0,1000,400)
"""Sky"""
brushColor(0,0,255)
rectangle(0,400,1000,650)
"""Oceon"""
brushColor(202,208,101)
rectangle(0,650,1000,900)
penColor(202,208,101)
x=0
for i in range(9):
circle(50+x,680,60)
x+=200
brushColor(0... |
548102271929affab01d3645de80698e4f1795e0 | malinowakrew/game_wiki_test | /src/page_reader/page_scraping.py | 1,694 | 3.5 | 4 | import requests
from bs4 import BeautifulSoup
from datetime import datetime
import re
"""
page_scrapping
=====================
Page scrapping depends on date and transform information from it into a dictionary.
Using:
*re
*bs4
*requests
"""
class Scraper:
"""
The main aim of this class is collecting data f... |
ec02674b8be560a1911972aaf749c4576a8f4cba | TongDist666/python-sort | /maopao.py | 1,189 | 3.671875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 16 14:01:15 2019
@author: TongDist
时间复杂度:N^2
"""
import time
list=input("请输入一串数字(以空格隔开):")
list_0=list.split()
print(list_0)
def swap(a,b):
temp=list_0[a]
list_0[a]=list_0[b]
list_0[b]=temp
length=len(list_0)
#n个输入,需要n-1个pop
def pop_sort(lis... |
7e3ad5d83a41cd22b7d9b4744279833b1631742e | bcdev/fiduceo | /cems/src/main/python/period.py | 4,616 | 3.734375 | 4 | import datetime
import exceptions
class Period:
def __init__(self, start_date, end_date):
"""
:raise exceptions.ValueError: If the start date is not less than the end date.
"""
if isinstance(start_date, datetime.date):
a = start_date
elif isinstance(start_date,... |
233b2d563d42a32a0a2badd355a6d53cc304c688 | adpoe/CloudComputing | /assignment04/PYTHON_SRC/MeanMapper.py | 496 | 3.8125 | 4 | #!/usr/bin/env python
import sys
def read_input(file):
# destructure each line and yield line-by-line, as a generator
for line in file:
(station, date, temp) = line.strip().split("\t")
yield (station, date, temp)
def main(separator='\t'):
data = read_input(sys.stdin)
for line in data:
... |
b9cb67819ea8994aecface973f20268fdd02f5e5 | michaelwty/-50- | /238. Product of Array Except Self.py | 740 | 3.609375 | 4 | # Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
# Example:
# Input: [1,2,3,4]
# Output: [24,12,8,6]
# Note: Please solve it without division and in O(n).
# Follow up:
# Could you solve it with constant s... |
a25a66f61b85c014fbaff4be5b1b30ac24642dbf | niyati2k/SSL | /Q4.py | 644 | 3.640625 | 4 | n = int(input())
l1=[]
for i in range(n):
l1.append(input())
#print(l1)
dict1=dict(item.split(":") for item in l1)
#print(dict1)
dict2={}
for k,v in dict1.items():
#print(v)
x = v.split(",")
#print(x)
dict2.__setitem__(k,dict(item.split("-") for item in x))
#print(dict2)
for k,v in dict2.items():... |
951137675d019f6f64a48961292f7e198421090f | KVasileva/cd101 | /CW2/dict.py | 170 | 3.578125 | 4 | data = {"Pablo": ["Es", 33, True, "Male"], "Mark": ["Em", 23, False, "Male"], "Loren": ["Er", 43, True, "Female"]}
for key, val in data.items():
print (key, val[1])
|
15e4e6430189b9163227c9a7489d43be4fdcca27 | KVasileva/cd101 | /CW3/class.py | 875 | 3.859375 | 4 | class User:
def __init__(self, first_name, last_name, birth, sex):
self.first_name = first_name
self.last_name = last_name
self.birth = birth
self.sex = sex
def grit(self): #метод класса
print (f"Name: {self.first_name}, {self.last_name}, birth: {self.birth}")
def c... |
88e54587c215498ba9910203f9c7d11213c8c448 | KantonsschuleEnge/ken_ef_inf | /pruefung/Aufgabe7.py | 195 | 3.71875 | 4 | #!/usr/bin/python3
file = open('ASCII-Aufgabe.txt','r')
content = file.read()
file.close()
out=''
for line in content:
for c in line:
out+=hex(ord(c))+','
print(out)
|
47e775cf0325008de8284e425ef7e29a0dc54d31 | balakrishnan-vasudevan/ProjectEuler | /prime_sum.py | 198 | 3.828125 | 4 | def isPrime(n):
prime = True
for i in range(2,n):
if (n%i==0):
prime = False
return prime
sum = 0
for x in range (2,2000000):
print x, isPrime(x)
if isPrime(x):
sum = sum+x
print sum
|
5428ebc75722a6b1e97f5cd4d8ae0319d3473ebf | balakrishnan-vasudevan/ProjectEuler | /counting_sundays.py | 282 | 3.78125 | 4 | #How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)
import datetime
count = 0
for y in range(1901,2001):
for m in range(1,13):
if datetime.datetime.weekday(datetime.datetime(y,m,1))==6:
print y, m
count+=1
print count
|
c0505efabbde68a652686fe79501d314b31577ee | balakrishnan-vasudevan/ProjectEuler | /CollatzSequence.py | 413 | 3.546875 | 4 | #Which starting number, under one million, produces the longest Collatz chain?
l = list()
max_list = list()
max_length = 0
for i in range (2,1000000):
n = i
l.append(n)
while (n!=1):
if (n%2 == 0):
n = n/2
l.append(n)
else:
n = 3*n + 1
l.append(n)
if len(l) > max_length:
max_length = len(l)
max_... |
dfc2cbb268f30871911fcbf3786f0b7e41adfc2f | CharlesLuoquan/knowledge | /testPY/xunhuan.py | 345 | 3.890625 | 4 | # nums = [5, 2, 5, 2, 2]
# for x in range(1, len(nums)+1):
# # print(nums[x-1]*'x')
# for i in nums:
# output = ''
# for count in range(i):
# output += 'x'
# print(output)
def find_max(nums):
# nums = [3, 6, 2, 8, 4]
max = nums[0]
for num in nums:
if num > max:
ma... |
745bf80c2e127df57ccd455e510559d0f1fdd369 | CharlesLuoquan/knowledge | /testPY/shuzidebushu.py | 763 | 3.59375 | 4 | class Solution():
def findComplement(self, num):
res = []
result = 0
# 十进制转二进制的方法:除2取余,逆序排
res.append(str(num % 2))
while (num//2 != 0):
num = num//2
res.append(str(num % 2))
# 逆序
res.reverse()
# 按位取反
for i, v... |
5bc02127456dc5eec874db1019797b92a60bde0a | CharlesLuoquan/knowledge | /testPY/towardsOffer/001-二维数组查找/code.py | 986 | 3.953125 | 4 | '''
在一个二维数组中(每个一维数组的长度相同),
每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。
请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
分治解题思路:
从右上角(或者左下角)开始查找:
如果target更大,指针下移
如果target更小,指针左移
'''
class Solution:
def find(self, target, array):
if len(array) == 0:
return False
i = 0
j = len(array[0])-1
wh... |
3f0f7495407580ab823e6e1167fa0aae806e2451 | sup3rcow/python_course_by_mosh | /app_1_basics.py | 1,533 | 4 | 4 | course = f"Python \"Programming {2019 + 1}"
print("*" * 10)
print(len(course))
print(course[0:2])
print(course[1:])
print(course.upper())
print(course.find("thon"))
print("ython" not in course)
print(10 / 3)
print(10 // 3)
print(10 * 3)
print(10 ** 3)
# x = input("x: ") # input je string
# print(x + str(1))
if 12 > 11... |
972419157c61dc5bcab0efb76f2b611b04b62468 | Hacker-BlackHATS/Blackjack_Capstone | /Blackjack_Capstone.py | 2,129 | 4.09375 | 4 | # Blackjack Project
"""
Our Blackjack House Rules
1> The deck is unlimited in size.
2> There are no jokers.
3> The Jack/Queen/King all count as 10.
4> The the Ace can count as 11 or 1.
5> Use the following list as the deck of cards:
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
6> The ... |
853882de1ef0c0ac6ddc0c41cbfd480fdcaabfef | agatakaraskiewicz/magic-pencil | /eveningsWithPython/stonePaperScissorsGame.py | 1,229 | 4.1875 | 4 | from random import randint
"""
1 - Paper
2 - Stone
3 - Scissors
1 beats 2
2 beats 3
3 beats 1
"""
points = 0
userPoints = 0
howManyWins = int(input('How many wins?'))
def userWins(currentUserScore):
print(f'You won!')
return currentUserScore + 1
def compWins(currentCompScore):
print(f'You loose!')
return curre... |
223f8d457c5c5157dcfd4c3e0a98a0f114f86758 | agatakaraskiewicz/magic-pencil | /Automate boring stuff excercises/commaCode.py | 460 | 4 | 4 | # it joins list elements into a simple sentence
def makeItSentence(x):
sentence = ''
for i in x:
if x.index(str(i)) < x.index(x[-2]):
sentence = sentence + str(i) + ', '
elif x.index(str(i)) < x.index(x[-1]):
sentence = sentence + str(i) + ' '
else:
... |
3890449f3f947d8f108a2ee97de7dc6922169afb | agatakaraskiewicz/magic-pencil | /eveningsWithPython/toddlerSimulator.py | 256 | 3.953125 | 4 | answer = ''
badWords = ['fuck', 'suck', 'damn']
endWord = 'Because'
while answer.lower() != endWord.lower():
answer = input('Why?')
if answer in badWords:
print('You told me not to use these words!')
print('Good! The end of the suffering of yours!') |
884be0faa48b02ffa14dd498dee0d4a397a0ddde | wgyn/tictactoe | /ttc.py | 4,724 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 18 17:37:38 2014
Game of Tic Tac Toe
TO DO:
- Allow for arbitrary dimensions!? (by changing board & directions)
"""
import re
class TicTacToe:
# Directions for checking result
directions = [(i,j) for i in [0,1] for j in [0,1]]
directions.remove((0,0))... |
118b90d1afe3f4da49c3b2a474b691751fde0513 | nltran12/othello-project | /Othello/computer_ai.py | 1,749 | 3.796875 | 4 | from game_manager import GameManager
# A class of the computer AI for a game of othello
class ComputerAi:
"""A computer moveset AI for othello"""
def __init__(self, valid_moves, size):
"""Creates an instance of the computer AI given the valid moves
and board size
"""
self.va... |
ad53282d610e522fc409d0bc401537e3a62ea45e | TheHellfire99/WebScrapingGuide | /ScrapeCraig.py | 938 | 3.640625 | 4 | #in this peice of code, we will scrape craigslist for jobs!
#step 1: always import these two libraries
from bs4 import BeautifulSoup
import requests
#step 2: select the target URL(the url you want to webscrape)
url = "https://boston.craigslist.org/d/software-qa-dba-etc/search/sof"
#step 3: create a response object... |
5b847179376f58430021b84f01b2b495b93bbaf9 | NorthcoteHS/10MCOD-Bella-SCHULZ | /user/10MCOD/Piglatin.py | 718 | 3.515625 | 4 | def main():
lst = [ 'sh' , 'gl' , 'ch' , 'ph' , 'tr' , 'br' , 'fr' , 'bl' , 'gr' , 'st' , 'sl' , 'cl' , 'pl' , 'fl']
# Text shown on screen
sentence = input('Type what you would like translated into Piglatin and press ENTER: ')
sentence = sentence.split()
for k in range(len(sentence)):
i = sente... |
0ac879f11a0b701911a830e9592a4e29647a917a | rlads2019/project-sea120424 | /src/essay_eye.py | 5,766 | 3.75 | 4 | import os
import math
essay_num = 312
beginner_num = 100
native_num = 60
medium_num = 43
professional_num = 109
beginner_len = 6529
medium_len = 11764
professional_len = 39555
native_len = 69943
total_len = beginner_len + medium_len + professional_len + native_len
beginner_dict = {}
native_dict = {}
professional_dict... |
8544e1aae64a81c21a7ba4cf37e91a8c6a3f71b3 | brudahm/desafios-python | /Problema 1 (Conversão das horas)/timeconversion.py | 454 | 3.78125 | 4 | #!/usr/bin/python
def to_24(am_pm):
meridian = am_pm[-2:]
hours = am_pm[:2]
minutes = am_pm[3:5]
seconds = am_pm[6:8]
if hours > '12' or minutes > '59' or seconds > '59':
raise ValueError("Nao e um horario valido")
if meridian == 'PM' and hours != '12':
am_pm = str(1... |
1d45822bd212310f9791a1dd55a5b454e56454a9 | MaxRyzhkov/python | /minmax.py | 292 | 3.859375 | 4 | def maximum(arr):
v = arr[0]
for a in arr:
if v < a: v = a
return v
def minimum(arr):
v = arr[0]
for a in arr:
if v > a: v = a
return v
def average(arr):
l = len(arr)
acc = 0
for a in arr: acc += a
avg = float(acc) / l
return avg
|
e0146939bfe2822709ed4ea162e6e07c3f5d09b1 | mmankt2/CodingDojo | /Python/python_fundamentals/selection_sort.py | 320 | 3.90625 | 4 | #! /usr/local/bin/python3.7
def selection_sort(myList):
for j in range(len(myList)):
minIndex = j
for i in range(j,len(myList)):
if myList[i] < myList[minIndex]:
minIndex = i
myList[minIndex], myList[j] = myList[j], myList[minIndex]
return myList
print(selection_sort([8,5,2,6,3,4,9,1,7])) |
1692a6d2244cad6f7e33552c6e338363b5b69d19 | mmankt2/CodingDojo | /Python/python_fundamentals/functions_basic2.py | 761 | 4 | 4 | #! /usr/bin/python3
def countdown(num):
new_list = []
for i in range(num,0,-1):
new_list.append(i)
return new_list
def print_return(list):
print(list[0])
return list[1]
def first_plus_length(list):
length = len(list)
first = int(list[0])
return first + length
def vals_greater_than_second(list):
... |
a7fdb86f34f4fc9d8bf6dbf336e9db878b68a934 | hossamabdullah/Hacker_Rank | /Python/calendar-modul/calendar-modul.py | 164 | 3.84375 | 4 | import calendar
m, d, y=map(int,input().split())
day_num = calendar.weekday(y, m, d)
days_list = list(calendar.day_name)
print(days_list[day_num].upper())
|
0b268f91714ebc4259d9ec628145e9031437fc93 | LachlanStevens/P2PU-ProgrammingTheory2 | /Module_2/2.3_LooseCoupling/Exercise_1/main.py | 289 | 3.859375 | 4 | def getExponent(num, exponent):
answer = pow(num, exponent)
return answer
def main():
num = int(raw_input("Enter in a number: "))
exponent = int(raw_input("Raise the number to the power of: "))
print "Answer: %d" % (getExponent(num, exponent))
if(__name__ == "__main__"):
main() |
6e4bc7d8121fe7e7d22acc0e33737ce563f40533 | bruinsan/home | /advent_calendar/day3/day3b.py | 3,998 | 3.625 | 4 | import sys
from pprint import pprint
from math import sqrt, ceil
finished = 0
def move_right(mem, x, y, times, final_pos):
global finished
#print "[RIGHT_START] x = {} \t y = {}".format(x, y)
for i in xrange(times):
# print "[RIGHT] x = {} \t y = {}".format(x + i + 1, y)
r = x + i + 1
positions = [mem[y + 1]... |
318f7b3e1567309cab72f11ce2863a33f8a3691f | bruinsan/home | /code_google/counting_sheeps.py | 1,131 | 3.5625 | 4 | #!/bin/python
import sys
def check_wakeup(seem):
final_list = ['0','1','2','3','4','5','6','7','8','9']
#print sorted(seem)
if sorted(seem) == final_list:
#fall asleep
return True
else:
return False
def split_digits(seem, number):
str_nb = str(number)
for digit in str_nb:
... |
d2fd772f54b226e64ad3ef95e820aa5f74fd0b1b | mr-m0nkey/20-questions | /answers/Python/@oseme-techguy/06-multiplication-table.py | 608 | 3.984375 | 4 | """
Solution to Multiplication Table
"""
if __name__ == '__main__':
num_of_rows = 12
num_of_columns = 12
row_index = 1
column_index = 2
table = ''
while True:
if row_index > num_of_rows:
break
# Do printing of table here
table += str(row... |
4829feea8e6968e760e5a5d6787af302c1c1c882 | mr-m0nkey/20-questions | /answers/Python/@oseme-techguy/02-lottery.py | 515 | 3.703125 | 4 | """
Solution to Lottery
"""
import random
if __name__ == '__main__':
while True:
input('Press any key: ')
lottery_values = random.sample(range(0, 10), 3)
print('{first} {second} {third}'.format(
first=lottery_values[0],
second=lottery_values[1],
... |
7df3f2406a688332e19b21279a5173bbdcf27237 | kahungunu/cs4hs | /hello.py | 163 | 3.625 | 4 | ingoa = str(input("Kia ora, ko wai koe? "))
print("kia ora " + ingoa)
mahi = str(input("E mahi ana koe i te aha?"))
print("Ka pai, e mahai ana koe i te " + mahi)
|
05f05c534ec8bdca72d8742d2f315efa66f1d30e | swar00p-kr1shna/pysampcode | /swaroop_domino_50A.py | 118 | 3.640625 | 4 | m,n=map(int,input().split())
if(m<=n):
a=m*n
a=int(a/2) #area of the quadrilateral/area of domino
print(a) |
5053fe5682f4c53a0ead432c64d5ef68a2de44ce | sineczek/Automate_the_Boring_Stuff | /GUIAutomationKeyboard.py | 477 | 3.546875 | 4 | import pyautogui
# dzięki ; możemy w jednej linii odpalić 2 polecenia
pyautogui.click(100, 100);
pyautogui.typewrite('Hello World!\n') # przesyłanie klawiszy
pyautogui.typewrite('Hello World!\n', interval=0.2) # z opóźnieniem
pyautogui.typewrite(['a', 'b', 'left', 'left', 'X', 'Y', 'right', 'right', '\n'], interv... |
05ee4a903cbb6ff9847543dc65e90ef5b4f0904a | AlejoCasti/holbertonschool-low_level_programming | /0x1C-makefiles/5-island_perimeter.py | 711 | 3.96875 | 4 | #!/usr/bin/python3
''' Perimeter function that return the perimeter of an island '''
def island_perimeter(grid):
''' islando function to get perimeter '''
width = len(grid[0])
height = len(grid)
perimetro = 0
for i in range(height):
for j in range(width):
if grid[i][j] == 1:
... |
77ab6b29a76c603d0fb7722a66e9f1afdfcc1cd0 | kaceyabbott/intro-python | /file_rename.py | 641 | 3.8125 | 4 | """
rename files from a folder
get: http://icarus.cs.weber.edu/~hvalle/hafb/prank.zip
"""
import os
def rename_files():
'''
rename files in a folder
:return: nothing
'''
pass
def main():
"""
test function
:return: nothing
"""
rename_files()
file = r"C:\Users\kaceyabbott... |
4dfae7405b59b54d8b94538f67cce274c76ffa9d | kaceyabbott/intro-python | /mydictionaries.py | 1,736 | 3.734375 | 4 | """
playing with dictionaries
"""
from pprint import pprint as pp
def main():
"""
test function
:return:
"""
urls = {
"google": "www.google.com",
"yahoo": "yahoo.com",
"twitter": "www.twitter.com",
"wsu": "weber.edu"
}
print(urls,type(urls))
# access b... |
1fe6cd8e407ae44133b561e4c885bc0ef4904560 | kaceyabbott/intro-python | /while_loop.py | 489 | 4.28125 | 4 | """
Learn conditional repetition
two loops: for loops and while loops
"""
counter = 5
while counter != 0:
print(counter)
# augmented operators
counter -= 1
print("outside while loop")
counter = 5
while counter:
print(counter)
counter -= 1
print("outside while loop")
# run forever
while Tru... |
9bd4ccc681ff0b91461c8d4120ea0b1f2ad17053 | drenomor/python_tanulas | /13_elagazasok.py | 964 | 3.625 | 4 | #!/usr/bin/env python3
# elágazások, feltételek - if statement, conditions
elvalaszto = "----------"
if True:
print('igaz')
print(elvalaszto)
if False:
print('igaz')
print(elvalaszto)
eletkor = 66
if eletkor < 18:
print('Se cigi, se pia!')
print(elvalaszto)
print('Életkor:', eletkor)
if eletkor < 1... |
e27773469d98201ab8d624cf19e2166de74579a4 | shagunsodhani/powerlaw | /powerlaw/regression.py | 7,543 | 3.546875 | 4 | import numpy as np
from sklearn import linear_model
import matplotlib.pyplot as plt
from scipy.special import zeta
from .distribution import frequency_distribution, powerlaw_series, random_series
from .utils import unique
from math import pow, e, log, sqrt
import sys
import random
def least_square_regression(x, y, ... |
56ba0b9dd20dcc0b32cf81042e855e24fc56aa0f | tjann/cskickstart | /recursion_problems/adddigitsB.py | 177 | 3.859375 | 4 | def addDigits(num):
if num < 10:
return num
else:
return addDigits(addDigits(num//10) + addDigits(num % 10))
print(addDigits(23))
print(addDigits(554))
|
9d55f4ceff661a8f4ff934738042ee80660c1340 | icevin/hackMIT2020-solutions | /puzzle_4/test.py | 918 | 3.5625 | 4 |
danger_words = [" drop ", " delete ", "information_schema.tables", "information_schema.columns", "information_schema.schemata","noam_chomsky"]
def sanitize_query(query):
# invalidate queries containing these words
danger_words = [" drop ", " delete ", "information_schema.tables", "information_schema.columns",... |
aa901adf350157f01dec64132da826467dd78f49 | jonathan-cj/Kel7Milestone2 | /kurangiPoin.py | 1,004 | 3.953125 | 4 | # masukan = matriks dataSIM, nomorSIM
# keluaran = matriks dataSIM dengan poin dari pengguna nomorSIM yang udah dikurangi
# asumsi:
# semua memiliki nomor SIM yang berbeda
# masukan pengurangan poin selalu valid
def minusPoin(dataSIM, nomorSIM):
print()
for i in dataSIM:
if i[0] == nomorSIM:
... |
41a21487a116174c20f786c911378f4f94239b68 | romanpindela/code-taboo-2nd--progbasic-python-codecool | /2nd_algorithm.py | 2,625 | 3.765625 | 4 | import random
import os
def clear_terminal():
os.system('cls' if os.name == 'nt' else 'clear')
def get_one_card(score_to_reach_limit):
cards = {
'2': 2, '3': 3, '4': 4, '5': 5,
'6': 6, '7': 7, '8': 8, '9': 9,
'10': 10, 'J': 10, 'Q': 10,
'K': 10, 'A': '?'
}
# ... |
8f5eb8951b6d53ef06defd95e47f12c280712ed8 | RajNirmal/HackerRank_30_Days_of_Code | /Day1.py | 578 | 4 | 4 | input_int = input()
input_double = input()
input_string = input()
#number = input_int + i
#doub = input_double + d
#print(number)
#rint(doub)
print ( int(input_int) + i )
print ( float(input_double) + d)
print( s + input_string )
# Declare second integer, double, and String variables.
# Read and save an integer, doub... |
73388fafce39a716429c08673659b54258a0c9a4 | leilei92/Coding-Algorithm | /binary_tree/tree_path_sum_to_target.py | 1,475 | 3.828125 | 4 | #Given a binary tree and a target sum, determine if the tree has a root-to-leaf path
# such that adding up all the values along the path equals the given target.
class Solution(object):
def exist(self, root, target):
"""
input: TreeNode root, int target
return: boolean
"""
r... |
50dce6727ea8fd3214a39f8cfc284fafe3fb0d1a | leilei92/Coding-Algorithm | /binary_tree/find_key_value.py | 937 | 3.703125 | 4 | class _None(object):
def __init__(self, key, value):
self.key = key
self.value = value
self.left = self.right = None
class BST(object):
def __init__(self):
self.root = None
def _query(self, root, key):
if not root:
return None
if key < root.value... |
5fae4809ef1033ddca3b9270bbc0083c51e2fea8 | appy2k13/python_codes | /gcd.py | 207 | 3.703125 | 4 | def swap(a,b):
if a<b:
b=a+b
a=b-a
b=b-a
return(a,b)
a, b = list(map(int,input().split()))
(a,b) = swap(a,b)
while a%b!=0 :
a=a%b
(a,b)=swap(a,b)
print(b)
|
71a1b224ed1e1a759e94d0c955a4e8c7e5e87ef2 | appy2k13/python_codes | /trysumfibtot.py | 243 | 3.71875 | 4 | n = int(input())
if n==0:
print(0)
elif n==1:
print(1)
else:
pn = 0
pnn = 1
sum = 1
for i in range(n-1):
pnew = pn + pnn
pn = pnn
pnn = pnew
sum = (sum+pnn)
print(sum)
|
51e98d926b10c0f93b181027e378718a43fea105 | CauanyRodrigues01/Codigos-Python | /Questões do URI/URI_1190.py | 462 | 3.5625 | 4 | operacao = input()
soma = 0
min = 11
cont = 0
m = []
for a in range(12):
linha = []
for b in range(12):
numero = float(input())
linha.append(numero)
m.append(linha)
for c in range(1, 11):
for d in range(min, 12):
soma = soma + m[c][d]
cont += 1
if c < 5:
... |
51c24e71c74200596f2cf3ce0c25cfae3ee2d2b7 | CauanyRodrigues01/Codigos-Python | /Questões do URI/URI_1234.py | 1,376 | 3.890625 | 4 | '''palavras = list()
while True:
try:
frase = input().lower()
minus = True
maius = False
for i in frase:
if i == ' ':
print(i, end="")
elif (minus == True and maius == False):
print(i.upper(), end="")
minus = Fal... |
067081c638cd82c4471d18852e5685797de8e713 | CauanyRodrigues01/Codigos-Python | /Questões do URI/URI_1238.py | 775 | 3.5 | 4 | loops = int(input())
for a in range(loops):
frase1, frase2 = input().split()
maior = 0
menor = 0
tam_frase1 = len(frase1)
tam_frase2 = len(frase2)
if tam_frase1 > tam_frase2:
maior = frase1
menor = frase2
elif tam_frase1 < tam_frase2:
maior = frase2
menor = ... |
214fb8f74c89d65b754c286f43256ab6b020e09f | atdavidpark/python-for-coding-test | /6/8.py | 367 | 3.578125 | 4 | # N 입력 받기
n = int(input())
# N명의 학생 정보를 입력 받아 리스트에 저장
array = []
for i in range(n):
array.append(input().split())
# 키(Key)를 이용하여, 점수를 기준으로 정렬
array = sorted(array, key=lambda student: student[1])
# 정렬이 수행된 결과를 출력
for student in array:
print(student[0], end=' ')
|
647a85fe8afa02d975d69804b369f7dc42996f03 | nitirat2001/Python | /ALL/หาค่าทางด่วน.py | 1,856 | 3.8125 | 4 | print ("\tโปรแกรมคำนวณค่าผ่านทางมอเตอร์เวย์")
print ("-"*50)
print("\tรถยนต์ 4 ล้อ กด 1")
print("\tรถยนต์ 6 ล้อ กด 2")
print("\tรถยนต์มากกว่า 6 ล้อ กด 3\n")
car1_list = ["ลาดกระบัง-->บางบ่อ:25 บาท","ลาดกระบัง-->บางประกง:30 บาท","ลาดกระบัง-->พนัสนิคม:45 บาท","ลาดกระบัง-->บ้านบึง:55 บาท","ลาดกระบัง-->บางพระ:60 บาท"]
car2... |
1d1094869a6004eae15422c79df5bb63eb614e2f | nitirat2001/Python | /ALL/test3.py | 244 | 3.703125 | 4 | name=input('Enter your name:')
surname=input('Enter surname:')
year=input('INPUT year')
password=input('INPUT YOUR PASSWORD')
print("Name is %s."%name)
print("Surname is %s."%surname)
print("Year is %s."%year)
print("Password is %s."%password) |
4672d91a73cf158dd4b53bb29b44e26a67e49745 | nitirat2001/Python | /ALL/DAYS CONVERTER.py | 198 | 4.0625 | 4 | days=int (input('INPUT NUMBER OF DAYS:'))
hour = days*24
print('DAYS --> hour :',hour)
minutes= hour*60
print('DAYS --> minutes :',minutes)
seconds= minutes*60
print('DAYS --> seconds :',seconds) |
ef9696efb851aa2d1507f7dae9a2c2b607a3f90d | spacewander/AlgorithmAndDataStructure | /python/heap.py | 1,279 | 3.96875 | 4 | # Implementation of heap algorithms
from heapq import heappush, heappop, heapify
def sort_heap(seq):
h = []
for v in seq :
heappush(h, v)
return [heappop(h) for i in range(len(h))]
def is_heap(seq):
for i in range(1, len(seq)) :
if seq[i] < seq[int((i - 1)/ 2)] :
return Fa... |
58623162aadc6b587262cbdaf495d7b6b36c5072 | spacewander/AlgorithmAndDataStructure | /python/min_max.py | 2,018 | 3.5 | 4 | # Implementation of min/max algorithms
def max(a, b):
if a < b : return b
return a
def min(a, b):
if a < b : return a
return b
# Unlike one implemented in c++, this version return value instead of index
def max_element(seq):
return reduce(max, seq)
def min_element(seq):
return reduce(min, se... |
bd106b603d4115b54524c1fdfb6e1054293c078c | Ivana-Korak/python-challenge | /pypoll/main.py | 2,045 | 3.671875 | 4 | import os
import csv
from collections import Counter
csv_file = os.path.join("election_data.csv")
with open (csv_file) as csv_file:
csvreader = csv.reader(csv_file, delimiter = ",")
csv_header = next(csvreader)
counter = 0
all_votes = []
d = {}
for row in csvreader:
counter = counter... |
b47ffc8f1a57417acac378e22b695d23c0d30165 | peteawalk/suck-less-at-python | /classes/main.py | 473 | 3.859375 | 4 | class ExoticCar():
wheels = 4
top_speed = "255 mph"
time_travel = True
def driveFast(self):
print(f"Driving super fast. Might reach {ExoticCar().top_speed}.")
print(type(ExoticCar))
# Instantiate ExoticCar
my_car = ExoticCar()
print(type(my_car))
# Access the class attribute
print(my_car.whee... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.