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 |
|---|---|---|---|---|---|---|
41013f1755fb67eb83fc864e9b6b6d5ce1b524ab | Poolitzer/telegram_bot_frontend | /conversation.py | 378 | 3.53125 | 4 | # -*- coding: utf-8 -*-
class Conversation(object):
def __init__(self, worker, user, type):
if worker == user:
raise ValueError("Worker can't be the same as user")
self.worker = worker
self.user = user
self.type = type
def __repr__(self):
return "Conversat... |
0b8b33519a877bbc9f8d81f3cbca2a196a75d5da | dhazu/Mygit | /python_workbook/if-elif/ex56.py | 2,791 | 4.1875 | 4 | """Exercise 56: Cell Phone Bill
A particular cell phone plan includes 50 minutes of air time and 50 text messages
for $15.00 a month. Each additional minute of air time costs $0.25, while additional
text messages cost $0.15 each. All cell phone bills include an additional charge of
$0.44 to support 911 call centers, an... |
b0c3cbf5423694c3695dec0db4f29440f47320f2 | KETULPADARIYA/Computing-in-Python | /5.2 Control Structures/4 Functions/23 VowelsAndConsonants.py | 1,398 | 4.375 | 4 | #In this problem, your goal is to write a function that can
#either count all the vowels in a string or all the consonants
#in a string.
#
#Call this function count_letters. It should have two
#parameters: the string in which to search, and a boolean
#called find_consonants. If find_consonants is True, then the
#functi... |
b12ac80d77148ab34b40095937d15f56083a5e53 | incipient1/Introduction_To_Algorithms_3rd_py3 | /02_sorting_and_order_statistics/08_3_quick_sort_hoare.py | 483 | 3.546875 | 4 | def hoare_partiton(A,p,r):
x = A[p]
i = p
j = r
while True:
while A[j] > x:
j -= 1
while A[i] < x:
i += 1
if i < j:
A[j], A[i] = A[i], A[j]
else:
return j
def quick_sort_hoare(A,p,r):
if p < r:
q = hoare_parti... |
58adaf34e8177b99f19b084358684f51ec9da485 | crossin/Crossin-practices | /python_weekly_modual/collections-ordereddict.py | 565 | 3.71875 | 4 |
import collections
dic = {'c':1,'a':2,'b':3}
# sorted_tuple = sorted(dic.items(),key=lambda x:x[0])
new_dic = collections.OrderedDict(dic)
print(new_dic)
#
# d = {}
# d['a'] = 1
# d['b'] = 2
# d['c'] = 3
# print(d)
# 提取 items
# print (new_dic.items())
# # 提取 keys
# print(new_dic.keys())
# # 提取 ... |
6d330b264c3f828bafb7bbcd64f5accdc0cef368 | ElielMendes/Exercicios-da-Faculdade-e-projeto-de-Numerologia-Karmica | /.vscode/aula7.py/ex5.py | 775 | 3.796875 | 4 | aprovado = 0
exame = 0
reprovado = 0
acm_media = 0
for cont in range(1,7):
print(f'----------Notas do {cont}ª aluno------------- ')
n1 = float(input('Digite a 1ª nota: '))
n2 = float(input('Digite a 2ª nota: '))
media = (n1 + n2) / 2
acm_media += media
if media < 3:
reprovado += ... |
57d1fbe543d1e2fcbd048b6cc089e9eda1c03b5f | mayank-prasoon/folder_manager | /Folder Manager/main.py | 4,507 | 3.53125 | 4 | from tkinter import Tk
from tkinter.filedialog import askdirectory
import databasemanager as DM
import foldercreator as fc
import os
import exicutesoftware
import tomatotimer as tt
dm = DM.DatabaseManager()
class Welcome:
def welcome(self):
welcome = input(
"\twelcome to the... |
618f678090a964caa78ef86e8199a2e3390ee522 | ArlexDu/PythonWeb | /exercise/thread.py | 999 | 3.671875 | 4 | '''
import time, threading
def loop():
print('thread %s is running...' % threading.current_thread().name)
n = 0
while n < 5:
n += 1
print('thread %s >>> %s' % (threading.current_thread().name,n))
time.sleep(1)
print('thread %s ended.' % threading.current_thread().name)
if __name__ == '__main__':
print('th... |
323dbdfe8a7bfeeaa473b3dea54404f054360187 | hguochen/algorithms | /python/interviews/g_interview.py | 1,670 | 4.1875 | 4 | #Say you're dealing with data that has a lot of repeated characters in it. You'd like to take advantage of that to compress the data. In particular, you are given the following run-length encoding scheme: An encoded string is normally passed through verbatim. However, if there is a decimal number followed by the charac... |
c27e175c8746d55593c950fffb25ec06556774f4 | praveenRI007/Basics-of-python-programming | /basics of python programming in 1hour/python basics #5_if else booleans.py | 1,406 | 4.1875 | 4 |
if True :
print('condition was true')
language = 'python'
if language == 'java':
print('language is java')
elif language =='python':
print('language is python')
else :
print('no match')
# and or not
user = 'admin'
logged_in = True
#and
if user == 'admin' and logged_in:
print('admin page')
el... |
78a7d53202e3e7b217c5c57b06bea72e1f07ca0d | GitHub-zd/python-test | /func-test.py | 1,877 | 3.796875 | 4 | def math_func(maths):
if 0 <= maths <= 100:
if maths < 75:
print("数学的评价为:bad")
elif 75 <= maths <85:
print("数学评价为:good")
else:
print("数学评价为:great")
else:
print("分数输入错误,请重新输入")
def english_func(english):
if 0 <= english <= 100:
if e... |
430beae98f2017f6546c686106a76a6f452b97cf | Ashleshk/Python-For-Everybody-Coursera | /Course-2-python_data_structures/assignment9.4_dictionaries_count.py | 1,074 | 4.03125 | 4 | # 1. Get file name
# 2. Open file
# 3. Look for 'From' each line
# 4. Get second word from each line
# 5. Create dictionary
# 6. Map address/count to dictionary
# 7. Count most common using maximum loop
# 1. Get file name
# fname = raw_input('Enter file: ')
# 2. Open file
fhandle = open('mbox-short.txt')
# 5. Create... |
26c5b3b335cf32130f39ee94e6d1dbfa0ab1f1a7 | JonatanCadavidTorres/Courses_Platzi | /algorithms/lineal_search.py | 596 | 3.90625 | 4 | import random
def lineal_search(the_list, objective):
match = False
for element in the_list: # O(n)
if element == objective:
match = True
break
return match
if __name__ == '__main__':
list_size = int(input('What is the size of the list? '))
objecti... |
8a9e99b3b72069278dcd1d5d2287399ae80390ee | NanaAY/cs108_projects | /homework07/find_genes.py | 1,734 | 4.28125 | 4 | '''A Python program that displays all the genes in a genome
Created Spring 2018
Homework07
@author: Nana Osei Asiedu Yirenkyi (na29)'''
#Function definition for finding a gene
def find_gene(genome):
'''receives a genome and returns all possible genes or false if otherwise'''
if "ATG" in genome:
... |
739a7b73a2018df0ec1d710e9d90ed98b2dbb999 | Alleinx/Notes | /modeling/Integral/Area.py | 615 | 4.09375 | 4 | #This program calculate the Area under a curve using "Finite sums"
# function : f(x) = x^2
# Domain : [0,1]
import math
def calculate_value(x):
return pow(x, 2)
def main():
slice_num = 8 #The more slice token, the more precise the result is.
stride = 1 / slice_num
lower_area = 0
upper_area = 0
... |
93f37467fb36e2e39628f7d45aeb85bd4072717d | macrespo42/Bootcamp_42AI | /day00/ex07/filterword.py | 350 | 3.640625 | 4 | import sys
import string
def error():
print("ERROR")
sys.exit(0)
if (len(sys.argv) == 3):
try:
min = int(sys.argv[2])
except:
error()
for ch in string.punctuation:
sys.argv[1] = sys.argv[1].replace(ch, "")
lst = sys.argv[1].split(" ")
final = []
for elt in lst:
if (len(elt) > min):
final.append(elt... |
2c40bd1503e27ac827d1ec689110f35de5214abd | openjamoses/ML-Kaggle | /Preprocessing.py | 3,724 | 4.0625 | 4 | """ Functions used to vizualize, process, and augmente the Image dataset """
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
def plot_digit(Xrow):
"""
Plot a single picture
"""
size = int(np.sqrt(Xrow.shape[-1]))
image = Xrow.reshape(size, size)
plt.imshow(image, ... |
ee9ee336ac38914526a2bfae9e3625617672136d | gabriellaec/desoft-analise-exercicios | /backup/user_061/ch68_2019_04_03_21_56_51_670379.py | 190 | 3.609375 | 4 | def separa_trios(lista_alunos):
i=0
while i<len(lista_alunos):
if lista_alunos % 3 != 0:
trio[0] = (lista_alunos % 3)
trios.append(lista_alunos[::3])
|
dbe5f7d024f7a94efce2d95bd0f1e96cf3004d3c | y43560681/y43560681-270201054 | /lab7/example1.py | 280 | 4.0625 | 4 | n = int(input("How many names and ages will you enter? "))
name_store = []
age_store = []
a = ''
for i in range(n):
name = input("Please enter a name : ")
age = input("Please enter a age : ")
if int(age) > 18:
name_store.append(name)
for i in name_store:
print(i) |
3dbf52c53dafe2e3cfb6ec3a65dda80045452847 | Mostofa-Najmus-Sakib/Applied-Algorithm | /Leetcode/Python Solutions/Recursion & Backtracking/GenerateParentheses.py | 1,876 | 3.921875 | 4 | """
LeetCode Problem: 22. Generate Parentheses
Link: https://leetcode.com/problems/generate-parentheses/submissions/
Language: Python
Written by: Mostofa Adib Shakib
Time complexity: Bounded by a catalan number
"""
"""
Conditions that makes parenthesis balanced:
1) An empty string is a string in which parenthesis are... |
b2f3b96ef02f284510f786dc46c9571711bab788 | tashakim/puzzles_python | /checkSubtree.py | 586 | 3.90625 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSubtree(self, s, t):
def match(s, t):
if not s or not t:
return s ... |
ee052bca48277341e4f0695b6ab4c6521794a356 | frimmy/LPTHW-exs | /ex15.py | 717 | 4.09375 | 4 | #imports from the python system the argv class/features/modules
from sys import argv
#defines two arguments entered on the CL
script, filename = argv
#defines txt as the file name enetered on the CL and
# assigns the txt obj to the variable 'text'
txt = open(filename)
# prints a line and the filename entered on the ... |
63196d41c5693e89f888d3edb65638496a4fe826 | zinechant/code | /ita/cities.py | 2,339 | 3.5 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'closestStraightCity' function below.
#
# The function is expected to return a STRING_ARRAY.
# The function accepts following parameters:
# 1. STRING_ARRAY c
# 2. INTEGER_ARRAY x
# 3. INTEGER_ARRAY y
# 4. STRING_ARRAY q
#
MA... |
ccf7a0c8ccf77c29b20dcb5cdebc3646cb897c4e | maxvalrus/python_learn | /codefights/checkPalindrome.py | 294 | 3.625 | 4 | def checkPalindrome(inputString):
i = 0
max = len(inputString) // 2
while i <= max:
if inputString[i] == inputString[-i - 1]:
i += 1
else:
return False
return True
if __name__ == "__main__":
print(checkPalindrome('aabaa')) |
66600da7f2d7f9cdf35eb2006d1862652c2c4f8b | NicholasArnaud/Python_FileUtility | /Renaming/music.py | 524 | 3.5625 | 4 | import os
def change_name(location):
directory = os.listdir(location)
os.chdir(location)
newlist = []
for filename in directory:
if filename.endswith(".mp3"):
newlist.append(filename)
os.rename(filename, filename[:-4])
if filename.endswith(" - Copy"):
... |
f949cafaa54c7287357cec2bc61c0ce77c014f28 | Darshan1917/python_complete | /demo_oops.py | 904 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 6 17:44:39 2018
@author: dumapath
"""
# this is a place we have oops concepts demo
# class creation
import datetime
class User:
#init is a constructer and must be present in the program
def __init__(self,fname,lname,dob):
self.fname = fname
... |
daa3ae1166bb20ee631f9281050d758fd2c1b8ed | langet0695/minigenerator | /main.py | 6,488 | 3.71875 | 4 | # Author: Travis Lange
# Description: This is an experiment to develop an algorithm that can generate a mini cross word (5x5) puzzle.
# TO DO:
# Identify why there is a possible ordering of words that won't work
import random
import json
# import dictConfig
# possible_words = dictConfig.WordGenerator()
#
#
#
possible... |
f826fcf0ba599a8a9547aaed6f41bfc93cab28b6 | chaofan-zheng/python_leanring_code | /month01/面向对象/类和对象/day02/demo03-属性各种写法.py | 1,184 | 4 | 4 | """
属性各种写法
"""
"""# 读写属性
# 适用性:有一个实例变量,但是需要对读取和写入进行限制
# 快捷键:props + 回车"""
class MyClass:
def __init__(self, data=0):
self.data = data
@property
def data(self):
return self.__data
@data.setter
def data(self, value):
self.__data = value
m01 = MyClass(10)
print(m01.data)
... |
adbd066d244ff11f89e47a5bbd29d4040e1fcfac | HomeroValdovinos/hello-world | /Cursos/devf/Lesson03/position_string.py | 134 | 3.515625 | 4 | my_list = [1, 2, 3, 4, 5, 6]
print my_list[2]
print my_list[2:5]
print my_list[5:]
print my_list[:5]
print my_list[:]
|
c4add82b0a1a6c8ab5f3e6e89881ac15f0f82f76 | Carvanlo/Python-Crash-Course | /Chapter 9/number_served.py | 714 | 3.671875 | 4 | class Restaurant():
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.number_served = 0
def describe_restaurant(self):
print(self.restaurant_name.title())
print(self.cuisine_type)
def open_restaurant(self):
print(self.res... |
6d2c6af169b2217822f346f13a9461d8ddc7638d | charanvengatesh/Main-Repo | /Mini-Programs/Python/Numbers to Words.py | 5,861 | 3.921875 | 4 | '''
NumWord v2.9.0
'''
print('This is an amazing 5 digit Number to Word Converter\nIt was a 3-day challenge\nHere you go!!\n')
num = input(' Number (0 - 99999): ')
def Num(Number):
Number = str(Number)
digit1 = {
1:'one',
2:'two',
3:'three',
4:'four',
5:'five',
6:'six',
7:'seven',
8:'eight',
9:'nine',... |
14c4826d2f6903432d3da2eee1c97e62191b2d2a | Faikavi/HW1_Image-Processing | /etc_function.py | 415 | 3.5 | 4 | def createHistogram(converted_img):
grey_level = []
frequency = []
histogram = {}
for i in range(len(converted_img)):
if converted_img[i] not in grey_level:
grey_level.append(converted_img[i])
grey_level.sort()
for i in range(len(grey_level)):
frequency.append(convert... |
29ea61555556ef84eb71f88b4d76dcdcdc48a63c | teenitiny/py-exercise | /algorithm/stack_algo.py | 2,028 | 3.734375 | 4 | """
Evaluating Postfix Expressions
Create a new stack
While there are more tokens in the expressioin
Get the next token
if the token is an operand
Push the operand onto the stack
Else if the token is an operator
Pop the two operands from the stack
Apply the operator to the two operands just opped
Push the res... |
334f08eb931bac3a6aa8fc9320188f76adfcfd39 | Dagmoores/PythonStudies | /Projeto_Integrador_Estudos/problema_pratico3-3.py | 821 | 3.9375 | 4 | #Retirado do livro Introdução à Computação em Python - Um Foco no Desenolvimento de Aplicações - PERKOVIC, Ljubomir
#Traduza estas declarações em instruções if/else do Python:
#(a)Se ano é divisível por 4, exiba 'Pode ser um ano bissexto.'; caso contrário, exiba 'Definitivamente não é um ano bissexto.'
#(b)Se a list... |
941c4c67aede72d0887d7527e5038b1b003e5774 | dwillia2/pythonStuff | /modules/printModule.py | 126 | 3.859375 | 4 | def printNoNewLine(string):
print(string, end = "")
def reverseString(string):
tempString = string[::-1]
return tempString |
3cac1017099644cbb46869b1a43ba752bbcc1978 | arslanislam845/DevNation-Python-assignments | /5.May26/q4.py | 839 | 4.03125 | 4 | import math
def Factors(x):
print("Factors of the given number is : ")
for i in range(1,x+1):
if x % i==0:
print(i)
def primeFactors(n):
print("Prime factors of the given number is : ")
while n % 2 == 0:
print (2)
n = n / 2
for i in range(3,int(math.sqr... |
6b54c8b15680678196904f7ab4f8a99b8977d141 | luizdefranca/Curso-Python-IgnoranciaZero | /Aulas Python/Exercícios Extras/Python Brasil/3 - Estrutura de Repetição/Ex 44.py | 1,351 | 4.1875 | 4 | """
44. Em uma eleição presidencial existem quatro candidatos. Os votos são
informados por meio de código. Os códigos utilizados são:
o 1 , 2, 3, 4 - Votos para os respectivos candidatos
o (você deve montar a tabela ex: 1 - Jose/ 2- João/etc)
o 5 - Voto Nulo
o 6 - Voto em Branco
Faça um programa que calcule e mostr... |
26cb6dacb4eaaa19c81c50f20f3867e6158dd0d7 | ArhiTegio/GB-Python-Basic_2 | /Lesson_2/03.Months.py | 960 | 3.8125 | 4 | print('Выбор месяца но номеру')
check_months = frozenset(['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'])
months_dict = {'1': 'Январь', '2': 'Февраль', '3': 'Март', '4': 'Апрель', '5': 'Май', '6': 'Июнь', '7': 'Июль',
'8': 'Август', '9': 'Сенябрь', '10': 'Октябрь', '11': 'Ноябрь', '12': '... |
4f5d64ba60ddd719331d54f514a6154d6c1b6081 | karuns/pylearn | /oop/CatClass.py | 268 | 3.5625 | 4 | class Cat:
number = 0
def __init__(self,color,legs):
self.color = color
self.legs = legs
felix = Cat("red",4)
felix.number = felix.number+2
print felix.color
print felix.legs
garf =Cat("b",3)
Cat.number = Cat.number+1
print Cat.number |
e48318e1dc8b9e8e57699af9d4654f3f9403ddf0 | akjalbani/Test_Python | /Misc/Network/validate_ip.py | 341 | 3.796875 | 4 | def validate_ip(addr):
a = addr.split('.')
if len(a) != 4:
return False
for x in a:
if not x.isdigit():
return False
i = int(x)
if i < 0 or i > 255:
return False
return True
addr=input("Enter the IP address:")
address=validate_ip(addr)
if address:
print('Valid IP')
else:
... |
bff6baaaf2c7d54fa533569433574a815a70603b | t0mm4rx/ftprintfdestructor | /inputs.py | 2,306 | 3.640625 | 4 | import random
import string
def random_string(length):
letters = string.ascii_letters + string.digits + " "
return ''.join(random.choice(letters) for i in range(length))
def input_string():
choice = random.choice([0, 1, 2])
if (choice == 0):
return '"{}"'.format(random_string(random.randint(1, 100)))
if (choic... |
f13e9a92a05f1945b6a17e947a57ad93d49f2dde | kirankhandagale1/Python_training | /Excercise2/p2_1.py | 394 | 3.734375 | 4 | # Write the program to print vowels and consonant letters from gnulinux.
while True:
print("....print only constant and vowels...")
input1=raw_input("Enter the char.....")
if(input1>='0' and input1<='9'):
print("costant no = ",input1)
elif(input1=='a' or input1=='e' or input1=='i' or input1=='o' or input1=='u')... |
feeade4ea30a3df0b610d1c7f77b12e57cdb6903 | runzezhang/Code-NoteBook | /lintcode/1266-find-the-difference.py | 1,018 | 3.703125 | 4 | # Description
# 中文
# English
# Given two strings s and t which consist of only lowercase letters.
# String t is generated by random shuffling string s and then add one more letter at a random position.
# Find the letter that was added in t.
# Have you met this question in a real interview?
# Example
# Example:
# ... |
3ed66bda5cafffea672259efef5e1c92b2c219c3 | suryak24/python-code | /45.py | 95 | 3.6875 | 4 | n=int(input("Enter the number:"))
count=1
while count<=n:
n=n/10
count+=1
print(count)
|
f8e09d8c55630500086d544b45fba87f76c2afcb | Picolino66/resmat-1-2 | /Resmat1/amador e carol/carol.py | 7,358 | 3.78125 | 4 | from math import* #importa funções matemáticas
import math
print ("Digite o nome do arquivo: ")
nome_arq=input()
arquivo = nome_arq + '.dat' #junção de string para ler o nome_arq do escrita
carregar = open(arquivo, 'r') #abrir escrita para carregar
#ler as entradas do escrita
figuras = int(carregar.readline())
ares... |
d3c4a30a051ccb8ae4e7abb108c45879733a6749 | tzvetandacov/Programming0 | /week8/is_increasing.py | 182 | 3.8125 | 4 | def is_increasing(seq):
for index in range(0, len(seq) -1):
if seq[index] > seq[index + 1]:
return False
return True
print(is_increasing([1,2,3,6,7]))
|
f21ab28dffd50fa592a13fab5e71f5aca37d4316 | mondas-mania/advent-of-code | /2022/Day_1/day1_part2.py | 338 | 3.59375 | 4 | input_file = open('input.txt', 'r')
calories_sums = [sum([int(calorie) for calorie in calories.split('\n')]) for calories in input_file.read().strip().split('\n\n')]
sorted_calories = sorted(calories_sums, reverse=True)
top_three = sorted_calories[0:3]
print(f"The top three elves have a total of {sum(top_three)} calori... |
be6d9bf14f8297dd36d57ba87fcba5dc63a97825 | chenweisomebody126/codebase | /python/log_base/memory_size.py | 1,322 | 3.671875 | 4 | from __future__ import division
import sys
import psutil
def get_object_size(obj, units='Mb'):
"""Calculate the size of an object.
Parameters:
obj (obj or str or array): Object.
units (str): Units [bytes, Kb, Mb, Gb]
Returns:
size (float): Size of the object.
Examples:
... |
e154d1366e2cb527ce0b897002f601b693c50ba2 | kalorie/RobotDemo | /demo/MyObject.py | 330 | 3.625 | 4 | class MyObject(object):
def __init__(self, name=None):
self.name = name
def eat(self, what):
return '%s eats %s' % (self.name, what)
def __str__(self):
return self.name
def get_variables(self):
return {'MY_OBJECT': MyObject('Robot'), 'MY_DICT': {1: 'one', 2: 'two', 3: ... |
f36a12da5fbf437be1bc6128fc84e88e5b46701f | eestevez/swighandles | /testMemory.py | 791 | 3.5625 | 4 | from standard import A,Handle_A, simpleFunction
def myfun(mya):
ha = mya.handle()
count = mya.RefCount()
print "Refcount after ha=handle():", count
print "\nCreate new handle:"
ha2 = Handle_A(mya)
count = mya.RefCount()
print "Refcount after creating new handle ha2:", count
apointer =... |
001957658ab4e3eb85397c97ccbaf079c95fb566 | ujjwalthapa/Election_results_python | /PyPoll/poll.py | 2,345 | 3.6875 | 4 |
#Importing operating software and csv module
import os
import csv
#Creating lists
voter_id = list()
candidate = list()
county = list()
#Declaring variable value
total_profit = 0
#Set path for the csv file
csvpath = "../Resources/election_data.csv"
#Open the CSV file
with open(csvpath,newline='') as csvfile:
... |
3c458282f8fc7dbb9ecc2985aa55ec4a99ce356e | toothless92/linear_gradient_py | /lingradpy.py | 4,454 | 4.09375 | 4 | class Linear_Gradient_Maker():
'''
This module is for calculating the hex color codes of a gradient going through
an arbitrary number of colors. The result is a linear gradient between each
ajacent color.
Written by Mike Reilly. Please contact mreilly92@gmail.com with questions.
'... |
05989c515b8b27de343a117e0f79996b77e9de15 | yangshimin/spider | /设计模式/duck_pattern.py | 1,783 | 3.5 | 4 | from abc import ABCMeta, abstractmethod
class QuackBehaivor(metaclass=ABCMeta):
@abstractmethod
def quack(self):
raise NotImplementedError
class Quack(QuackBehaivor):
def quack(self):
print('我是一只会Quack的鸭子')
class SQuack(QuackBehaivor):
def quack(self):
print('我是一只会SQuack的鸭子... |
d7b5069527ede2736fa8d507cdd8ae5cff3f1a3e | HendersonSC/project_B | /projectB.py | 4,006 | 4.15625 | 4 | # COSC 505: Summer 2019
# ProjectB - Group 12
# Damilola Olayinka Akamo
# Nicole Callais
# Shane Christopher Henderson
# Stephen Opeyemi Fatokun
#
# 07/22/2019
# A python program retrieving lotto data from an internet website, and plotting
# the frequency of each number to show the most frequently occuring number.
from... |
cf3fd7d6d3dfab837dba524bd1c1e9ab213d45ed | Katherinaxxx/leetcode | /502. IPO.py | 2,154 | 3.5625 | 4 | '''
Author: Catherine Xiong
Date: 2021-09-08 19:16:27
LastEditTime: 2021-09-08 19:33:26
LastEditors: Catherine Xiong
Description: 给你 n 个项目。对于每个项目 i ,它都有一个纯利润 profits[i] ,和启动该项目需要的最小资本 capital[i] 。
最初,你的资本为 w 。当你完成一个项目时,你将获得纯利润,且利润将被添加到你的总资本中。
总而言之,从给定项目中选择 最多 k 个不同项目的列表,以 最大化最终资本 ,并输出最终可获得的最多资本。
来源:力扣(LeetCode)
链接:h... |
b0811c3831e5d7dfddafbd32f9016bac39192027 | divyat09/Stance_Classification_Tweets | /Feature.py | 7,380 | 3.5 | 4 | import re
import pandas as pd
from collections import Counter
'''
#Making the matrix automatically using sklearn
vectorizer = CountVectorizer(lowercase=True, stop_words="english")
matrix = vectorizer.fit_transform(list_tweets)
print matrix.shape
'''
#Calculate the count of word specificially when it occurs with the ... |
c9c54ae12c2f4a129034887957baf6f94452221d | gitHirsi/PythonNotes | /001基础/019面向对象_继承/04子类重写父类的同名属性和方法.py | 894 | 3.875 | 4 | """
@Author:Hirsi
@Time:2020/6/11 23:44
"""
# 师傅类
class Master(object):
def __init__(self):
self.kongfu = '《独门煎饼果子大法》'
def make_cake(self):
print(f'运用{self.kongfu}制作煎饼果子')
# 学校类
class School(object):
def __init__(self):
self.kongfu = '《乾坤煎饼果子大法》'
def make_cake(self):
... |
9bcbd59a957b7099af4c4ded107d4cbf13bc02f6 | imZTY/mydemo | /try-learn.python/project/docx2html/test.py | 444 | 3.5 | 4 | # -*- coding:utf-8 -*-
import re
def f(x):
if x>=6:
return 0;
return x * x
r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
print type(r)
l=list(r)
print r
print l
#m=input("birthday:")
#print m
def abcd(m):
print m.group()
print "Ƚķ"
return "111111111111111"
abc="<img src='dasdadsa.jpg'/>12312312"
match_number=... |
3862a86b753c67b220800ee8c661f5f91298fbc5 | 88b67391/AlgoSolutions | /python3-leetcode/leetcode009-leetcode9-palindrome-number.py | 338 | 3.734375 | 4 | class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0:
return False
else:
str0 = str(x)
reversedStr = str0[::-1]
if reversedStr == str0:
return True
return False
# Below is testing
sol = Solution()
print(sol.... |
c440163228ee19440664cacfd30e3cfbf5bff61b | Akhil-64/Data-structures-using-Python | /Assignment Recursion 3.py | 1,357 | 3.578125 | 4 | #Q3. Finding the length of connected cells of 1’ s (regions) in an matrix of 0s and 1’s.
def Safe(m, row, col, visited): #function to check if a given row,col can be included in DFS
return ((row >= 0) and (row < row1) and(col >= 0) and (col < col1) and (m[row][col] and not visited[row][col]))
def DFS(m,... |
69447c2b042f1836baa7c7cec42a96f4bc871b10 | tommydo89/CTCI | /8. Recursion and Dynamic Programming/permutationWithDups.py | 674 | 4.03125 | 4 | # Write a method to compute all permutations of a string whose characters are not necessarily unique. The list of permutations should not have duplicates.
def permutations(string):
results = []
recursivePermutation(list(set(string)), [], results)
return results
def recursivePermutation(remaining, permutation, res... |
7563e483382a3bdedfe13cf2c4924a569db4553f | jihongsheng/python3 | /python入门/day_2_列表/2-4-使用方法sort()对表进行永久性排序.py | 865 | 4.0625 | 4 | # -*- coding: UTF-8 -*-
# "Python方法sort() 让你能够较为轻松地对列表进行排序。假设你有一个汽车列表,
# 并要让其中的汽车按字母顺序排列。为简化这项任务,我们假设该列表中的所有值都是小写的。"
cars = ['bmw', 'audi', 'toyota', 'subaru']
# 方法sort();永久性地修改了列表元素的排列顺序。现在,汽车是按字母顺序排列的,再也无法恢复到原来的排列顺序:
cars.sort()
print(cars)
print("-" * 80)
# 你还可以按与字母顺序相反的顺序排列列表元素,为此,只需向sort() 方法传递参数reverse=True 。
# 下... |
7308e97300e43706e907f0f7439ae3386a190fa2 | BrandonHung343/Hack112 | /circle.py | 2,915 | 3.578125 | 4 | import pygame
from pygameGame import *
import math, string, copy, time, random
import numpy as np
def remove_holes(surface, background=(0, 0, 0)):
"""
Removes holes caused by aliasing.
The function locates pixels of color 'background' that are surrounded by pixels of different colors and set them to
... |
7ec138770513c71dbddc12f66869dbf42b695fe3 | zhuxiaodong2019/VIP9Base2 | /objecttest/testobject4.py | 1,132 | 3.5 | 4 | # -*- coding: utf-8 -*-
'''
@Time : 2021/1/23 17:37
@Author : zxd
'''
#super
#师傅类
class Master():
def __init__(self):
self.kongfu = '[五香煎饼果子]'
def make_cake(self):
print(f'运用{self.kongfu}制作五香#####')
#学校继承老师傅类
class School(Master):
def __init__(self):
self.kongfu = '[香辣煎饼果子]'
... |
40946d2824afc0a38382c8294bbaa6745ad967b2 | guntankoba/csv_subtitles | /util_csv.py | 423 | 3.6875 | 4 | # -*- coding:utf-8 -*-
import csv
def read_csv(file_name):
""" [row, row, row]の形式の2次元リストを返す"""
file = []
with open(file_name) as f:
for row in csv.reader(f):
file.append(row)
return file
def write_csv(file_name, rows):
with open(file_name, 'w') as o:
writer = csv.write... |
b5cf2bef535359e2e51739d931e7ad75097be528 | avengerryan/daily_practice_codes | /eleven_sept/py_set_methods/copy.py | 581 | 4.4375 | 4 |
# python set copy() : returns shallow copy of a set
# the copy() method returns a shallow copy of the set
"""
# using = operator
numbers = {1, 2, 3, 4}
new_numbers = numbers
print(new_numbers)
"""
"""
# NOTE:
numbers = {1, 2, 3, 4}
new_numbers = numbers
new_numbers.add(5)
print('numbers: ', numbers)
prin... |
4c0920e80f2c5ccda19dd013942b5edafc69381e | OlegNG86/SkillBoxLessons | /python_homeworks/lesson_005/02_district.py | 1,090 | 3.5 | 4 | # -*- coding: utf-8 -*-
# Составить список всех живущих на районе и Вывести на консоль через запятую
# Формат вывода: На районе живут ...
# подсказка: для вывода элементов списка через запятую можно использовать функцию строки .join()
# https://docs.python.org/3/library/stdtypes.html#str.join
from district.central_s... |
1470c125a2ea5121b3d25173e11714a6219cf5fb | LYoung-Hub/Algorithm-Data-Structure | /insertionSortList.py | 1,124 | 3.953125 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def insertionSortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return Non... |
8c8f451a16712caf58a12ec7aae75712b8a11015 | reyeskevin9767/modern-python-bootcamp-2018 | /36-challenges/05-vowel-count/app.py | 645 | 4.09375 | 4 |
# * Exercise
'''
vowel_count('awesome') # {'a': 1, 'e': 2, 'o': 1}
vowel_count('Elie') # {'e': 2, 'i': 1}
vowel_count('Colt') # {'o': 1}
'''
# def vowel_count(word):
# lower_case_word = word.lower()
# new_word = [char for char in lower_case_word if char in "aeiou"]
# dict_words = {}
# for word in new_... |
816fe7c6bea4cff60111282b55b7ce1d90c0f836 | VIadik/School | /fractal/Cross.py | 398 | 3.734375 | 4 |
import turtle
def Cross(l, level):
if level != 0:
Cross(l / 3, level - 1)
turtle.left(90)
Cross(l / 3, level - 1)
turtle.right(90)
Cross(l / 3, level - 1)
turtle.right(90)
Cross(l / 3, level - 1)
turtle.left(90)
Cross(l / 3, level - 1)
el... |
4210e71fb1c3eb6c2c8748e86b2fbc12133f0aa8 | kirbylovesfood/Exercises | /Str Char Manipulation.py | 1,005 | 4.15625 | 4 | Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> str = "Python is User-friendly"
str_split = str.split(" ")
print(str)
print(str.upper())
#to capitalize the string
print(str.lower())
#to put in lo... |
63bbf982c35ac29e353538d562958b87ea7c37f4 | meghanagottapu/Leetcode-Solutions | /leetcode_py/Anagrams.py | 1,553 | 3.734375 | 4 | from collections import defaultdict
class Solution:
# @param {string[]} strs
# @return {string[]}
def anagrams(self, strs):
dict = defaultdict(list)
map(lambda s: dict[''.join(sorted(s))].append(s), strs)
return [y for x in dict.keys() for y in dict[x] if len(dict[x]) > 1]
if __n... |
347b322ee9da33aa02eff04a17614b9fa1b163d7 | ljm9748/Algorithm_ProblemSolving | /practice/0406_practice/SWEA_5177_이진 힙_이정민.py | 594 | 3.53125 | 4 | # 트리 자리바꿔주는 함수
def treecheck(last):
if last<0:
return
if tree[last]<tree[last//2]:
tree[last],tree[last//2]=tree[last//2],tree[last]
treecheck(last//2)
# 합계찾는 함수
def findsum(node):
global answer
if node<1:
return
answer += tree[node]
findsum(node//2)
for tc in ... |
d5676710d78543e097bc68405335c802651bce5d | edu-athensoft/stem1401python_student | /py200622_python2/day13_py200803/homework/stem1402_python_homework_7_ken.py | 1,421 | 4.28125 | 4 | """
For August 3rd, 2020.
Ken.
stem1402_python_homeowrk_7_ken
idea: ok
"""
# def pangram_checker(string):
def ispangram(string):
string = string.lower()
# global pangram
pangram = True
alphabet_checker = {
"a" : False,
"b" : False,
"c" : False,
"d" : False,
... |
687cb2ed0de1e88a4bd65e915ec1a7b602aebbf8 | JiaXingBinggan/For_work | /code/stack/min_stack.py | 996 | 4 | 4 | class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.items = []
self.items_ = [] # 辅助栈,存最小的
def push(self, x):
"""
:type x: int
:rtype: None
"""
self.items.append(x)
if not self.it... |
51671779b49c8112395c6e818d8ea1b59ff4ac56 | Vador05/iec_codeclub | /day2/firstquiz.py | 597 | 4.15625 | 4 | while(True):
print("Are you Male or Female?")
gender= input()
if(gender=="female"):
print("Can you give me your phone number?")
phone=input()
if(phone!=""):
print("Do you like beer?")
beer=input()
elif(gender=="male"):
print("Do you like beer?")
beer=input()
if(... |
b3a3b9295475ed53dc7ba3e9032143189801276c | Tingting0618/python-server-book1 | /employees/request.py | 6,525 | 3.640625 | 4 | import sqlite3
import json
from models import Employee, Location
def get_all_employees():
# Open a connection to the database
with sqlite3.connect("./kennel.db") as conn:
# Just use these. It's a Black Box.
conn.row_factory = sqlite3.Row
db_cursor = conn.cursor()
# Write the ... |
821e11c14a58db4023971849a8621b9d22a564f0 | alejandroMAD/python-exercises | /data-structures/get_sum.py | 167 | 3.65625 | 4 | from functools import reduce
def get_sum(list):
return reduce((lambda total, element: total + element), list)
total = get_sum([1, 2, 3, 4, 5, 6])
print(total)
|
de4b5333fc4f9183edefc420063ed9f418181e91 | immanuelpotter/wordcloudifier | /program/wordcloudifier.py | 1,671 | 3.6875 | 4 | #!/usr/bin/env python
#Take in user's long string of input, run the text against nltk, spit out a wordcloud
import re
import time
import wordcloud as wcld
import matplotlib.pyplot as plt
class Wordcloudifier:
def __init__(self,stopwords):
try:
stopwords_list = open(stopwords).read().split()
... |
9b79f181b52183cc5c88d6e34eb922144e408d4a | hujuu/py-test | /paiza/C036辞書の追加.py | 1,021 | 3.875 | 4 | first = input()
first = first.split()
two = input()
two = two.split()
first_rap = input()
second_rap = input()
first_dic = {}
second_dic = {}
for x in range(1, 5):
temp = first_rap.split()
first_dic[x] = int(temp[x-1])
win_lst = []
one_left = int(first[0])
if first_dic[one_left] < first_dic[int(first[1])]:
wi... |
82d38645adc33f2aaded760076d1f91a34433eb1 | hazemshokry/Algo | /Leetcode/BST.py | 1,391 | 4.15625 | 4 | class Node(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BST(object):
def __init__(self, root):
self.root = Node(root)
def preorder_search(self, start, find_val):
"""Helper method - use this to create a
recu... |
f3e734a4104d79c3d4e79d5c81a5b88f3558c747 | dev-schueppchen/programmier-aufgaben | /aufgaben-mittel/aufgabe01/loesungen/python/main.py | 416 | 3.953125 | 4 | def get_smallest_dividend(num):
for i in range(2, num + 1):
if num % i == 0:
return i
def prime_factorizing(num):
factors = []
current = num
while current > 1:
dividend = get_smallest_dividend(int(current))
factors.append(dividend)
current /= dividend
ret... |
efe4c9880a20122f84a6faaacff838daa9c927cc | svn89nine/python-prac-1 | /bmi_calc_v2.py | 193 | 3.796875 | 4 | h = float(input("Your height in Inches: "))
w = float(input("Your weight in pounds: "))
i = h * 0.0254
p = w * 0.4536
import math
sh=(math.pow(i,2))
bmi= p / sh
print("Your BMI: "+ str(bmi))
|
f8c497636600e0ad100e27194deab0fd11ee9299 | vad2der/Python_examples | /Clustering/clustering_methods.py | 10,097 | 3.703125 | 4 | '''
Algorithmic Thinking Project 3:
Closest pairs and clustering algorithms
four functions:
slow_closest_pairs(cluster_list)
fast_closest_pair(cluster_list) - implement fast_helper()
hierarchical_clustering(cluster_list, num_clusters)
kmeans_clustering(cluster_list, num_clusters, num_iterations)
where cluster_l... |
d7a0cda8734ab23e5df98ad1a5c1223cdd9adbed | ogulcandemirbilek/ProgramingLab | /Online_Hafta04&Odev04/180401061_hw_4.py | 2,581 | 3.609375 | 4 | #min_heapyfy(array,i) : array ve i olmak üzere iki parametre alır. Array bizim heap düzenine sokacak olduğumuz dizi, i ise belirleyeceğimiz index'i temsil ediyor. Fonksiyon belirlediğimiz index'in Minheap düzeninde olmayan child ları da dahil olmak üzere MinHeap düzenine sokar.
#build_min_heapy(array) : array parametr... |
add66478ded2a6e33a30a84aeea4aa8fb20d6f80 | h4ckfu/magical_universe | /code_per_day/day_47_to_48.py | 881 | 3.921875 | 4 | from collections import defaultdict
class CastleKilmereMember:
"""
Creates a member of the Castle Kilmere School of Magic
"""
def __init__(self, name: str, birthyear: int, sex: str):
self._name = name
self.birthyear = birthyear
self.sex = sex
self._traits = defaultdict(... |
303ce6bcd37bb26ad35be19bf9a0866c3c17f993 | DouglasCarvalhoPereira/Interact-OS-PYTHON | /M4/VeirificIs_Sucesfull_or_not.py | 329 | 3.703125 | 4 | #!/usr/bin/env python
#Script que verifica se o código foi executado com sucesso ou não.
import os
import sys
filename=sys.argv[1]
if not os.path.exists(filename):
with open(filename, 'w') as f:
f.write("New file created\n")
else:
print("Error, the file {} already exists!".format(filename))
sys.... |
5a61bb0dea1ee778428302bd28138b02795d4fb5 | officialstephero/codeforces | /Codeforces solutions/Petya and strings.py | 183 | 3.875 | 4 | first = input()
first = first.lower()
second = input()
second = second.lower()
if first < second:
print('-1')
if first > second:
print('1')
if first == second:
print('0')
|
2dda7901d5acfc09717c76b3652d5b0878033071 | Svetlanamsv/pass_word | /main.py | 165 | 3.71875 | 4 | print("Enter twice password")
answer1=input()
answer2=input()
if answer1==answer2:
print("Password is right")
else:
print("There is mistake in the password") |
1f3d79f8c68779d79d02ee5e0b8c09e879692cc6 | Walrick/Projet_3 | /package/item.py | 595 | 3.8125 | 4 | #!/usr/bin/python3
# -*- coding: utf8 -*-
class Item:
""" Class Item for item management """
def __init__(self, name, data, x, y):
""" init the item """
self.name = name
self.data = data
self.x = x
self.y = y
self.bag = False
def pickup_item(self):
... |
d99aa48ea25023fecdfffaaffeadd5a750356d45 | westgate458/LeetCode | /P0485.py | 476 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 7 20:43:38 2020
@author: Tianqi Guo
"""
class Solution(object):
def findMaxConsecutiveOnes(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# steps:
# 1) join the list to form a string
# 2) split the st... |
d1591773d30377c0c3f91179e9d34fc96cf93b4a | LalitTyagi/New-Onboards-Training-Solution | /Python/ProblemSet01/PS0104.py | 1,235 | 4.125 | 4 | #Practice using the Python interpreter as a calculator:
#a) The volume of a sphere with radius r is 4/3pr3. What is the volume of a sphere with radius 5?
#Hint: 392.7 is wrong!
import math
r=int(input())
print( 4/3*math.pi*(r**3))
#b) Suppose the cover price of a book is Rs.24.95, but bookstores get a 4... |
69576315428860e0f5427750a2254f45a267c441 | orlova-lb/PythonIntro06 | /lesson_05/strings.py | 1,958 | 3.515625 | 4 | # print(chr(0x26bd))
# print('\u26bd')
# print(chr(9917))
#
# print(ord('⚽'))
# print(hex(ord('⚽')))
#
# wave = '~'
# boat = '\U0001F6A3'
# seagull = '\u033C'
# fish = '\U0001F41F'
# penguin = '\U0001F427'
# wale = '\U0001F40B'
# octopus = '\U0001F419'
#
# row = wave * 10 + boat + wave * 15 + '\n'
# fish_row = wave * 4... |
bdafa9e2d3440e65b21370fe80795659ae6446da | arunson/eBay-RAM | /cs130/eram/utils.py | 1,855 | 3.53125 | 4 | from cs130.eram.review_modules import review_module
# Filters a space-delimited string based on a blacklist.
# The blacklist should be a list of lowercase words.
# The input will automatically be lowercased.
def filter(string, blacklist) :
# Lowercase the input
lowercase = string.lower()
word_list = l... |
9e774c735d1a836da022ba8140f9e7a87fc96cd5 | b72u68/coding-exercises | /Project Euler/p7.py | 395 | 3.765625 | 4 | # 10001st prime
import math
def check_prime(n):
if n <= 1:
return False
for i in range(2, int(math.sqrt(n))):
if n % i == 0:
return False
return True
def main():
counter = 0
num = 2
while counter < 10001:
if check_prime(num):
counter += 1
... |
7ff066725aac30991a2025378f36dc6a0a280a45 | masterashu/Semester-3 | /ADSA/Lab/Lab7/u_knapsack.py | 752 | 3.625 | 4 | def get_max(I, cost):
m = 0
for w,v in I:
if w == cost:
m = max(m, v)
return m
def UnboundedKnapsack(I, cost):
I.sort()
arr = [0]*(cost+1)
for i in range(1, cost+1):
arr[i] = max(arr[i], get_max(I, i))
for j in range(i):
arr[i] = ... |
495d0c3f3992c4cf96ad82da94d3d70cfd9fbb1e | ebiggers/libdeflate | /scripts/gen_bitreverse_tab.py | 523 | 3.953125 | 4 | #!/usr/bin/env python3
#
# This script computes a table that maps each byte to its bitwise reverse.
def reverse_byte(v):
return sum(1 << (7 - bit) for bit in range(8) if (v & (1 << bit)) != 0)
tab = [reverse_byte(v) for v in range(256)]
print('static const u8 bitreverse_tab[256] = {')
for i in range(0, len(tab),... |
875ffe11b5e30a033006835e8405f5a0615bac8d | billylin14/CSE415_Assignments | /a6-starter-files/binary_perceptron.py | 2,553 | 3.828125 | 4 | '''binary_perceptron.py
One of the starter files for use in CSE 415, Winter 2021
Assignment 6.
Version of Feb. 18, 2021
'''
def student_name():
return "Billy Lin" # Replace with your own name.
def classify(weights, x_vector):
'''Assume weights = [w_0, w_1, ..., w_{n-1}, biasweight]
Assume x_vector = [x_0, ... |
a5936ef5d7c847c0081980ba2954f4184aae1be1 | gabriellaec/desoft-analise-exercicios | /backup/user_097/ch48_2019_09_30_19_58_14_296160.py | 237 | 3.8125 | 4 | meses = ["janeiro", "fevereiro", "março", "abril", "maio", "junho", "julho", "agosto", "setembro", "outubro", "novembro", "dezembro"]
nomeMes = input("Informe o nome do mês: ")
i = 0
while(meses[i]!=nomeMes):
i = i + 1
print(i+1) |
18040fa7d7b909853ff7c0ab610cbc784c8ab3ca | MarkusHarrison21/PythonCourse | /Chapters4.py | 2,044 | 4.59375 | 5 | # =========================================== Turtles ===========================================
# Turtles are the name of a slow running visual program in Python
# A module in Python is a way of providing useful code to be used by another program (among other things, the module can contain functions we can use).
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.