blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
3ddd465a7ddfddba1f4bf0d987b36f7022dbeac4 | x-ider/a3200-2015-algs | /lab5/Evtushenko/quicksort.py | 794 | 3.578125 | 4 | from sys import stdin, stdout
import random
def quick_sort(a, l, r):
if l < r:
t = partition(a, l, r)
left_border, right_border = t
quick_sort(a, l, left_border)
quick_sort(a, right_border, r)
def partition(a, l, r):
pivot_id = random.randint(l, r)
a[l], a[pivot_id] = a[p... |
a8f267d620c607b021cea16fc2613e2f9c1692a7 | objectfox/bottle_talk | /api-gevent/9.py | 1,722 | 3.65625 | 4 | #!/usr/bin/env python
# We can also use gevent to stream content to our users, or output
# it as we generate it or recieve it from a database or other service.
from gevent import monkey, sleep; monkey.patch_all()
from bottle import route, run, request, HTTPResponse, redirect
from time import sleep
@route("/old/")
d... |
c5ad9c3bbb44c3441e1a06af9077684cce121d69 | juanhurtado4/CS-2-Tweet-Generator | /rearrange.py | 583 | 3.953125 | 4 | import sys
import random
words = sys.argv[1:] # Command line arguments
def random_python_quote():
'''
Functions scrambles the order of the elements in the list "words"
Returns a set of strings which is a scrambled version of words list.
'''
scramble_words = []
if len(words) == 0:
retur... |
da9590d5f866483b96babe81cc8674867501f72c | aniamirjanyan/Python-Basics | /basic_lists.py | 1,973 | 4.34375 | 4 | courses = ["History", "Math", "Physics", "CompSci"]
print(courses[0])
print(courses[:2])
print(len(courses))
courses.append("Art") # adding item to the list
courses.insert(0, "Art") # inserting at position 0
courses_2 = ["Art", "Education"]
courses.insert(0, courses_2) # will add the list t... |
6c4871f0a93dfb5d3d8a18c806d33de5b2537fc5 | dopqob/Python | /Python学习笔记/基础练习/hello.py | 617 | 3.671875 | 4 | # coding=UTF-8
# def fun(args):
# print (args,type(args))
#
# phone = ('13098765432', '16602700006', '18502799989')
# fun(phone)
# dict1 = {'name':'荸荠', 'age':30, 'work':'测试工程师'}
# print ('我的姓名是{name},我{age}岁,我是{work}'.format(**dict1))
# a = lambda a,b:a+b
# print (a(3,5))
#
# b = 1
# name = 'Bilon' if b == 1 ... |
a7a9f37fa98cf6fc72cebe85d9f187e802ebe8c9 | GuilhermeAntony14/Estudando-Python | /ex040.py | 317 | 3.84375 | 4 | print('vamos descobrir a sua nota!')
n = float(input('Digite sua primeira nota: '))
n1 = float(input('Digite o segundo valor: '))
n2 = float((n+n1)/2)
print(f'A media e {n2}!')
if n2 <= 4:
print('Reprovado!')
elif n2 >= 5 and n2 < 7:
print('Recuperação!')
elif n2 >= 7:
print('\033[32mAprovado!\033[m')
|
ee8f5d997683dfb1853cbf9fc0468454bcc79574 | Tyrna/adventofcode | /3/sol3.py | 605 | 3.703125 | 4 | f = open("input.txt", "r+")
i = 0
two = False
twoNum = 0
three = False
threeNum = 0
map = {}
for line in f.readlines():
#Fill the map
for char in line:
if char in map:
map[char] = map[char] + 1
else:
map[char] = 1
#Check the map
for char in map:
if map[... |
88742ce49f07c1b09f4970738a849673a9477c5b | helenaj18/Gagnaskipan | /Tímadæmi/Tímadæmi15/15. MoreTrees/AlphabetTreeBase/alphabet_tree_student_program.py | 1,431 | 3.828125 | 4 |
import sys
class TreeNode:
def __init__(self, word = ""):
self.word = word
self.children = []
class AlphabetTree:
def __init__(self):
self.root = TreeNode('')
def add_word(self, word):
if word == '':
return self.root
node = sel... |
e8222c6f5cfc3680991139065e79c07c2e64abc2 | fatrujilloa/BootCampJ00 | /count.py | 723 | 3.9375 | 4 | import sys, string
def text_analyzer(*args):
if len(args) == 0:
T = input('What is the text to analyze?: ')
elif len(args) > 1:
print ("Too many arguments")
return
else:
T = args[0]
l, u, s, p = 0, 0, 0, 0
for i in range(0, len(T)):
if T[i] in string.ascii_l... |
5ce4dc12fe1ba247d570fd32be21a030ba12096a | Jpocas3212/whatsapp-play | /wplay/locationfinder.py | 324 | 3.53125 | 4 | import os
from bs4 import BeatifulSoup
def locationfinder(name):
"""
# to find location by ip address
print('Get you ipinfo token from https://ipinfo.io/account')
ip_address = '*'
token = str(input("Enter your ipinfo token: "))
ip_string = 'curl ipinfo.io/'+ip_address+'?token='+token+''
os.system(ip_string)
"... |
2d16de2ebd39074c1e2dc80e4a43688f04fa4677 | rafathossain/Encrypt-Decrypt | /main.py | 1,193 | 4.25 | 4 | import string
# Alphabet List
alphabet = list(string.ascii_uppercase)
# Encrypted List
encrypted = ['Z', 'A', 'Y', 'B', 'X', 'Z', 'A', 'Y', 'B', 'X', 'Z', 'A', 'Y', 'B', 'X', 'Z', 'A', 'Y', 'B', 'X', 'Z', 'A', 'Y', 'B', 'X', 'R']
# Python code to convert string to list character-wise
def Convert(data):
list1 = ... |
d8ef18c3ad837ed058a8926b506ece04c3e0782d | fcortesj/AssistMe | /gui/linkers/getEvents.py | 1,601 | 3.859375 | 4 | """ Script used to store the events in a local text file """
# Import dependencies to access to the data
import sys
# Get data sent from the client to store all the events
nombres = sys.argv[1]
lugares = sys.argv[2]
fechas = sys.argv[3]
# Check if there's at least one event to be downloaded
if nombres is not "":
#... |
c9e967ee6461b1ef5a0b00eca30793b9c8a0388d | sahands/coroutine-generation | /combgen/helpers/permutations/move.py | 633 | 3.640625 | 4 | from .transpose import transpose
# Movement directions
LEFT = -1
RIGHT = 1
def move(pi, inv, x, d, poset=None):
# Move x in permutation pi in the direction given by d, while maintaining
# inv as pi's inverse. If a poset is given, x is only moved if pi will
# continue to be a linear extension of the pose... |
abe6f9571793c64ee261ffc001080030cfb0a8b2 | AntonZykov85/python | /task2.py | 280 | 3.53125 | 4 |
my_list_str = (input('введите переменные через пробел'))
my_list = my_list_str.split( )
print(my_list)
print(type(my_list))
k = len(my_list) - 1
i = 0
while i < k:
my_list[i], my_list[i + 1] = my_list[i + 1], my_list[i]
i += 2
print(my_list)
|
ea6e300dfc7ba4b0d6b74ca24380fa9658f0911f | ZJXzjx78/lease-of-land | /python/ten/c3.py | 187 | 3.671875 | 4 | import re
s = "A83C72D1D8E67"
def convert(value):
matched = value.group()
if int(matched) >= 6:
return'9'
else:
return'0'
r = re.sub('\d',convert,s)
print(r) |
c1dde2f2b6b987d308e5b9ff18166297016ba35c | vespinoza0/grader | /grader.py | 10,755 | 3.609375 | 4 | import csv
import tkinter
from tkinter import filedialog
import os
import datetime
import config
myTAlist = config.TAlist
avgDict = []
b = ['Assignment','AvgScore','Sub_Rate', 'Sub_Avg']
avgDict.append(b)
JScolumn = 0
pyColumn = 0
#### Get a single Canvas CSV file to update! #############
print("########... |
e98e76f8a909723fe340e72dbb83d13eac50901e | JAreina/python | /4_py_libro_2_2/venv/py_2_listas/py_2_4_lists_in.py | 155 | 3.71875 | 4 | print(3 in [1, 3, 4, 5])
#True
print(3 not in [1, 3, 4, 5])
#False
print(3 in ["one", "two", "three"])
#False
print(3 not in ["one", "two", "three"])
#True |
fbb4cea42816b4cfbea382c7666cc1e73a652614 | dtokos/FLP | /project-euler/33_Digit-cancelling-fractions.py | 1,079 | 3.546875 | 4 | # coding=utf-8
# Digit cancelling fractions
# Problem 33
# https://projecteuler.net/problem=33
#
# The fraction 49/98 is a curious fraction, as an inexperienced mathematician in attempting to simplify it may incorrectly believe that 49/98 = 4/8, which is correct, is obtained by cancelling the 9s.
# We shall consider f... |
333ee3aff66b98604610b35c98190c6a1eb2706c | wo-shi-lao-luo/Python-Practice | /LeetCode/Range Sum of BST.py | 1,738 | 3.625 | 4 | # Given the root node of a binary search tree, return the sum of values of all nodes with value between L and R (inclusive).
#
# The binary search tree is guaranteed to have unique values.
#
#
#
# Example 1:
#
# Input: root = [10,5,15,3,7,null,18], L = 7, R = 15
# Output: 32
# Example 2:
#
# Input: root = [10,5,15,3,7,... |
55735dc84d0c8bbee42f707695c18f6dd7367b42 | andytanghr/python-exercises | /turtle/shapes.py | 1,942 | 3.671875 | 4 | from turtle import *
def drawEquilateralTriangle(size=100, fill=False, hue='black'):
color(hue)
if fill == True:
begin_fill()
for line in range(3):
right(120)
forward(size)
end_fill()
else:
for line in range(3):
right(120)
forward(size)
def drawSquare(size=100, fill=False... |
07ac60877c3e49c093210c558128105a84359c2f | JackSmithThu/quant | /data_clean/power.py | 1,218 | 3.515625 | 4 | #!/usr/bin/env python
# coding=utf-8
file = open("res.txt")
div = [] # 需要除权的 list,每个元素第一列是时间,第二列是价格(string)
for line in file:
# print line
line = line.split('\n')[0]
div.append(line.split(' '))
# print div
for div_node in div:
price = float(div_node[1])
# print price, type(price)
base_data =... |
da9966e71749b03370b758ddeda5739530964b74 | nwaiting/wolf-ai | /wolf_alg/Data_structures_and_algorithms_py/union_find_sets.py | 2,630 | 3.578125 | 4 | #coding=utf-8
"""
并查集:
并查集是一种树型的数据结构,用于处理一些不相交集合(Disjoint Sets)的合并及查询问题
"""
class edge(object):
def __init__(self, start=None, end=None):
self.start = start
self.end = end
class GraphManager(object):
def __init__(self, edge_num=3):
if edge_num:
self.parents = [-1 for i in ... |
cc4ba67faab9a7966555d64d39d1934655ac063a | liush79/codewars | /6kyu/string_evaluation.py | 465 | 3.546875 | 4 | def string_evaluation(strng, conditions):
result = []
for cond in conditions:
left = cond[0] if cond[0].isdigit() else str(strng.count(cond[0]))
right = cond[-1] if cond[-1].isdigit() else str(strng.count(cond[-1]))
result.append(eval('%s%s%s' % (left, cond[1:-1], right)))
return res... |
66ec9272e34d5c0e053d84d4110b64a422225287 | Carlos21Reyes/Mision-02 | /cuenta.py | 539 | 3.625 | 4 | # Autor: Carlos Alberto Reyes Ortiz
# Descripcion: Te ayuda a saber cuanta propina y IVA va a ser de tu comida. Dando como propina un 13% y un IVA de 15%
# Escribe tu programa después de esta línea.
costoComida = int(input("Costo de su comida:"))
porcentajePropina = 13
porcentaheIVA = 15
propina = costoComida*porcen... |
f34a4ef8f1604aa144e3faff2b9b1a7fe74399a2 | anguszxd/leetcode2 | /PalindromeNumber.py | 1,120 | 3.9375 | 4 | #coding:utf-8
#该方法思路:取最前一位和最末尾一位进行比较,看两者是否相同
#若相同则在原数上去除最高位和最低位,继续进行比较
#但该方法存在的问题是:去除最高位和最低位后,余下的不一定能成为数
#如:1000001,去除最高位最低位后全是0,不是一个数了
def isPalindrome(x):
x1 = x
digit = 0
isPalin = True
while x1 > 0:
x1 /= 10
digit += 1
print digit
x2 = x
while x2 > 10:
tail = x2%10
head = x2/(pow(10,digit-1))
if ... |
854034d70081466d3808bcb843e251c737858d05 | GabrielePiumatto/Scuola_2020-21 | /SISTEMI-E-RETI/PYTHON/COMPITI PYTHON NATALE/ES_03.py | 329 | 4.0625 | 4 | def fibonacci (fib, num, a ,b):
if num <= 0:
return
else:
fib.append(fib[a] + fib[b])
a += 1
b += 1
num -= 1
fibonacci(fib, num, a, b)
fib = [0, 1]
a = 0
b = 1
num = int(input("Quanti numeri vuoi stampare ? "))
fibonacci(fib, num, a, b)
print(f... |
16bfb242e498dccd5b3203a4ce0c90340865e9b2 | joycebrum/online-judge-problems | /UVA/10098-generating-fast-sorted-permutation.py | 1,190 | 3.515625 | 4 | def get_min_greater_than(array, letter):
value = max(array)
for c in array:
if c > letter and c < value:
value = c
return value
def get_next_permutation(letters):
i = len(letters) - 1
removed = []
while i >= 0:
if not removed:
removed.append(letters.pop()... |
878dfc95bd4069c89a95b64b6561cabfe03f6d9f | Justice0320/python_work | /ch3/self_test_cars.py | 319 | 3.578125 | 4 | cars = ["ford", "honda", "Lamborghini", "McLaren"]
message = "My next car will be a " + cars[0] + "."
print(message)
message = "My next car will be a " + cars[1] + "."
print(message)
message = "My next car will be a " + cars[2] + "."
print(message)
message = "My next car will be a " + cars[3] + "."
print(message)
|
b53f027b847f51556779b1de68e3a76bde68ef6c | Evilzlegend/Structured-Programming-Logic | /Chapter 02 - Elements of High Quality Programs/D2L Assignments/tiemens_temp.py | 519 | 4.3125 | 4 | # Fahrenheit to Celsius formula -32*5/9
# Entering the input for the desired temperature conversion.
temperatureRequest=float(input("Please enter your degree temperature: "))
# Conversion formula for Fahrenheit to Celsius first part
temperatureFirst=temperatureRequest-32
# Conversion formula for Fahrenheit t... |
878132831dc91c803084bb844ae2afdb11f9c1a1 | joysreb/python | /addelement_tuple.py | 93 | 3.640625 | 4 | tuples=(1,2,3,4,5,6)
print(tuples)
tuples=tuples+(7,8,9,10)
listx=list(tuples)
print(listx)
|
6c04804e7f5e7bb85360ea29d721ac77cc8fb2d5 | emag-notes/automatestuff-ja | /ch05/picnic.py | 705 | 3.671875 | 4 | all_guests = {
'アリス': {
'リンゴ': 5, 'プレッツェル': 12
},
'ボブ': {
'ハムサンド': 3, 'リンゴ': 2
},
'キャロル': {
'コップ': 3, 'アップルパイ': 1
}
}
def total_brought(guests, item):
num_brought = 0
for v in guests.values():
num_brought = num_brought + v.get(item, 0)
return num_bro... |
010af8a1940ce2336935c87f5eecbb5bf2bd1e17 | BrunoAfonsoHenrique/CursoEmVideoPython | /AlgoritmosPython_parte1/088.py | 246 | 3.796875 | 4 | num = qtd = soma = 0
while num != 999:
num = int(input('Digite um numero [999 para parar]: '))
if num != 999:
qtd = qtd + 1
soma = soma + num
print('Você digitou {} números e a soma entre eles é {}.'.format(qtd, soma))
|
6efaf44fc9af001abe1e606462021979d112bcdd | saibi/python | /angela_course/section10_calculator.py | 1,578 | 4.21875 | 4 |
# def format_name(f_name, l_name):
# formated_f_name = f_name.title()
# formated_l_name = l_name.title()
# return formated_f_name + ' ' + formated_l_name;
# print(format_name("angela", "ANGELA"))
# def is_leap(year):
# if year % 4 == 0:
# if year % 100 == 0:
# if year % 400 == 0:
# print("... |
467a8fa204bf55c7126f414fcaf7b257eebcd65f | Roiw/LeetCode | /Python/131_PalindromePartitioning.py | 1,377 | 3.921875 | 4 | """
Backtracking
- Add initial case (full word) as a base case, line 47
- Slice on every index from 1 to len-1
- If PartA and PartB are palindrome append to the list.
- Continue backtracking only if PartA is palindrome. It becomes an offset now.
"""
class Solution:
def partition(self, s: s... |
5210887824ae21fa69dec0d45dcaa4d36a3388ea | rafael6/p3_essentials | /p3_essentials/build-in_functions/about_map.py | 767 | 4.84375 | 5 | # Map a function to an iterable object; run the function for each item in the iterator object
print('Example 1')
def fahrenheit(c):
return (9.0/5)*c + 32
temps = [0, 64, 80, 93]
print(list(map(fahrenheit, temps))) # With Python 3 must cast map to a list
print('Same as above but using lambda expression which is... |
729704bfaf3222ac850e605af3faa3589c76742a | sprotg/2019_3d | /datastrukturer/linked_list.py | 1,211 | 3.765625 | 4 | class Linked_list:
def __init__(self):
self.head = None
def list_search(self, k):
x = self.head
while x is not None and not (x.key == k):
x = x.next
#Denne metode skal returnere None
# hvis k ikke findes i listen.
# eller skal den returnere x
... |
21579143b9c593d70bd49bc0b3bdb191c52112f9 | muraleo/play_algorithm_python3 | /binarySearch/binarySearch.py | 757 | 3.796875 | 4 | def binarySearchIter(arr, target):
if not arr:
return None
# search in [l,r]
l, r = 0, len(arr)-1
while(l <= r):
mid = l + (r-l)//2
if(arr[mid] < target):
l = mid + 1
elif(arr[mid] > target):
r = mid - 1
else:
return mid
ret... |
75a49b14b46aee3e0554e093c459a8012b631400 | jeeras/allexerciciespython3 | /ex044.py | 876 | 3.890625 | 4 | print('-=' * 11)
print('GERENCIADOR DE COMPRAS')
print('-=' * 11)
gastou = float(input('Quanto você gastou em compras?'))
print('Você vai pagar em: ')
print('[ 1 ]Dinheiro á vista')
print('[ 2 ]Á vista no cartão')
print('[ 3 ]2x no cartão')
print('[ 4 ]3x ou mais no cartão')
opcao = str(input('Sua opção: '))... |
76f579c0ef41abc77e35668d09654e9fdacaea15 | yodji09/Arkademy-Test | /soal4.py | 2,171 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Feb 8 11:24:15 2020
@author: Players
"""
def kataganti(kataasal):
kalimatbaru = []
listkata = list(kataasal)
for hurufganti in listkata:
if hurufganti == 'a':
kalimatbaru.append('u')
elif hurufganti == 'b':
... |
b9d885f03b89aaf571b0af24bc1d225718ea1074 | itsrohanvj/Data-Structures-Algorithms-in-Python | /Data Structures/IMP-BST.py | 3,546 | 3.890625 | 4 | # Returns true if a binary tree is a binary search tree
def IsBST3(root):
if root == None:
return 1
# false if the max of the left is > than root
if (root.getLeft() != None and FindMax(root.getLeft()) > root.get_data())
return 0
# false if the min of the right is <= than root
if (r... |
7b52802663db038295473e82650035fe415f4668 | Blueflybird/Python_Study | /Python_Inty/practise_2020406_args.py | 248 | 4.125 | 4 | '''什么是*args'''
# def add(num1,num2,num3):
# print(num1+num2+num3)
#
# add(1,1,2)
# def add(*args):
# print(sum(args))
#
# add(1,1,2,2)
def add(*args):
for name in args:
print('i love',name)
add('我','是','天','才')
|
8ce9dd805f8692dd0cee869a834301a105afcc83 | gabrielos307/cursoPythonIntersemestral17-2 | /Intermedio/Manejo de Ficheros/modSys.py | 648 | 3.90625 | 4 | ############
# Modulo sys
############
import sys
print(sys.platform) #version instalada 32 o 64 bits
print(sys.version) #version del interprete
print(sys.argv) #parametros por linea de comandos
""">>> import sys
>>> sys.ps1
'>>> '
>>> sys.ps1="$ "
$ print("Hola")
Hola
$ sys.ps1="-> "
-> sys.getre... |
f86364ba2cb64e69ee22736009ae72f4d8bbdfd3 | newmancodes/python_exercises_for_tony | /string_sequences.py | 376 | 3.953125 | 4 | string_values = list(input('Enter a comma separated list of strings: ').split(','))
max_found = ''
for start in range(len(string_values[0])):
for end in range(len(string_values[0][start:])):
look_for = string_values[0][start:start+end+1]
if len(look_for) > len(max_found) and look_for in string_value... |
d6b496d3bea76db1f9f008150dbba15732700722 | giovannyortegon/holbertonschool-machine_learning | /supervised_learning/0x07-cnn/2-conv_backward.py | 3,164 | 4 | 4 | #!/usr/bin/env python3
""" Convolutional Back Prop """
import numpy as np
def conv_backward(dZ, A_prev, W, b, padding="same", stride=(1, 1)):
""" conv_backward - performs back propagation over a
convolutional layer of a neural network.
Args:
dZ is a numpy.ndarray of shape (m,... |
ea314d6bae8572c19d84c0ce5b143594ba3a75a6 | Bharath-6/Assignemnt-module5 | /remove items from dict Q6.py | 484 | 4.125 | 4 |
# Initializing dictionary
test_dict = {"Arushi" : 22, "Anuradha" : 21, "Mani" : 21, "Haritha" : 21}
# Printing dictionary before removal
print ("The dictionary before performing remove is : " + str(test_dict))
# Using del to remove a dict
# removes Mani
del test_dict['Mani']
# Printing dictio... |
34c6793e81d6daaca7b5958586fda3bc66bcd36e | 27Saidou/cours_python | /Algorithme_Permutation.py | 230 | 3.859375 | 4 | # a=5
a=int(input("Entrez la valeur de A!"))
# b=10
b=int(input("Entrez la valeur de B!"))
a=a+b #a=5+10=>a=15
b=a-b #b=15-10=>b=5
a=a-b #a=15-5=>a=10
print("La nouvelle valeur de A est:",a)
print("La nouvelle valeur de B est:",b) |
fb367a7622fa6bf2a1bde591a502cc024cfb888c | ChangxingJiang/LeetCode | /0001-0100/0014/0014_Python_1.py | 870 | 3.90625 | 4 | from typing import List
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
# 处理空列表的情况
if len(strs) == 0:
return ""
# 统计最长的字符串长度
min_len = min([len(s) for s in strs])
# 处理只有空字符串的情况
if min_len == 0:
return ""
for ... |
074e36169c24ced4c1bf69f522073f560b716c01 | Jcontresco/for_loop_basics1 | /for_loop_basic1.py | 2,449 | 3.734375 | 4 | #Básico : imprime todos los enteros del 0 al 150.
'''
for x in range(0, 151,):
print(x)
'''
#Múltiplos de cinco : imprime todos los múltiplos de 5 de 5 a 1,000
'''
for y in range(5, 1001, 5):
print(y)
'''
#Contar, Dojo Way - imprime enteros del 1 al 100. Si es divisible por 5, imprima "Coding" en su lug... |
5567be33551c3b06513c35777752adcc681a53c1 | anselrognlie/kanji-worksheet | /builddb/addkanken.py | 3,388 | 3.546875 | 4 | #!/usr/local/bin/python3
class KanjiRecord:
def __init__(self, kanji, grade, english, readings):
self.kanji = kanji
self.grade = grade
self.english = english
self.readings = readings
self.kanken = None
class KanjiRecordKankenRater:
def __init__(self, db, kk4, kk3, kk2_5... |
9d2b8f0302bc6dd4d7abce1f09cb66a973da5d49 | iamsarin/LearnDataStructuresWithPython | /L01-BasicClass/index.py | 3,750 | 3.78125 | 4 | import math
class Shape(object):
def __init__(self, color: str = 'red', filled: bool = True):
self.__color = color
self.__filled = filled
def get_color(self) -> str:
return self.__color
def set_color(self, color: str):
self.__color = color
def is_filled(self) -> bool... |
9d1ab7f7b6b0b6e9b002ff262ba521c4cca9d7ee | Ramblurr/CodeGolf | /prisoner/warriors/theves.py | 1,392 | 3.53125 | 4 | #!/usr/bin/env python
"""
Honor Among Thieves, by Josh Caswell
I'd never sell out a fellow thief, but I'll fleece a plump mark,
and I'll cut your throat if you try to cross me.
"""
from __future__ import division
import sys
PLUMPNESS_FACTOR = .33
WARINESS = 10
THIEVES_CANT = "E" + ("K" * WARINESS)
try:
histor... |
cd91b449414cf2a28609547d1c62b9019696e6c7 | hengyangKing/python-skin | /Python基础/code_day_12/装饰器/装饰器对有参数函数和无参数函数进行装饰.py | 679 | 3.984375 | 4 | #coding=utf-8
#无参数
def Decorator(funcName):
print("Decorator----");
funcName();
def func_in():
print("func_in-----");
funcName();
print("func_in2----");
return func_in;
@Decorator
def test():
print("-----test-----");
test();
print("-"*100);
#有参数
def Decorator2(func):
print("Decorator2------")
def func_i... |
971964384447e88f3a833ac327124dcf599041e7 | Ehco1996/leetcode | /labuladong/二叉树/105.从前序与中序遍历序列构造二叉树.py | 1,341 | 3.71875 | 4 | #
# @lc app=leetcode.cn id=105 lang=python3
#
# [105] 从前序与中序遍历序列构造二叉树
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def test(self, preorder=[3, 9, 20, 15, 7], ino... |
7c71e2f70997d4520662f78b8ed89edc4d0bfc42 | Parth1267/PythonAssignment | /31-03-2021/factorial.py | 318 | 4.375 | 4 | # Python 3 program to find
# factorial of given number
def factorial(n):
if n < 0:
return 0
elif n == 0 or n == 1:
return 1
else:
fact = 1
while(n > 1):
fact *= n
n -= 1
return fact
# Driver Code
num = 5
print("Factorial of", num, "is",
factorial(num))
# This code is contributed by Dharmik T... |
a2e32c804fe9b5e938b677f2d6e6c3cb687c0d60 | tomaszbobrucki/coffee-machine | /Problems/Calculator/task.py | 543 | 4.03125 | 4 | # put your python code here
first = float(input())
second = float(input())
operation = input()
if operation in '/, mod, div' and second == 0:
print("Division by 0!")
elif operation == '+':
print(first + second)
elif operation == '-':
print(first - second)
elif operation == '*':
print(first ... |
95d86b874511a613aedb42d3a76bf18de0854688 | kartikkodes/String-Practice-Python | /str2.py | 105 | 3.71875 | 4 | n = input("Enter a string")
if len(n) > 1:
print(n[0]+n[1]+n[-1]+n[-2])
else:
print("Empty")
|
855ead9427599664234fe1f7bcc6afec188ac5f2 | xsank/cabbird | /leetcode/largest_rectangle_in_histogram.py | 615 | 3.796875 | 4 | def largestRectangleArea(heights):
heights.append(0)
stack = [0]
res = 0
length = len(heights)
for i in range(1, length):
while stack and heights[i] < heights[stack[-1]]:
h = heights[stack.pop()]
w = i if not stack else i - stack[-1] - 1
res = max(res, w *... |
827a1e0a61c20a92a3874af1fc421614accb160f | urduhack/urduhack | /urduhack/tests/test_stop_words.py | 512 | 3.65625 | 4 | # coding: utf8
""" Test cases updated"""
from urduhack.normalization.character import COMBINE_URDU_CHARACTERS
from ..stop_words import STOP_WORDS
from ..urdu_characters import URDU_ALPHABETS
def test_stop_words():
""" Test case"""
for word in STOP_WORDS:
for chars in COMBINE_URDU_CHARACTERS:
... |
b1c671f8e181b9237d75167f26a29cc398188b8a | Galaxyknight346/Tic-Tac-Toe-AI | /functions.py | 1,929 | 3.859375 | 4 | import random
def makeBoard():
a = " "
board = [[a for i in range(3)]for j in range(3)]
return board
def printBoard(board):
c = 0
for i in range(5):
if i%2 == 0:
print(" "+" | ".join(board[c]))
c += 1
else:
print("---+---+---")
def getInput(board):
userrow = int(input("Row(1... |
99dc795ac864b8d9edbab08955889af6f92437aa | MarvinBertin/NLP-Algorithms | /Levenshtein Distance/LevenshteinNumpy.py | 956 | 3.96875 | 4 | import numpy as np
def levenshtein_numpy(s1, s2, cost_sub):
"""Takes 2 words and a cost of substitution, returns Levenshtein distance.
>>>levenshtein('foo', 'poo', cost_sub=2)
2
>>>levenshtein('intention', 'execution', cost_sub=2)
8
"""
if len(s1) < len(s2): # If one word is ... |
de391043cb48a94f0c1de1445575bddd04097d99 | bai345767318/python-java | /python/python/day01/demo03.py | 976 | 3.75 | 4 | '''
数据类型和变量
'''
'''数据类型'''
# 整数
a = 100
b = -5
c = 0b01010100010101 # 二进制整数
print(c)
d = 0o10 # 八进制
print(d)
e = 0xab12f # 十六进制
print(e)
# 浮点数
f = 123456789.0
g = 1.23456789e8 # 科学计数法
h = 123.45678926
print(g)
# 字符串
i = 'abc' # 用单引号
j = "xyz" # 用双引号
k = "I'm fine"
print(k)
# \ : 转义字符
l = 'I\'m fine'
print(l)
m = ... |
7bdd7f3ba1fe8859c6689a348ed0fcd584d1b2fb | madhuri-kesanakurthi/madhuri-kesanakurthi | /bill1.py | 566 | 3.96875 | 4 | amt=int(input('enter amount'))
if(amt in range(1000,2000)):
print('Discount is 10%')
discount=amt*10/100
bill_amt=amt-discount
elif(amt in range(2000,3000)):
print('Discount is 20%')
discount=amt*20/100
bill_amt=amt-discount
elif(amt in range(3000,5000)):
print('Discount is 30%')
discoun... |
e6e43409b510e3718f0bf6dc09bcbf84f87e8a63 | notruilin/LeetCode | /993. Cousins in Binary Tree/isCousins.py | 647 | 3.625 | 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 isCousins(self, root: TreeNode, x: int, y: int) -> bool:
family = {}
def dfs(node, father):
if n... |
172026d07d1031b5b78a9d8562d3dfd69b7466a0 | Andrewpqc/python_exercises | /python_algorithom/DandC.py | 589 | 3.890625 | 4 | def sum_recursive(l):
"""
递归计算列表的元素之和
"""
if len(l)==1:
return l[0]
else:
return l[0]+sum_recursive(l[1:])
def counter_recursive(l):
"""
递归统计列表的元素个数
"""
if len(l)==1:
return 1
else:
return 1+counter_recursive(l[1:])
def max_recursive(l):
... |
69b1a4abfcc6481bc621602f0745af6d8c56b66c | gemking/COMProj1- | /venv/Scripts/parser.py | 19,461 | 3.5625 | 4 | import re
import sys
with open(sys.argv[1], "r") as file: #opens file
filelines = file.read().splitlines() # reads file and splits lines
file.close() #closes file
insideComment = 0
keywordchecklist = ["else", "if", "int", "return", "void", "while", "float"] # list of all keywords
#keywords = ["if", "else", ... |
32be2d9afd39d2d95a49e6e0ea61322a54237461 | jonachung/uvaproblems | /p10050.py | 635 | 3.515625 | 4 | def main():
testCases = int(input())
for case in range(testCases):
numDays = int(input())
calendar = []
for day in range(numDays):
calendar.append(False)
numParties = int(input())
for p in range(numParties):
partyDay = int(input())
cale... |
dcdce966cb6a996846de18e58c3ca9ce056e9f3f | MohamedMurad/Computer-Vision-Exercises | /Stereo Vision/dynamic_programming_disparity.py | 2,782 | 3.734375 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import numpy as np
import cv2
from matplotlib import pyplot as plt
# Stereo Matching function as per the given paper
def stereoMatching(leftImg, rightImg):
# image shape
(rows, cols) = leftImg.shape
# matrices to store disparities: left and right
left_di... |
9b508908eddd78c221b376455eced77f41a29b98 | BoyYongXin/algorithm | /Problemset/reorder-list/reorder-list.py | 1,293 | 3.75 | 4 |
# @Title: 重排链表 (Reorder List)
# @Author: 18015528893
# @Date: 2021-02-04 15:38:09
# @Runtime: 104 ms
# @Memory: 23.7 MB
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reorderList(self, head:... |
a853f2fb5f6f55804b0c6e8f6025cde2a7962f65 | gistable/gistable | /all-gists/3754590/snippet.py | 456 | 3.78125 | 4 | #!/usr/bin/python
def f(x):
return x*x
def fastmodexp(x, y, mod):
p = 1
aux = x
while y > 0:
if y % 2 == 1:
p = (p * aux) % mod
aux = (aux * aux) % mod
y = y >> 1
return p
def main():
x = int(raw_input("Escribe tu x -> "))
d = int(raw_input("Escribe tu d... |
171599f0f7b2f3127a8a99aa507bfd5b7e548c37 | MasterAlexM/SnakePyGame | /Main.py | 4,589 | 3.609375 | 4 | #Importation
import pygame
import Difficulties
#Initialisaiton des couleurs
WHITE = pygame.Color(255, 255, 255)
GREY = pygame.Color(160,160,160)
GREYY = pygame.Color(100,100,100)
BLUE = pygame.Color(0,0,255)
#Initialisation de l'écran de jeu
pygame.init()
screenSize = 800
screen = pygame.display.set_mode((scre... |
6ebc9777085327e460c1dce3ec45a50607b50bd9 | amensh07/start_python- | /hw - 6.2.py | 383 | 3.578125 | 4 | class Road:
def first(self, _length, _width):
self._length = _length
self._width = _width
def _area(self):
result = self._length * self._width * 25 * 5
print(f'Масса асфальта,необходимая для покрытия всего дорожного полотна = {result}')
road = Road()
road.first(10, 15)
road._... |
1251fb6e265138164951077854cbb4de9c8869ac | jonam-code/Machine-Learning-Laboratory | /2/Machine-Learning-Algorithms-from-Scratch-master/Linear Regression.py | 3,966 | 3.578125 | 4 | #================================================================================================================
#----------------------------------------------------------------------------------------------------------------
# SIMPLE LINEAR REGRESSION
#--------------------------------------------------------... |
9e5724977363a1881194b9852e83833e5528b623 | DanielFHermanadez/Readme | /Trabajo#2/Python/Trabajo#9.py | 128 | 3.875 | 4 | n1 = int(input("Digite el numero: "))
if n1%2==0:
print("el numero es par")
else:
print ("el numero es impar")
|
cbd2ec5da690aadfe2cf1a88adebec5bc83205b4 | rajitbanerjee/kattis | /Datum/datum.py | 364 | 3.515625 | 4 | """https://open.kattis.com/problems/datum"""
D, M = map(int, input().split())
months = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
# 01/01/2009 was a Thursday
day = ["Thursday", "Friday", "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday"]
total_days = 0
for i in range(M):
total_days += months[i]
tota... |
010f96de082eb5d4b463858c8655947a34ba4f16 | Jflinchum/asl-recognition | /util.py | 864 | 3.859375 | 4 |
def getCoord(percentX, percentY, image_size):
"""
Returns the width and height coordinates given the percentage of
the image size you want
percentX - percentage along x axis
percentY - percentage along y axis
image_size - tuple (width, height) of the total size of the image
@return - tuple... |
dd5df38a9abfba10698099e7879146f7f1c1616f | isobelfc/eng84_python_tdd_exercises | /bread_factory.py | 573 | 3.859375 | 4 | # Bread factory exercise
class Bread():
def make_dough(self, ingredient1, ingredient2):
if ingredient1 == "water" and ingredient2 == "flour":
return "dough"
else:
return "recipe unknown"
def bake_dough(self, ingredient):
if ingredient == "dough":
ret... |
e1ab2774e310898d36e9e335363d5499d6f60132 | sandeepkundala/Python-for-Everybody---Exploring-Data-in-Python-3-Exercise-solutions | /ex9_3_4.py | 1,211 | 4.3125 | 4 | # Chapter 9
# Exercise 3: Write a program to read through a mail log, build a histogram using
# a dictionary to count how many messages have come from each email address, and
# print the dictionary.
# Exercise 4: Add code to the above program to figure out who has the most
# messages in the file.
# After all the da... |
dd415d28ad24b63ec47f41c5dc0227a9b8e4d3b1 | iasminqmoura/algoritmos | /Lista 1/Exercicio03.py | 417 | 4.0625 | 4 | print("Insira a idade no formato de Anos/Meses/Dias. Ex: 20 anos, 2 meses e 7 dias")
ano = int(input("Anos: "))
mes = int(input("Meses: "))
dia = int(input("Dias: "))
if(mes < 0 or mes > 12):
print("Um ano possui 12 meses, insira um valor entre 0 e 12")
else:
mesDia = mes * 30
anoDia = ano * 365
... |
e755ba689fd28230f6bdf13b7dd74d7c59d72908 | TCLloyd/pwp-capstones | /TomeRater/TomeRater.py | 5,750 | 3.828125 | 4 | class User(object):
def __init__(self, name, email):
self.name = name
self.email = email
self.books = {}
def get_email(self):
return self.email
def change_email(self, address):
self.email = address
print("Email has been changed to {}".format(address))
def ... |
02b50ab3efd5c50ceeab8c1263f53ec86d130b13 | RishabhKatiyar/CorePython | /LeetCode/Problem34.py | 1,355 | 3.609375 | 4 | from typing import List
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
index = self.binarySearch(nums, target, 0, len(nums) - 1)
#print(f'Index = {index}')
if index == -1:
return [-1, -1]
right_index = index
left_index = index
... |
84f34f672867723f46d7230483b5e0826741c8a6 | DukhDmytro/py_levenstein | /levenstein.py | 672 | 3.71875 | 4 | """module for creating matrix"""
import numpy
def dist(strf: str, strs: str) -> int:
"""calculate Levenstein distance"""
rows = len(strf) + 1
cols = len(strs) + 1
matrix = numpy.zeros((cols, rows))
matrix[0, :] = numpy.arange(rows)
matrix[:, 0] = numpy.arange(cols)
for i in range(1, cols)... |
36affac2c3a215808c46d0e99c6da5188f4d0dc9 | Journey99/boj-studyfolio | /class1/1157.py | 478 | 3.84375 | 4 | word = input()
word = word.upper() # 문자열을 대문자로 변경
# 알파벳 개수 세기
dic = {}
for i in word:
if i in dic:
dic[i] += 1
else:
dic[i] = 1
# 가장 많이 사용된 알파벳 찾기
max_key = max(dic, key=dic.get) # key를 기준으로 최대값을 찾는다.
max_value = dic[max_key]
dic.pop(max_key) # max_key위치에 있는 요소를 pop
if ma... |
3ee8b10f97971de017fcadafaa67d4f0a91225a6 | mengyangbai/leetcode | /practise/replacewords.py | 1,432 | 3.9375 | 4 | class Node(object):
def __init__(self):
self.children = dict()
self.isWord = False
class Trie(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = Node()
def insert(self, word):
"""
Inserts a word into the tr... |
b49f3cf68908bf5aeb60aab7f3f0e2c44bbdb10d | simrangrover5/Advance_Pythonbatch | /dbms/sqlite1.py | 528 | 3.953125 | 4 | import sqlite3 as sql
db = sql.connect("bank.db")
c = db.cursor()
#cmd = "create table customer(id integer,name varchar(50),address varchar(100))"
#c.execute(cmd)
while True:
id1 = int(input("Enter your id : "))
name = input("Enter your name : ")
address = input("Enter address : ")
cmd = "insert into... |
9670c74f92863aa5a7e9c5474d9c8a8cb6b8a404 | adelaideramey/Formation-Data-Science | /Exo 2 - Formation Datascience.py | 4,170 | 4.15625 | 4 |
# coding: utf-8
# In[7]:
# A. donuts
# Given an int count of a number of donuts,
# return a string of the form 'Number of donuts: ',
# where is the number passed in. However, if the count is 10 or more, then use the word 'many' instead of the actual count.
# So donuts(5) returns 'Number of donuts: 5' an... |
cdf5093e8b9cc5047cbe4aa0576baff3d7e9f0d6 | narenchandra859/DAALab | /Final Python Solutions/3a.py | 208 | 3.53125 | 4 | g = {
0: [1,2,3],
1: [0,2,4],
2: [0,1,4],
3: [0,4],
4: [1,2,3]
}
visited = [0 for i in range(5)]
def dfs(s):
visited[s]=1
print(s," --->")
for i in g[s]:
if visited[i]==0:
dfs(i)
print(dfs(0)) |
8c9c3fa4d04635480dc8c3653403f448eea4b7aa | amanjn38/pythondemo | /Practice Problems/pp.py | 656 | 4.1875 | 4 | print("Enter the numbers of the list one by onw\n")
size = int(input("Enter size of list\n"))
mylist = []
for i in range(size):
mylist.append(int(input("Enter list Element")))
print(f"Your list is {mylist}")
reverse1 = mylist[:]
reverse1.reverse()
print(f"My first reversed list is {reverse1}")
reverse2 = mylist[... |
b3d95c3e64c2015c027eca5e91153c283ebc9d13 | hsrwrobotics/Robotics_club_lectures | /Week 2/Functions/simple_echo.py | 681 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 21 16:15:36 2019
HSRW Robotics
@author: mtc-20
"""
# Use a variable to store the input string
string = input("Shout out something: ")
# This is like a confirmation check stating what is going to be
# echoed to cross check th input
print("Echoing ", string)
... |
8a7672fe3736e23df9646f92e6f3f5afbbdae370 | ParisRohan/Python_Projects | /MultipleInputs.py | 225 | 3.828125 | 4 | #Given 3 integers A, B, C. Do the following steps-
#Swap A and B.
#Multiply A by C.
#Add C to B.
#Output new values of A and B.
a,b,c=map(int,input().split()) #code to take multiple inputs
a,b=b,a
a=a*c
b=b+c
print(a,b) |
971a45935891dfdc1d2f5ef3cf233e2ff201abec | takayuu1999/Pythin-study | /11ユーザ定義クラス/11_11.py | 6,511 | 3.765625 | 4 | import math
import copy
# テスト結果の順位の順番に並べて表示する
class School:
""" 国語の点数リスト """
__jap_score_list = []
""" 数学の点数リスト """
__math_score_list = []
""" 英語の点数リスト """
__eng_score_list = []
""" 学生リスト """
student_list = []
def get_student_list(self):
return self.student_list
... |
cbec1051e0bc11ec33814afb151868f7ba2bb340 | nikhilsharan/python-learning | /day4-ex-abc.py | 156 | 3.75 | 4 | def abc(a,b,c):
if a+b == c:
return True
else:
return False
a = int(input())
b = int(input())
c = int(input())
print(abc(a,b,c)) |
86c13ed87e38dae4b5eee5a6f08ea3a0fc2a2747 | Neil-C1119/Practicepython.org-exercises | /practicePython5.py | 953 | 4.125 | 4 | # I'm going to make this more complicated than the exercise calls for
# Import the random module
import random
# Create two empty lists to compare
list1 = []
list2 = []
# Create an empty list to push any similar numbers into
listSame = []
# For loops to fill the two lists with random numbers to compare
... |
563c087a7a8cf2472812b00a9025872cb2836040 | boisdecerf/jeudupendu | /jeudupendu.py | 2,526 | 3.84375 | 4 | import random
title = "Jeu du pendu"
print("---{:^14}---".format(title))
playing = True
while playing :
# Counting the numbers of lines in the file
def len_file(file) :
with open(file) as f :
for index, line in enumerate(f) :
pass
return index + 1
lenFile= len... |
81a509d34b1289560e111cfaf2103fe29f327009 | AlymbaevaBegimai/TEST | /2.py | 401 | 4 | 4 |
class Phone:
username = "Kate"
__how_many_times_turned_on = 0
def call(self):
print( "Ring-ring!" )
def __turn_on(self):
self.__how_many_times_turned_on += 1
print( "Times was turned on: ", self.__how_many_times_turned_on )
m... |
92d154c9f27fd1b215694f960353d856d08ac952 | kmenon89/python-practice | /cond_challenge_ip_ad.py | 990 | 4.21875 | 4 | #program to get ip address as input , count number of segments in it and length of each segments
#get ip adress from user
ip_address=input("please enter the ip address:")
len_ip=len(ip_address)
segment=0
segment_length=""
#count the number of segments
if ip_address:
for i in range(0,len_ip):
... |
696342915b27268c8f5669456659cf6cdebd489d | Dheeraj-1999/interview-questions-competitve-programming | /Comp pro qus and sol/gfg/general/prime/1 prime bruteForce.py | 297 | 3.828125 | 4 | import math
def prime(n):
for i in range(2, int(math.sqrt(n))+1):
if(n%i == 0):
return False
return True
def nPrimes(n):
primes = []
for i in range(n+1):
if(prime(i)):
primes.append(i)
return(primes)
n = int(input())
print(nPrimes(n)) |
8184f753c482209b51abd0b1e909cdd4a974587c | vidojeg/python | /cube.py | 277 | 3.796875 | 4 | from random import *
mini = 1
maxi = 6
def randomly():
x = randint(mini, maxi)
print x
while (1):
print ("Would you like run again:")
text = raw_input("")
if text == "":
randomly()
elif text == "no":
print "Good bye"
break
|
225bae46a8892d2b3c434a27d85dc23efb2c0fac | otisscott/1114-Stuff | /Lab 5/romanbullshit.py | 576 | 3.640625 | 4 | # Otis Scott
# CS - UY 1114
# 4 Oct 2018
# Homework 4
num = int(input("Enter a decimal number: "))
orig = num
roman = ""
while num > 0:
if num > 1000:
roman += "M"
num -= 1000
elif num > 500:
roman += "D"
num -= 500
elif num > 100:
roman += "C"
num -= 100
... |
84233c76b2937cf7f7ec0b7c1315c5be14702670 | fuzhanrahmanian/python_euler | /fibonacci.py | 233 | 3.875 | 4 | def fibonacci(x, y, n):
even_num = list()
while n < 4000000:
if n % 2 == 0:
even_num.append(n)
y = x
x = n
n = x + y
return sum(even_num)
fibonacci(1, 0, 1)
print("Hello")
|
3db4cebeecf7adb1e2b531f8a867c86ed293a93f | hsmith851/Python-Projects | /Adding Numbers Input:Output.py | 315 | 4.0625 | 4 | from numpy import double
#program to add two numbers
#Store input numbers
from numpy import double
num1 = input('Enter the first number: ')
num2 = input('Enter the second number: ')
# Adding two nos
sum = double(num1) + double(num2)
# printing values
print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.