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 |
|---|---|---|---|---|---|---|
4e4cd16fac3bd2d47e60c49bbae377358ac88187 | danieltran67/All-In-One-Agenda | /venv/Lib/site-packages/somepackage/module1.py | 647 | 3.8125 | 4 | from .module2 import another_function
def some_function():
"""
Describe here what this function does,
its input parameters, and what it returns.
"""
t = _internal_function('hey ho -')
return another_function(t, t)
def test_some_function():
assert some_function() == 'HEY HO -HEY HO -'
#... |
6baf41fdd2caa806dc54bf4500f75657ef2e3f97 | ktkrista/SVM | /SVM-p8.py | 2,457 | 3.5 | 4 | from numpy.random import seed
from sklearn import svm
import numpy as np
import sklearn.preprocessing as preprocessing
import sklearn.model_selection as selection
# Set the random seed to 1
seed(1)
# ====================================
# STEP 1: read the training and testing data.
# specify path to training data an... |
11ff68b22418e0eac9e639d5bf2fdb0610cd6345 | zhongpei0820/LeetCode-Solution | /Python/100-199/190_Reverse_Bits.py | 851 | 3.90625 | 4 | #Reverse bits of a given 32 bits unsigned integer.
#
#For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000).
#
#
#Follow up:
#If this function is called many times, how would you optimize it?
#
... |
823a128d1bc8806d2be2466d9862d1d26f18d233 | zhongpei0820/LeetCode-Solution | /Python/200-299/266_Palindrome_Permutation.py | 413 | 3.796875 | 4 | #Given a string, determine if a permutation of the string could form a palindrome.
#
#For example,
#"code" -> False, "aab" -> True, "carerac" -> True.
#
from collections import Counter
class Solution(object):
def canPermutePalindrome(self, s):
"""
:type s: str
:rtype: bool
... |
76560df649ae4f23f1c9a57c444dabc20cb10a17 | zhongpei0820/LeetCode-Solution | /Python/400-499/468_Validate_IP_Address.py | 2,941 | 4.09375 | 4 | #
#Write a function to check whether an input string is a valid IPv4 address or IPv6 address or neither.
#
#
#
#IPv4 addresses are canonically represented in dot-decimal notation, which consists of four decimal numbers, each ranging from 0 to 255, separated by dots ("."), e.g.,172.16.254.1;
#
#
#
#Besides, lea... |
c763d2479b9a97ef88cf96264957e6371ad5054f | zhongpei0820/LeetCode-Solution | /Python/1-99/022_Generate_Parentheses.py | 786 | 3.8125 | 4 | #
#Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
#
#
#
#For example, given n = 3, a solution set is:
#
#
#[
# "((()))",
# "(()())",
# "(())()",
# "()(())",
# "()()()"
#]
#
class Solution(object):
def generateParenthesis(self, n):
... |
1217052aafda56c9f9d22f53c580f739d733219a | zhongpei0820/LeetCode-Solution | /Python/300-399/301_Remove_Invalid_Parentheses.py | 1,422 | 3.546875 | 4 | #
#Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results.
#
#Note: The input string may contain letters other than the parentheses ( and ).
#
#
#
#Examples:
#
#"()())()" -> ["()()()", "(())()"]
#"(a)())()" -> ["(a)()()", "(a())()"]
#")(" -> [""... |
a2c22202813e7a9681a0ae2bf91f92248f2fd365 | zhongpei0820/LeetCode-Solution | /Python/1-99/031_Next_Permutation.py | 1,385 | 3.890625 | 4 | #
#Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
#
#
#If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
#
#
#The replacement must be in-place, do not allocate extra memory.... |
c21f12a10c30a740edf988560a441d37379c2940 | zhongpei0820/LeetCode-Solution | /Python/1-99/054_Spiral_Matrix.py | 1,610 | 3.84375 | 4 | #Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
#
#
#
#For example,
#Given the following matrix:
#
#
#[
# [ 1, 2, 3 ],
# [ 4, 5, 6 ],
# [ 7, 8, 9 ]
#]
#
#
#You should return [1,2,3,6,9,8,7,4,5].
#
class Solution(object):
def spiralOrder(sel... |
964bcfdd68d4ce43ca924220fef16c8016b879cb | budkina/mipt_rosalind | /heap.py | 1,080 | 3.71875 | 4 | def repairHeap(H,i):
heap=H
largestChild = 0
if i >= len(H)//2:
return
# choose largest child element of i
l = 2*i+1
r = 2*i+2
largestChild = l if (heap[l] >= heap[r]) else r
if (heap[i] < heap[largestChild]):
heap[i], heap[largestChild] = heap[largestC... |
b47123c353f795719dcc74aadb58b2f2ec251f98 | ntrallosgeorgios/python_Add_remove_org | /getServerName.py | 540 | 3.875 | 4 | def getServerName(search, org):
"""
Take the name of server at the
print it if exist
"""
# take the list of organisations and take every time one organisation
for i in org:
# If the seach name is equal with the first element of the organisation
# list then return the website o... |
4a395f599412816ebd9599004457bc5caa16d73c | toledompm/Matematica-Discreta | /programas_1_prova/interseccao.py | 1,031 | 3.84375 | 4 | #recebe um vetor e uma posicao, verifica se algum dos valores anteriores no vetor é igual o que esta na posicao indicada
def repete(vet, pos):
for i in range(0,pos):
if vet[pos] == vet[i]:
return True
return False
#recebe um valor e um vetor, verifica se o valor existe no vetor
def existe(v... |
c963bc56677e8542cf2e5057a93668938816f812 | Javharbek-Yuldashev/game-find-word | /functions.py | 1,857 | 4.0625 | 4 |
def get_word():
from random import choice
from uzwords import words
word = choice(words)
while "-" in word or " " in word or "‘" in word or "’" in word:
word = choice(words)
return (word).upper()
def display(user_letters, word):
display_letter = ""
for letter in word:
if le... |
db34081655237708a347a56c6bf73a40ec4301f6 | GuilhermePeyflo/loja-python | /Sistema/Menu.py | 20,909 | 3.578125 | 4 | from datetime import datetime
from Categoria import Categoria
from Cliente import Cliente
from Produto import Produto
from Cartao import Cartao
from Venda import Venda
class Menu:
"""
Classe para representar a função do menu de interação com o usuário do sistema de Loja.
"""
def __init__(self):
... |
ffb500f887d8bcbcf33ce505ead46306f72e262e | anuragknp/algorithms | /float_str.py | 285 | 4.1875 | 4 | def convert_to_binary(n):
bin = ''
while n > 1:
bin = str(n%2) + bin
n = n/2
bin = str(n) + bin
return bin
def convert_float_to_binary(n):
bin = ''
while n != 0:
n = n*2
bin += str(int(n))
n -= int(n)
return bin
print convert_float_to_binary(0.625)
|
3097f3df840469b1d88d9c69645f5fa1605f0fc2 | anuragknp/algorithms | /linked_list.py | 788 | 4 | 4 | class Node:
def __init__(self, val):
self.val = val
self.next = None
class LinkedList:
def __init__(self):
self._head = None
def insert(self, val):
node = Node(val)
node.next = self._head
self._head = node
def reverse(self):
ptr = self._head
prev = None
while ptr != Non... |
f4565567fcda0a73ea760e305bc1bcf9db3f39d2 | SeuperHakkerJa/Project-Euler-Solutions | /python_sol/p004.py | 896 | 4.0625 | 4 | #
# Solution to Project Euler problem 4
#
# Author: Xiaochen Li
# Date: May 11, 2019
#
#
# Problem: Find the largest palindrome made from the product of two
# 3-digit numbers.
#
# The largest palindrome made from the product of two 2-digit numbers is
# 9009 = 91 × 99.
#
'''
1. check from 999 x 999 to 100 x ... |
21a8c7b37dfa2568af6eb2ca900088f23a9184a5 | nate-fleming/python_tutorial | /lambdas.py | 295 | 3.59375 | 4 | def cube(num): return num ** 3
print(cube(2))
def decrement_list(numbers):
return list(map(lambda num: num - 1, numbers))
print(decrement_list([1, 2, 3]))
def remove_negatives(numbers):
return list(filter(lambda num: num > 0, numbers))
print(remove_negatives([-1, 3, 4, -99]))
|
04f4fb2ff014ebf818edbc2c98f62fc9a7683879 | min-yeong/Python-Basic | /basic_set.py | 3,238 | 3.8125 | 4 | # Set 연습
evens = {0, 2, 4, 6, 8} # 짝수 집합
odds = {1, 3, 5, 7, 9} # 홀수 집합
numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} # 전체 집합
mthree = {0, 3, 6, 9} # 3의 배수 집합
def define_set():
"""
Set 정의 연습
- 순서가 없고 중복 불허
- 인덱싱, 슬라이싱 불가
- len, 포함여부(in, not in) 정도만 사용 가능
- 집합을 표현하는 자료형(집합 연산 가능)
"""
# 리터럴 기호... |
d86282ee11cb7cf8d31feac6eabd8bd6eeccc295 | wieczszy/Project-Euler | /problem042.py | 1,265 | 3.625 | 4 | def generate_triangle_numbers():
triangle_numbers = []
for i in range(10000):
t_number = int(0.5 * i * (i + 1))
triangle_numbers.append(t_number)
return triangle_numbers
def check_if_triangle(number):
triangle_numbers = generate_triangle_numbers()
if number in triangle_numbers:
... |
5c216863d2424c1f2eba9c3a796b1b8d9e5df3ef | wieczszy/Project-Euler | /problem041.py | 510 | 3.609375 | 4 | def get_primes(x):
assert(x >= 0)
sieve = [1] * (x + 1)
primes = []
for i in range(2, x + 1):
if sieve[i] == 1:
primes.append(i)
for j in range(i, x + 1, i):
sieve[j] = 0
return primes
primes = get_primes(10000000)
result = 0
for prime in primes:
... |
958718e8a3414f0271687d4be32493d7fd50460e | MOGAAAAAAAAAA/magajiabraham | /defining functions 2.py | 328 | 4.125 | 4 | text="Python rocks"
text2 = text + " AAA"
print(text2)
def reverseString(text):
for letter in range(len(text)-1,-1,-1):
print(text[letter],end="")
def reverseReturn(text):
result=""
for letter in range(len(text)-1,-1,-1):
result = result + text[letter]
return result
print(reverseReturn(... |
4c343f3c47cbcb5450ffd8262ce82f29ba752172 | MOGAAAAAAAAAA/magajiabraham | /division of numbers.py | 258 | 4.0625 | 4 | usernumber1 =int(input("Pick a number:"))
if usernumber1 %2 ==0 and usernumber1 %4 != 0:
print ("Your number is even")
elif usernumber1 %2 ==1:
print ("Your number is odd")
elif usernumber1 %4 ==0:
print ("Your number is even and divisible by 4") |
7d534a8b400370807db155de1f9fc9f2ed182bad | dLac-biXi1/Keylogger | /keylogger.py | 819 | 3.515625 | 4 | from pynput.keyboard import Key,Listener
class Keylogger:
def __init__(self) -> None:
self.n = 0
with Listener(self.onPress,self.onRelease) as listener :
listener.join()
def appendFile(self,key):
with open(f"log{self.n}.txt", "a+", encoding="UTF-8") as file :
... |
19456c41fc9d4a7f76af8b2c5d60772338c56979 | cheesepuff90/code-kata | /day12.py | 567 | 3.578125 | 4 | def reverse_string(s):
for i in range(len(s)//2):
s[i], s[-i-1] = s[-i-1], s[i]
return s
# a, b = 0, len(s) - 1
# while a < b:
# s[a], s[b] = s[b], s[a]
# a += 1
# b -= 1
# return s
# 문자로 구성된 배열을 input으로 전달하면, 문자를 뒤집어서 return 해주세요.
# 새로운 배열을 선언하면 안 됩니다.
# 인자로 받은 배열을 수정해서 만들어주세요.
# I... |
b3d8417d12409175a8c97b6b0a9344d0d52c9edd | SekouDiaoNlp/sandbox | /processing_tibetan.py | 3,036 | 3.765625 | 4 |
# coding: utf-8
# In[12]:
import re
# In[13]:
#chunk = re.sub(r'([^།])\s', r'\1', chunk) # eliminate the extra spaces added by the segmentation in words
# In[14]:
# syllable = re.sub("་", "", syllable)
# In[7]:
def add_tsheg(line_list):
'''
takes as input a list of text splitted at the tshek.
It... |
a28faa5287000d5c056df0058c3834f299dccb1c | Guilherme-Galli77/Curso-Python-Mundo-3 | /Teoria-e-Testes/Aula023 - Tratamento de Erros e Exceções/main2.py | 1,173 | 4.15625 | 4 | try:
a = int(input("Num: ")) # 8
b = int(input("Denominador: ")) # 0
r = a / b
except:
print(f"Erro!")
else:
print(f"resposta: {r}") # Divisão por zero --> erro
finally:
print("FIM DO CODIGO")
print("="*50)
# Outro formato de tratamento de exceção
try:
a = int(input("Num: ")) # 8
b... |
fc017550df1a79ae77378faba63cbcaee9793ec8 | Guilherme-Galli77/Curso-Python-Mundo-3 | /Exercicios/Ex081 - Extraindo dados de uma Lista.py | 850 | 4.1875 | 4 | # Exercício Python 081: Crie um programa que vai ler vários números e colocar em uma lista. Depois disso, mostre:
# A) Quantos números foram digitados.
# B) A lista de valores, ordenada de forma decrescente.
# C) Se o valor 5 foi digitado e está ou não na lista.
c = 0
lista = list()
while True:
valor = int(input("... |
096ace50fea78a700ab0dad3900b7df4284e45d6 | Guilherme-Galli77/Curso-Python-Mundo-3 | /Exercicios/Ex079 - Valores únicos em uma Lista.py | 680 | 4.25 | 4 | #Exercício Python 079: Crie um programa onde o usuário possa digitar vários valores numéricos
# e cadastre-os em uma lista. Caso o número já exista lá dentro, ele não será adicionado.
# No final, serão exibidos todos os valores únicos digitados, em ordem crescente.
Lista = list()
while True:
valor = int(input("Di... |
889d79103018cde6d0d033a9726d97dfb590f8a5 | Guilherme-Galli77/Curso-Python-Mundo-3 | /Exercicios/Ex077 - Contando vogais em Tupla.py | 341 | 3.890625 | 4 | palavras = ("teste", "codigo", "programar", "casa", "livro", "python",
"programacao", "caneta", "cachorro", "gato", "cadeira", "verde"
"maça", "arroz")
for p in palavras:
print(f"\nNa palavra {p.upper()} temos: ", end="")
for letra in p:
if letra.lower() in "aeiou":
... |
26a3838fea00d6c73fd418d569e7d6871caf58cb | Guilherme-Galli77/Curso-Python-Mundo-3 | /Exercicios/Ex097 - Um print especial.py | 468 | 3.890625 | 4 | # Exercício Python 097: Faça um programa que tenha uma função chamada escreva(), que receba um texto qualquer como
# parâmetro e mostre uma mensagem com tamanho adaptável. Ex:
# escreva(‘Olá, Mundo!’) Saída:
# ~~~~~~~~~
# Olá, Mundo!
# ~~~~~~~~~
def printEspecial(msg):
tam = len(ms... |
e213daa5f9d78a730b3977de1f5c45aafa7b9db3 | Guilherme-Galli77/Curso-Python-Mundo-3 | /Exercicios/Ex089 - Boletim com listas compostas.py | 1,073 | 3.9375 | 4 | # Exercício Python 089: Crie um programa que leia nome e duas notas de vários alunos e guarde tudo em uma lista
# composta. No final, mostre um boletim contendo a média de cada um e permita que o usuário possa mostrar as notas de
# cada aluno individualmente.
dados = list()
while True:
nome = str(input("Nome: "))
... |
4dab86694d10f4214fd440961073d51fd0468853 | naila20/hackinscience | /exercises/097/solution.py | 386 | 3.671875 | 4 | def love_meet(bob, alice):
list = []
for i in bob:
for j in alice:
if i == j:
list.append(i)
list2 = set(list)
return set(list2)
def affair_meet(bob, alice, silvester):
res = []
for j in alice:
for k in silvester:
if j == k an... |
e0b3379e82d7287b4ea4e150366c0d6f3b241b3e | fotonus/PythonLessons | /lesson_002/04_my_family.py | 974 | 3.84375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Создайте списки:
# моя семья (минимум 3 элемента, есть еще дедушки и бабушки, если что)
my_family = ['отец', 'Бабушка Валя', 'Дедушка Петя' ]
# список списков приблизителного роста членов вашей семьи
my_family_height = [[my_family[0],188], [my_family[1], 156], [my_fam... |
66a5ea8a7ae8c68417882705a0492c282e5e26f3 | akshaychanna/all | /data/akshay/python/short_if.py | 109 | 3.9375 | 4 | a = 2
b = 23
#if b > a : print("b is greater")
print("b is greater") if b > a else print("a is greater")
|
8ec60e5c57bc06dee3c675e5b5a1b7c63c264a5f | hms1707/source | /tk연습03.py | 202 | 3.53125 | 4 | from tkinter import *
window = Tk()
btnList = [None] *10
for i in range(0,10) :
btnList[i] = Button(window, text="버튼"+str(i+1))
for btn in btnList :
btn.pack(side=LEFT)
window.mainloop() |
e98133b98b62a1a35398e275fa12fc08935eb831 | Remco123/CactusOS | /tools/fontGenerator/fontgen.py | 4,503 | 3.53125 | 4 | # import required classes
from PIL import Image, ImageDraw, ImageFont
from time import sleep
import sys
# Array that holds a collection of data for each character
characterData = []
# Print iterations progress
def printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█', ... |
4bb7bb6e2a7d1c1aeb4b132b781607ddb54d9f4e | McWixy/college_snake | /game.py | 2,438 | 3.796875 | 4 | from random import randint
from snake import Snake
class Game:
def __init__(self, game_size : int):
self.size = game_size
self.map = []
for _ in range(self.size):
ligne = []
for _ in range(self.size):
ligne.append(0)
self.map.append(ligne)... |
eedd795007ad76013cf69832637e39178046e84d | EgorVezhnin/2021_ZHIGALSKII_infa | /laba3python/ex2.py | 5,002 | 3.515625 | 4 | import turtle
lenbit = 20
diagonal = (2 ** 0.5)*lenbit
dlinlenbin = 2 * lenbit
def printzero():
global lenbit
global diagonal
global dlinlenbin
turtle.pendown()
turtle.forward(lenbit)
turtle.right(90)
turtle.forward(dlinlenbin)
turtle.right(90)
turtle.forward(lenbit)
turtle.rig... |
1617b07865d687b10ba15984a39d0f2148940ddb | EgorVezhnin/2021_ZHIGALSKII_infa | /laba2python/ex11.py | 572 | 3.921875 | 4 | import turtle as t
t.shape('turtle')
t.speed(0)
t.left(90)
def paintfigure(n, razmer, napravlenie):
startrazmer = 20 / n
if napravlenie == "left":
for i in range(n):
t.forward(startrazmer + razmer)
t.left(360 / n)
else:
for i in range(n):
t.forward(star... |
570a82d9a3a3cf97ee913efb2d1779b6edbbeb25 | psJnttl/RaspberryPI | /python/wordPuzzleSolver/FoundWordsList.py | 3,597 | 3.921875 | 4 | '''
contains a list of Words found during searchPath
--
+ InsertWord(
+ WordsFound() returns a list of words found
- SortList before solutionlist returned it's sorted based on points and alphabets
public?
'''
from Word import *
import json
class FoundWordsList():
def __init__(self):
self.... |
f62276e3aade3eddcffa424d40f24716558a6586 | sachanraveesh/python-advanced | /lru_cache.py | 1,620 | 3.65625 | 4 | from collections import deque
class LRUCache:
def __init__(self, capacity:int):
self.c = capacity
self.m = dict()
self.deq = deque()
def get(self, key: int) -> int:
if key in self.m:
value = self.m[key]
self.deq.remove(key)
self.deq.appe... |
9f6a7da78745464d2508b134e51400d07dbba8fa | wilbrodn/python_tutorials | /Coursework3.py | 769 | 3.90625 | 4 |
name = raw_input('What is your name? ')
marks = []
grade = []
gps=[]
for i in range (1,4):
score = input("What is "+str(i)+"th mark?: ")
if score>=80:
grad="A"
gp=4
elif score>=75 and score<80:
grad="B"
gp=3.5
else:
grad="C"
gp=3
marks = marks+[score]
grade = grad... |
5b2633f2664fb18a4c7dbcb483f00db628f33f78 | vtkrishn/EPI | /22_Honors_class/52_Implement_A_Producer_Consumer_Queue/Consumer.py | 766 | 3.734375 | 4 | from threading import Thread, Condition
import random
import time
condition = Condition()
MAX_NUM = 10
#Producer thread
class Consumer(Thread):
def set(self,q, l):
self.queue = q
self.lock = l
#consume
def run(self):
global queue
while True:
#get the loc... |
d19ff58945bad7e67ba9308119a5b8a6d23cfa88 | sakars1/python | /num_digit validation.py | 494 | 4.21875 | 4 | while 1:
name = input("Enter your name: ")
age = input("Enter your date of birth: ")
num = input("Enter your phone number: ")
if name == '' or num == '' or age == '':
print("Any field should not be blank...")
elif name.isalpha() and age.isdigit() and int(age) > 18 and num.isdigit():
... |
ee43539f557136ebc8168d15f90bde533935dd07 | sakars1/python | /oop.py | 453 | 3.796875 | 4 | # class Student:
# def __init__(self):
# print("Hello")
# def display(self):
# print("this is the display func")
# s1=Student()
# s1.display()
# s1=Student
# s1.display(s1)
class Student:
def __init__(self,name,age):
self.age=age
self.name=name
def display(self):
... |
287ae427798413284cc5c9ee99545de0f36f0931 | sakars1/python | /inheritance.py | 476 | 3.890625 | 4 | class Child:
def __init__(self,name,age):
self.age=age
self.name=name
def display(self):
print("Name: ",self.name)
print("Age: ",self.age)
class Student(Child):
def __init__(self,degree,Child):
self.degree=degree
self.name=Child.name
self.age=Child.ag... |
9796ff0fcb53c619510d7fdfb387177a2c27415f | eirvandelden/2IA05 | /FP/assignment3/hs2lhs.py | 741 | 3.71875 | 4 | # this python script converts a hs file to a lhs file
input_file = open("picoParser2011.hs", "r")
output_file = open("picoParser2011.lhs", "w")
consecutive_comment = False
for line in input_file:
if len(line) >= 2:
if line.startswith("--"):
line = line[2:len(line)].strip() + '... |
2c07ac8b9390a494a8b2838b93962808410cc129 | taddes/algos_python | /Recursion/factorial_tail_recursion.py | 360 | 3.953125 | 4 | # Tail recursion implementation
# Eliminate dependancy on stack frames. There is no need for back tracking.
# Does not require you to return a value after each function call to pass
# to next, due to accumulator
def factorial_tail(n, accumulator=1):
# base case
if n == 1:
return accumulator
ret... |
728f6e51eb42897c5bcdd390ae706596bb2c073d | taddes/algos_python | /Interview Questions/Sudoku/sudoku_solve.py | 1,503 | 4.28125 | 4 | # sudokusolve.py
""" Sudoku Solver
Note: A description of the sudoku puzzle can be found at:
https://en.wikipedia.org/wiki/Sudoku
Given a string in SDM format, described below, write a program to find and
return the solution for the sudoku puzzle in the string. The solution should
be returned ... |
f6763623fb0d75530abcb8723f786f46fae76fea | taddes/algos_python | /Binary Search Tree/binary_search_tree.py | 2,251 | 4.09375 | 4 | class Node:
"""Vertex in the search tree"""
def __init__(self, data, parent):
self.data = data
self.left_child = None
self.right_child = None
self.parent = parent
class BinarySearchTree:
def __init__(self):
self.root = None
def insert_node(self, data, ... |
1c2e4eb1290ba9e81ba77f2ef7b3e743fd466a69 | azul-007/tools | /network_analysis/binary.py | 328 | 3.578125 | 4 | #!/usr/bin/python3
#Author: azul007
#Date: 03/11/2020
def bin_num():
for num in range(256):
bin_a = bin(num)
bin_a = bin_a[2:] #Strip "0b"
if len(bin_a) < 8:
diff = 8 - len(bin_a)
add_zero = "0" * diff
print("*", num, "\t", str(add_zero + bin_a))
else:
print("*", num, "\t", bin_a)
bin_n... |
b29f723ed11f5c2537e673b44ac9628046fc3777 | Diego415-Creador/Prueba | /tiposdedatos.py | 235 | 3.640625 | 4 | #Programa para calcular las raices de una ecuacion de segundo grado
from math import sqrt
a = 1
b = 0
c = 1
x_1 = 0
x_2 = 0
x1 = (-b + cmath.sqtr(b**2 - 4*a*C)/2
x2 = (-b - cmath.sqtr(b**2 - 4*a*C)/2
print(x_1, 'n')
print(x_2)
|
f6948df6bdc398de4e17f693aa029ca4da965e7d | vk312/todo | /todo5.py | 3,895 | 3.546875 | 4 | class todo:
def __init__(self):
self.lis = []
self.items = []
self.temp = []
self.i = 1
def addtask(self, task):
global i
self.lis.append({'task':task,'id':self.i, 'is_deleted': False, 'is_complete': False})
self.i += 1
print("task is added in you... |
f9560d72aff3355785d71742a48b1ca950d41a61 | krishxx/python | /practice/Prg100Plus/Pr113.py | 177 | 4.125 | 4 | '''
113. Write a program to Count the Number of Digits in a Number
'''
num=int(input("enter a number: "))
count=0
while num!=0:
count=count+1
num = int(num/10)
print(count)
|
ed52487eea3210a5020cb7ecd5f7d77dc00db997 | krishxx/python | /practice/lphw/ex44d.py | 659 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri May 25 17:37:03 2018
@author: Srikrishna.Sadula
"""
class Parent(object):
def override(self):
print ("PARENT override()")
def implicit(self):
print ("PARENT implicit()")
def altered(self):
print ("PARENT altered()")
class Child(Parent):
... |
c036e74da29234ee9cd9e0caaa29955cc45a9e12 | krishxx/python | /practice/Prg100Plus/Pr115.py | 175 | 4.15625 | 4 | '''
115. Write a program to Print all Integers that Aren't Divisible by Either 2 or 3 and Lie between 1 and 50.
'''
for i in range(1,51):
if i%2!=0 or i%3!=0:
print(i)
|
fadd06193eb3ae24ee17ada185a248199306506b | krishxx/python | /practice/Prg100Plus/Pr130.py | 402 | 4.21875 | 4 | '''
130. Write a program to Print Largest Even and Largest Odd Number in a List
'''
li=list()
print("enter numbers in to the list")
num=input()
while num!='':
li.append(int(num))
num=input()
sz=len(li)
i=0
lo=-1
le=-1
while i<sz:
if li[i]%2==0 and li[i]>le:
le=li[i]
i=i+1
elif li[i]%2!=0 and li[i]>lo:
lo=li[i... |
fee66281c1b6b4443c664c8aa0f452b926620ca5 | krishxx/python | /practice/cp_sols/pr32.py | 338 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun May 27 07:25:48 2018
@author: Srikrishna.Sadula
"""
def checkValue(n):
if n%2 == 0:
print ("It is an even number")
val = 1
else:
print ("It is an odd number")
val = 0
return val
#checkValue(7)
if(checkValue(8) == 1):
pri... |
f7d755b926d5f9789c6e470f19f3b26f82108edc | krishxx/python | /practice/cp_sols/Pr56.py | 388 | 3.859375 | 4 | '''Question: 56
Write a function to compute 5/0 and use try/except to catch the exceptions.
Hints:
Use try/except to catch exceptions.
Solution:
'''
def throws():
5/0
#err
print("tintintitin")
return
try:
throws()
except ZeroDivisionError:
print ("division by zero!")
except Exception:
print ('Caugh... |
69c86dc61b1da9b98e2566a9e37b717a61758631 | krishxx/python | /practice/Prg100Plus/Pr118.py | 227 | 4.40625 | 4 | '''
118. Write a program to Print an Identity Matrix
'''
num=int(input("enter size of sq matrix: "))
for i in range(1,num+1):
for j in range (1,num+1):
if i==j:
print(1,end=' ')
else:
print(0,end=' ')
print("\n") |
fe6f43a9e0f4335c28d5b63292c37542a1e2b932 | ovwane/leetcode-1 | /src/MaximumAverageSubarrayI.py | 703 | 3.6875 | 4 | '''
LeetCode: Reverse Integer
description: Given an array consisting of n integers, find the contiguous subarray of given length k that has the maximum average value. And you need to output the maximum average value.
author: Ehco1996
time: 2017-08-11
'''
class Solution(object):
def findMaxAverage(self, nums, ... |
f3f3fc1759292472e8e27cde3df49393c1877b55 | ovwane/leetcode-1 | /src/PalindromeNumber.py | 632 | 3.953125 | 4 | '''
LeetCode: Palindrome Number
description: Determine whether an integer is a palindrome. Do this without extra space.
author: Ehco1996
time: 2017-10-27
'''
class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
return False
... |
beb4a3820cde261ffc047371048e6a018126f7e8 | ovwane/leetcode-1 | /src/ArrayPartitionI.py | 695 | 3.734375 | 4 | '''
LeetCode: Add Two Numbers
description:
Given an array of 2n integers, your task is to group these integers into n pairs of integer,
say (a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible.
Input: [1,4,3,2]
Output: 4
Explanation: n is 2, and the maximum su... |
ee3c0a88f1a98acb948dce04574274c5a7f12765 | jacobtread/Freddys-Fast-Food | /order.py | 6,085 | 3.671875 | 4 | from random import random
from typing import Dict, List, NoReturn
class Order:
order_id: str # The id of the order
name: str # The name of the user
phone: str # The phone number of the user
address: str # The address of the user
delivery: bool # Whether or not to deliver the order
fish: ... |
0426a2503a4ada50099c08799ec5ee689da9df3f | Tonu-2020/python | /cycle5/bank.py | 947 | 3.875 | 4 | class bankaccount:
def __init__(self,accno,name,acctype,balance):
self.accno= accno
self.name= name
self.acctype= acctype
self.balance= balance
def deposit(self):
amount = float(input("\nenter amount to be deposited : "))
amount = amount + self.balance
... |
b9372fca8ccb71c852e23e2ecb265ed51744639b | ssam9423/Physics | /E-Field Motion.py | 5,652 | 3.65625 | 4 | #!/usr/bin/env python
# coding: utf-8
# # PHYS 301 Problem Set 2
#
# Computational Part
#
# Sammy Song | 94237328
# # Motion of a Charge Through a Charged Ring
#
# Write down the formula for the electric field along the axis of a charged ring of radius $R$ that carries a total charge $-Q$. Imagine that a charge $Q... |
aa151ee9827460075e609151b9062dc9601cd847 | yanminglun0519/Exercise-3 | /tableCheck.py | 247 | 3.96875 | 4 | import sqlite3
conn = sqlite3.connect('wordCount.db')
cursor = conn.cursor()
print("Connected")
sql = '''select * from wordCount'''
results = cursor.execute(sql)
all_words = results.fetchall()
for word in all_words:
print(word) |
0caf21ad24399368799cd001509dd4ea8d85fc11 | LeroySalih/aoc_2020 | /day5/main.py | 950 | 3.515625 | 4 |
def getRow(code, low, high):
#length of the list is 2**length of code
if len(code) == 1 and code == code[0] in ["F", "L"]:
return low
if len(code) == 1 and code == code[0] in ["B", "R"]:
return high
if code[0] in ["F", "L"]:
return getRow(code[1:], low, (low + high) // 2)
else:
retur... |
5abaf19fbc586fa30f55a44253c4be963cce9970 | NSCC-Fall-2020/PROG1700-da-course-notes | /blackjack.py | 2,665 | 3.53125 | 4 |
# Game of Blackjack
# Deal the user two random cards and show their values (assume Ace = 11)
cards = {
'Two of Clubs': 2,
'Three of Clubs': 3,
'Four of Clubs': 4,
'Five of Clubs': 5,
'Six of Clubs': 6,
'Seven of Clubs': 7,
'Eight of Clubs': 8,
'Nine of Clubs': 9,
'Ten of Clubs': 10... |
615b4972f4f0bef35073f90566e9f61a85a9d2fb | davidiwu/TensorFlowForBeginner | /tfMNISTTutorial.py | 1,447 | 3.578125 | 4 | import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# load the MNIST data
mnist = input_data.read_data_sets("MNIST_data", one_hot=True)
# batch size: number of pics per batch
batch_size = 100
# number of batches
n_batch = mnist.train.num_examples // batch_size
x = tf.placeholder(tf.fl... |
9949436544cadcda6713f86cae3e348f8dcad041 | davidiwu/TensorFlowForBeginner | /mcts-easy.py | 5,569 | 3.796875 | 4 | from math import *
import random
class GameState:
def __init__(self):
self.playerJustMoved = 2
def Clone(self):
st = GameState()
st.playerJustMoved = self.playerJustMoved
return st
def DoMove(self, move):
self.playerJustMoved = 3 - self.playerJustMoved
def Ge... |
cc72801fc66d1c6097b987ae7ee7a43bae4ab2e1 | Ashutos-h/python-L15 | /4.py | 282 | 3.75 | 4 | #Answer 4
from tkinter import *
def display():
global lbl
lbl.configure(text=namE.get())
root=Tk()
nam=Label(root,text="Enter your name")
namE=Entry(root)
btn=Button(root,text="Submit",command=display)
lbl=Label(root)
nam.pack()
namE.pack()
btn.pack()
lbl.pack()
root.mainloop() |
8fe52274b12326cdbcf108019ac4aff7fa9c685a | juanfcreyes/python-exercises | /np/np_random.py | 1,327 | 3.71875 | 4 | from numpy import random
import numpy as np
## ramdom numbers
x = random.randint(100)
print('random integer number under 100: ', x)
x = random.rand()
print('\nrandom number between 0 and 1:', x)
x=random.randint(100, size=(5))
print('\nrandom integer number array of five elements:', x)
x = random.randint(100, siz... |
4f1c683a98d112484891549d7ea6a08a21a00056 | juanfcreyes/python-exercises | /more_dictionaries.py | 613 | 4.15625 | 4 | def anagrams(array):
wordsMap = {}
for item in array:
if "".join(sorted(item)) in wordsMap:
wordsMap.get("".join(sorted(item))).append(item)
else:
wordsMap.setdefault("".join(sorted(item)),[item])
return wordsMap
valuesort = lambda m: [pair[1] for pair in sorted(m.it... |
badb954ac5b0cc4a3ba768b4090ff07cec30eeb1 | juanfcreyes/python-exercises | /functional_programing/json_decode.py | 1,327 | 3.59375 | 4 | def json_encode(data):
if isinstance(data, bool):
if data:
return "true"
else:
return "false"
elif isinstance(data, (int, float)):
return str(data)
elif isinstance(data, str):
print('str', data)
return '"' + escape_string(data) + '"'
elif i... |
9b9d4e0de5866fc84ab558987ed6141e1dfd92d2 | juanfcreyes/python-exercises | /make_slug.py | 315 | 3.703125 | 4 | import re
def make_slug(text):
pattern = '[^a-zA-Z0-9\s]'
slug = re.sub(pattern, '', text)
slug = re.sub('\s', '-', slug.strip())
slug = re.sub('-{2,}', '-', slug)
return slug
print(make_slug("hello world"))
print(make_slug("hello world!"))
print(make_slug(" --hello- world--"))
|
676e9904c7e8ebf8c84fd721d9e07288555d3ebb | juanfcreyes/python-exercises | /np/np_practice_l2.py | 1,245 | 3.546875 | 4 | import numpy as np
def maxx(x, y):
"""Get the maximum of two items"""
if x >= y:
return x
else:
return y
pair_max = np.vectorize(maxx, otypes=[float])
a = np.array([5, 7, 9, 8, 6, 4, 5])
b = np.array([6, 3, 4, 8, 9, 7, 1])
print(np.where(a >= b, a, b))
print(pair_max(a, b))
arr = np.ar... |
d62c34c059c0074ca01d4196d5c26202be417145 | Banerjeed/grocerylist_2.0 | /shoppinglist_practice.py | 1,228 | 4.09375 | 4 | groceries = [ ]
def addone_shopping(item):
global groceries
if item in groceries:
print "Error: that item is already on your grocery list"
else:
item.lower()
groceries.append(item)
groceries.sort()
return groceries
def delete_shopping(R_item):
R_item.lower()
if R_item not in groceries:
print "Er... |
c0e7f61eb85f4aaf4c72c9aa3144fe38a5383e25 | sadikul1500/wumpus-world-simulation | /world.py | 2,993 | 3.515625 | 4 | import random
class Percept:
def __init__(self):
self.wumpus = False
self.pit = False
self.glitter = False
self.stench = 0
self.breeze = False
self.visited = False
self.pitValue = 0
self.wumpusValue = 0
self.visitedValue = 0
... |
eb603fd134b839074fbdf831b142c3c7ca33a5f9 | ByteLorde/RSEnterprise | /src/base/modules/Drawable/Color/Color.py | 1,683 | 3.65625 | 4 |
class Color:
@staticmethod
def RED():
return Color(90, 0, 0)
@staticmethod
def GREEN():
return Color(0, 90, 0)
@staticmethod
def BLUE():
return Color(0, 0, 90)
def __init__(self, red=0, green=0, blue=0):
self._red = ColorValue(red)
self._blue ... |
51f556851248fb22defdbdeda57597b7cd35fe63 | ByteLorde/RSEnterprise | /src/tests/Tests1/ChatTest.py | 904 | 3.546875 | 4 | from chatterbot import ChatBot
import os
from gtts import gTTS
chatbot = ChatBot(
'Ron Obvious',
trainer='chatterbot.trainers.ChatterBotCorpusTrainer'
)
# Train based on the english corpus
chatbot.train("chatterbot.corpus.english")
# Get a response to an input statement
text = input("YOU: ")
# Language in... |
06e11a4041d7be64059dd1b27ae2212e7ca51f73 | Husnah-The-Programmer/simple-interest | /Simple interest.py | 300 | 4.125 | 4 | # program to calculate simple interest
def simple_interest(Principal,Rate,Time):
SI = (Principal * Rate * Time)/100
return SI
P =float(input("Enter Principal\n"))
R =float(input("Enter Rate\n"))
T =float(input("Enter Time\n"))
print("Simple Interest is",simple_interest(P,R,T))
|
32aa5e979a48e4fdf35a6d61f57a71a5de6d58e2 | josephimathias/Beer-Hypothesis-Testing | /test_modules.py | 4,505 | 3.734375 | 4 | """This module contains functions used to perform hypotesis testing."""
# Data analysis packages:
# import pandas as pd
import numpy as np
import scipy.stats as stats
import seaborn as sns
def welch_t(a, b):
"""Return Welch's t statistic for two samples."""
# welch t calculation
numerator = a.mean() - b.... |
e37504cb15e63c012fa902aabdea7d0ed4bd098c | JigarShah110/Python | /Pattern/pattern7.py | 325 | 3.546875 | 4 | from __future__ import print_function
class Pattern:
def __init__(self):
self.row_counter = 1
self.max_no = input("Enter Max. No: ")
def draw(self):
for self.row_counter in range(1, self.max_no+1):
for count in range(self.row_counter, 0, -1):
print (count, end="")
print ("")
obj1 = Pattern()
obj1.d... |
793eb68ce13b595cc55e8b2e1f7b42adbd68d999 | JigarShah110/Python | /Pattern/pattern6.py | 412 | 3.65625 | 4 | from __future__ import print_function
class Pattern:
def __init__(self):
self.row_counter = 1
self.space = " "
self.max_no = input("Enter Max. No: ")
def draw(self):
for self.row_counter in range(1,self.max_no+1):
print (self.space*(self.row_counter-1), end=" ")
for count in range(self.max_no-self.row... |
91e24f837e6f4508995577eeb9b9cf149665d63e | michelejolie/PDX-Code-Guild | /happy_sad.py | 320 | 3.671875 | 4 | how_many_children_do_you_have
x =3+5
print(how_many_children_do_you_have)
#3 integer(int)
how_much_do_you_weigh_in_Kg
class2 = ('float')
print(how_much_do_you_weigh_in_Kg)
#75.6 float
what_is_your_name
class3 = ('str')
print(what_is_your_name)
#"Jeff" string(str)
are_you_happy
class4 = ('bool')
#true Boolean
|
b2352c3fca442ba2280b8a535d627917d562eb96 | michelejolie/PDX-Code-Guild | /converttemperuter.py | 223 | 4.25 | 4 | # This program converts from Celsius to Fahrenheit
user_response=input('Please input a temperature in celsius :')
#celsius=int(user_response)
celsius=float(user_response)
fahrentheit=((celsius *9) /5)+32
print(fahrentheit)
|
df4675e51ae70067d8d5747071d440216ceb2ba0 | michelejolie/PDX-Code-Guild | /file_io.py | 1,223 | 3.546875 | 4 | from pig_latin import pig_latin
def read_file(file_path):
with open(file_path, 'r') as file:
return file.readlines()
def write_file(file_path, new_lines):
with open(file_path, 'w') as file:
for line in new_lines:
file.write(line + '\n')
def append_to_file(file_pat... |
488ab904ea898c452ff5c2eecbd832a8de6fac3e | michelejolie/PDX-Code-Guild | /phonebook.py | 509 | 3.640625 | 4 | f = open('filename.py', 'w')
f.close()
def main():
name = input("jon snow (or press enter to end input): ")
number = input("555-555-5555: ")
Phonebook['jon snow'] = 555-555-5555
name = input("adam jones (or press enter to end input): ")
number = input("666-666-6666: ")
Phonebook['adam jones'] = 666-666-6666... |
d5a9c22ede263e457f0b76d6f6ebe01406d8da0b | michelejolie/PDX-Code-Guild | /Chris/hello_beautiful.py | 192 | 4.0625 | 4 | # print('hello beautiful')
#
# #input("how's it going?")
name = input('what is your name? ')
#print('hello' +name)
#conditional logic
if name == "michele":
print('you are learning')
|
48d494fbc16f2458590d4a9bbfcbddfd1a951cff | michelejolie/PDX-Code-Guild | /sunday.py | 829 | 4.15625 | 4 | # how to use decorators
from time import time
#def add(x, y=10):
#return x + y
#before = time()
#print('add(10)', add(10))
#after = time()
#print('time taken:', after - before)
#before = time()
#print('add(20,30)', add(20, 30))
#after = time()
#print('time taken:', after - before)
#before = time()
#print... |
1b932e62aca7800ad491fe4f39f818dafaa44683 | bamboodew/Python_Cookbook | /Chapter01_data_structures_and_algorithms/12/The_element_with_the_most_occurrences_in_the_sequence.py | 1,676 | 3.921875 | 4 | '''
Created on 2018年3月18日
怎样找出一个序列中出现次数最多的元素呢?
@author: Administrator
'''
# collections.Counter 类就是专门为这类问题而设计的,
# 它甚至有一个有用的most_common() 方法直接给了你答案。
# 为了演示,先假设你有一个单词列表并且想找出哪个单词出现频率最高。
# 你可以这样做:
words = ['look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',
'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not... |
bc0d8df23d35c840f7aad94bd9da6c8ce27720e2 | bamboodew/Python_Cookbook | /Chapter01_data_structures_and_algorithms/16/Filter_sequence_element.py | 1,364 | 3.640625 | 4 | '''
Created on 2018年3月20日
你有一个数据序列,想利用一些规则从中提取出需要的值或者是缩短序列
@author: Administrator
'''
# 最简单的过滤序列元素的方法就是使用列表推导。比如:
mylist = [1, 4, -5, 10, -7, 2, 3, -1]
list1 = [n for n in mylist if n > 0]
print(list1)
list2 = [n for n in mylist if n < 0]
print(list2)
# 使用列表推导的一个潜在缺陷就是如果输入非常大的时候会产生一个非常大的结果集,
# 占用大量内存。如果你对内存比较敏感,
# 那么你... |
a3cce1eae429024007c681ca4b8213b5a7ba053e | chrisadbr/python-101 | /loop.py | 551 | 4.03125 | 4 | '''
https://github.com/BenestaBiseko/python-101/invitations
'''
'''
Write a simple script that demonstrate your understanding of loops in python
'''
'''
Write a simple script that demonstrate your understanding of loops in python
'''
# Start with wile loop
i = 1
while i <= 7:
print(i)
i += ... |
33a1a4a041ceb5b931720b6ae018ab73fbee20bb | SixroomSandwich/infa_2021_fomicheva | /laba2/turtle5.py | 138 | 3.703125 | 4 | import turtle as t
from random import *
t.shape('turtle')
for i in range(100):
t.forward(randint(0, 40))
t.left(randint(0, 360))
|
d7614f9207bbd81611bf28b2dc6a2f246aabc976 | zxs1215/LeetCode | /19_Remove_Nth_Node_From_End_of_List.py | 825 | 3.75 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# @return a ListNode
def removeNthFromEnd(self, head, n):
if head == None:
return
node = head
count = 1
while node.next != No... |
f5f6d942565e076577c15ce93bd4a4da936b9c33 | zxs1215/LeetCode | /208_implement_trie.py | 1,505 | 4.125 | 4 | class TrieNode(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.val = None
self.children = []
self.has_word = False
def next(self, val):
for child in self.children:
if child.val == val:
return chil... |
52821198076dadf7db6e06e9de2ac0a8ca7ebc26 | Veena-Wanjari/My_Programs | /fizzbuzz.py | 392 | 3.796875 | 4 |
n = 100
FIZZ = []
BUZZ = []
FIZZBUZZ = []
number = []
for i in range(1,n):
if (i % 3 == 0) and (i % 5 == 0):
FIZZBUZZ.append(i)
elif (i % 3 == 0):
FIZZ.append(i)
elif (i % 5 == 0):
BUZZ.append(i)
else:
number.append(i)
print(f" FIZZ : {FIZZ} \n B... |
a795f4d70c99ac5c5844f8762d867570ee527363 | Veena-Wanjari/My_Programs | /season_guess.py | 477 | 4 | 4 | guess = input("Please guess the season : ")
guess.lower()
if guess == 'winter':
print("Yes .. You are right !!")
elif guess == 'summer':
print("OOPS !! Try again....")
elif guess == 'spring':
print("OOPS !! Try again....")
elif guess == 'autumn':
print("OOPS !! Try again....")
elif gue... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.