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 |
|---|---|---|---|---|---|---|
809e3e52798bd91a1c7ef42dc71ad6487fd0ee1c | 7oranger/Statistical_learning | /ex2/EX2_1.py | 2,042 | 3.6875 | 4 | # -*- coding:utf-8 -*-
'''
Created on 2016-10-04
stat leaning Ex2: chapter 2 programming 3.
Plot boxes to show the distributioins of the 4 variables in the Iris data set
@author: RENAIC225
'''
from sklearn import datasets
import numpy as np
import matplotlib.pyplot as plt
iris = datasets.load_iris()
label=iris.target
a... |
3746d20389da2bd7ae37f9b9d3a8a47d3e2bba23 | TalhaYa/My_Python_Project | /AnnemYemek.py | 1,722 | 3.671875 | 4 | tum_siparis = {"Siparisleriniz": [], "Hesabınız": []}
annem = {"Musakka": 12, "Kuru Fasulye": 9,
"Taze Fasulye": 9,
"Tavuklu Pilav": 10,
"Ciger": 18}
print("*****Annem Yemek*****")
print(annem)
def siparis(yemek):
siparis_listesi = []
adet = int(input("Kaç adet pide si... |
f7b509b39b6ac604079dc2cf54a79c5850dc5634 | Mostar23/python-practice | /eccomerse/west.py | 1,780 | 3.828125 | 4 | import random
import time
def add(n, m):
return [n + m]
print(add(8, 9))
def kent(n):
return n + "you"
print(kent("yess "))
def boss(y):
return [ch for ch in y]
co = input("place a word in here: ")
ceo = co.join(random.choice(co))
print("word: ", co)
print("shuffling....")
print(boss(ceo))
def le... |
9dcdde4e82ba9c9dffa4b742b285efa3b917f089 | Mostar23/python-practice | /eccomerse/north.py | 1,403 | 3.796875 | 4 | import random
import time
from math import *
import threading
name = input("Enter your name: ")
print(time.sleep(1))
print("Welcome ", name, "lets start the game")
def number(n):
n = r
count = 0
r = int(input("Enter a number: "))
print("number: ", r)
print("checking...")
if r < 150 and r:
print("wro... |
b1377859cf7433acd0f7133204dd5af633e7ff8a | Mostar23/python-practice | /eccomerse/functions.py | 1,897 | 3.765625 | 4 | def times_table(x):
for a in [1,2,3,4,5,6,7,8,9]:
print(f"{x} x {a} = {x * a}")
def multiply(f):
f(10)
multiply(times_table)
def takeout():
n = input("Enter a word:")
print(n)
if n in "abdcdefghijklmnopqrstuvwxyz":
print(n[1], n[2], n[3], n[4], n[5])
return n[1], n[2], n[3],... |
704045f6eaaa5c51d088b11ceb7877a7cf69b2d3 | hannahmclarke/python | /dice_roll.py | 1,199 | 4.28125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue May 21 21:02:54 2019
@author: Hannah
"""
"""
Program will roll a pair of dice (number of sides will be randomly determined)
and ask the user to guess the total value, to determine who wins
Author: Hannah
"""
from random import randint
from time import sleep
def get_sides... |
aa10af05d03beeeb6175a178ece1d20af845724d | supervisaproject/Escuela-Analitica | /Bloque 1/Sesion 1/HomeWorks/HomeWork 2 - Operacion/hw2.py | 430 | 4.03125 | 4 | #ejercicio 2
#Cambia los valores para que todos los resultados en pantalla sean "True"
#Change the values so that all the results on the screen are "True"
a = -3
b = [3, 9, 5]
c = True
d = 20
'''
DO NOT TOUCH !!!!
NO TOCAR !!!!
'''
#a
resultado_1 = a is 3.0
print(resultado_1)
#b
resultado_2 = b[1]<0
print(resulta... |
a16aeb45a19ab709ab4aca7412b93f2cbcd4fb00 | supervisaproject/Escuela-Analitica | /Bloque 1/Sesion 1/Ejemplos/Ejemplos - Operadores/ej13_logico.py | 1,237 | 4.3125 | 4 | #Ejemplo 13
#operadores de identidad
#is.
#si dos variables son dienticas devuelve True si no devuelve False
#identity operators
#is.
#if two variables are scientific it returns True if it does not return False
x = "hola"
y = "hola"
resultado = x is y
print(resultado)
#diferencia entre is y ==
#difference between is ... |
8a7c58ba13a2295ffbf4866d61eaef210814a58b | supervisaproject/Escuela-Analitica | /Bloque 1/Sesion 2/HomeWorks/HomeWork 2 - Macedonia de frutas/hw2.py | 633 | 4.28125 | 4 | # - *- coding: utf- 8 - *-
#ejercicio 4
#sin modificar el listado de frutas crea un codigo que muestre el siguiente mensaje
#without modifying the fruit list, create a code that displays the following message
#Mis frutas favoritas son:
#uva
#platano
#limon
#naranja
frutas = ["manzana", "pera", "uva", "cebolla", "pla... |
bc6fa3567e8a670a2aa348ae0a5acfac953355bc | supervisaproject/Escuela-Analitica | /Bloque 1/Sesion 2/Ejemplos/Ejemplos - Condicionales/ej1_edad.py | 196 | 3.671875 | 4 | # - *- coding: utf- 8 - *-
#Ejemplo 1
edad = int(raw_input("Escriba su edad: "))
#Comprobacion acceso por edad al contenido A
if edad >= 18:
print("Ha accedido correctamente al contenido")
|
4390dc478adf44ff2f9c19a7fb65aeab5cdfb495 | supervisaproject/Escuela-Analitica | /Bloque 1/Sesion 2/Ejemplos/Ejemplos - Bucles/ej8_while.py | 266 | 3.90625 | 4 | # - *- coding: utf- 8 - *-
#Ejemplo 8
#bucle while 1
i = 1
while i <= 3:
print(i)
i += 1
print("Programa terminado")
#bucle while 2
i = int(input("introduce numero para empezar el bucle: "))
while i <= 50:
print(i)
i += 1
print("Programa terminado") |
19598e89136d8877cbac882d3a37884f328f0ce8 | anandmcts1/Data-structures-using-python | /circular_ll.py | 891 | 4.0625 | 4 | class Node:
def __init__(self,data):
self.data=data
self.next=None
class CircularLinkedList:
def __init__(self):
self.head=None
def prepend(self,data):
new_node=Node(data)
if not self.head:
self.head=new_node
else:
p=self.head
while p.next!=self.head:
p=p.next
p.next=new_node
new_node... |
d237537805c5484ad197b93b6f689faf4d7e479a | anandmcts1/Data-structures-using-python | /Traversing_of_a_tree.py | 1,152 | 4 | 4 | class Node:
def __init__(self,value):
self.value=value
self.left=None
self.right=None
class BinaryTree(object):
def __init__(self,root):
self.root=Node(root)
def preOrder(self,root):
if root.value!=None:
print(root.value,end=" ")
if root.left!=None:
self.preOrder(root.left)
if root.right!=N... |
b1785ee71ee859f25942519427967c9a327fcca0 | cluelessidiot/Machine-learning | /python basics/dict.py | 437 | 4.03125 | 4 | def dictionary():
print("1")
ab={'a':'z','b':'x','c':'y','aathil':'nasi'}
print("aathil is ",ab['aathil'])
print("there are {} elements in dictionary and {} crosses to {}".format(len(ab),"aathil",ab['aathil']))
print(ab.keys())
l=list(ab.keys())
#listing keys......
for i in range(len(l)):
print(l[i])
if 'a... |
fb25de3c4e3a5b5fb0417bff46165ad5278816d4 | suekwon/FEProgramming1 | /scipy examples/linear_regression.py | 544 | 3.625 | 4 |
from scipy.stats import linregress
import numpy as np
def f(x):
return 2*x
x = np.random.randn(200)
y = f(x) + 0.3*np.random.randn(200)
gradient, intercept, r_value, p_value, std_err = linregress(x,y)
print("intercept = %g"%intercept)
print("slope = %g"%gradient)
print("r^2 = %g"%r_value**2)
print("p_value = %g... |
9b2dc6146ac5377403facaaaa02d16734277b9ad | asim-ibushe/Spark_Foundation_DA_DataScience_internship | /Task1 GRIP/Percentage_predictor.py | 2,340 | 4.09375 | 4 | '''
Regression : Simple Linear Regression
DataSet : Study_Score
Training Dataset : study_hrs, Percentage obtained
Testing Dataset : Actual study hours
'''
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
from sklearn.model_selection import train_t... |
35095c567c2c0a470a7d25f16ea19492439abcbf | Alveo/alveo-galaxy-tools | /tools/nltk/g_frequency.py | 1,191 | 3.6875 | 4 | import nltk
from nltk import FreqDist
import argparse
nltk.download('punkt', quiet=True)
def arguments():
parser = argparse.ArgumentParser(description="generate a word frequency table from a text")
parser.add_argument('--input', required=True, action="store", type=str, help="input text file")
parser.add_... |
91d7c8687cd659ae48aedc533fc96eab18c13039 | marandmart/CS50 | /pset6/mario/more/mario.py | 295 | 3.90625 | 4 | from cs50 import get_int
# gets the number of blocks as input
while True:
number_of_blocks = get_int("Height: ")
if number_of_blocks >= 1 and number_of_blocks <= 8:
break
for n in range(1, number_of_blocks + 1):
print((number_of_blocks - n) * " " + n * "#" + " " + n * "#") |
491b01ac88b8be27a9602297af76c53d63f6d3af | cookjw/misc | /algorithms/data_structures/linked_list.py | 4,108 | 3.671875 | 4 | class ObjectThatCouldBeInList:
def __init__(self, value=None):
self.value = value
def __repr__(self):
return str(self.value)
def __str__(self):
return self.__repr__()
def __eq__(self, other):
return self.value == other.value
def objecti... |
023f40c1c2a6fea69d9f903c6641a1927b8ea112 | callmeliuchu/LeetCode | /Problems/98ValidateBinarySearchTree.py | 628 | 3.515625 | 4 | class Solution:
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
self.flag = True
self.isValid = True
self.judge(root)
return self.isValid
def judge(self,root):
if root:
self.judge(root.left)
... |
52e70f9c172c20deee711a76f9cf864380e8af29 | Lanottez/IC_BA_2020 | /2nd Term/Optimisation_Decision_Models/Assignments/Assignment 3/Belmont.py | 996 | 3.640625 | 4 | from pulp import *
# define the town names
names = ['Arlington', 'Belmont', 'Cambridge', 'Lexington', 'Somerville', 'Winchester']
# define the distance matrix
distances = [[ 0, 5, 10, 15, 20, 15],
[ 5, 0, 8, 10, 15, 12],
[10, 8, 0, 15, 20, 10],
[15, 10, 15, 0, 10, 12],
... |
18440ad27f90f49a1c08f5df08ffe73d743d6967 | Lanottez/IC_BA_2020 | /1st Term/Data_Structure_and_Algorithms/Codes/Exercises/ses02/ses02_extra.py | 2,174 | 4.4375 | 4 | def middle_of_three(a, b, c):
"""
Returns the middle one of three numbers a,b,c
Examples:
>>> middle_of_three(5, 3, 4)
4
>>> middle_of_three(1, 1, 2)
1
"""
# DON'T CHANGE ANYTHING ABOVE
# YOUR CODE BELOW
return ...
def sum_up_to(n):
"""
Returns the sum of integers ... |
6b0c5403c93f1c7572071ccd03fb07a2810f5c9c | Lanottez/IC_BA_2020 | /1st Term/Data_Structure_and_Algorithms/Codes/Exercises/ses07/tests/more_monsters.py | 7,393 | 4 | 4 | test = {
'name': 'Extending Monster Class',
'points': 0,
'suites': [
{
'cases': [
{
'answer': '453cf288da1dfd386b98842f7679fc94',
'choices': [
'1',
'3',
'4',
'5'
],
'hidden': False,
'locked': True,
... |
bd22d6b13580996baf61585819f2d143aff7eaad | Lanottez/IC_BA_2020 | /1st Term/Data_Structure_and_Algorithms/Exercises/Exercise_2/tests/q1.py | 1,925 | 3.609375 | 4 | test = {
'name': 'Recap',
'points': 0,
'suites': [
{
'cases': [
{
'code': r"""
>>> print(4 * 3) # If there is an error, type Error
12
""",
'hidden': False,
'locked': False
},
{
'code': r"""
>>> x = 2
... |
8ee4f7214d13842468a03b05f7fdd25e3947c7fc | Lanottez/IC_BA_2020 | /1st Term/Data_Structure_and_Algorithms/Codes/Exercises/ses02/ses02.py | 1,057 | 4.375 | 4 | def sum_of_squares(x, y):
"""
Returns the sum of squares of x and y
Examples:
>>> sum_of_squares(1, 2)
5
>>> sum_of_squares(100, 3)
10009
>>> sum_of_squares(-1, 0)
1
>>> x = sum_of_squares(2, 3)
>>> x + 1
14
"""
# DON'T CHANGE ANYTHING ABOVE
# YOUR CODE BELOW... |
0c143e6c44d259294ada8ee2cda95c37f74a15ff | Lanottez/IC_BA_2020 | /1st Term/Data_Structure_and_Algorithms/Codes/Exercises/ses06/ses06_extra.py | 1,525 | 4.5625 | 5 | def caesar_cipher_encrypt(str_to_encrypt, n):
"""
Encrypt string using Caesar cipher by n positions
This function builds one of the most widely known encryption
techniques, _Caesar's cipher_. This works as follows:
you should be given a string str_to_encrypt and an encoding
integer n, wh... |
7fa2f78013545c0bbd9893d05ab1da806552fcde | ariqbasyar/Mini-Project | /E_GIM_1806205110_MuhammadAriqBasyar_Tugas04/E_GIM_1806205110_MuhammadAriqBasyar_Tugas04.pyw | 1,720 | 3.515625 | 4 | """
Importing the libraries
"""
import sys, pygame
from pygame.locals import *
"""
Make the function of main and try to open the files
"""
def main():
try:
from assets.game import Game
from assets.character import Character
from assets.obstacle import Obstacle
# Call the class of ga... |
df67ab04a476dffaf692cd5211ee65a6cc8f256d | PlanetTeamSpeakk/CLI-Games | /battleship.py | 10,562 | 3.984375 | 4 | from __main__ import *
import random
import time
from termcolor import colored
from sys import argv
from typing import Final
__name__ = "Battleship"
term_width: Final[int] = 45
term_height: Final[int] = 39
def gen_board(sea: list[list[bool]], boats: list[tuple[tuple[int, int], tuple[int, int], int]], sho... |
9e3b43f720717b98833aa61d43c612ed86f8e541 | JairoReyes/python | /ejercicio1.py | 1,889 | 3.984375 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#UNAM-CERT
#Jairo Alan Reyes Aldeco
aprobados = []
def aprueba_becario(nombre_completo):
"""
Guarda el nombre del alumno en letras mayusculas en la lista aprobados en dado caso de que
su nombre no se encuentre en la lista que se esta comparando y los ordena.
Rec... |
c4a931c64a6d6d479f419ffdd22f85b980540fc3 | Gui25Reis/Mudanca-de-base | /arquivos/outras-versoes/_outros/Mudança de Base 02.py | 7,013 | 3.9375 | 4 | print('O resultdo começa a partir do número abaixo do "zero" do quociente')
print('Máx. 15 dígitos')
print()
bi = int(input("Base inicial: ", ))
bf = int(input("Base final: ", ))
if bi != 2:
print()
num = int(input('Digite o número, SEM ESPAÇO: ', ))
print()
#Separando por dezenas, centenas..
div... |
8baf544d3a435d1d39b6c05cf82b8156c152b836 | nikrasiya/Two-Pointers-2 | /88_merge_sorted_array.py | 1,708 | 4.0625 | 4 | from typing import List
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
"""
https://leetcode.com/problems/merge-sorted-array/
// Time Complexity : O(m... |
409ef5ba6745db47dbff12729c87e41eb9761e21 | dpochernin/Homework_2 | /Homework_2_6.py | 266 | 4.125 | 4 | list_1 = []
while len(list_1) < 3:
list_1.append(int(input("Enter number:")))
i = 0
if list_1[0] == list_1[1] or list_1[1] == list_1[2] or list_1[0] == list_1[2]:
i = 2
if list_1[0] == list_1[1] == list_1[2]:
i = 3
print("In list is ", i, "mach digits")
|
851d8a5e8fa43ba1ff514ac64d6b72d2b08fab86 | joelcamera/metnum-tp2 | /implementacion/knn.py | 983 | 3.625 | 4 | import numpy as np
import matplotlib.pyplot as plt
from sklearn import neighbors, datasets
def plot(df, k, step):
data = df.as_matrix()
X = data[:,1:3] # columns 2 and 3
y = data[:,0]
clf = neighbors.KNeighborsClassifier(k, weights='uniform')
clf.fit(X, y)
# Plot the decision boundary. For th... |
f28a065e507ad9a5d6f1be401ae1b78cf3b6f89a | maraha13-meet/MEET-YL1 | /Lab4/number.py | 503 | 3.875 | 4 | class Integer(object):
def __init__(self, number, variable) :
self.number = number
self.variable = variable
def display(self):
print self.variable + str(self.number)
class NegativeInteger(Integer):
def __init__(self, number):
super(NegativeInteger, self).__init__(number, variable = "-")
def display(self):
... |
1f97e1566e08344f6e446a078e485e3b6ed04fb5 | KlipperKyle/dotfiles | /bin/util/yaml2json.py | 289 | 3.703125 | 4 | #!/usr/bin/env python3
#
# yaml2json → Python version
#
# Read a YAML document on stdin and print its equivalent JSON.
#
import json
import sys
import yaml
# https://pyyaml.org/wiki/PyYAMLDocumentation
json.dump(yaml.load(sys.stdin, Loader=yaml.CLoader), sys.stdout, indent=4)
print()
|
b45107089651dbe73617d7bc09c604b38ef33933 | Y161537/mypython | /class2.py | 829 | 4 | 4 | import random as r
class Fish:
def __init__(self):
self.x = r.randint(0, 10)
self.y = r.randint(0, 10)
print('初始位置:(%d, %d)' % (self.x, self.y))
def move(self):
self.x += r.choice([1, -1, -2, 2])
self.y += r.choice([1, -1, -2, 2])
print('移动后位置:(%d, %d)' % (self... |
fd6cdfa7aa53d7ee9f6c669ee99591b8f1a168e0 | tsaklidis/skroutz-custom-basket | /skroutzbasket/Utilities/sanitize/functions.py | 1,858 | 3.59375 | 4 | import re
class Allow():
def alphanumeric(self, data):
# Allow letters, numbers and underspace
if not re.match(r'(^[\w._]+$)', data, re.UNICODE):
return False
return data
def letters(self, data):
# Allow only letters
if not re.match(r'(^[\D.]+$)', data, re... |
0b2fb61b66dc632c5b80c585189e6e09408f1d2a | ericsperano/dougiebot | /tests/test_last_word.py | 433 | 3.84375 | 4 | """
test_last_word
"""
import unittest
from dougiebot import last_word
class TestLastWord(unittest.TestCase):
"""
TestLastWord
"""
def test_last_word(self):
"""
test_last_word
"""
self.assertEqual("hello", last_word("hello"))
self.assertEqual("you", last_word("... |
7d3e24b89e54f42068ce2b8dca77ca5e3fc2abed | santhosh15798/k | /sa.py | 233 | 4.15625 | 4 | ch=input()
if(ch=='a'or ch=='e'or ch=='i'or ch=='o' or ch=='u' or ch=='A' or ch=='E'or ch=='I'or ch=='O' or ch=='U'):
print ("Vowel")
elif((ch>='a' and ch<='z') or (ch>='A' and ch<='Z')):
print("Consonant")
else:
print("invalid")
|
b679f1f3ecfbcdfd3b193e996e5b7a12f3c97e98 | CookieVulture/Questions | /Array/Run-length encoded list.py | 1,299 | 4 | 4 | '''
1313. Decompress Run-Length Encoded List
Easy
125
391
Add to List
Share
We are given a list nums of integers representing a list compressed with run-length encoding.
Consider each adjacent pair of elements [freq, val] = [nums[2*i], nums[2*i+1]] (with i >= 0). For each such pair, there are freq elements with ... |
1737ae560ebee4037c593745f47137d21e784e65 | kovacszitu/Essentials | /PythonBootcamp/FunctionPracticeLevel1.py | 1,108 | 3.9375 | 4 | #OLD MACDONALD: Write a function that capitalizes the first and fourth letters of a name
'''
old_macdonald('macdonald') --> MacDonald
Note: 'macdonald'.capitalize() returns 'Macdonald'
'''
def OldMacDonald (name):
if (len(name) > 3):
return name[:3].capitalize() + name[3:].capitalize()
return 'T... |
2124627b9af47243dc5db466391e34d7059dbcb5 | kovacszitu/Essentials | /PythonBootcamp/decorator.py | 1,138 | 4.03125 | 4 | def func():
return 1
def hi():
print("Hi!")
hi2= hi
del hi
hi2()
def hello(name="Agent"):
print("The hello() function has been executed!")
def greet():
return "\t This is the greet() function inside the hello()"
def welcome():
return "\t This is welcome() function inside... |
cfdad0faa4f9b37134eae169b8ee7cfd541fa85e | kovacszitu/Essentials | /PythonBootcamp/advanced_data.py | 1,911 | 3.8125 | 4 | # 1. Advanced Numbers
print(hex(12), bin(12))
print(pow(2,4), pow(2,4,3))
print(abs(-3))
print(round(8.1))
import math
print(math.pi)
print(round(math.pi, 4))
# 2. Advanced Strings
s = "hello python"
print(s.capitalize(), s.upper(), s.lower())
print(s.count('o'), s.find('o'))
print(s.center(20, '-'))
print("Hello\t... |
49e3ebc69264c62fcc421132204a578ca9537a5e | kovacszitu/Essentials | /PythonBootcamp/Project1TicTacToe.py | 4,257 | 4.09375 | 4 | # Initalize board
def InitBoard(boardSize):
return ([' '] * boardSize)
# Board display
def DisplayBoard (board):
print(' | |')
print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[4] + ' | ' + board[... |
f7e4fe715a3f45719528cf4d4dbd37eeae511e05 | t2y/python-study | /NFC_NFD_problem/read_file_and_show_unicode_name.py | 484 | 3.671875 | 4 | import sys
import unicodedata
def show_unicode_name(line):
for char in line.strip():
name = unicodedata.name(char)
space = ' '
if unicodedata.combining(char) != 0:
space += ' '
print(f'{char}{space}: {name}')
filename = sys.argv[1]
with open(filename, encoding='utf-8') ... |
c215b7bfef62ac935565ad167d4026ef35b3ae13 | t2y/python-study | /B-Tree/b-tree/height_of_btree.py | 2,459 | 3.96875 | 4 | """
Understand the best and worst case height of a B-tree
* https://en.wikipedia.org/wiki/B-tree
* https://cs.stackexchange.com/questions/59453/why-is-b-tree-search-olog-n
* https://www.quora.com/How-do-I-derive-the-best-and-worst-case-height-of-a-B-Tree # noqa
"""
import argparse
import logging
import math
import ... |
857f74ea7fe272f76b453b0184f38e510d3d47f6 | t2y/python-study | /Testing/03_use_type_hint/type_hint_classes.py | 438 | 3.90625 | 4 | # -*- coding: utf-8 -*-
class MyClass:
# The __init__ method doesn't return anything, so it gets return
# type None just like any other method that doesn't return anything.
def __init__(self) -> None:
...
# For instance methods, omit `self`.
def my_class_method(self, num: int, str1: str) -> str:
... |
d1f63bc973099508fd5fa1c8b97c9be5b04a96a5 | t2y/python-study | /MiniOsaka/namedtuple_class.py | 157 | 3.5 | 4 | from typing import NamedTuple
class Point(NamedTuple):
x: int
y: int
p = Point(x=1, y='x') # Argument has incompatible type "str"; expected "int"
|
5590f6ce3573044974ff971aab2d0d87b9420ad9 | t2y/python-study | /B-Tree/b-tree/visitor.py | 605 | 3.640625 | 4 | from abc import ABC
from abc import abstractmethod
class NodeVisitor(ABC):
@abstractmethod
def visit_root(self, node, **kwargs):
pass
@abstractmethod
def visit_node(self, node, **kwargs):
pass
@abstractmethod
def visit_leaf(self, node, **kwargs):
pass
def visit(... |
f9666b1af8c040d4cc88461a2648169ed2e55053 | t2y/python-study | /Testing/03_use_type_hint/type_hint_functions.py | 1,128 | 4.03125 | 4 | # -*- coding: utf-8 -*-
from typing import Callable, Iterable, Union, Optional, List
# This is how you annotate a function definition.
def stringify(num: int) -> str:
return str(num)
# And here's how you specify multiple arguments.
def plus(num1: int, num2: int) -> int:
return num1 + num2
# Add type annotati... |
dbf674c925d35400ca1b8eee98eab9f7ffb714e4 | t2y/python-study | /HighPerformancePython/05/yield_sample.py | 743 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
ジェネレーターの利用例
"""
def tuggle():
"""
>>> g = tuggle()
>>> next(g)
True
>>> next(g)
False
>>> next(g)
True
"""
r = False
while True:
r = not r
yield r
def file_read(file_name):
with open(file_name) as f:
for line in f:
... |
b3276e2772d17cf1ffa0ddfa346675cb7a315d39 | t2y/python-study | /Testing/03_use_type_hint/type_hint_complicated.py | 1,362 | 3.75 | 4 | # -*- coding: utf-8 -*-
from typing import Union, Any, List, cast
# To find out what type mypy infers for an expression anywhere in
# your program, wrap it in reveal_type. Mypy will print an error
# message with the type; remove it again before running the code.
reveal_type(1) # -> error: Revealed type is 'builtins.... |
28ae0899dadaa6c9aa97f51964ac091bc0a4af58 | t2y/python-study | /LanguageProcessing/100-knocks-2015/chapter1/02.py | 308 | 3.890625 | 4 | """
02. 「パトカー」+「タクシー」=「パタトクカシーー」
「パトカー」+「タクシー」の文字を先頭から交互に連結して文字列「パタトクカシーー」を得よ.
"""
s1 = 'パトカー'
s2 = 'タクシー'
print(''.join(i + j for i, j in zip(s1, s2)))
|
6a4fe106472a57f5522beda4a44c5611e7016cdb | ShawnnWatson/CTI-110 | /P2T1_SalesPrediction_WatsonS.py | 368 | 3.828125 | 4 | # This program a sales prediction based on total sales
# 02/11/2018
# CTI-110 P2T1 - Sales Prediction
# Shawnn Watson
# Total sales input
total_sales = float(input('Enter the projected sales:'))
# Calculates the profit as 23 percent of the total sales
profit = total_sales * 0.23
# Displays the profi... |
497cc587ab1de6d8d63ebe7ddb82f7af3384bfc1 | kileyneushul/python_stack | /_python/python_fundamentals/Week 1/functions_intermediate_I.py | 246 | 3.5625 | 4 | import random
def randInt(min=0, max=100):
range = max-min
return (random.random()*range + min)
print(randInt())
print(randInt(max=50))
print(randInt(min=50))
print(randInt(min=50, max=100))
print(randInt(min=74, max=75))
|
93c3e4cdb4f911490ebcdbc2f63c548cb21e05ad | wi3734/TicTacToe | /tictac.py | 4,020 | 3.8125 | 4 | import sys
import random
class Engine():
def __init__(self):
self.game = Game()
def start(self):
self.game.game_current_status()
class Game():
def __init__(self): #requires an instance of 'Grid' and 'Referee' and two "User"
self.grid = Grid()
self.check = Decider()
... |
c7424fc3cfc8289cac34ee3cf35a9640e2810602 | hyuraku/Python_Learning_Diary | /section12/coroutine_lesson.py | 228 | 3.65625 | 4 | def s_hello():
yield 'Hello1'
yield 'Hello2'
yield 'Hello3'
def g_hello():
while True:
y = yield from s_hello()
yield y
g = g_hello()
print(next(g))
print(next(g))
print(next(g))
print(next(g))
|
b42e8264567ce2f9cbdc7022645d7d5c5c8a745c | hyuraku/Python_Learning_Diary | /section7/test_sqlite3.py | 747 | 4.09375 | 4 | import sqlite3
#test_sqlite3.dbを開く、無ければ生成する。
conn = sqlite3.connect('test_sqlite3.db')
#メモリー上にDBを作成する
#conn = sqlite3.connect(':memory:')
curs=conn.cursor()
# curs.execute(
# 'CREATE TABLE persons(id INTEGER PRIMARY KEY AUTOINCREMENT,name STRING )')
# conn.commit()
#データの挿入
# curs.execute('INSERT INTO persons(n... |
90f827ddde885c279fbf54ec75e9d04f743b59d3 | hyuraku/Python_Learning_Diary | /section2/comprehension/inSet.py | 156 | 3.8125 | 4 | s=set()
#これは通常の集合型データの生成
for i in range(10):
s.add(i)
print(s)
#集合内包表記
s2={i for i in range(10)}
print(s2)
|
638cd82594d426b03aa471ead40ee21e696ca814 | hyuraku/Python_Learning_Diary | /section1/dictionary.py | 1,183 | 4.125 | 4 | #辞書型のデータの基本的な作り方。
d={'x':10,'y':20}
print(d)
print(type(d))
#> <class 'dict'>
print(d['x'],d['y'])
#xの値を100にする。
d['x']=100
print(d['x'],d['y'])
#> 100 20
#'z':200 を追加する
d['z']=200
#'1':50 を追加する
d[1]=50
print(d)
#> {'x': 100, 'y': 20, 'z': 200, 1: 50}
#これも辞書型データの作り方
d2=dict(a=10,b=20)
print(d2)
#> {'a': 10, 'b': 20... |
d807c70cb9925cd3408811bd8c8e7d98e4c5d1c5 | Conor12345/alevel-stuff | /schoolio-may/venv/linked_lists.py | 586 | 3.84375 | 4 | class Node():
def __init__(self, data):
self.data = data
self.next = None
def print(self):
if self.next == None:
print(self.data)
else:
print(self.data)
self.next.print()
def add(self, newData):
if self.next is None or self.next.d... |
3718818da97f86f6fa423730fdd7e947e2955e6b | Conor12345/alevel-stuff | /school-jan/venv/A Object Orientated/person.py | 497 | 3.640625 | 4 | class Person():
def __init__(self, firstname, surname):
self.firstname = firstname
self.surname = surname
def speak(self):
print("Hello, my name is", self.getfullname() + "!")
def getfullname(self):
return self.firstname + " " + self.surname
def kiss(self, otherperson)... |
a4bae0c2a5c53ca1119e70d6fee2181a92c38366 | tsbawa61/Machine-Learning | /sentiAnalySimple.py | 1,274 | 3.96875 | 4 | import nltk.classify.util
from nltk.classify import NaiveBayesClassifier
from nltk.corpus import names
def word_feats(words):
return dict([(word, True) for word in words])
positive_vocab = [ 'awesome', 'outstanding', 'fantastic', 'terrific', 'good', 'nice', 'great', ':)' ]
negative_vocab = [ 'bad', 'ter... |
d3c176dd25f1799da027de15397df2dca7533dae | tsbawa61/Machine-Learning | /kwargs.py | 499 | 3.703125 | 4 | def my_func(**kwargs):
for i, j in kwargs.items():
print(i, j)
my_func(name='tim', sport='football', roll=19, sex='M')
def my_three(a, b, c):
print(a, b, c)
a = [1,2,3] ; my_three(*a) # here list is broken into three elements
def my_four(a, b, c,d):
print(a, b, c, d)
a = {'a': "one", 'b... |
ed66ce1f15335f02892c67549ba2ecfe299ab6a4 | tsbawa61/Machine-Learning | /posTag.py | 661 | 3.96875 | 4 | import nltk
from nltk.tokenize import word_tokenize
text = word_tokenize("Smart John of Washington met sweet Jenny who was also very beautiful and was going quickly to her big home")
# We will get words tagged as Nouns, Verbs, Etc by the following statement
pos_text=nltk.pos_tag(text)
print(pos_text)
prin... |
0927ab0b267daa2cc6c16c978fecca6de11ff24c | tsbawa61/Machine-Learning | /decisinTreeEx1.py | 1,916 | 3.6875 | 4 | #Importing required libraries
import pandas as pd
import numpy as np
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
#Loading the iris data
data = load_iris()
print('Classes to predict: ', data.target_names)
#Extrac... |
2a8a00a85779f20010af278428aa1912741f605b | rmukkamala/ds-alg | /task2/union_intersection.py | 4,271 | 4.03125 | 4 |
"""
1. Create a class Node with instance variables data and next.
2. Create a class LinkedList with instance variable head.
3. The variable head points to the first element in the linked list.
10. Define the function remove_duplicates which removes duplicate elements from the list passed as argument.
11. Define the fu... |
8ba8acfd8f0889372100dff79cbe9aefa5a42022 | rmukkamala/ds-alg | /task3/max_and_min.py | 1,504 | 3.953125 | 4 |
"""
Max and Min in a Unsorted Array
In this problem, we will look for smallest and largest integer from a list of unsorted integers.
The code should run in O(n) time. Do not use Python's inbuilt functions to find min and max.
Bonus Challenge: Is it possible to find the max and min in a single traversal?
Sorting usual... |
385ed5928e46caeba48239d8303f9b34ffcc5310 | ritwik15416/Scientific-Computing-with-Python | /Polygon Area Calculator/Area_calc.py | 1,153 | 3.765625 | 4 | class Rectangle:
def __init__(self,width,height):
self.width = width
self.height = height
def set_width(self,width):
self.width = width
def set_height(self,height):
self.height = height
def get_area(self):
area = self.width * self.height
return area
... |
0bae952affbebfcb6926b4588431c5f406835200 | JHMamun/Python-Practice-Codes | /typeconversion.py | 157 | 3.671875 | 4 | x = input("x: ")
#y = x + 1
print(int(x))
print(float(x))
print(bool(x))
# Falsy
# ""
# 0
# []
# None(null)
# Only these values will give Flase bool value
|
509967c500a49669a2f2053701b739bbae11b755 | zspatter/stack-vs-queue | /data_set/generate_numbers.py | 1,318 | 3.6875 | 4 | import random, csv
def generate_randints(n):
"""
Generates n random integers between 0 and 1,000,000 (inclusive)
:param int n: number of ints to generate
:return: list of random ints
"""
rand_ints = list()
for x in range(n):
rand_ints.append(random.randint(0, 1000000))... |
a81b5d89e29be080db822771fbfa505842801980 | johnbaldwin/sqlsoup_demo | /tests/test_models.py | 2,292 | 3.53125 | 4 |
import unittest
from notebook import db
class Notebook_models_TestCase(unittest.TestCase):
def setUp(self):
self.library_definitions = (
('Library of Alexandria', 'library-of-alexandria',
'an ancient library of importance which was destroyed by fire '+\
'For more info... |
46fbb12a9a626163ceb28c2299e7bb04abe04932 | zombiyamo/nlp100 | /1/03.py | 254 | 3.75 | 4 | # -*- coding: utf-8 -*-
import string
str = "Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics.".translate(None,',.')
strlength = []
strs = str.split()
for i in strs:
strlength.append(len(i))
print(strlength) |
937b252cf0f3ae5c26c1eb5b353f597cfe5fa879 | rentixeli/CTF | /Net-Force 2020/Cryptography/2/py.py | 873 | 3.515625 | 4 | s = 'ogrk hg tl`n srbszizrzig aiphgu mg ycahzylluf vllu fg ahcoogneg pceinc is ngzdluag'
for c in s:
if 'o' == c:
print ('l', end = '')
elif 'g' == c:
print ('e', end = '')
elif 'r' == c:
print ('u', end = '')
elif 't' == c:
print ('z', end = '')
elif 'e' == c:
print ('g', end = '')
elif 'u' == c:
pr... |
5ee32dc61765de0a9eeeb52bd4cfc8b587a56397 | become-iron/ADS_lab-works | /2/var5.py | 1,158 | 3.875 | 4 | # -*- coding: utf-8 -*-
def is_identity_matrix(matrix):
is_identity = True
for i in range(len(matrix)):
for j in range(len(matrix[i])):
if (matrix[i][j] != 0 and i != j) or (matrix[i][i] != 1 and i == j):
is_identity = False
break
if not is_identity:... |
bff0c1e82c743e5a41d802709663bc14294428c4 | Tamunokorite/python-practice | /functions/addfive.py | 297 | 4.03125 | 4 | '''
This code will add five to a list of numbers and print the equation and result
'''
numbers = [i for i in range(0, 41)]
five_added = list(map(lambda x: (x + 5), numbers))
len_numbers = len(numbers)
for i in range(len_numbers):
print(f"{numbers[i]} + 5 = {five_added[i]}") |
172574a9448eed2fe666bd1dc13cd2412f519f43 | erweil17/window | /contactsensor.py | 375 | 3.546875 | 4 | #This program is for testing the window contact sensor.
#The red LED should light up whenever the sensor is making contact (or the window is closed)
from gpiozero import LED, Button
import time
led = LED(26)
window = Button(21)
while True:
if window.is_pressed:
led.on()
else:
led.off()
tim... |
a03b4a67494222120d3752a3c4a749abec64bbe3 | tingli99/bootcamp | /exercis_1.4.py | 294 | 3.8125 | 4 | def longest_common_substring(seq1,seq2)
"""return the longest_common_substring between two sequences"""
# Initialize the longest_common_substring
longest_common_substring = ''
for base in longest_common_substring(seq1,seq2):
if Aa in seq1, find Aa in seq2
|
a858fbfb5b2570d28a04edf7ef7d99fae6cd1038 | mcwiseman97/Programming-Building-Blocks | /adventure_game.py | 1,829 | 4.1875 | 4 | print("You started a new game! Congratulations!")
print()
print("You have just had a very important phone call with a potential employer.")
print("You have been in search of a new job that would treat you better than you had been at your last place of emplyement.")
print("John, the employer, asked you to submit to him ... |
d2d7081a2d3abbdbab7098153c73b1567bdbf80c | DanFlannel/PythonLearning | /Operators.py | 497 | 4.03125 | 4 |
def add(nums):
val = nums[0]
for n in range(1, len(nums)):
val += nums[n] #this is shorthand for val = val + nums[n] is the same as val += nums[n]
return val
def sub(nums):
val = nums[0]
for n in range(1, len(nums)):
val -= nums[n]
return val
def div(nums):
val = nums[0]
... |
041f854df75852bbf01de5da9c11dbd933b6f176 | SDoman/HelloWorld | /untitled3.py | 270 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 16 13:45:16 2020
@author: Admin
"""
#words = ['cat', 'ate', 'a', 'very', 'fat', 'rat']
words = ['you', 'all', 'are', 'very', 'smart', 'students']
for length in words:
if len(length)>=4:
print(length)
|
440d7421e3f5a138f13f43f9ce1b79d170ef8eb4 | Soooyeon-Kim/Object-Oriented-Programming | /Practice/Encapsulation_PointClass.py | 946 | 4.4375 | 4 | #2차원 평면상의 점(point)을 표현하는 클래스 Point를 정의하라.
import math
class Point:
def __init__(self, x=0.0, y=0.0):
self.__x = x
self.__y = y
@property
def x(self):
return self.__x
@property
def y(self):
return self.__y
def move(self, x, y):
self... |
755827221a3fca4588fe47d38c843f459f348f07 | mesturrica/Python | /Data Wrangling/1_3_Data_Wrangling_Conditional_Subset.py | 1,196 | 3.703125 | 4 | import pandas as pd
# First, we read a local csv
data = pd.read_csv('../Datasets/customer-churn-model/Customer Churn Model.txt')
# We print data to see that we're loading correctly.
print(data.head())
# Get n rows of data (First value included, last one not)
data_subset = data[1:3]
print(data_subset.head())
# User... |
9bfac18685061cad5f78f2b3f63c93121215b869 | mesturrica/Python | /1_2_Data_Cleaning_Basic_Boxplot.py | 732 | 3.578125 | 4 | import pandas as pd
import os
import matplotlib
import matplotlib.pyplot as plt
# Plots and data Visualization
main_path = "Datasets/"
filepath = "customer-churn-model/Customer Churn Model.txt"
data = pd.read_csv(os.path.join(main_path, filepath))
print(data)
# We print the boxplot with a label on the y axis.
plt.... |
26eeca2fda332e7113887da66b91edf8ad362a2c | nerminkekic/Guessing-Game | /guess_the_number.py | 912 | 4.4375 | 4 | # Write a programme where the computer randomly generates a number between 0 and 20.
# The user needs to guess what the number is.
# If the user guesses wrong, tell them their guess is either too high, or too low.
import random
# Take input from user
guess = int(input("Guess a number between 0 and 20! "))
# Number of... |
b9d444ef7cef146d7ba281b55fd8d751f4f1bfbb | SaidazimovaAziza/hackerrank | /solutions/power_mod_power.py | 345 | 3.953125 | 4 | def power(first_number, second_number):
return first_number ** second_number
def mod_power(first_number, second_number,mod):
return first_number**second_number%mod
first_number = int(input())
second_number = int(input())
mod = int(input())
print(power(first_number, second_number))
print(mod_power(first_numb... |
805704cb3b3eb21495a76e49af5f99836709167f | SaidazimovaAziza/hackerrank | /solutions/company_logo.py | 478 | 3.734375 | 4 | import math
import os
import random
import re
import sys
def company_logo():
chars = input()
dict = {}
for letter in chars:
if letter in dict:
dict[letter] += 1
else:
dict[letter] = 1
sorted_list = sorted(dict.items(), key=lambda x: x[0])
sorted_list.sort(re... |
f6c29e7bf6f63dda77d2e6bca51b9b4305647ec6 | SaidazimovaAziza/hackerrank | /solutions/shape_reshape.py | 163 | 3.890625 | 4 | import numpy
def shape_reshape():
my_array = numpy.array(list(map(int,input().split())))
return numpy.reshape(my_array, (3, 3))
print(shape_reshape())
|
150db869c69cbbb76491ca7ded97db67f2c7350e | SaidazimovaAziza/hackerrank | /solutions/validating_phone_number.py | 407 | 3.9375 | 4 |
import re
def checking_number_for_validating(phone_number):
if re.search(r'[789][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]',phone_number):
return True
return False
number_of_phones=int(input())
for i in range(number_of_phones):
phone_number=input()
if checking_number_for_validating(phone... |
a454a1a1b8b25cc379f943c66a066169477bc764 | AlexHalbesleben/StringQuartetGenerator | /generate.py | 1,009 | 3.5 | 4 | from textgenrnn import textgenrnn
textgen = textgenrnn()
def generate(model_weights_path: str, output_dir: str, model_name: str, n=5, temperature=[2, 1.5, 1.0, 0.5]):
"""Generates samples given the weights of a neural network
Args:
model_weights_path (str): The path to the .hdf5 file containing the we... |
46a27617765aef984dda4cdcc82a0d0dc55ef7f6 | Ena-Sharma/Meraki-Requests-API | /Saral_Request_API/thodi_si_programming_3.py | 1,078 | 3.625 | 4 | import requests
import json
import os
saral_url=("http://saral.navgurukul.org/api/courses")
def request(url):
response=requests.get(url)
with open("courses.json","wb") as file:
file.write(response.content)
return response.json()
# id_list is a varible in which a new list is assigned to store id of the courses. ... |
b7dac6183310b9197361a1724dd4897a6456e2a2 | KickItLikeShika/FindingThingsWithPython | /alliterations/alliterationInClipboard.py | 724 | 3.890625 | 4 | #! python3
# alliterationInClipboard.py - Finds alliteration on the clipboard and copies them to the clipboard
# Usage: Copy some text and call the program
# Example: >>> alliterationInClipboard.py
import pyperclip, re
# Create alliteration regex.
alliRegex = re.compile(r"((\s)(\w)\w*\s\3\w*((\s\3\w*)?)*)", re.IGNORE... |
6f1c0f530ee7ee604176e7e4899b9f83e40f6bda | Mark90/my-adventofcode-2018 | /day4/solution_part2.py | 1,740 | 3.578125 | 4 | from typing import Dict, Tuple
from day4.solution import (
test_input_sorted, test_input_unsorted, get_guards,
Guard
)
def find_guard_most_asleep_same_minute(guards: Dict[int, Guard]) -> Tuple[int, int, int]:
"""Given all Guards, find the one that was most asleep on the same minute.
Return a tuple of... |
8b15953debbf44cf1af78fc9e49a1d86b5d98e88 | Mark90/my-adventofcode-2018 | /day3/solution.py | 1,345 | 3.78125 | 4 | import re
from collections import defaultdict
from typing import Tuple, List, Iterable
def generate_positions(claim: str) -> Iterable[Tuple]:
"""Given a claim, yield tuples of the (x, y) positions on the fabric."""
match = re.match(r'#\d+ @ (\d+),(\d+): (\d+)x(\d+)', claim.strip())
start_x, start_y, width... |
4d070215dbe90662f6bb0c15f36c974550995562 | kilmer7/workspace_python | /Curso em Video/desafio10.py | 237 | 3.84375 | 4 | real = float(input('Digite quanto de dinheirinhos tem na sua carteira: '))
dolar = real / 3.27
print('Você tem {:.2f} reais na carteira e em dolar você teria {:.2f}'.format(real, dolar))
#O :.2f - é um encurtado de casas decimais.
|
6dcdbb28e0f1214b3b636df11b2b57ec1812c5c7 | kilmer7/workspace_python | /Curso em Video/desafio18.py | 273 | 3.75 | 4 | import math
ang = float(input('Informe o angulo: '))
ang2 = math.radians(ang)
seno = math.sin(ang2)
coseno = math.cos(ang2)
tangente = math.tan(ang2)
print('O seno é {:.2f}, o coseno é {:.2f}, e a tangente é {:.2f} do angulo {:.0f}'.format(seno,coseno,tangente,ang))
|
22624e6b528de8cce4096a5786039a57b46686f4 | kilmer7/workspace_python | /codigos a parte/firstProgram.py | 314 | 3.84375 | 4 | nome = input("Digite o nome do cliente: ")
diavenc = input("Digite o dia de vencimento: ")
mesvenc = input("Digite o mês de vencimento: ")
valor = input("Digite o valor da fatura: ")
print("olá, ", nome)
print("A sua fatura com vencimento em ", diavenc," de ", mesvenc," no valor de ", valor," está fechada.")
|
e0fd54fe84a10dc5d8e15ded5538fd5674b40e6e | kilmer7/workspace_python | /Curso em Video/desafio16.py | 345 | 4.21875 | 4 | import math
num = float(input('Digite um número real: '))
num = math.trunc(num)
print('O número inteiro do algarismo que você escreveu é {}'.format(num))
'''
Outra forma de resolver sem adicionar bibliotecas.
num = float(input('Digite um valor'))
print('O valor digitado foi {} e a sua porção inteira é {}'.format(nu... |
3fb97fc880548d16a0323bf1e65fe0eeb281744f | kilmer7/workspace_python | /Curso em Video/desafio19.py | 306 | 3.65625 | 4 | import random
al1 = input('Escreva o nome do primeiro aluno: ')
al2 = input('Escreva o nome do segundo aluno: ')
al3 = input('Escreva o nome do terceiro aluno: ')
al4 = input('Escreva o nome do quarto aluno: ')
rand = random.choice([al1, al2, al3, al4])
print('O aluno escolhido foi o {}'.format(rand))
|
f53c2061416c5899b99fb579f2e368fcb9ff8f3b | MJeremy2017/algorithms | /linked-list/linked_list.py | 1,419 | 4.0625 | 4 | class Node:
def __init__(self, val):
self.val = val
self.next = None
class ListNode:
def __init__(self):
self.head = None
def add(self, value):
node = Node(value)
if self.head is None:
self.head = node
return
# st... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.