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 |
|---|---|---|---|---|---|---|
205d757e0e6aa561f8a9ab0a42e6d0e74247a7a3 | georgebzhang/Python_LeetCode | /310_minimum_height_trees.py | 1,227 | 3.71875 | 4 | import sys
from collections import defaultdict
class Solution(object):
def findMinHeightTrees(self, n, edges):
def max_height(v):
if v in visited:
return 0
visited.add(v)
n_heights = []
for n in g[v]: # for neighbor of vertex
... |
98f137239463f7aac4534ed3a594111572727ded | georgebzhang/Python_LeetCode | /39_combination_sum_2.py | 844 | 3.8125 | 4 | class Solution:
def combinationSum(self, candidates, target):
def backtrack(candidates, nums, rem):
# print(nums) # uncomment this to understand how backtrack works
if rem == 0:
result.append(nums)
for i, cand in enumerate(candidates):
if ... |
6d6d97e0070e2d0177c2a35d8d39fb636eec391a | georgebzhang/Python_LeetCode | /200_number_of_islands_2.py | 1,313 | 3.625 | 4 | class Solution(object):
def numIslands(self, grid):
dirs = ((-1, 0), (1, 0), (0, -1), (0, 1))
def neighbors(i0, j0):
result = []
for di, dj in dirs:
i, j = i0 + di, j0 +dj
if 0 <= i < N and 0 <= j < M and grid[j][i] == '1':
... |
41fe3b7409fb596692851d7887d4750795996189 | georgebzhang/Python_LeetCode | /29_divide_two_integers.py | 714 | 3.765625 | 4 | class Solution:
def divide(self, dividend: int, divisor: int) -> int:
sign_dividend = -1 if dividend < 0 else 1
sign_divisor = -1 if divisor < 0 else 1
dividend = abs(dividend)
divisor = abs(divisor)
result = 0
while True:
dividend -= divisor
... |
4ccdd7851dc2177d6a35e72cb57069685d75f72c | echo001/Python | /python_for_everybody/exer9.1.py | 706 | 4.21875 | 4 | #Exercise 1 Write a program that reads the words in words.txt and stores them as
# keys in a dictionary. It doesn’t matter what the values are. Then you
# can use the in operator as a fast way to check whether a string is
# in the dictionary.
fname = input('Enter a file na... |
19e74e3bc318021556ceec645597199996cfba98 | echo001/Python | /python_for_everybody/exer10.11.3.py | 1,251 | 4.40625 | 4 | #Exercise 3 Write a program that reads a file and prints the letters in
# decreasing order of frequency. Your program should convert all the
# input to lower case and only count the letters a-z. Your program
# should not count spaces, digits, punctuation, or anything other ... |
4d2c3cc265f440b827c555747ed6df82b811ebac | noamm19-meet/meet2017y1lab6 | /part4.py | 1,123 | 4.03125 | 4 | import turtle
UP_ARROW='Up'
LEFT_ARROW='Left'
DOWN_ARROW='Down'
RIGHT_ARROW='Right'
SPACEBAR='space'
UP=0
LEFT=1
DOWN=2
RIGHT=3
direction=UP
def up():
global direction
direction=UP
old_pos=turtle.pos()
x= old_pos[0]
y=old_pos[1]
turtle.goto(x , y+10)
print(turtle.pos())
print('you presse... |
76f3d4905ac4e6d1900f10595b2988390317f54e | Himanshu1222/Perceptronalgorithm | /perceptron.py | 9,272 | 4.09375 | 4 | #Daniel Fox
#Student ID: 201278002
#Assignment 1: COMP527
import numpy as np
import random #redundant unless random.seed/random shuffle is used
class Data(object):
"""Main class which focuses on reading the dataset and sorting the data into samples,features.
filleName = name of file in string ... |
170ba09d016d552111884a9a8802caf57c38d5a7 | gvsurenderreddy/software | /wprowadzenie_python/lotto.py | 187 | 3.75 | 4 | #!/usr/bin/env python
from random import randint
lista = []
def lotto():
a = randint(1,49)
if a not in lista:
lista.append(a)
else:
lotto()
for x in range(6):
lotto()
print lista
|
884c0ecc5e544b25657765b55c64c13b6b22ed96 | randyLobb/Rock-Ppapper-Scissors | /RPS.py | 1,577 | 4.09375 | 4 | import random
from random import randint
repeat = True
cursewords = ['fuckyou','fuck you', 'FuckYou', 'fuck','shit','fucker']
while repeat:
user_choice = input("Rock(1), Paper(2), Scisors(3): Type 1, 2, or 3. type exit to close the game: ")
Comp_choice = randint(1,3)
if user_choice == ... |
688ef8d0f61313d828492d10031c888a65187803 | bonaert/NeuralNet | /xor.py | 876 | 3.5 | 4 | import random
from NeuralNet import NeuralNet
data = {
(0, 0): 0,
(0, 1): 1,
(1, 0): 1,
(1, 1): 0
}
TRAINING_SAMPLES = 10000
network = NeuralNet(input_size=2, hidden_layer_size=3, output_size=1, learning_rate=0.75, momentum=0.4)
# Step 1: training
samples = list(data.items())
errors = []
for i in ra... |
5648e2935a971992a4ccb03aae3c7b474318fb39 | uriyapes/VCL_DC | /my_utilities.py | 3,186 | 3.765625 | 4 | import os
import logging
from datetime import datetime
def set_a_logger(log_name='log', dirpath="./", filename=None, console_level=logging.DEBUG, file_level=logging.DEBUG):
"""
Returns a logger object which logs messages to file and prints them to console.
If you want to log messages from different module... |
e43348c97ff6d6b0ce16c9cb90d133038eb9b2a5 | optirg-39/dailycode | /F_450_58.py | 182 | 4.125 | 4 | Print all the duplicates in the input string?
#Using Hashing
r="Rishabhrishabh"
def strigduplcate(S):
d={}
for i in S:
d[i]=S.count(i)
print(strigduplcate(r))
|
6b17a0b06b3d25f439cc2951da7c0bf2528e7ffc | marialui/ADS | /quick sort.py | 674 | 3.703125 | 4 | def partition(lista,p,r):
x=lista[r]
i= p-1
for j in range (p,r):
if lista[j]< x:
i=i+1
estremo=lista[i]
lista[i] = lista[j]
lista[j]= estremo
lista[i+1], lista[r] = lista[r] , lista[i+1]
return (i+1)
#x, y = y, x is a good way to exchange... |
f30b7b68b9b3fbfa14adc4bd4981e2b7a5bdc492 | nav-bajaj/python-course | /Intro Course/counting in a loop.py | 159 | 3.9375 | 4 | #counting in a loop
i = 0
print("Before",i)
for counter in [5,21,34,5,4,6,12,3445,4432]:
i=i+1
print(i,counter)
print("Done, total items:", i)
|
d52a1639d49854a0bc7846e74faa1d0051768da3 | CarlosTrejo2308/TestingSistemas | /ago-dic-2019/practicas/practica.py | 321 | 3.546875 | 4 | import math
def v_cilindro(radio = None, altura = None):
if radio == None:
radio = float( input("Radio: ") )
if altura == None:
altura = float( input("Volumen: ") )
volumen = math.pi * (math.pow(radio, 2)) * altura
return volumen
print(v_cilindro())
... |
86a414b4486661edeca46d5b53e76d00704861c0 | marcluettecke/programming_challenges | /python_scripts/floor_puzzle.py | 2,170 | 4.09375 | 4 | """
Function to solve the following puzzle with a generator.
------------------
User Instructions
Hopper, Kay, Liskov, Perlis, and Ritchie live on
different floors of a five-floor apartment building.
Hopper does not live on the top floor.
Kay does not live on the bottom floor.
Liskov does not live on either the top or... |
3168d9379b4ff8064b60ed5e6db65d504c91f5a0 | marcluettecke/programming_challenges | /python_scripts/rot13_translation.py | 482 | 4.125 | 4 | """
Function to shift every letter by 13 positions in the alphabet. Clever use of maketrans and translate.
"""
trans = str.maketrans('ABCDEFGHIJKLMabcdefghijklmNOPQRSTUVWXYZnopqrstuvwxyz',
'NOPQRSTUVWXYZnopqrstuvwxyzABCDEFGHIJKLMabcdefghijklm')
def rot13(message):
"""
Translation by rot... |
9694eb43b3219502319ca40dbf580a88bf309c85 | khaleeque-ansari/CodeChef-Problem-Solutions-Python | /Python Codes/HS08TEST.py | 255 | 3.671875 | 4 |
amount, balance = [float(x) for x in raw_input().split()]
if amount%5 != 0:
print '%.2f' %balance
elif amount > balance - 0.50:
print '%.2f' %balance
else :
print '%.2f' % (balance - amount - 0.50)
|
ae038beb027640e3af191d24c6c3abbb172e398e | mihaidobri/DataCamp | /SupervisedLearningWithScikitLearn/Classification/02_TrainTestSplit_FitPredictAccuracy.py | 777 | 4.125 | 4 | '''
After creating arrays for the features and target variable, you will split them into training and test sets,
fit a k-NN classifier to the training data, and then compute its accuracy using the .score() method.
'''
# Import necessary modules
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_sele... |
e03ee23d27385f92bde5067aa3158823807ac747 | ismael-lopezb/employee_class_project | /data_cleaning.py | 2,303 | 3.59375 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 22 23:20:36 2021
@author: ismaellopezbahena
"""
#import usefull libraries
import pandas as pd
import numpy as np
#read csv file and get the info
df = pd.read_csv('aug_train.csv')
df.info()
#let's replace the gender missing data with the mode
gmode... |
34880def1217c10482dbbd3c637552fff0035ef3 | mishra-ankit-dev/tkinter-chat-automation | /chatApp/gui_chat.py | 1,659 | 3.625 | 4 | # -*- coding:utf-8 -*-
import sys
import time
import signal
import socket
import select
import tkinter
from tkinter import *
from threading import Thread
class client():
""" This class initializes client socket
"""
def __init__(self, server_ip = '0.0.0.0', server_port = 8081):
if len(sys... |
52b60e4bba09587fefd57678440a8afe275b955c | chiachunho/NTNU_OOAD_Homework | /Homework1/Homework1-2/main.py | 1,133 | 3.703125 | 4 | from Triangle import Triangle
from Square import Square
from Circle import Circle
from ShapeDatabse import ShapeDatabase
# construct shapes
shape1 = Triangle(0, 1, 6)
shape2 = Square(2, 2, 4, side_length=2)
shape3 = Circle(3, 3, 5, radius=3)
shape4 = Circle(2, 3, 3, radius=4)
shape5 = Square(1, 2, 1, side_length=5)
sh... |
f0d679d573068b5fc1f2d66b2f0d2c17824c22ed | mdzierzecki/algorithms | /binarytree/Node.py | 370 | 3.53125 | 4 | class Node:
def __init__(self, key=None):
self.key = key
self.left = None
self.right = None
def set_root(self, key):
self.key = key
def insert_left(self, new_node):
self.left = new_node
def insert_right(self, new_node):
self.right = new_node
def __... |
cc0c510075db7641bd5ae83e88c52b248473d999 | nik-panekin/pyramid_puzzle | /button.py | 1,238 | 4.09375 | 4 | """Module for implementation the Button class.
"""
import pygame
from blinking_rect import BlinkingRect
class Button(BlinkingRect):
"""The Button class implements visual rectangular element with a text
inside. It can be used for GUI.
Public attributes:
caption: str (read only) - stores button cap... |
1bb64c12a5738bc206746e547ed525089aaf0742 | lux563624348/Python_Learn | /basic/OI.py | 965 | 3.796875 | 4 | ########################################################################
#### Reading and Writing Files
###### Xiang Li Feb.18.2017
########################################################################
########################################################################
##Module
###############################... |
5ce316ef78144c1268521a913a494eead0b2baee | Yanhenning/python-exercises | /one/test_first_exercise.py | 1,213 | 3.65625 | 4 | from unittest import TestCase
from one.first_exercise import return_duplicated_items
class FirstExerciseTests(TestCase):
def test_return_empty_list_given_an_empty_list(self):
duplicated_items = return_duplicated_items([])
self.assertEqual([], duplicated_items)
def test_return_empty_list_giv... |
735e3a6325d2805d14e72615163138df6e79679f | Akawi85/Tiny-Python-Project | /03_picnic/picnic.py | 1,477 | 4.09375 | 4 | #!/usr/bin/env python3
"""
Author : Me <ifeanyi.akawi85@gmail.com>
Date : 31-10-2020
Purpose: A list of food for picnic!
"""
import argparse
# --------------------------------------------------
def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
descri... |
e650ddccebf0c6e1e97ee8c934e7c12948d299ab | BoHyeonPark/test1 | /028.py | 393 | 3.546875 | 4 | #!/usr/bin/python3
seq1 = "ATGTTATAG"
new_seq = ""
seq_dic = {"A":"T","T":"A","C":"G","G":"C"}
for i in seq1:
new_seq += seq_dic[i]
print(seq1)
print(new_seq)
new_seq1 = ""
for i in seq1:
if i == "A":
new_seq1 += "T"
elif i == "T":
new_seq1 += "A"
elif i == "C":
new_seq1 += "G"... |
c18490e52668ed9fc558ab7e4c1438dccd72427c | BoHyeonPark/test1 | /029.py | 207 | 3.53125 | 4 | #!/usr/bin/python3
seq1 = "ATGTTATAG"
print("C" in seq1)
for s in seq1:
b = (s == "C") #s == "C" -> False
print(s,b)
if b:
break
import re
p = re.compile("C")
m = p.match(seq1)
print(m)
|
cf7706deabaa3e1f59c8bb31bf34980cee4ea881 | BoHyeonPark/test1 | /014.py | 112 | 3.890625 | 4 | #!/usr/bin/python3
a = input("Enter anything: ")
if a.isalpha():
print("alphabet")
else:
print("digit")
|
cb8c1db76f1c7184635920f5811c56141929dbbf | BoHyeonPark/test1 | /034.py | 378 | 3.96875 | 4 | #!/usr/bin/python3
l = [3,1,1,2,0,0,2,3,3]
print(max(l))
print(min(l))
for i in range(0,len(l),1):
if i == 0: #set max_val, min_val
max_val = l[i]
min_val = l[i]
else:
if max_val < l[i]:
max_val = l[i] #max_val change
if min_val > l[i]:
min_val = l[i] #m... |
c891cd0f585b21859cfde5ffc0ef3aa77dbf2401 | BoHyeonPark/test1 | /assignment1_3.py | 111 | 3.515625 | 4 | #!/usr/bin/python3
try:
n = input("Enter number: ")
print(10/n)
except TypeError:
print("no zero")
|
3cada4756c6fd7259becea52725a3b85a0d7c25d | maxalbert/micromagnetic-standard-problem-ferromagnetic-resonance_v3_rewrite | /src/postprocessing/util.py | 1,478 | 3.96875 | 4 | def get_conversion_factor(from_unit, to_unit):
"""
Return the conversion factor which converts a value given in unit
`from_unit` to a value given in unit `to_unit`.
Allowed values for `from_unit`, `to_unit` are 's' (= second), 'ns'
(= nanosecond), 'Hz' (= Hertz) and 'GHz' (= GigaHertz). An error
... |
34c657d098bd5e80640c4da17189022219528c7e | zhangchuan92910/cmpt419 | /k_nearest_neighbor.py | 2,899 | 3.609375 | 4 | import numpy as np
from math import log10, floor
from collections import defaultdict
import os
from utils import *
def round_to_1(x):
return round(x, -int(floor(log10(abs(x)))))
def compute_distances(X1, X2, name="dists"):
"""Compute the L2 distance between each point in X1 and each point in X2.
It's pos... |
56df42f25fc0a3dddd57a8d70c63d7a3a4754900 | devmadhuu/Python | /assignment_01/check_substr_in_str.py | 308 | 4.34375 | 4 | ## Program to check if a Substring is Present in a Given String:
main_str = input ('Enter main string to check substring :')
sub_str = input ('Enter substring :')
if main_str.index(sub_str) > 0:
print('"{sub_str}" is present in main string - "{main_str}"'.format(sub_str = sub_str, main_str = main_str))
|
92d2b840f03db425aaaedf22ad57d0b291bb79e6 | devmadhuu/Python | /assignment_01/odd_in_a_range.py | 505 | 4.375 | 4 | ## Program to print Odd number within a given range.
start = input ('Enter start number of range:')
end = input ('Enter end number of range:')
if start.isdigit() and end.isdigit():
start = int(start)
end = int(end)
if end > start:
for num in range(start, end):
if num % 2 != 0:
... |
020278f3785bb409de5cd0afd67c4ccaf295e011 | devmadhuu/Python | /assignment_01/three_number_comparison.py | 1,464 | 4.21875 | 4 | ## Program to do number comparison
num1 = input('Enter first number :')
if num1.isdigit() or (num1.count('-') == 1 and num1.index('-') == 0) or num1.count('.') == 1:
num2 = input('Enter second number:')
if num2.isdigit() or (num2.count('-') == 1 and num2.index('-') == 0) or num2.count('.') == 1:
num3 =... |
bca391936ad2f918c4700dc581de7558dd081f41 | devmadhuu/Python | /assignment_01/ljust_rjust_q18.py | 409 | 3.6875 | 4 | my_str = 'Peter Piper Picked A Peck Of Pickled Peppers.'
sub_str = 'Peck'
index = 0
str_index = -1
replaced_str = ''
while my_str[index:]:
check_str = my_str[index:index + len(sub_str)]
if check_str == sub_str:
replaced_str = sub_str.rjust(index+1, '*')
replaced_str+=sub_str.ljust(len(my_str) - ... |
66c8afbcdd793b3817993abfb904b4ec0111f666 | devmadhuu/Python | /assignment_01/factorial.py | 410 | 4.4375 | 4 | ## Python program to find the factorial of a number.
userinput = input ('Enter number to find the factorial:')
if userinput.isdigit() or userinput.find('-') >= 0:
userinput = int(userinput)
factorial = 1
for num in range (1, userinput + 1):
factorial*=num
print('Factorial of {a} is {factorial}'.... |
83c5184a88d030bfd7d873e728653ac1f0248245 | alee86/Informatorio | /Practic/Estructuras de control/Condicionales/desafio04.py | 1,195 | 4.28125 | 4 | '''
Tenemos que decidir entre 2 recetas ecológicas.
Los ingredientes para cada tipo de receta aparecen a continuación.
Ingredientes comunes: Verduras y berenjena.
Ingredientes Receta 1: Lentejas y apio.
Ingredientes Receta 2: Morrón y Cebolla..
Escribir un programa que pregunte al usuario que tipo de receta desea,
... |
e4fe2f3a2fcb0f61de0a04aa746de174b64c9256 | alee86/Informatorio | /Practic/Estructuras de control/Complementarios/Complementarios4.py | 325 | 3.90625 | 4 | """
Realizar un programa que sea capaz de, habiéndose ingresado dos números m y n, determine si n es divisor de m.
"""
m = int(input("Ingrese el valor para el numerador "))
n = int(input("Ingrese el valor para el denominador "))
if m%n == 0:
print(f"{n} es DIVISOR de {m}")
else:
print(f"{n} es NO es DIVISOR de {m}"... |
213dab8cccc5a3d763c4afd329e6a461bb920b01 | alee86/Informatorio | /Practic/Estructuras de control/Repetitivas/desafio04.py | 973 | 4.03125 | 4 | '''
DESAFÍO 4
Escriba un programa que permita imprimir un tablero Ecológico (verde y blanco) de
acuerdo al tamaño indicado. Por ejemplo el gráfico a la izquierda es el resultado
de un tamaño: 8x6
import os
os.system('color')
columna = int(input("ingrese columnas: "))
fila = int(input("ingrese filas: "))
for fil... |
55efa3a71c684d8f68040ef917434b00a2bb589d | alee86/Informatorio | /Practic/Estructuras de control/Condicionales/desafio01.py | 793 | 4.09375 | 4 | '''
En nuestro rol de Devs (Programador o Programadora de Software), debemos elaborar un programa
en Python que permita emitir un mensaje de acuerdo a lo que una persona ingresa como
cantidad de años que viene usando insecticida en su plantación. Si hace 10 o más añoss,
debemos emitir el mensaje "Por favor solicite ... |
90965bb42e72a97fbea66ed53de0feff2eecc19c | alee86/Informatorio | /Practic/Listas/complementarios16.py | 1,164 | 4.03125 | 4 | '''
f. Se tiene una lista con los datos de los clientes de una compañía de telefonía celular,
los cuales pueden aparecer repetidos en la lista, si tienen registrado más de un número
telefónico. La compañía para su próximo aniversario desea enviar un regalo a sus clientes,
sin repetir regalos a un mismo cliente. En u... |
e23daf79dd41f1bce58bbaab7858941562be66ef | alee86/Informatorio | /Practic/Listas/complementarios12.py | 437 | 3.9375 | 4 | '''
b. Leer una frase y luego invierta el orden de las palabras en la frase. Por Ejemplo:
“una imagen vale por mil palabras” debe convertirse en “palabras mil por vale imagen una”.
'''
frase = str(input('Ingrese una frase para verla invrertida: '))
lista = frase.split()
#el metodo split toma un string y lo divide se... |
77329d1eb28a5d3565a346a30047871d2306abc6 | alee86/Informatorio | /Practic/Estructuras de control/Repetitivas/desafio01.py | 1,484 | 4.21875 | 4 | '''
DESAFÍO 1
Nos han pedido desarrollar una aplicación móvil para reducir comportamientos inadecuados para el ambiente.
a) Te toca escribir un programa que simule el proceso de Login. Para ello el programa debe preguntar
al usuario la contraseña, y no le permita continuar hasta que la haya ingresado correctamente.
... |
dd112a464e3c0ad07c28a31b94b693d533f758b3 | alee86/Informatorio | /Practic/06distribucionEstudiantes.py | 470 | 3.84375 | 4 | name = ""
while name != "quite":
name = input("Ingresa tu nombre completo: ").upper()
turn = input("ingresa si sos del TT (Turno Tarde) o del TN (Turno Noche): ").upper()
letters = "ABCDEFGHIJKLMNÑOPQRSTUVWYZ"
ft_letra = name[0]
if (letters[0:13].find(ft_letra) >= 0 and turn == "TT") or (letters[13:25].find(f... |
5112700bd8249864e978ed76dd52f85586fe848c | alee86/Informatorio | /Practic/Profe y compañeros/Desafio3.py | 1,400 | 4.09375 | 4 | '''Para el uso de fertilizantes es necesario medir cuánto abarca un determinado compuesto en el suelo el cual debe existir en una cantidad
de al menos 10% por hectárea, y no debe existir vegetación del tipo MATORRAL. Escribir un programa que determine si es factible la
utilización de fertilizantes.'''
print("Inicia... |
2649df22c828074a1eff5bcace5a2bf86dc5db98 | alee86/Informatorio | /Practic/numerosPrimos.py | 216 | 3.890625 | 4 | num = int(input("Numero para evaluar: "))
contador = 0
for x in range(num):
if num%(x+1) == 0:
contador += 1
if contador > 2:
print(f"El número {num} NO es primo")
else:
print(f"El número {num} SI es primo")
|
dd1eb3db497541007cb6abc22addb58838732c45 | bp345sa/Fizz | /Ex 5.py | 553 | 3.53125 | 4 | name = 'Zed A. Shaw'
age = 23 # not a lie
height = 74 # inches
h1 = height * 2.54
weight = 180 # lbs
w1 = weight * 0.456
eyes = 'Blue'
teeth = 'White'
hair = 'Brown'
print "Let's talk about %s." % name
print "He's %f centimetres tall." % h1
print "He's %f kilograms heavy." % w1
print "Actually that's not too heavy."
p... |
edff8364358f12b7248f2adb0d61cf18a97c349b | dds-utn/patrones-comunicacion | /corutinas/generator.py | 165 | 3.6875 | 4 | def productor():
n = 0
while True:
yield n
n += 1
def consumidor(productor):
while True:
println(productor.next())
consumidor(productor())
|
372fb0a40da5ea72d757f22ca8ed239abc52910d | CompAero/Genair | /geom/aircraft.py | 2,040 | 3.78125 | 4 | from part import Part
__all__ = ['Aircraft']
class Aircraft(Part, dict):
''' An Aircraft is a customized Python dict that acts as root for
all the Parts it is composed of.
Intended usage
--------------
>>> ac = Aircraft(fuselage=fus, wing=wi)
>>> ac.items()
{'wing': <geom.wing.Wing at ... |
1ee513ff7f5aac3fd043c7a907f7339a2348224a | vinvaid1989/training | /datecheck.py | 613 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 17 14:20:10 2018
@author: RPS
"""
import datetime
print(datetime.datetime.now().hour)
def cutoff(amount):
currtime=datetime.datetime.now().hour;
if(currtime > 17):
print ("tomorrow")
else:
print ("ok")
cutoff(56) ... |
a877604bf5f4ed8a8ebb23c4a5e123113084a9cf | Tyshkevichvyacheslav/Lr3 | /22.4.py | 1,435 | 4.09375 | 4 | print("Уравнения степени не выше второй — часть 2")
def solve(*coefficients):
if len(coefficients) == 3:
d = coefficients[1] ** 2 - 4 * coefficients[0] * coefficients[2]
if coefficients[0] == 0 and coefficients[1] == 0 and coefficients[2] == 0:
x = ["all"]
elif coeffici... |
5cb27604af3a7a610dd5c6f0c072d10254141496 | Tyshkevichvyacheslav/Lr3 | /23.1.py | 282 | 3.625 | 4 | print("Мимикрия")
transformation = lambda x: x
values = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
transformed_values = list(map(transformation, values))
if values == transformed_values:
print('ok')
else:
print('fail')
input("Press any key to exit")
exit(0) |
e2a854d1e492f741a8eb5746d76e51532edf5e68 | Tyshkevichvyacheslav/Lr3 | /21.4.py | 332 | 4.09375 | 4 | print("Фрактальный список – 2")
def defractalize(fractal):
return [x for x in fractal if x is not fractal]
fractal = [2, 5]
fractal.append(3)
fractal.append(9)
print(fractal)
print("____________")
fractal = [2, 5]
fractal.append(3)
print(fractal)
input("Press any key to exit")
exit(0)
|
bb02d54d7e24832e5fac78aed4fc6ae2ab765dc6 | CognitiveNetworking/IOT-Malware | /ScoringAndPerformance/stats_calcutaion.py | 7,994 | 3.5 | 4 | '''
Program name : stats_calculation.py
Author : Manjunath R B
This program Calcutes the statistics and generate statistical features.
The program calculates statistics per class per feature basis.
The program accepts three command line arguments
1. input file name
2. output file name
3. Quartile step value
... |
96ee7f84b68f60c999e8450ade3f30ad667b89e8 | amark02/ICS4U-Classwork | /Classes/Encapsulation_1.py | 665 | 3.84375 | 4 |
class Person:
def __init__(self, name: str, age: int):
self.set_name(name)
self._age = age
def get_age(self):
#age = time_now - self.date_of_birth
return self._age
def set_age(self, value: int):
self._age = value
def get_name(self):
return self._fi... |
6d030f79eb3df2a3572eaadb0757401d3a330326 | amark02/ICS4U-Classwork | /Quiz2/evaluation.py | 2,636 | 4.25 | 4 | from typing import Dict, List
def average(a: float, b: float, c:float) -> float:
"""Returns the average of 3 numbers.
Args:
a: A decimal number
b: A decimal number
c: A decimal number
Returns:
The average of the 3 numbers as a float
"""
return (a + b + c)/3
def c... |
5b632636066e777092b375219a7a6cd571619157 | amark02/ICS4U-Classwork | /Classes/01_store_data.py | 271 | 4.1875 | 4 |
class Person:
pass
p = Person()
p.name = "Jeff"
p.eye_color = "Blue"
p2 = Person()
print(p)
print(p.name)
print(p.eye_color)
"""
print(p2.name)
gives an error since the object has no attribute of name
since you gave the other person an attribute on the fly
""" |
4a1e0cd10aa31c063f1b38f2197e6c640ab0e1d9 | robotBaby/linearAlgebrapython | /HW3.py | 608 | 3.671875 | 4 | from numpy import linalg as LA
import numpy as np
#Question 1
def get_determinant(m):
return LA.det(m)
##### Examples
#Eg: 1
#a = np.array([[4,3,2], [1,2,6], [5,8,1]])
#print get_determinant(a)
#b = np.array([[1, 2], [1, 2]])
#print get_determinant(b)\
#Question 2
def find_area(three_points):
m = np.array(three... |
012b65d8534f8d52d843fb52bed3e2827ff2d605 | doranbae/shinko | /images/playShinko_vanilla.py | 6,761 | 3.640625 | 4 | # +--------------------------+
# | SHINKO |
# | Play the mobile game |
# +--------------------------+
import numpy as np
# set random seed
np.random.seed(84)
# define variables
matrix_min = 1
matrix_max = 5
matrix_width = 5
level_num = 2
shinko_goal = 5
han... |
72f64a3b98ee883737a0ea668eda1151365d72b6 | MorHananovitz/CSCI-315-Artificial-Intelligence-through-Deep-Learning | /Assignment2/perceptron.py | 1,034 | 3.515625 | 4 | import numpy as np
#Part 1 - Build Your Perceptron (Batch Learning)
class Perceptron:
def __init__(self,n, m):
self.input = n
self.output = m
self.weight = np.random.random((n+1,m))-0.5
def __str__(self):
return str( "This is a Perceptron with %d inputs and %d outputs... |
e2fc0eb8047bbe73f5be60371a03ad388bc7f388 | ClaeysKobe/Kobeehhh | /Thuis 3.py | 520 | 3.609375 | 4 | print("*** Welkom bij het kassasysteem ***")
broeken = int(input("Hoeveel broeken werden er verkocht? "))
tshirts = int(input("Hoeveel T-shirts werden er verkocht? "))
vesten = int(input("Hoeveel vesten werden er verkocht? "))
prijs_broeken = broeken * 70.5
prijs_tshirts = tshirts * 20.89
prijs_vesten = vesten * 100.3
... |
23ee2c8360e32e0334a31da848043cf6187cd636 | cosinekitty/astronomy | /demo/python/gravity.py | 1,137 | 4.125 | 4 | #!/usr/bin/env python3
import sys
from astronomy import ObserverGravity
UsageText = r'''
USAGE:
gravity.py latitude height
Calculates the gravitational acceleration experienced
by an observer on the surface of the Earth at the specified
latitude (degrees north of the equator) and height
(met... |
6d0702099e71e5065cc3a1bdfeb152995fccdc81 | loki2236/Python-Practice | /src/Ej2.py | 439 | 3.71875 | 4 | #
# Dada una terna de números naturales que representan al día, al mes y al año de una determinada fecha
# Informarla como un solo número natural de 8 dígitoscon la forma(AAAAMMDD).
#
dd = int(input("Ingrese el dia (2 digitos): "))
mm = int(input("Ingrese el mes (2 digitos): "))
yyyy = int(input("Ingrese e... |
c5c9ed70accfeafc3d4ec07f8e9b9a556ec7143c | Dibyadarshidas/py4e | /open_files and big_count.py | 449 | 3.671875 | 4 | name = input("Enter file:")
handle = open(name)
counts = dict()
bigcount = None
bigword = None
smallcount = None
smallword = None
for line in handle:
words = line.split()
for word in words:
counts[word] = counts.get(word,0) + 1
#print(counts)
for p,q in counts.items():
print(p,q)
i... |
11575571fe85a08533ad8cfaffcdbd1c4936a8d8 | Dibyadarshidas/py4e | /19.09.2020.py | 640 | 3.640625 | 4 | # Sort by values instead of key
#c = {'a':10, 'b':1, 'c':22 }
#tmp = []
#for k, v in c.items() :
# tmp.append((v, k))
#print(tmp)
#tmp = sorted(tmp, reverse=True)
#print(tmp)
# Long Method
#fhand =open('words.txt')
#counts = {}
#for line in fhand:
# words = line.split()
# for word in words:
# ... |
a7f2d4a9a20c2eb58a04861708ac895baa6156ee | abeltomvarghese/Data-Analysis | /Learning/DataFrames.py | 724 | 3.765625 | 4 | import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import style
style.use("fivethirtyeight")
web_stats = {"Day":[1,2,3,4,5,6],
"Visitors":[43,34,65,56,29,76],
"Bounce Rate": [65,67,78,65,45,52]}
#CONVERT TO DATAFRAME
df = pd.DataFrame(web_stats)
#PRINT THE FIRST FEW VALUES
pri... |
b8aa70ebee9c3db49bbc8905f88f0e604734894d | pureforwhite/ToyEncryptionAlgorithm | /main.py | 1,729 | 4.09375 | 4 | #PureForWhite create a string encryption program with Toy Encryption Algorithm
#The source code will be in the link description below
#Follow me on reddit, subscribe my youtube channel, like this video and share it thanks!
#creating decryption function
def decryption(s):
s = list(s)
for i in range(len(s)):
... |
de463c40b80011fd725e2675aa1ab0c4a16cf8c6 | joshinihal/dsa | /recursion/basic_problems.py | 1,146 | 3.828125 | 4 | # Write a recursive function which takes an integer
# and computes the cumulative sum of 0 to that integer
def rec_sum(n):
if n == 0:
return 0
return n + rec_sum(n-1)
rec_sum(10)
#-------------------------------------------------
# Given an integer, create a function which returns the sum of all... |
e27d035e4e5e2cb1a95204bcdbccae9237d70eda | joshinihal/dsa | /trees/binary_heap_implementation.py | 2,258 | 3.796875 | 4 | # min heap implementation
# https://en.wikipedia.org/wiki/Binary_heap
# list has a '0' element at first index(0) i.e. [0,.....]
class BinHeap():
def __init__(self):
self.heapList = [0]
self.currentSize = 0
def perUp(self, i):
while i // 2 > 0:
... |
e79076cd45b6280c2046283d9a349620af0f8d70 | joshinihal/dsa | /trees/tree_implementation_using_oop.py | 1,428 | 4.21875 | 4 | # Nodes and References Implementation of a Tree
# defining a class:
# python3 : class BinaryTree()
# older than python 3: class BinaryTree(object)
class BinaryTree():
def __init__(self,rootObj):
# root value is also called key
self.key = rootObj
self.leftChild = None
self.righ... |
4999709b618b6edca8a2e462c4575a56f81a580c | Amit998/python_software_design | /Intro/guess_game.py | 1,036 | 3.78125 | 4 | class GuessNumber:
def __init__(self,number,min=0,max=100):
self.number = number
self.guesses=0
self.min=min
self.max=max
def get_guess(self):
guess=input(f"Please guess a Number ({self.min} - {self.max}) : ")
if (self.valid_number(guess)):
retur... |
2e41ccaf34b9b6d8083df766a3a578418bbf6db0 | Khizanag/algorithms | /FooBar/Level 3/Bunny Prisoner Locating/Bunny Prisoner Locating.py | 186 | 3.796875 | 4 | def solution(x, y):
H = x + y - 1
n = 1 # value when x = 1
temp = 0 # n increases by temp
for i in range(H):
n += temp
temp += 1
print(n + x - 1)
print(solution(3, 2)) |
6d67c92e324e39b17788d860548bfd23059ca5af | domzhaomathematics/Competitive-Coding-8 | /minimum_window_substring.py | 2,246 | 3.53125 | 4 | #Time Complexity: O(s+t), traversal and building hashmaps
#Space complexity: O(s+t),length of S and T
'''
Evertime we encounter a letter that belongs to T, we append it to a queue and
increment the hashmap with that key. We keep a hashmap to check how many times
the letter appear in T. If we've found all the letter of... |
20ac70eaf04d544691436bbd5c6c0f5323ba40f8 | rizveeredwan/UID-Generation-Based-On-Polynomial-Hashing | /PhoneticMeasurePerformance/name_generator.py | 1,631 | 3.65625 | 4 | import csv
"""
### SEGMENT 1: Name collection
### Taking input of all the names ######
names=[]
with open('/home/student/Desktop/PhoneticAccuracyMeasure3/UID-Generation-Based-On-Polynomial-Hashing/TrainingData.csv') as csvFile:
csvReader = csv.DictReader(csvFile)
for row in csvReader:
v=row['name'].split(' ')
... |
74725fc2d2c7d06cec7bc468aa078f59e6aa21e7 | AGriggs1/Labwork-Fall-2017 | /hello.py | 858 | 4.125 | 4 | # Intro to Programming
# Author: Anthony Griggs
# Date: 9/1/17
##################################
# dprint
# enables or disables debug printing
# Simple function used by many, many programmers, I take no credit for it WHATSOEVER
# to enable, simply set bDebugStatements to true!
##NOTE TO SELF: in Python, first letter ... |
dbf03069fac82c54e3a158dae1d62b0589440176 | jphilippou27/kingmakers_capstone | /data/os2/load_cmte_advanced.py | 1,002 | 3.640625 | 4 | import csv, sqlite3, sys
if __name__ == "__main__":
conn = sqlite3.connect("os2.db")
cur = conn.cursor()
cur.execute("DROP TABLE IF EXISTS cmte_advanced;")
conn.commit()
cur.execute("""CREATE TABLE cmte_advanced (
id TEXT(9),
name TEXT(50),
parent TEXT(50),
cand_... |
4188c44dda65c2849f1ae89fd19eb46b7efffd14 | dancing-elf/add2anki | /add2anki/add2anki.py | 2,805 | 3.734375 | 4 | """Interactively translate and add words to csv file if needed"""
import argparse
import sys
import tempfile
import urllib
import colorama
import pygame
import add2anki.cambridge as cambridge
def add2anki():
"""Translate and add words to csv file if needed"""
parser = argparse.ArgumentParser()
parser.ad... |
29855d475c40a99d9c99896389b0129981d29131 | ochuerta/bolt | /docs/_includes/lesson1-10/Boltdir/site-modules/exercise8/tasks/great_metadata.py | 853 | 3.53125 | 4 | #!/usr/bin/env python
"""
This script prints the values and types passed to it via standard in. It will
return a JSON string with a parameters key containing objects that describe
the parameters passed by the user.
"""
import json
import sys
def make_serializable(object):
if sys.version_info[0] > 2:
return ob... |
243f97a94733bea6491fda338ab7831a6e773e4a | solonmoraes/CodigosPythonTurmaDSI | /Exercicio1/segunda atv.py | 186 | 3.9375 | 4 | print("===========Atividade=============")
salaTotal = float(input("Informe o quanto recebeu:\n"))
horasDia = int(input("Informe suas horas trabalhadas:\n"))
print(salaTotal / horasDia)
|
38445453493bcae3afdfafc93fd6568027dca64d | solonmoraes/CodigosPythonTurmaDSI | /Listas.py | 656 | 4.09375 | 4 | pessoas = ["Fabio","Carlos","Regina","Vanuza"]
print(type(pessoas))
print(pessoas)
pessoas[1] = "Sergio"
# adicionar elementoas
pessoas.append("Sarah")# adiciona no final
pessoas.insert(2,"Flavio")#adiciona em qualquer lugar
for chave, valor in enumerate(pessoas):
print(f"{chave:.<5}{valor}")
#removendo eleme... |
079e2d347895e1d1cf900b4772a3ad5902f793d7 | solonmoraes/CodigosPythonTurmaDSI | /banco de dados mongo/POO/aula3/conta.py | 1,220 | 3.8125 | 4 | class Conta:
def __init__(self, numero, titular, saldo, limite=1000):
self.__numero = numero
self.__titular = titular
self.__saldo = saldo
self.__limite = limite
def depositar(self, valor):
if valor < 0:
print("Voce nao pode depositar valor negativo")
... |
f2794e3c31b085db9b10afa837d6026848ef1318 | lucasferreira94/Python-projects | /jogo_da_velha.py | 1,175 | 4.25 | 4 | '''
JOGO DA VELHA
'''
# ABAIXO ESTAO AS POSIÇÕES DA CERQUILHA
theBoard = {'top-L':'', 'top-M':'', 'top-R':'',
'mid-L':'','mid-M':'', 'mid-R':'',
'low-L':'', 'low-M':'', 'low-R':''}
print ('Choose one Space per turn')
print()
print(' top-L'+' top-M'+ ' top-R')
print()
print(' mid-L'+' mid-... |
a9746ae70ae68aefacd3bb071fae46e949a7e29f | YangYishe/pythonStudy | /src/day8_15/day8_2.py | 683 | 4.40625 | 4 | """
定义一个类描述平面上的点并提供移动点和计算到另一个点距离的方法。
"""
class Point:
def __init__(self, x, y):
self._x = x
self._y = y
def move(self, x, y):
self._x += x
self._y += y
def distance_between(self, other_point):
return ((self._x - other_point._x) ** 2 + (self._y - other_point._y) *... |
f12289953bccf14110d3d75acca9b35797bf9b30 | YangYishe/pythonStudy | /src/day1_7/day4_3.py | 481 | 3.984375 | 4 | """
打印如下所示的三角形图案。
"""
for i1 in range(1, 6):
for i2 in range(1, i1 + 1):
print('*', end='')
print('')
for i1 in range(1, 6):
for i2 in range(1, 6):
if i2 + i1 <= 5:
print(' ', end='')
else:
print('*', end='')
print('')
for i1 in range(1, 6):
for i2 i... |
5c754378bc33111b88a28b80317c95ba075664a5 | YangYishe/pythonStudy | /src/day1_7/day7_6.py | 339 | 3.734375 | 4 | """
打印杨辉三角。
"""
def yhsj(n):
arr1=[1,1]
for i in range(n-1):
arr2=[1]
for j in range(i):
arr2.append(arr1[j]+arr1[j+1])
arr2.append(1)
arr1=arr2
yield arr1
pass
def main():
for i in yhsj(10):
print(i)
pass
if __name__ == '__main__':
m... |
bd49df8de11f36cfc6b881024001c01f6c88348e | benb2611/AmericanAirlines-scraper | /american_airlines.py | 16,446 | 3.828125 | 4 | """
Contains AmericanAirlines class, where help methods and logic for scraping data
from American Airlines web site are implemented. (all for educational purposes only!)
Check '__init__()' docstring for required parameters. To start scraping - just create instance of AmericanAirlines
and use 'run()' method. Example:
... |
aab450116da1a0597767e1062274c9088cf8a9ef | damilarey98/user_validation | /user_validation.py | 1,813 | 3.90625 | 4 | import random
value = "abcdefghijklmnopqrstuvwxyz1234567890"
client_info = {}
n = int(input("How many number of users?: "))
#since range begins from 1, when n=2, it request only one value
for i in range(1, n):
new_client = {}
print("Enter first name of user", i, ":")
fname = input()
print("Enter l... |
43d06f5cb81bd0e3c924b99164a4526758979052 | SanamKhatri/school | /student_update.py | 4,554 | 3.828125 | 4 | import student_database
from Student import Student
def update_student():
roll_no = int(input("Enter the roll no:"))
is_inserted = student_database.getStudentDetails(roll_no)
if is_inserted:
student_deatail = student_database.getStudentDetails(roll_no)
print(student_deatail)
print(... |
73a9544105ca7eae0d7997aa2e0a4b74bf8723b7 | SanamKhatri/school | /teacher_delete.py | 1,234 | 4.1875 | 4 | import teacher_database
from Teacher import Teacher
def delete_teacher():
delete_menu="""
1.By Name
2.By Addeess
3.By Subject
"""
print(delete_menu)
delete_choice=int(input("Enter the delete choice"))
if delete_choice==1:
delete_name=input("Enter the name of the... |
8103864502cd9649a73788870dabc9ac9cca1c6f | simhaonline/Database-Service-REST-API | /apps/app.py | 4,488 | 3.53125 | 4 | '''
SAMPLE DATABASE AS A SERVICE API
Register a user with username and password
Login a user with username and password
A user gets 10 coins by default when registration completed.
Every time a user logs in 1 coin is used up.
Once all coins are used up the registered user won't be able to l... |
551d2c2c5d240929b8289bd9e86c95bd1c599114 | DRogalsky/dataVisualizationPythonCC | /dice.py | 317 | 3.625 | 4 | from random import randint
class Die:
"a class to represent a single die"
def __init__(self, num_sides=6):
"""assume 6 sides"""
self.num_sides = num_sides
def roll(self):
"""spit out a random number between 1 and the number of sides"""
return randint(1, self.num_sides)
|
b86433902a7cf3e9dcba2d7f254c4318656ca7f7 | heba-ali2030/number_guessing_game | /guess_game.py | 2,509 | 4.1875 | 4 | import random
# check validity of user input
# 1- check numbers
def check_validity(user_guess):
while user_guess.isdigit() == False:
user_guess = input('please enter a valid number to continue: ')
return (int(user_guess))
# 2- check string
def check_name(name):
while name.isalpha() == False:
... |
f782209a4fb946cb6834f6c60cd33dd93d40b86e | josephevans24/SI106-Files | /ps6.py | 13,035 | 4.09375 | 4 | import test106 as test
# this imports the module 106test.py, but lets you refer
# to it by the nickname test
#### 1. Write three function calls to the function ``give_greeting``:
# * one that will return the string ``Hello, SI106!!!``
# * one that will return the string ``Hello, world!!!``
# * and one that ... |
020cea430b8939fef9b71ed4836c8bf85bf2211a | josephevans24/SI106-Files | /Final Project/finalproject.py | 18,208 | 3.6875 | 4 | import test106 as test
import csv
def collapse_whitespace(txt):
# turn newlines and tabs into spaces and collapse multiple spaces to just one space
res = ""
prev = ""
for c in txt:
# if not second space in a row, use it
if c == " " or prev == " ":
... |
a9a96b6bc344c5a44a45e61e4a947b1e37543e58 | ricew4ng/Slim-Typer-v1.0 | /code/class_thread_show_time_speed.py | 1,721 | 3.609375 | 4 | #coding:utf8
#显示用时以及计算打字速度的线程的类脚本
import threading
import time
# 创建此实例时,需要传入一个run_window(QtWidgets.QWidget对象)
# running是启动和关闭thread的标志。设置为false,则关闭线程。
class thread_show_time_speed(threading.Thread):
def __init__(self,run_window):
super(thread_show_time_speed,self).__init__()
self.run_window = run_window
self.... |
67df8cb2c8409510d9b0d1f0c859402db1993e93 | aswarth123/DevoWorm | /parse-beautiful-stone-soup.py | 298 | 3.515625 | 4 | import lxml.etree as ET // uses lxml for parsing
content = "data.xml"
doc = ET.fromstring(content)
data = doc.find('data of interest') //tag that defines source of data
print(data.text)
info = doc.find('information') //tag that defines metadata
print(info.tail)
outfile = "test.txt"
FILE.close |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.