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 |
|---|---|---|---|---|---|---|
dd6f39e8efb0309ba27b70c091d686550c82bad9 | huyngopt1994/python-Algorithm | /bigo/day_14_trie/trie_lib.py | 521 | 4.0625 | 4 | """Root class to build a Trie."""
class Node:
def __init__(self):
"""We have count_word and child."""
self.count_word = 0
self.child = dict()
self.weight = 0
def add_word(root, s, weight=1):
tmp = root
for ch in s:
# loop for per character.
if ch not in tm... |
d7cee56605d3d89199673b1b1e78123bd6c56201 | huyngopt1994/python-Algorithm | /green/green-02-condition/elephan.py | 330 | 3.515625 | 4 | "http://codeforces.com/contest/617/problem/A"
position = int(input())
step = 0
while position > 0:
if position > 4:
position -=5
elif position> 3:
position -= 4
elif position >2:
position -= 3
elif position >1:
position -= 2
else:
position -= 1
step +=1
p... |
9f5da305b0fdadfd4651349a603c570ca8d7dea2 | huyngopt1994/python-Algorithm | /green/cubes.py | 243 | 3.84375 | 4 | number_cubes = int(input())
max_level_cube = 0
used_cubes =0
while (used_cubes<=number_cubes):
max_level_cube +=1
used_cubes += max_level_cube
# we subtract 1 to get the right max_level_cube
max_level_cube -= 1
print(max_level_cube) |
0fb335e92ddd1fc10cbd6852d751d495adfe8515 | huyngopt1994/python-Algorithm | /bigo/day-9-mid-sem/solutionD.py | 1,757 | 3.6875 | 4 | from queue import Queue
def is_valid(u, row, col, bomb_nodes):
# very is a point is valid or not
return u[0] >= 0 and u[0] < row and u[1] >= 0 and u[1] < col and not bomb_nodes.get('{}_{}'.format(u[0], u[1]))
def bfs(start, end, bomb_nodes, row, col):
"""
:param s: start node
:param e: end nod... |
988886ad6a450d16f224c47b43a7c797c70cb9c6 | huyngopt1994/python-Algorithm | /green/green-07-string/count_diferrent_character.py | 361 | 3.890625 | 4 | def count_number(my_string):
# first we will store
count = 0
unique_dict = {}
for ch in my_string: #O(n)
if unique_dict.get(ch,None): #O(1)
unique_dict[ch] +=1
else:
unique_dict[ch]= 1
count +=1
print(count)
# Call O(n) ,space complexity : O(k)
m... |
6d45a8ae9084155b987914af439e07ced0f9fd55 | huyngopt1994/python-Algorithm | /green/green-03-loop/Vanya_and_Cubes.py | 223 | 3.875 | 4 | s = int(input())
height = 0
def need_cubes_for_index(index):
count = 0
for i in range(index+1):
count +=i
return count
while s >=0:
height += 1
s -= need_cubes_for_index(height)
print(height-1) |
e5a55d07ab4524ab79c789f7d8ef2ef6e643d833 | dani3390/Fondamenti-di-Programmazione | /lezione3_esercizio4.py | 461 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Oct 16 09:32:58 2019
@author: Danilo
Testo: Scrivere una funzione che verifica
se una lista è ordinata in modo crescente
(<=) (supponiamo che la lista contenga oggetti ordinabili).
"""
def Ordinata_Crescente(lista):
if sorted(lista) == list... |
7e85204e9a214d5dd1ddd3e22bef6a31d7a0b77e | SheepySean/UoA-GitHub | /NLP/keyword_extractor.py | 1,127 | 3.703125 | 4 | from nlp.input_preprocessor import InputPreprocessor
class KeywordExtractor:
"""
Class that preprocess a set of documents and extracts its keywords based on the frequency of each term.
"""
def __init__(self, doc_set):
"""
Initializes the new KeywordExtractor instance with the given set ... |
cc970808fab8db4377cfef2d18313746e1c02e28 | lisaolson/higher_level_programming | /0x0C-python-almost_a_circle/models/base.py | 2,403 | 3.59375 | 4 | #!/usr/bin/python3
"""Module to define Base Class
"""
import json
class Base:
"""Defines Base
"""
__nb_objects = 0
def __init__(self, id=None):
"""Instantiation with id
Args:
id (int): id value as integer
"""
if id is not None:
self.id = id
... |
2d18eacb996e8acb307d9fd3ee20b3b0caa67e3a | lisaolson/higher_level_programming | /0x02-python-import_modules/2-args.py | 444 | 4 | 4 | #!/usr/bin/python3
from sys import argv
if __name__ == "__main__":
num_args = len(argv)
num_args -= 1
if num_args == 0:
print("0 arguments.")
if num_args == 1:
print("{:d} argument:".format(num_args))
print("{:d}: {}".format(num_args, argv[1]))
if num_args > 1:
print(... |
f187f980ff92bd130b730956b383ee6e87731918 | lisaolson/higher_level_programming | /0x03-python-data_structures/0-print_list_integer.py | 122 | 4.0625 | 4 | #!/usr/bin/python3
def print_list_integer(my_list=[]):
for x in my_list:
print("{:d}".format(my_list[x - 1]))
|
32be29afd348f0258b0e216e8df0f2f9c9a091d3 | marcelosoliveira/trybe-exercises | /Modulo_4_Ciencia da Computacao/Bloco 34: Introdução à Python e Raspagem de Dados da Web/dia_2: Entrada e Saída de Dados/conteudo/manipulando_csv/entendendo_manipulacao_csv.py | 237 | 3.546875 | 4 | a, b = "cd"
print(a) # saída: c
print(b) # saída: d
head, *tail = [1,2,3] # Quando um * está presente no desempacotamento,
#os valores são desempacotados em formato de lista.
print(head) # saída: 1
print(tail) # saída: [2, 3]
|
a57ab223342720dbd0dd8b49e95a0bc849b307e3 | marcelosoliveira/trybe-exercises | /Modulo_4_Ciencia da Computacao/Bloco 35: Programação Orientada a Objetos e Padrões de Projeto/dia_1: Introdução à programação orientada a objetos/conteudo/primeira_entidade.py | 816 | 4.1875 | 4 | class User:
def __init__(self, name, email, password):
""" Método construtor da classe User. Note que
o primeiro parâmetro deve ser o `self`. Isso é
uma particularidade de Python, vamos falar mais
disso adiante!"""
self.name = name
self.email = email
self.pass... |
b94d0eb10d025ba5aa21a81b3c3c9b2ca35135f3 | marcelosoliveira/trybe-exercises | /Modulo_4_Ciencia da Computacao/Bloco 35: Programação Orientada a Objetos e Padrões de Projeto/dia_3: Padrões de projeto/exercicios/exercicio5.py | 1,041 | 3.96875 | 4 | """ Exercício 5: Imagine que você tem a implementação de uma classe capaz renderizar
imagens através de uma interface que utiliza o método draw . Porém, no momento
ela só suporta formato PNG e você também precisa ser capaz de renderizar imagens
em SVG. Altere o código sem modificar a classe SvgImage , para que isso s... |
99f823a38c9e2819af904c4d221e9f21003aa6ee | marcelosoliveira/trybe-exercises | /Modulo_4_Ciencia da Computacao/Bloco 37: Estrutura de Dados: Hash e Set/dia_2: Hashmap e Dict/conteudo/exemplo_3.py | 963 | 3.65625 | 4 | # Exercício 3
# Tente descobrir qual técnica de tratamento de colisão é utilizada pelo Dict,
# de Python e o HashMap , do Java. Em inglês, o termo de busca
# é " collision resolution ".
# Solução:
# A classe Dict utiliza o Open Addressing e Java utiliza Separate Chaining.
# Vamos entender isso com mais detalhes.
# A ... |
125f1dfaffb6403114b58246d6f16dd7f10c76f6 | marcelosoliveira/trybe-exercises | /Modulo_4_Ciencia da Computacao/Bloco 38: Estrutura de Dados II: Listas, Filas e Pilhas/dia_2: Deque/exercicios/exercicio_3.py | 1,179 | 4.25 | 4 | # Exercício 3: Desafio do Palíndromo - Uma palavra é um palíndromo se a sequência de
# letras que a forma é a mesma, quer seja lida da esquerda para a direita ou vice-versa.
# Crie um algorítimo que, ao receber uma sequencia de caracteres, indique se ela é
# ou não um palíndromo. Para este exercício iremos considerar ... |
c329d94c2cf17349c3af91e275b630e36276baad | marcelosoliveira/trybe-exercises | /Modulo_4_Ciencia da Computacao/Bloco 38: Estrutura de Dados II: Listas, Filas e Pilhas/projeto-bloco_38_project-ting/sd-07-project-ting/ting_file_management/queue.py | 2,130 | 3.75 | 4 | class DoublyNode:
def __init__(self, value):
self.value = value
self.next = None
self.previous = None
def __str__(self):
return f"Node(value={self.value} next={self.next})"
class DoublyLinkedList:
def __init__(self, iterable):
self.iterable = iterable
def __n... |
0403b9cc85f7581304f242523226bc541e9c21e7 | Nuaboc/Budget-Planning-App | /app.py | 1,644 | 3.921875 | 4 | """
Main file for the Budge Master App.
This is an app for budget management.
All the print statements are being used just in the current developing
phase for testing and debugging purposes.
Authors: Gabriel Martinez and Estalin Martinez
Date: Oct 18, 2019
"""
import sys
import functions as func
def run_app():
"... |
0831bc62e428c6368a961b86733cd4548142f1db | powerlego/Main | /select_median.py | 1,464 | 3.828125 | 4 | from store_location import *
from quick_sort import *
from time import *
def quick_select(L, k):
if L != []:
pivot = L[len(L) // 2]
smallerList, same, largerList = partition(pivot, L)
count = len(same)
m = len(smallerList)
if k >= m and k < m + count:
return piv... |
1d675bd4f0271c09a8998b7ea02f4b2d3110b6cf | powerlego/Main | /insertion_sort.py | 1,053 | 4.125 | 4 | """
file: insertion_sort.py
language: python3
author: Arthur Nunes-Harwitt
purpose: Implementation of insertion sort algorithm
"""
def insertion_sort(lst):
"""
insertionSort: List( A ) -> NoneType
where A is totally ordered
effect: modifies lst so that the elements are in order
"""
for m... |
618f408fc137bac9c20117ed574ed61297ab951a | powerlego/Main | /hw08.py | 7,537 | 4.21875 | 4 | """
File: HW08.py
Author: Nicholas Curl
"""
# Import the necessary libraries and programs to run this program.
import random
from time import *
import insertion_sort
import merge_sort
import quick_sort
# Definitions and functions to test different sorting algorithms and for running a merge-quick sort algorithm
def... |
ea5d47047deba4daa8d420d4d2175a5045b017c1 | MarquezLuis96/BasicAlgorithms | /Sort/Bubble Sort/Python/bubble_sort.py | 3,157 | 4.375 | 4 | # Author: Luis Márquez
# Date: 2021/01/21
# Description:
# This is a simple program in which the "Bubble Sort" algorithm is implemented in Python.
#
# The user enters a number serie and then, this algorithm, is in charge of ordering in a
# increasing or decreasing way the numbers, dependi... |
85f0c216b4c389e500c53b482a6ae778d9a49f52 | chnls17/network-programming-and-asyncio | /线程-进程-协程/线程/死锁.py | 591 | 3.59375 | 4 | import threading
# import time
# 创建锁
lock = threading.Lock()
def func(index):
# 上锁
lock.acquire()
my_list = [3, 6, 8, 1]
# 判断下标释放越界
if index >= len(my_list):
print('越界下标', index)
# 当索引超过列表长度时,需要进行解锁,如果不进行解锁,则会造成死锁(程序未停止)
lock.release()
return
value = my_lis... |
2e99aa8b128cee5cb3a004c27ef7713fd662f908 | chnls17/network-programming-and-asyncio | /asyncio并发编程/wait和 gether.py | 1,203 | 3.546875 | 4 | # -*- coding:utf-8 -*-
import asyncio
import threading
import time
async def get_html(url): # 定义协程函数
print("start---{}".format(threading.current_thread()))
await asyncio.sleep(2) # 时长2s
print("end---{}".format(threading.current_thread()))
return url # 返回对象为协程对象
# python3.7 语法
async def main():
... |
aa723f57389114f1681829f38801e93297b658e9 | thesauravs/NLP | /removeStopwords.py | 477 | 3.8125 | 4 | from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
#word_tokenize accepts a string as an input, not a file.
stop_words = set(stopwords.words('english'))
file = open("test.txt")
line = file.read()# Use this to read file content as a stream:
words = line.split()
print(line)
print(words)
f... |
6c99c03df6ea8f6e7e864aa79c08f31718b26c9b | csancini/Data-Struct-Alg | /week2/scramble.py | 1,451 | 3.84375 | 4 | import numpy as np
def interleave(one, other):
"""
Given two messages, A and B, which have the same length,
creates a new message by taking the first character from A,
then the first character from B, then the second character
from A, then the second character from B, and so on.
"""
... |
1ab11f7aa32af28139dc0303979d8cf3482858a8 | qa-vickie/qa-test | /PYTHON-FILES/CODING-TEST-2-2.py | 335 | 3.859375 | 4 | def lucky_sum (numbers):
my_sum = 0
for i in numbers:
n = int(i)
if n != 13:
my_sum = my_sum + n
else:
break
return (my_sum)
str_numbers = raw_input('Enter the list of values, separated by comma: ')
list_of_numbers = str_numbers.split(',')
print lucky_sum(list_... |
a0dbb5f621dd2a58469e0d26bf9190f45dfc86d8 | Rossorboss/Python_Functions_Prac | /map,filter,lambda.py | 2,621 | 4.5625 | 5 | #map, lambda statements
def square(num):
return num ** 2
my_nums = [1,2,3,4,5]
for x in map(square,my_nums): #the map function allows it to be used numerous times at once
print(x)
# Luke i am your father example--using map to call all 3 at the same time
def relation_to_luke(name):
if name == 'Darth Vad... |
619c47741f2483730fa6bb3c3faa5a7d2a831d18 | mamine2/My-First-Repository | /List_MA.py | 986 | 3.5 | 4 | import webbrowser
import time
name = "JuJu Smith-Schuster"
subjects = ["Mandarin","Science","History","English","Math"]
print("Hello " + name)
for i in subjects:
print("One of my classes is " + i)
games = ["Call of Duty","Fortnite","Pubg","CS:GO"]
for i in games:
if i == "Fortnite":
... |
67065afeef4f82ff240a6920f642cc739a486010 | dearwendy714/web-335 | /week-8/Portillo_calculator.py | 645 | 4.625 | 5 | # ============================================
# ; Title: Assignment 8.3
# ; Author: Wendy Portillo
# ; Date: 9 December 2019
# ; Modified By: Wendy Portillo
# ; Description: Demonstrates basic
# ; python operation
# ;===========================================
# function that takes two parameters(numbers) and adds th... |
60daa700ba1d2080c5ccc489a052e4e1b88f4743 | aribambang/piwai | /6.py | 764 | 3.921875 | 4 | my_list = [0, 1, 2, 3, 4]
an_equal_list = [x for x in range(5)]
multiply_list = [x * 3 for x in range(5)]
print(an_equal_list)
print(multiply_list)
print([n for n in range(10) if n % 2 == 0])
people_you_know = ["Ari", "bambang", "KURNIAWAN"]
normalised_people = [person.strip().lower() for person in people_you_know]
p... |
74887e6e3df593b0f0f554c60fdfafa2de4d704c | aribambang/piwai | /12.py | 297 | 3.515625 | 4 | def methodception(another):
return another()
def add_two_number():
return 37+77
print(methodception(add_two_number))
print(methodception(lambda: 37+77))
my_list = [2, 10, 19, 97]
def not_two(x):
return x != 2
print(list(filter(not_two, my_list)))
print([x for x in my_list if x != 2]) |
5150bc8a95a1729f2adf20d745476907ea5915e4 | DaniasHerlambang/codemi | /lokers.py | 3,680 | 3.671875 | 4 | from collections import OrderedDict
input_loker = OrderedDict()
lokers = OrderedDict()
# fungsi untuk menambah jumlah loker
def init(values):
for i in range(0,int(values)):
result = 'loker'
lokers[i+1] = result
print ('Berhasil membuat loker dengan jumlah %s' % len(lokers))
# fungsi untuk mena... |
b1dacd9dc69ad286f187328fa23e80e74ffc895b | lillami/PE1 | /PE1.py | 197 | 3.71875 | 4 | selected_numbers = []
for number in range(1,1000):
if number % 3 == 0 or number % 5 == 0:
selected_numbers.append(number)
summa = sum(selected_numbers)
print("Summa summárum " + str(summa))
|
87b7d4e9fac036de6bc6f80afcac0a26736ceda1 | LiJiaqi96/Play-with-Leetcode | /160_Intersection_of_Two_Linked_Lists.py | 897 | 3.59375 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
lena, lenb = self.... |
4b09bd2d8376d4c01228acabd4aac782cde1ff4c | jianli0/Leetcode | /Merge k Sorted Lists.py | 802 | 3.5 | 4 | '''Remains to be sovled'''
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param a list of ListNode
# @return a ListNode
def mergeKLists(self, lists):
finalList = []
listsoffirst = self.... |
57a20abedbb5e1c93dd36f02728d965781e5c829 | jianli0/Leetcode | /Search Insert Position.py | 606 | 3.78125 | 4 | class Solution:
# @param A, a list of integers
# @param target, an integer to be inserted
# @return integer
def searchInsert(self, A, target):
if target < A[0]:
return 0
elif target > A[len(A) - 1]:
return len(A)
for i in range(0,len(A)):
if A[... |
3b04133444c3b6a9553da4a3eebc77f8ba9f8a84 | kaleksi/rockpaperscissors | /main.py | 2,169 | 4.09375 | 4 | from random import *
rock = "Rock"
paper = "Paper"
scissors = "Scissors"
guess = ""
rounds = 0
round_select = input("Welcome to Rock, Paper, Scissors! How many rounds would you like to play? \n")
round_select = int(round_select)
com_score = 0
plyr_score = 0
while rounds < round_select:
roll = randint(1, 3)
... |
81a5bea73600bca7a56cffd7202946c59ec82b6f | adrriano/python_projeto_tela_software | /teste_software.py | 921 | 3.75 | 4 | from tkinter import *
global azul
azul= False
global verde
verde= False
def comando(op):
global azul
global verde
if(op == 1 and azul == False):
print("led azul ligado")
azul = True
elif (op == 1 and azul == True):
print("Led Azul Desligado")
azul = False
elif... |
318a106c428b8d3893e5b26185c8e86870f3c24c | davestudin/Projects | /Euler Problems/Euler Problems/Question 10.py | 314 | 3.578125 | 4 | from math import *
def f():
n=0
x=0
triNum=1
list=[]
while n<1000:
n=n+1
triNum=(n*(n+1))/2
list.append(triNum)
for n in list:
if (1+sqrt(1+8*(n)))/4%1==0 and(1+sqrt(1+24*(n)))/6%1==0 and n!=1:
print 'The next triangular number that is also a pentagonal and hexagonal number is ',n
break
f() |
84f611ef059a51b87074835a430eedf3da9f346c | davestudin/Projects | /Euler Problems/Euler Problems/Question 6.py | 529 | 4.34375 | 4 | from math import *
input = int(raw_input("Enter sum of the desired Pythagorean Triple: "))
def pythag(sum):
a,b,c=0.0,0.0,0.0
for a in range (1,sum):
for b in range(a,sum):
c=sqrt(a*a+b*b)
if c%1==0 and a%1==0 and b%1==0:
if (a+b+c)==sum:
return 'The Pythagorean triple with sides that add up to '+... |
24f50b10bd931e18e4646f02f4b1b62cd2f11895 | gutierrezfamily/calculator | /calculatorpart5.py | 547 | 3.953125 | 4 | firstNum = int(raw_input ("What is the first number? "))
secondNum = int(raw_input ("What is the second number? "))
calQuest = raw_input ("What operation do you want to use? ")
if calQuest == ("add"):
x = (firstNum) + (secondNum)
print (x)
elif calQuest == ("subtract"):
x = (firstNum) - (secondNum)
... |
5968fedee2160c2a4b512de4d0ae5102deb0613c | PankovIlya/yahtzee | /combinatorics_g.py | 1,713 | 3.75 | 4 | # -*- coding: utf-8 -*-
import math
def combinations(lst, k):
""" combinations """
if not k:
yield []
else:
for idx in xrange(len(lst)):
for item in combinations(lst[idx+1:], k-1):
yield [lst[idx]] + item
def combinationsr(lst, k):
""" combinations with rep... |
9a467310d9318cdb343640e8119f1281b3c0d7b2 | UN-FISICA/taller-2-2018-2-cddelgadillol | /Ejercicio1.py | 411 | 3.640625 | 4 | #!/usr/bin/env python
# -*- coding: UTF-8-*-
import turtle
from turtle import *
title("ejer1")
penup()
goto(-60,-190)
turtle.backward
#setup(640,480,0,0)
def cuadrado():
g=1
turtle.forward(50)
turtle.left(90)
turtle.forward(180)
pendown()
while (g<=4):
turtle.forward(50)
turtle.left(90)
g... |
113b8ac1bb43753da38a4a386862706c43dd48bd | ssinad/quera-solutions | /643.py | 93 | 3.609375 | 4 | arr = [int(x) for x in input().split()]
arr.sort()
for item in arr:
print(item, end=" ")
|
9570b9d184bac902a3ef702afbd6492a5ee83797 | ssinad/quera-solutions | /3406.py | 815 | 3.90625 | 4 | def palindrome(n):
return int(str(n)[::-1])
def compare2(x, y):
a, b = palindrome(x), palindrome(y)
if a < b:
return '<'
elif a == b:
return '='
else:
return '>'
def compare(x, y):
equal = True
greater = True
tx = x
ty = y
for cnt in range(3):
a... |
bde7eff5715f3f75b540ae6a25a426d6a5d1202f | g-nerd25/plantation | /plantationTheGame.py | 20,822 | 3.90625 | 4 | #Plantation The game
#A farming game by G - NERD
#written in Python 3.6.9
#This game is a basic farming game written with python with the turtle module
#My very first actual ame that I made using python turtle
#I leaned a lot of stuffs from this coding
#Enjoy playing the Game!
#importing stuff we needed
import turtl... |
9d0d26915f88bf1c070e5ab3f8f0aa137c2d7c5b | doroshroman/EulerProject | /003.py | 457 | 3.625 | 4 | # https://projecteuler.net/problem=3
import math
number = 600851475143
def is_prime(num):
sqrt = math.sqrt(num)
start = 2
while start <= sqrt:
if num % start == 0:
return False
start += 1
return True
start = 3 if sum(map(int, str(number).split())) else 2
for divider in ra... |
8e34577043f722adf2aec7d83d5509ae84275683 | doroshroman/EulerProject | /utils.py | 382 | 3.53125 | 4 | from functools import reduce
from operator import mul
from math import ceil, sqrt
def seq_prod(sequence):
return reduce(mul, sequence, 1)
def eratosthenes_sieve(N):
primes = [True] * N
for i in range(2, int(ceil(sqrt(N)))):
if primes[i]:
j = i * i
while j < N:
... |
ffa0718b362ee711b37b2af3830019112a80eb8e | Cleyton200K/Perceptron_MultiLayer-Flappy_Bird | /Matrix.py | 5,820 | 3.8125 | 4 | from random import randrange
class Matrix(object):
"""
Define uma matriz N x M, e oferece operações básicas para a Rede
"""
def __init__(self, linhas, colunas):
self.info = [];
for i in range(linhas):
self.info.append([]);
for j in range(colunas):
self.info[i].append(0);
self.__linhas = linhas;
s... |
a8bab701988c6ac7174ffd8fd179d97749476168 | Keshav-Asopa/python_projects | /opencv1.py | 1,113 | 3.9375 | 4 | #importing the libraries
import cv2
#loading the image NOTE:- the program file and the image which is to be loaded should be on the same location
img = cv2.imread("dog1.jpeg")
#printing the dog image in black and white form...0 is used
img1 = cv2.imread("dog.jpg",0)
#printing the image in the numpy format
print(img... |
7f7540b3d36e2553d79beba13e024c39a5f2381f | yuta-ys0603/aizu_online | /chap3/sec_36.py | 681 | 3.703125 | 4 | def insertionSort(A,n,g):
cnt = 0
for i in range(g,n):
v = A[i]
j = i - g
while j >= 0 and A[j] > v:
A[j+g] = A[j]
j = j - g
cnt += 1
A[j + g] = v
return cnt
def shellSort(A,n):
total_cnt = 0
G = [1]
for i in range(1,n):
... |
52bba175c25709cba107b06831e7afd422abd670 | yuta-ys0603/aizu_online | /chap5/sec_54.py | 473 | 3.875 | 4 | n = int(input())
dic = {}
for i in range(n):
com,num = input().split()
if com == 'insert':
dic[num] = num
elif com == 'find':
if num in dic:
print('yes')
else:
print('no')
# dic = []
#
# for i in range(n):
# com, num = input().split()
# if com == 'in... |
dbeb1d34ce70e28069f61361b6d656d860479d6d | ybgirgin3/DjangoChatBot | /TerminaChatBot/chk/1_readdb.py | 1,171 | 3.8125 | 4 | import sqlite3
from sqlite3 import Error
### tablo isimler #####
# kullanıcı isimleri ve şifreleri : register_customuser
def create_connection(db_file):
""" create a database connection to the SQLite database
specified by the db_file
:param db_file: database file
:return: Connection object or None... |
fccd76e4a524527d5fd8ebac08d9ce17f95ef58d | isaacschaessenscoleman/PureGym | /Functions.py | 4,528 | 4 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
gym_data = pd.read_csv('/Users/isaaccoleman/PycharmProjects/Puregym/data.csv')
'''Producing a pivot table with the days of the week as the index, the times throughout the day as columns, and the mean
number of people in the gym as the values.'''
... |
1b8943d22984b3174fbb31e51717f3eed9a473c6 | asharma567/practice_problems | /codeeval/easy/slang_flavor.py | 931 | 3.53125 | 4 | '''
https://www.codeeval.com/open_challenges/174/submit/?lid=731009
'''
import sys
def print_outcome(s):
'''
INPUT
OUTPUT
'''
ending_punc = {'.', '!', '?'}
ending_punc_ctr = 0
position_ctr = 0
lis = [
', yeah!',
', this is crazy, I tell ya.',
', can U believe thi... |
f3a2d2ba7ef4dc623004720f0366e82c181a4025 | asharma567/practice_problems | /codeeval/easy/REMOVE_characters.py | 391 | 3.65625 | 4 | '''
https://www.codeeval.com/open_challenges/13/submit/?lid=717936
'''
import sys
def delete_char(s):
new_s = ''
set_del_chars = set(del_chars)
for sent_char in sentence:
if sent_char not in set_del_chars: new_s += sent_char
return new_s
if __name__ == '__main__':
with open(sys.argv[1], 'r')... |
4b3f447c832012f1baf5aa17d52049ba1a6a442e | asharma567/practice_problems | /codeeval/easy/longest_word.py | 988 | 4.1875 | 4 | '''
https://www.codeeval.com/open_challenges/111/
'''
import sys
def find_longest_word_greedy(sent):
#Greedy: O(n)
if sent == '' : return None
longest_word = None
for word in sent.split():
if not longest_word or longest_word < len(word):
longest_word = word
return ... |
7e374212b819d1a614a1830eea4950e0867a6619 | asharma567/practice_problems | /codeeval/easy/read_more.py | 838 | 3.6875 | 4 | '''
READ MORE
https://www.codeeval.com/open_challenges/167/
'''
import sys
def sentence_trimmer(line):
#there must be other ways to read in a sentence... ?, !, etc.
# final_filtered_list = re.split('\n', file_name)
# final_filtered_list = [str_ele.strip('\n') for str_ele in final_filtered_list][:-1]... |
24916f5c7a20dc3d8935f22963b4f9679a42b105 | asharma567/practice_problems | /change_machine.py | 1,649 | 3.90625 | 4 | '''
Write a function that, given:
an amount of money
a list of coin denominations
computes the number of ways to make amount of money with coins of the available denominations.
Example: for amount=4 (4¢) and denominations=[1,2,3] (1¢, 2¢ and 3¢), your program would output 4—the number of ways to make 4¢ with those deno... |
28cdb358ec4e0051c775c64339bf8dc7c1db4bf2 | asharma567/practice_problems | /bigrams.py | 343 | 3.65625 | 4 | def create_bigram(input_string):
#bigrams of a string will be 1 less than total length
bigram_array = [None] * (len(input_string) - 1)
for index in xrange(1, len(input_string)):
trailing_index = index - 1
bigram_array[trailing_index] = input_string[index] + input_string[trailing_index]
r... |
73548afc325491d4c17c2c7730c9df05a8bb03f4 | asharma567/practice_problems | /random_practice_probs/fibonacci_seq.py | 909 | 4 | 4 | '''
Generate fibonacci sequence
'''
# Exponential O(2^N)
# --
def fib(n):
if n == 0 or n == 1: return n
return fib(n - 2) + fib(n - 1)
# Linear O(N) iteratively
# --
def fib(n):
fib_values = [0, 1]
for i in range(2, n + 1):
fib_values.append(fib_values[i - 1] + fib_values[i - 2])
return fib_values[n... |
b8acc8eb61190c7686b550749cca7809082a5720 | miramen7/learning-software | /python/input-string.py | 466 | 3.734375 | 4 | # !C:\Python27\python
from __future__ import print_function
def main():
#membuat prompt dengan tipe data string
nama = raw_input("Masukan nama anda: ")
#masukan prompt dengan tipe data karakter
karakter = raw_input("Masukan sebuah karakter: ")
print("Halo, %s, Apa kabar?" % nama)
print (... |
de395df61eb6f4ad6c9e775e6f676af75960bdce | ih/pi | /experiments/pagedExperiment/tugofwar/tugofwarQuestions.py | 820 | 3.671875 | 4 | #-To Do
#- make order of shuffle persistent
#- use javascript to cycle through training examples
import random,string
finalQuestionNumber = 5
#this is actually called for every page load so the shuffle gets lost each time...
def generateQuestions():
stimuliNumbers = range(finalQuestionNumber)
random.shuffle... |
2369793fb4509957524937a4d47e2231436e46d9 | gazibo-Pixel/OOPewPie | /actors.py | 1,373 | 3.65625 | 4 | from random import randint
class Player:
def __init__(self, name, level):
self.name = name
self.level = level
def __repr__(self):
return (
'Player {} is at level {}'.format(self.name, self.level)
)
def get_attack_power(self):
return randint(1,100)*s... |
b5c15f25a5b05ca84722991423c844c4f24daea9 | kalhauge/Anaconda | /build/lib/Anaconda/Table.py | 10,216 | 3.5625 | 4 | """
.. module:: Table
:platform: Unix
:synopsis: A module to handle Tables
.. moduleauthor:: Christian Gram Kalhauge : kalhauge@cbs.dtu.dk
7th August - 2012
ATable is a class deticated to handeling the loading of tables and accces. If you'll need to
change the data a AMutableTable class is available.
Curr... |
c31c477460a5b593be03290db87d6687bde3c10f | GuidoPollini/MuTools | /MuTools/_deque6levelQueue.py | 884 | 3.640625 | 4 | import collections # <deque> = double ended queue
class MessageQueue(object):
def __init__(self, maxSize=6):
self._queue = collections.deque()
self._numUnanswered = 0
self._maxSize = maxSize
def sendMessage(self, message):
self._queue.append(message)
... |
0e06bc1f938f34183388ac64c76def7a328c4ba1 | BNHub/Python- | /Made_Game.py | 495 | 4.40625 | 4 | #1. Create a greeting for your program.
print("Welcome to the best band name game!")
#2. Ask the user for the city that they grew up in.
city = input("What is name of the city you grew up in?\n")
#3. Ask the user for the name of a pet.
pet_name = input("What's your pet's name?\n")
#4. Combine the name of their ci... |
ea78c69bf7f187c3a6034e905eef43c12b485ec9 | sweick23/learning-python | /Factorial.py | 302 | 3.9375 | 4 | def factorial(n):
num = 1
while n >= 1:
num = num * n
n = n -1
return num
print factorial(1)
print factorial(2)
print factorial(3)
print factorial(4)
print factorial(5)
print factorial(6)
print factorial(7)
print factorial(8)
print factorial(9)
print factorial(10)
|
2a41e952bd062d1335c4afa4d176d5f25e6eb910 | anindyasdas/MLearn_AI | /KMeans/K_means_ML114.py | 6,217 | 3.6875 | 4 | ################################K-Means Clustering algorithm############################################################
#######################################################################################################################
import os
import random
import numpy as np
from matplotlib import style
... |
98fd5ca509b6d54447a331844031363bd5e798f9 | anindyasdas/MLearn_AI | /Deducation Theorem/Deduction Theorem.py | 6,708 | 3.671875 | 4 | ######################################################Modus Ponens Theory proover##############################################################
#Read me instruction
# OR is denoted by V
# AND is denoted by ^
# NOT is denoted by ~
# Implications are denoted by >
#P implies Q is noted as (P>Q), (NOT)P implies Q is ... |
c3b56b92bfddb7936978e5660e8618d9629e4256 | cabudies/WebScrapping-Quote-SQLite | /sqlite_module.py | 1,522 | 3.921875 | 4 |
import sqlite3
database: sqlite3.Connection
QUOTE_ID = "QUOTE_ID"
QUOTE_QUOTATION = "QUOTE_QUOTATION"
QUOTE_AUTHOR = "QUOTE_AUTHOR"
TABLE_NAME = "QUOTATION"
## establishing connection between database and python
def database_connection():
global database
database = sqlite3.connect("Quotes_Dat... |
bd756574c9ff54568f863b642d5e4ae198fafc47 | git13708/python-study | /day07/14-可迭代对象的检测.py | 855 | 4.0625 | 4 | """
isinstaance(待检测的对象, Iterable)
返回值:True 可以迭代
Flase 不可以迭代
"""
from collections.abc import Iterable
print(isinstance([1, 2, 3], Iterable))
# 自定义一个类
class MyClass(object):
# 增加一个__iter__方法
# 该方法就是一个迭代器
def __iter__(self):
pass
# 创建对象
myclass = MyClass()
print(isinstance(myclass, Iterable... |
7714568c169134400cb9cc9fcd773e805c662419 | git13708/python-study | /day07/11-进程池中的进程间通信.py | 1,660 | 3.53125 | 4 | """
思路:
1、准备两个进程
2、准备一个队列 一个进程向队列中写入数据,然后把队列传递到另外一个进程
3、另外一个进程读取数据
"""
import time
import multiprocessing
# 写入数据到队里的函数
def write_queue(cqueue):
# for 循环,向队列写入数据
for i in range(10):
# 判断队列是否已满
if cqueue.full():
print("队列已满")
break
# 向队列中放入值
cqueue.put(i)... |
e1703989b99e3e99d6f32a3f9301233438b88f96 | Astroxslurg/ovinger | /euclidean_algorithm.py | 887 | 3.703125 | 4 | #!/usr/bin/python3
#Euclidean Algorithm
from sys import stdin
import fractions
import random
def gcd(a, b):
n = max(a, b)
k = min(a, b)
r = n%k
print(n, ' = ', k, '*', n//k, ' + ', r, sep='')
while (not r == 0):
n = k
k = r
r = n%k
print(n, ' = ', k, '*', n//k, ' + ... |
d1df5e0f43abe2b2c2a5b7d651ac3ff6d5577624 | AllCoolNicknamesWereTaken/PYTHON-WORKSHOP | /Lesson-1/SimpleCalculator.py | 513 | 3.53125 | 4 | print 7 + 8, 12+ 4, 5 * 7 + 3, 5 * (7 + 3), 10 / 5, 7 / 2, 7 // 2, 7 % 2, 7 ** 5;
# _ + 5;
# _ ** 2;
#strings
print('"Isn\'t," they said.');
s = 'First line.\nSecond line.' # \n means newline
print s;
print('C:\some\name');
print(r'C:\some\name')
print("dluuuuuuuu"
"uuuuuuuugi napis")
print s[7];
print s[0:7];
pr... |
1a25ee3ab08653e9d793aa24c39c1d3b54b2caa1 | stiftcast/mtsort | /mtsort.py | 6,506 | 3.578125 | 4 | #!/usr/bin/env python3
"""Sorting files by time, made easy.
Gets last modification time from file(s) and folder(s),
then moves them to a new directory, sorting them in new
folders. These folder names are in 'yyyy-mm-dd' format.
"""
import os
import time
import shutil
import errno
from datetime import d... |
94ea1fadb02e307dc4946884ca63ba7ec5ed62e2 | ntoll/code-dojo | /adventure/week1/team3/game2.py | 3,575 | 3.828125 | 4 | DIRECTIONS = 'N', 'E', 'S', 'W'
NORTH, EAST, SOUTH, WEST = DIRECTIONS
class Player(object):
def __init__(self, location, name='Player'):
assert isinstance(location, Location)
self.location = location
self.name = name
class Location(object):
def __init__(self, name, description="")... |
b663b275647be5b9106b0898ea7f275d261c10c8 | Ngangolo/python-liste | /exo4.py | 434 | 3.8125 | 4 | N=int(input("Donner le nombre d'entier:"))
L1=[]
for i in range (N):
A=int(input("Donner un entier:"))
L1.append(A)
print("affichage des nombres de la liste")
print(L1)
LPOS=[]
LNEG=[]
for i in range(N):
if L1[i]>0:
LPOS.append(L1[i])
else:
LNEG.append(L1[i])
print("affichage... |
b7c4cf3b2e254d0b99d43b6c8da415278dc6a245 | logotip123/py_max | /max.py | 512 | 3.890625 | 4 | """Search max digit module"""
from typing import Iterable
from functools import reduce
def max_(lst: Iterable[int]) -> int:
"""
Search max digit with reduce method function
:param lst: list
:return: result
"""
def maxfrom2(first, second):
"""
func max analog for 2 arguments
... |
1689f5917ee66e8fbdc904983a506f0afdfb06fc | tochukwuokafor/my_chapter_4_solution_gaddis_book_python | /bug_collector.py | 285 | 4.15625 | 4 | NUMBER_OF_DAYS = 5
total = 0
for day in range(NUMBER_OF_DAYS):
print('Enter the number of bugs collected on day #' + str(day + 1) + ': ', sep = '', end = '')
bugs_collected = int(input())
total += bugs_collected
print('The total number of bugs collected is', total) |
0d1890ddd1b000d26c4f5433970f2db1dc26090a | tochukwuokafor/my_chapter_4_solution_gaddis_book_python | /average_word_length.py | 372 | 4.25 | 4 | again = input('Enter a sentence or a word: ')
total = 0
words_list = []
while again != '':
words = again.split()
for word in words:
words_list.append(word)
total += len(word)
again = input('Enter another sentence or another word: ')
average = total / len(words_list)
print('The aver... |
2503b97bdfe498cd534ca46b66d718f52c32bcd5 | lauosi/Coursera-Principles-of-Computing- | /week2_game_2048.py | 5,795 | 3.625 | 4 | """
Clone of 2048 game.
"""
import poc_2048_gui
import random
# Directions, DO NOT MODIFY
UP = 1
DOWN = 2
LEFT = 3
RIGHT = 4
# Offsets for computing tile indices in each direction.
# DO NOT MODIFY this dictionary.
OFFSETS = {UP: (1, 0),
DOWN: (-1, 0),
LEFT: (0, 1),
RIGHT: (0, -1)}
d... |
0855e83c12a6a0310e63efb9d455fdb767080fc0 | zecabanhas/estudo_dirigido2 | /exerc5.py | 130 | 3.78125 | 4 | nat = int(input("Digite o valor de nat: "))
i = 0
impar = 1
while i < nat:
print(impar)
i = i + 1
impar =\
impar + 2 |
5739765bc094d69ff6747449bb305b7380ba3f13 | liangfei2016x/py_socket_thread | /test_object_2.py | 1,057 | 3.625 | 4 | #test_object_2.py
class Date_test(object):
"""docstring for Data_test"""
day = 0
month = 0
year = 0
def __init__(self,day,month,year, *arg):
self.day = day
self.month = month
self.year = year
@classmethod
#classmethod用来指定一个类方法,没有此参数指定的类的方法为实例方法
def date_int2str(c... |
b2b61c0468f0e17cddda27def1f5443d75c240a6 | daniel-salamanca/Curso_Basico_de_Python | /Tablas_de _multiplicar.py | 306 | 3.65625 | 4 | def run():
print("Las tablas de mustiplicar")
for tablas in range(1,11):
print("tabla del "+ str(tablas) )
for multiplicador in range(1,11):
print(str(tablas)+"*"+str(multiplicador)+"="+str(tablas * multiplicador))
if __name__ == "__main__":
run() |
7ed9540529f28ea1a98cbc9709e327b114485f0f | stephenroller/ice9 | /ast.py | 12,687 | 3.546875 | 4 | #!/usr/bin/env python
"""
Used for converting a parse tree into an AST.
"""
from tree import Tree
# global dictionary of transformation rules
transform_rules = dict()
# lispy functions to help with the various transformations ------------------
def transformation_rule(trans):
"""
Marks the rule as a transf... |
8c169d3aa6a26c5977b2fd5a66e7bf1c2af286fc | ofisser86/py-check-io | /Scientific Expedition/Time Converter (24h to 12h)/mission.py | 807 | 3.921875 | 4 | def time_converter(time):
# replace this for solution
am = 'a.m.'
pm = 'p.m.'
hours = int(time[0] + time[1])
minutes = time[3] + time[4]
if hours > 12:
return f'{hours - 12}:{minutes} {pm}'
elif hours == 12:
return f'12:{minutes} {pm}'
elif time == '00:00':
return... |
503a7b0e8527a998df35ec8d934f51e4e6756430 | ofisser86/py-check-io | /Electronic Station/Similar Triangles/mission.py | 1,074 | 3.90625 | 4 | from typing import List, Tuple
Coords = List[Tuple[int, int]]
def similar_triangles(coords_1: Coords, coords_2: Coords) -> bool:
# your code here
return False
if __name__ == '__main__':
print("Example:")
print(similar_triangles([(0, 0), (1, 2), (2, 0)], [(3, 0), (4, 2), (5, 0)]))
# These "asse... |
b8e5befc8a1101eb127ad3b8314b81bfe9b79fc6 | abyssxsy/mtools | /mfile.py | 158 | 3.703125 | 4 | import os
import os.path
def make_dir(dir):
'''Create a directory (recursively) if it doesn't exist'''
if not os.path.exists(dir):
os.makedirs(dir)
|
9801344f8961727815a723188ec727b208ea710b | sharma-prerna/Machino | /django_ml_project/machino/algorithms/k_means_cluster.py | 4,606 | 3.59375 | 4 | ''' K means clustering : Unsupervised learning :'''
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def load_dataset(filename):
df = pd.read_csv(filename)
#print("\n------------ UNCLUSTERED DATA ---------\n")
#print(df.head())
#print("---------------------------------------\n")
... |
e08014dfc4e47a396e938e492d8a754abc9dee37 | akash-c-dev/datasciencefromscratch | /src/chap1/chap1.py | 5,191 | 3.640625 | 4 | #!/usr/bin/python
from __future__ import division
users = [
{ "id": 0, "name": "Hero" },
{ "id": 1, "name": "Dunn" },
{ "id": 2, "name": "Sue" },
{ "id": 3, "name": "Chi" },
{ "id": 4, "name": "Thor" },
{ "id": 5, "name": "Clive" },
{ "id": 6, "name": "Hicks" },
{ "id": 7, "name": "Devin" },
{ "id": 8, "na... |
0f45b8b634411e1820fd23e3d1a36fbabf55b2a8 | Olilioli/Lesson-6 | /Lesson 6_5.py | 1,768 | 3.828125 | 4 | # Задание 5 (Реализовать класс Stationery (канцелярская принадлежность).
# Определить в нем атрибут title (название) и метод draw (отрисовка).
# Метод выводит сообщение “Запуск отрисовки.” Создать три дочерних класса
# Pen (ручка), Pencil (карандаш), Handle (маркер).
# В каждом из классов реализовать переопределени... |
2342ebdb3ca638187bed1e42e7686725df39efc0 | teline/LPTHW | /ex33.py | 278 | 3.953125 | 4 | def number_count(x, n):
i = 0
numbers = []
while i < x:
print "At the top i is %s" % i
numbers.append(i)
i = i + n
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
print "The numbers: "
for num in numbers:
print num
number_count(14, 2) |
bfe4795f228feb5cb97fc24e62a1e2a6d811c653 | wangyufu/interview_practice | /数据结构/linked_list.py | 1,513 | 3.921875 | 4 | #!/usr/bin/env python
class Node:
def __init__(self, dataval=None):
self.dataval = dataval
self.nextval = None
class SLinkedList:
def __init__(self):
self.headval = None
def add_left(self,newdata):
old_node = self.headval
self.headval = Node(newdata)
self.h... |
e1d498a9dd74e313f21f30db9fee1d7071d3b2b6 | akinori47/py_practice | /first_practice/first.py | 268 | 3.71875 | 4 | # Python 3.6 practice file
name =''
number_of_try = 0
while name != 'your name':
print('Type your name.')
name = input()
number_of_try += 1
if number_of_try == 5:
print('Превышено число попыток')
break
print('GZ')
|
bbb34324d17716d82eeeb99bca7310fe5539b424 | FunVeeee/Python- | /简单的名片管理系统/cards_tool.py | 4,405 | 4 | 4 | # 记录所有名字的字典
cards_list = []
def show_menu():
"""显示菜单"""
print("*" * 50)
print("欢迎使用【名片管理系统V1.0】")
print(" ")
print("1:新建名片")
print("2:显示全部名片")
print("3:搜索名片")
print("")
print("0:退出系统")
print("*" * 50)
print("")
def new_card():
"""新增名片"""
print("-" * 50)
print(... |
adbf6f0cc74a40af9d6edfce1526aee170c8fefb | amitaa11/Data-Structures-and-Algos | /Big O/O(m*n).py | 371 | 4.0625 | 4 |
array1 = ['a','b','c','d','e']
array2 = [1,2,3,4,5]
def pairs(array1, array2):
for i in range(len(array1)): # n*O(m)
for j in range(len(array2)): # m*O(n)
print(array1[i],array2[j]) # m*n*O(1)
pairs(array1,array2)
# Here there are two different inputs array1 and array2 (m ... |
39515d68b4905ec6b3831664c83c3d3b8646fda6 | Yasar67/Projects | /Tic-Tac-Toe/tic_tac_toe.py | 4,340 | 3.96875 | 4 | tic_tac_toe_board = {'1': ' ' , '2': ' ' , '3': ' ' , '4': ' ' , '5': ' ' , '6': ' ' , '7': ' ' , '8': ' ' , '9': ' ' }
values = []
for key in tic_tac_toe_board:
values.append(key)
def get_board(board):
print(board['1'] + '|' + board['2'] + '|' + board['3'])
print('-+-+-')
print(board['4'] + '|' + bo... |
0792a63a45f8d4f8abb1ba8a8e480fe4b9d7a38f | htrinhq/201yams | /201yams | 1,920 | 3.578125 | 4 | #!/usr/bin/env python3
from sys import argv
from math import factorial
from check import *
from proba import proba
from full_straight import full, straight
def helper():
"""Helper for Yams."""
print("USAGE\n\t\t./201yams d1 d2 d3 d4 d5 c \n")
print("DESCRIPTION\n\t\td1\tvalue of the first die (0 if not th... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.