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 |
|---|---|---|---|---|---|---|
3c5c9ed01a5c25b31ae42feb6bea161b78164088 | gabrielegilardi/BinaryTree | /Code_Python/BinaryTree.py | 17,556 | 3.921875 | 4 | """
Binary Tree and Binary Node Data Structures
Copyright (c) 2021 Gabriele Gilardi
Notes
-----
- Written and tested in Python 3.8.5.
- Binary tree class implementation using a binary node class.
- Five search methods: pre-order, post-order, in-order, using a stack, and
using a queue.
- Possible to search the enti... |
27bad93c73e3f7e63b432cdc7fbf2591d852304a | Aimee-zcp/qcb75 | /python_class/lesson_04.py | 4,765 | 4.25 | 4 | """
for 循环:遍历对象 数据对象里的所有元素:str,list,tuple,dict,集合
for 变量名 in 数据对象
子代码(循环体)
循环多少次是由元素个数决定的。
中断:
break --跳出循环
continue ---结束当前循环,本次循环该语句后面的语句不执行
range() --内置函数:生成一个整数序列:1,2,3,4,5,6
跟for循环一起使用,start开始,stop结束,step步长--取头不取尾
eg: for i in range(1,5,1):
print(i)... |
c6ff6195fc366e0c776b58ceb0833d2c2bff7359 | CinnaKenToast/CSCI-4270-Algorithm-Design-and-Analysis | /Assignment 9 Maximum Clique/makeGraph.py | 2,117 | 3.515625 | 4 | #!/usr/bin/env python3
import argparse
import random
def generateGraph(v, e, m, allowreflexive, mustbesymmetric):
print(v)
print(e)
matrix = [0] * (v*v)
i = 0
while i < e:
a = random.randint(0, v-1)
b = random.randint(0, v-1)
while a == b and allowreflexive == False:
... |
040782cea873d5d76c5808b4d5c864b9f33d24cf | himgoy/Train_Booking | /Train_Booking.py | 2,144 | 3.9375 | 4 | class Train:
@staticmethod
def greet():
print("Hello User")
def __init__(self, name, fare, seats, source, destination, trainNo):
self.trainNo = trainNo
self.seats = [i for i in range(1, seats + 1)] # import numpy as np list(np.arange(1, seats + 1))
self.capacity ... |
81e19fedc79a231daf225808896d7abb9204d688 | mallph/Python-for-Informatics-class | /dicts_and_tuples.py | 829 | 3.796875 | 4 | # PJ Mallery
# Assignment 5
# python 3
import sys
fname = input('Enter mbox or mbox-variant filename: ')
try:
fhand = open(fname)
except:
print('Could not find specified file. Please ensure filename is correct and/or the file is in the directory.')
sys.exit(0)
d = dict() # initalize empty dictionar... |
8662bda8ca8c11a857c90048e588861d7eb475c7 | rshandilya/IoT | /Codes/prac2d.py | 1,523 | 4.3125 | 4 | ############# EXPERIMENT 2.D ###################
# Area of a given shape(rectangle, triangle, and circle) reading shape and
# appropriate values from standard input.
import math
import argparse
import sys
def rectangle(x,y):
"""
calculate area and perimeter
input: length, width
output: dict - area, p... |
9bf689d8ec751df0b2b7e9106e78843afba8aafd | rshandilya/IoT | /Codes/prac4a.py | 507 | 3.53125 | 4 | # Program:
# Light an LED through Python program
#
import RPi.GPIO as GPIO
from time import sleep
LED = 10
def led_setup():
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(LED, GPIO.OUT, initial=GPIO.LOW)
def main():
led_setup()
while True:
GPIO.output(LED, GPIO.HIGH)
... |
d4b0e8aa7d0ea7d0e1dd57368524979cc72555c2 | kanishkegb/python-classes | /timer.py | 592 | 3.9375 | 4 | class Timer(object):
'''
A class that gives time difference between two time instances
'''
def __init__(self, name=None):
self.name = name
self.t_start = 0
self.t_end = 0
def tic(self):
''' timer starts '''
self.t_start = time.time()
def toc(self):
... |
03e3c1811ded81c7108c2a661d826e797be1dfc1 | Rengineer13/Python | /hackingGame.py | 545 | 3.5 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 23 10:18:54 2017
@author: kwbatson
"""
userPass = ["Admin", "Basalisk","Groundhog","Football","Rearrange"]
print("Type one from among these: " + str(userPass))
for guessesTaken in range (1,5):
print("Take a guess.")
guess = input()
if gu... |
f94f5fde22d47d516a9cb2462bd6614544aa3372 | xxchaosxx210/vectors | /box/vector.py | 2,118 | 4.0625 | 4 | import math
class Vector:
def __init__(self, x: float, y: float):
self.x = x
self.y = y
def __add__(self, other):
if isinstance(other, self.__class__):
return Vector(self.x + other.x, self.y + other.y)
return Vector(self.x + other, self.y + other)
def ... |
8317efa0e12bb41073305262fd19f5672be92356 | ass8/PZ-2004 | /par 2/par 2 e 5.py | 335 | 3.921875 | 4 | print("Input A,B and C: ")
a = int(input())
b = int(input())
c = int(input())
if(a>=b and b>=c):
a *= 2
b *= 2
c *= 2
print(a,b,c)
print("Неравенства выполняются")
else:
a = abs(a)
b = abs(b)
c = abs(c)
print(a, b, c)
print("Неравенства не выполняются") |
36220cb2d2dd135d7c95bcd4dc66cfc2a0f33a2e | ass8/PZ-2004 | /prog/dirControl.py | 1,010 | 4 | 4 | #!/usr/bin/python
import os
import os.path
from os import path
def invalidInput():
print("Invalid input, please try again.\n")
quit()
systemDetect=os.name
if systemDetect!='posix':
print("Program is oriented on the UNIX systems.\n")
quit()
defaultName="~/newFoldersDir"
print ("File exists:"+str(pat... |
8e6351f85329a1ba7dbe8418807743ed34a178bc | vtymch12/pp1 | /04-Subroutines/13.py | 194 | 3.53125 | 4 | def suma(tab):
suma=0
print("tablica",end=" ")
for i in tab:
print(i,end=" ")
suma+=int(i)
return suma
tablica=[4,3,7,1,3]
print("\nsuma wartosca:",suma(tablica)) |
2306a8230865f21171fb07ee0a8d3c0b64070265 | vtymch12/pp1 | /05-ModularProgramming/zadanie 4.py | 503 | 3.671875 | 4 | import math
x=3.7
y=4
sqrtX = math.sqrt(x)
print(f'Pierwiastek kwadratowy z {x} wynosi {sqrtX}')
powXY=math.pow(x,y)
print(f"X do potęgi y z {x} wynosi {powXY}")
sqrty=math.pow(x,1/y)
print (f"Pierwiastek y-tego stopnia z x wynosi: {sqrty}")
polekoła=math.pi*(y**2)
print(f"Pole koła o promieniu y wynosi: {polekoła}")
s... |
bb1c9f894d94df57fdd1d851f574809c9f5119e0 | vtymch12/pp1 | /Thonny programs/24.py | 484 | 3.875 | 4 | x=int(input("Podaj ocenę:"))
for x in range(1,6):
if x==1:
print(" Ocena słownie:niedostateczny")
break
continue
elif x==2:
print(" Ocena słownie:mierny")
elif x==3:
print(" Ocena słownie:dostateczny")
elif x==4:
print(" Ocena słownie:dobry")
elif x==... |
a2d402eff6e64366d96f77066cd20809646f151c | vtymch12/pp1 | /Thonny programs/02.10.py | 179 | 3.640625 | 4 | x=int(input("Wprowadź liczbę: "))
if x>0 and x%2!=0:
print(f"{x} jest liczbą dodatnią i nieparzystą")
else:
print(f"{x} jest albo liczbą ujemną albo parzystą") |
faefe15f1997f2b9e7a5c2cc2d6e7e6a0c866355 | veyu0/Python | /les_8/les_8_task_7.py | 508 | 3.8125 | 4 | class Complex_number:
def __init__(self, a, b):
self.a = a
self.b = b
def __add__(self, other):
return Complex_number(self.a + other.a, self.b + other.b)
def __mul__(self, other):
return Complex_number(self.a * other.a, self.b * other.b)
def __str__(self):... |
7bf6f58e13b0f780d83aeadd9893382d68762ab5 | veyu0/Python | /les_6/les_6_task_4.py | 2,470 | 4.1875 | 4 | class Car:
''' Автомобиль '''
_speed = None
_color = None
_name = None
_is_police = False
def __init__(self, name, color):
self.name = name
self.color = color
print(f'Новая машина: {self.name} (цвет {self.color}) {type(self)}')
def go(self):
pri... |
7ad247c561871ac54719ae32ad42be206364b6b5 | veyu0/Python | /les_2/les_2_task_2.py | 655 | 4.46875 | 4 | '''Для списка реализовать обмен значений соседних элементов, т.е. Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д.
При нечетном количестве элементов последний сохранить на своем месте. Для заполнения списка элементов необходимо использовать функцию input().'''
list = list(input('Введите число: '))
... |
25daeb1c2ec1f97b23144d083e1c3798c1bd85e8 | veyu0/Python | /les_5/les_5_task_2.py | 552 | 3.984375 | 4 | '''Создать текстовый файл (не программно), сохранить в нем несколько строк, выполнить подсчет количества строк, количества слов в каждой строке.'''
counter = 0
with open('2.txt', 'r', encoding='utf-8') as f_obj:
for line in f_obj:
counter += 1
l_words = line.split(' ')
print(f'Строка... |
d659f7bc67bbda7455437324b6d871a097a6dd56 | erobinson97/CINS465 | /Assignment3/ex5/pig_latin.py | 620 | 3.546875 | 4 | import sys
vowels = ['a', 'e', 'i', 'o', 'u'] # consider adding 'y'
text = sys.stdin.readlines()
temp = []
returnList = []
for x in text:
x = x.rstrip("\n")
x = x.lower()
temp.append(x)
for x in temp:
if((x[0]) in vowels):
x = x + "-yay"
returnList.append(x)
else:
consonan... |
d9d8d7e389813e7317681ffdee60a18d9c90b1a4 | jaskaran1/CLI_Games | /BubbleBreaker/BubbleBlast.py | 7,014 | 3.59375 | 4 | import numpy as np
import random
from collections import deque
def bfs(A,i,j,disc,m,n):
"Searches the grid to return a connected component"
component=[]
Q=deque()#use this for BFS
Q.append([i,j])
c=A[i][j]
disc[i][j]=1
while len(Q)>0:
u=Q.popleft()
i,j=u
component.app... |
a99e780ecded04cc82d192d8a4a1fb13f72cd6c2 | bkbv/CSE | /victor - pythagorean.py | 120 | 3.671875 | 4 | def pythagorean(a, b):
inside = a ** 2 + b ** 2
answer = inside ** 0.5
return answer
print(pythagorean(5,12)) |
277f051ad603bd3e2f23b64a0b95a251758ac0b0 | chekkitapp/chekkit_technology | /chekkitapp/includes/code.py | 2,369 | 3.859375 | 4 | import random, datetime
from math import floor
def rand_string (config = {"length" : 5}):
###
"""
This fn generates very random numbers config["length"] is created
then the current microsecond timestamp is appended to the string
Firstly a sequence of numbers with length
:param config: {Dict}
... |
2ccca35795866c4fecc2812498177e280b212339 | PoliOwl/python_homework | /inheritance.py | 515 | 3.5 | 4 | def chek(p, k, tree) :
if p == k or p in tree[k] :
return "Yes"
else:
for i in tree[k] :
if chek(p, i, tree) == "Yes" :
return "Yes"
return "No"
inher = {}
for _ in range(int(input())) :
s = input().split()
inher[s[0]] = []
if (len... |
5f1f4753338164ede9febd8ee3565b9a50695571 | alvesouza/ces-22 | /aula 07/aula_07.py | 1,616 | 3.5 | 4 | from threading import Thread, Event
from queue import Queue
import threading
import time
import random
class producer(Thread):
def __init__(self,queue):
Thread.__init__(self)
self.queue = queue
def run(self):
for i in range(10):
self.queue.begin_task()
... |
d65ff59df6fb6b9b783a5b1e06a00309abb9c1bb | alvesouza/ces-22 | /aula 3/12/wordtools.py | 1,191 | 3.796875 | 4 | import string
def cleanword(word):
char = string.ascii_letters
cleanedWord = ""
for x in word:
if x in char:
cleanedWord += x
return cleanedWord
def has_dashdash(word):
if "--" in word:
return True
return False
def extract_words(word):
char = string.a... |
405b6b42a5524fab2960666eafa33887d7b8447f | antigravitybird/pynet_test | /ex_17_callfunc.py | 888 | 4.25 | 4 | #!/usr/bin/env python
def my_func(x, y, z=20):
return x + y + z
def my_func2(x, y, z=20):
return x, y, z
print
print "Calling with three positional arguments: "
print "Value: ", my_func(10, 20, 30)
print
print "Calling with two named arguments: "
print "Value: ", my_func(x=10, y=20)
print
print "Calling with... |
d0948fa60e4485b9dbe517865583baffadd2a0ce | antigravitybird/pynet_test | /ex_6_math.py | 306 | 4 | 4 | #!/usr/bin/env python
num1 = int(raw_input ("Input first number here: "))
num2 = int(raw_input ("Input second number here: "))
print
print "Sum: {}".format(num1 + num2)
print "Difference: {}".format(num1 - num2)
print "Product: {}".format(num1 * num2)
print "Quotient: {}".format(num1/float(num2))
print
|
7a00d673dbeef2c6dd54dc75ab2bd22e8d91b89b | wangsn0212/data-structure | /反转链表/反转链表.py | 1,519 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# 返回ListNode
def ReverseList(self, pHead):
# write code here
... |
abf8aa9371650c7f3511a0b88d89634e5c06ed86 | wangsn0212/data-structure | /矩阵中的路径/矩阵中的路径.py | 2,725 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
# -*- coding:utf-8 -*-
# =============================================================================
# :param matrix:字符矩阵
# :param rows:矩阵的行数
# :param cols:矩阵的列数
# :param path:需要寻找的路径
# ========... |
3dfbd5bc74afeffee55624a9ca257e4785d1e7a1 | o-l-e-z-a/structures_and_algorithms | /structures/priority_queue.py | 994 | 3.78125 | 4 | from structures.heap import MinHeap
class Node:
def __init__(self, value, priority):
self.info = value
self.priority = priority
def __repr__(self):
return f'({self.info}, {self.priority})'
def __eq__(self, other):
if isinstance(other, Node):
return (self.info... |
982f7d1934e85e2ecb625ce99a2810ea221396fe | o-l-e-z-a/structures_and_algorithms | /structures/base.py | 789 | 3.609375 | 4 | import abc
class BaseQueue(abc.ABC):
def __init__(self):
self._list = []
@abc.abstractmethod
def push(self, value):
""" Добавление элемента """
def pop(self):
if not self.is_empty():
return self._list.pop(0)
def get(self):
if not self.is_empty():
... |
77731c8bb566c2ce7eb05c537eedf1f1c84c93c4 | o-l-e-z-a/structures_and_algorithms | /algorithms/graph_algorithms/dijkstra.py | 2,250 | 3.828125 | 4 | class Dijkstra:
def __init__(self, graph: dict):
self._graph = graph
self._costs = {}
self._processed = []
self._parents = {}
def __call__(self, root: str, item: str):
"""алгоритм Дейкстры"""
self.set_start_value(root, item)
node = self.find_lower_cost_no... |
af2410ae65c168c3683b04107c01fd921268b02f | digitalap3/PythonLotteryExercise | /generation1/lotteryrun_build3.py | 2,280 | 3.875 | 4 | import lottery_build3 as lb ##BE SURE THIS IMPORT IS CURRENT!!!!!!!!!!
## SEE STRATEGIES2.TXT - MATURING ALGORITHM, USING NUMLIST TO GENERATE DIFFERENT DICTIONARIES/LISTS
## CHANGE NAMES FROM LISTS TO DICTS WHERE APPLICABLE TO AVOID CONFUSION
def newfulllist(testlist): ## clear testerlist dict each use
testerlist... |
eb70dd3ab6ee5fb2b58f1c46a757988fb0f28bfd | chkgk/ScientificPython | /project1/sumUp.py | 374 | 3.875 | 4 | def sumUp(flatList, summe = 0):
if not flatList:
return summe
else:
return sumUp(flatList[:-1], summe+flatList[-1])
# one liner:
def sumUpInOneLine(flatList, summe = 0):
return summe if not flatList else sumUpInOneLine(flatList[:-1], summe+flatList[-1])
myList = [1, 2, 3, 4, 5, 6]
print("normal: ", sumUp(my... |
19fc94137f5c857ba831224868e758355b811ce1 | chkgk/ScientificPython | /project1/fizz.py | 1,002 | 4.0625 | 4 | # FizzBuzz
# Originally a drinking game, count from 1 to 100 one after another.
# Every time the number is divisible by three, you say fizz.
# Every number divisible by five is replaced with buzz.
# If the number is divisible by 3 and 5, you say fizzbuzz,
# so the progression is:
# 1 2 fizz 4 buzz fizz 7 8 fizz... |
7a8d846439acb6aad0c04c0fc8326cc15911ad65 | JulianMullins/python_class | /session04/quadratic.py | 307 | 3.703125 | 4 | import math
# quadratic function
def quadratic(a, b, c):
if a == 0:
return 'INVALID: a must not be 0'
x1 = (-b + math.sqrt(b**2 - (4*a*c))) / 2*a
x2 = (-b - math.sqrt(b**2 - (4*a*c))) / 2*a
if x1 == x2:
return x1
else:
return x1, x2
print(quadratic(1, 0, -4)) |
3d5ed6d1ae3c9a2edfbedf7322a27a5caea0afe6 | EricSchles/personal_projects | /python3_analysis/basic_functionality/basic_python_code.py | 749 | 3.71875 | 4 | from multiprocessing import Process,Queue
from time import time
def processing(x,q):
q.put(x*x)
def proc(x):
return x*x
start = time()
q = Queue()
results = []
for i in range(1000):
p = Process(target=processing,args=(i,q,))
p.run()
results.append(q.get())
print(time()-start,"multiprocessing run... |
9af831e3d4915d91e832f2b2afaed9c3c56100d6 | EricSchles/personal_projects | /cpp_tutorial/experiments/linked_list_prototype.py | 634 | 3.953125 | 4 | class Node:
def __init__(self,data,next=None):
self.data = data
self.next = next
def __str__(self):
return repr(self.data)
class LinkedList:
def __init__(self):
self.head = Node(None)
def append(self,data):
if not self.head.next:
self.head.next = Node... |
ec7595751ffc93a33da266726338d2e9154fd8d2 | osherz/penguins_bot | /mapchecker.py | 2,229 | 3.640625 | 4 | from penguin_game import *
from utils import get_avg_distance_between_all_icebergs, get_avg_distance_between_natural_groups
map_checker = None
class MapChecker:
"""
Class that check in which map we play.
"""
def __init__(self, game, stay_default=False):
self.__is_2X2_map = False
sel... |
95a2206327d3e92951cfaf612567ba4061140569 | inmass/Python-calculator | /CALCULATOR.py | 4,223 | 3.90625 | 4 | from tkinter import *
ws = Tk()
ws.title('CALCULATOR')
#ENTRY CREATION
e=Entry(ws, border=5)
#FUNCTIONS CREATION
def num_button(x):
current = e.get()
e.delete(0, END)
e.insert(0, str(current) + str(x))
def clearing():
e.delete(0, END)
def addition():
global task
global first_number... |
4c86190ccc43240d034771304c77170a127d6ec4 | CarverFan/PythonStudyNotes | /hacker-rank.py | 878 | 3.84375 | 4 | """
Iterators and iterables
"""
import itertools
n_length_of_list = int(input())
n_space_sep_list = input()
k_indices = int(input())
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
# create dict to g... |
d6a6b5d8ccb2779b4549d53fff2d5c1b78f6c633 | Likazyabra/git-lesson | /4.py | 665 | 3.796875 | 4 | plates = int(input('Количество тарелок: '))
fairy = float(input('Количество моющего средства: '))
sum_plates = 0
while plates > 0 or fairy > 0:
if plates == 0:
print('\nВымыто тарелок: {} шт \nОсталось моющего средства: {} мл'.format(sum_plates, fairy))
break
elif fairy == 0:
print('\n... |
766ede6baa3eb1045d18360abb516666cb6b5bf0 | Likazyabra/git-lesson | /8.py | 263 | 4 | 4 | # Первое задание
from datetime import date
def new_year():
today = date.today()
next_year = date(today.year + 1, 1, 1)
return (next_year - today).days
print('До нового года осталось {} дней'.format(new_year()))
|
e29ba1fb81149076ffea5207b0db14fbdb50d1ef | CarlosNavaR/Estructura.Datos | /MetodosOrdenamiento/Burbuja.py | 1,518 | 4.0625 | 4 | import random ## Libreria que permite usar la funcion randint
class Bubble(): ## Clase que contendra las operaciones para implementar el metodo burbuja
def listaAleatorios(self): ## FUncion que genera nuneros aleatorios
lista = [0] * 50 ## Se declara la lista y se multiplica por la cantidad de elementos que... |
3ca4c1516dfeca029ece0747b82f27635299ba62 | CarlosNavaR/Estructura.Datos | /Colas circulares/Circularpush.py | 2,134 | 4.0625 | 4 | import os ## Libreria que permite usar la sentencia os.system("clear")
front = 0 ## Frente de la cola
rear = 0 ## Final de la cola
index = 0 ## Variable que controla el numero de datos ingresados
class ColasC():
def __init__(self):
self.cola = [0,0,0,0,0] ## Crea e inicializa el arreglo/Lista que almacena los da... |
a5df626753727cf717706a560d3dd188315d57aa | grigorgevskaya/lesson1 | /while.py | 323 | 3.8125 | 4 |
def main(self):
pass
while True:
user_say=input("Как дела?")
if user_say=="Хорошо":
print("Ok")
elif user_say=="Болею":
print("Выздоравливай")
break
else:
print("Я думал, что Хорошо")
|
2a5c562d7e41dec6126f7503d1c7494e051ab845 | hcpmiyuki/hukuzakuna_keisan | /flask/calculator_tools.py | 4,306 | 3.921875 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*
def readNumber(line, index):
# string to number
number = 0
while index < len(line) and line[index].isdigit():
number = number * 10 + int(line[index])
index += 1
if index < len(line) and line[index] == '.':
index += 1
keta = 0.... |
f162c5e381ae2abae9e4436d68bbe7ff8b8b3902 | Alcacer/Calculator-repo | /Calculator GUI.py | 4,001 | 3.859375 | 4 | # A simple calculator GUI
from tkinter import *
def button_click(number):
global expression
expression = expression + str(number)
input_var.set(expression)
def clear_button():
global expression
expression = ""
input_var.set(expression)
def clear_one():
global expression
new_string = ... |
997bc35fdff3ac8c83a07a6d487546f2ccdf9ff5 | tea-with-lemon/IU9 | /Python/лаба6.py | 2,928 | 3.75 | 4 | # -*- coding: utf8 -*-
#1 задание циклом
def lcm(a,b):
m = a*b
while a != 0 and b != 0:
if a > b:
a %= b
else:
b %= a
return m // (a+b)
def gcd(a, b):
a,b=abs(a),abs(b)
while a!=b:
if a>b:
a=a-b
else:
b=b-a
return a... |
a894afd1066ab7ff865db91d020b9b8729f478e9 | AurelijaNorvaisaite/Software-testing | /Software testing fundamentals/01-unittest/example-01.py | 1,032 | 3.515625 | 4 | # 1.We have create a new test case by creating class TestBuiltins which inherits unittest.TestCase. (Inheritance will be explained in further modules)
# 2.The test case contains three separate tests -def test_* functions.
# 3.Test function names have to start with test
# 4.Each of the functions invokes at least one sel... |
ae27923e8466fd0844a247e30d9ebf2642f51fd2 | neetipandey3/Dynamic-Programming | /ways-to-distance.py | 1,358 | 4.0625 | 4 | '''
Dynamic Programming:
Count number of ways to cover a distance
Given a distance ‘dist, count total number of ways to cover the distance with 1, 2 and 3 steps.
Examples :
Input: n = 3
Output: 4
Below are the four ways
1 step + 1 step + 1 step
1 step + 2 step
2 step + 1 step
3 step
Input: n = 4
Output: 7
***... |
7b4169f2a6cb3b246b79a3a61599c4c84eeee26c | niscee/Data_visualization-app | /main.py | 1,697 | 3.5625 | 4 | from operations import option_one,option_two,option_three,option_four
#exit program
def exit():
print('---------------------------- THANK YOU!! --------------------------------------')
start = input('CLICK ANY KEY TO RUN THE SYSTEM:\n')
if start:
user_input()
# program display start
def ... |
3d120963e6082fc867cb0b2266e0f4aa63ff458e | wensheng/tools | /r2c/r2c.py | 1,795 | 4.25 | 4 | #!/bin/env python
"""
Author: Wensheng Wang (http://wensheng.com/)
license: WTFPL
This program change change rows to columns in a ASCII text file.
for example:
-----------
hello
world
!
-----------
will be converted to:
-----------
h w!
e o
l r
l l
o d
-----------
If you specify '-b', vertical bars will be added to... |
b45417c1afaca40809efe085351d50339fa2166b | giahieu01/giahieu01 | /b2.py | 220 | 3.765625 | 4 | import math;
x1=int(input("enter x1 ---> "))
y1=int(input("enter y1 ---> "))
x2=int(input("enter x2 ---> "))
y2=int(input("enter y2 ---> "))
d1=(x2 -x1)*(x2 -x1);
d2=(y2-y1)*(y2-y1);
c=math.sqrt(d1+d2)
print(c)
|
b93028a6664ea948dcb6c69f89ad24747219a73b | giahieu01/giahieu01 | /b2c5.py | 375 | 3.84375 | 4 | import datetime as dt
format= '%Y-%m-%dT%H:%M:%S'
t1= dt.datetime.strptime('2008-10-12T14:45:52',format)
print('Day'+str(t1.day))
print('Day'+str(t1.day))
print('Month'+str(t1.month))
print('Minute'+str(t1.minute))
print('Second'+ str(t1.second))
# Define todays date and time
t2=dt.datetime.now()
diff=t2-t1... |
ae05726ca7b82f281b58f655469c6b6529283bfd | giahieu01/giahieu01 | /b1.py | 128 | 3.796875 | 4 | n1=int(input("enter n1 vualue"))
n2=int(input("enter n2 vualue"))
if n1>n2:
print(' n1 big')
else:
print(' n2 big')
|
8979256966a6e9101ae39fb87831563d24167f0a | giahieu01/giahieu01 | /hieu.py | 482 | 3.703125 | 4 | from tkinter import *
root = Tk()
Label(root, text="Red Sun", bg="red", fg="white").pack()
Label(root, text="Green Grass", bg="green", fg="black").pack()
Label(root, text="Blue Sky", bg="blue", fg="white").pack()
mainloop()
from tkinter import *
colours = ['red','green','orange','white','yellow','blue']
r = 0
... |
7337c7c8121c365c24b380678a05d9e1ecd32eae | jamalrizki/cs-1101 | /wk6_pt2.py | 926 | 3.96875 | 4 | nest = [1, 2, [3,4], 5] #nested list example
def no_more_nest(nest):
newlist = []
for i in nest:
if type(i) == list:
for j in i:
newlist.append(j)
else:
newlist.append(i)
return newlist
print("nest:" +" " + str(no_more_nest(nest)))
def times(a, b, c... |
e1603677c01ca667105c6e4f318183a40fcca6b4 | jamalrizki/cs-1101 | /test_unit3.py | 176 | 3.703125 | 4 | if 5==4:
if 11>10:
print("no way")
else:
print("yes way")
elif 5<4:
print("here is another option")
else:
print("yes, but actually, no"
|
0b44b64de6e6b1c1e58b40b4d793d4e5bb14cbc2 | zertrin/zkpytb | /zkpytb/priorityqueue.py | 2,082 | 4.25 | 4 | """
An implementation of a priority queue based on heapq and
https://docs.python.org/3/library/heapq.html#priority-queue-implementation-notes
Author: Marc Gallet
Date: 2018-01
"""
import heapq
import itertools
class EmptyQueueError(Exception):
pass
class PriorityQueue:
"""Based on https://docs.python.org/... |
cd006fa810f43593fd0c2849011e5cc44ef73c31 | clark-xie/algorithms_python | /1/1.1/1.1.3.py | 97 | 3.84375 | 4 | str1 = input()
str2 = input()
if str1 == str2:
print(" equal")
else:
print("not equal")
|
16833e1fee97dd299940f6b0ed9662ef79e956d4 | Naheuldark/Codingame | /Puzzles/Easy/TheDart101.py | 1,600 | 3.625 | 4 | import sys
import math
TARGET_SCORE = 101
def simulate(shoots):
rounds, throws, misses, score = 1, 0, 0, 0
prev_round_score = 0
prev_shot = ''
for shot in shoots.split():
throws += 1
if 'X' in shot:
misses += 1
score -= 20
if prev_shot == 'X': scor... |
08c4dcad7e8adefdcbb31c2ed68fc36edd06ea46 | Naheuldark/Codingame | /Puzzles/Easy/OrganicCompounds.py | 884 | 3.65625 | 4 | import sys
import math
def check_for_bond(row, col, formula):
if row < 0 or row >= len(formula):
return 0
if col < 0 or col >= len(formula[row]):
return 0
return int(formula[row][col]) if formula[row][col] in '0123' else 0
def sum_bonds(row, col, formula):
return check_for_bond(row, ... |
8f942265a47466f69898acdda49416cf3814e06a | efraimrocha/Avaliacao2-LPG1 | /Grupo1_lacos.py | 529 | 3.84375 | 4 | #02)
def NotaZerodez():
f = True
while f:
n = int(input("Digite um valor entre 0 e 10. "))
if 0 <= n <= 10:
print(f'Você valor entre 0 e 10.\nO programa será encerrado\nFIM')
f = False
break
else:
continue
NotaZerodez()
#----------------... |
d3dc56235ded6a9f1258770ef7e44da7c7e10a36 | NatRidgard/NYU-Intro-to-Python-Spring-2018 | /Monday Febuary 12th/Lectures/demo_for_class/conditionals.py | 272 | 3.75 | 4 | space = 20
if space < 20:
print('We still have space!')
elif space == 20:
print(
'We are just at capacity, so no room for a friend today srewrkw3rkwl / '
';rkwesrewrewrw werjwerjwo3pi awrw3ip[ire ;3w4322342.')
else:
print('Sorry, we are full')
|
4c6581a335227d54d843578af72972554cb0410d | dyuri/repacolors | /repacolors/types.py | 1,248 | 3.546875 | 4 | """Named tuples for color spaces
"""
from typing import Tuple, NamedTuple, Optional
CTuple = Tuple[float, ...]
class HSLTuple(NamedTuple):
hue: float = 0
saturation: float = 0
lightness: float = 0
class RGBTuple(NamedTuple):
red: float = 0
green: float = 0
blue: float = 0
class HSVTuple(... |
4c767b70fffb96e8cf16069da5849f410bd90600 | Collin-Campbell/games | /blackjack.py | 21,665 | 3.734375 | 4 | import random
import time
import sys
instructions = """
General rules for how to play Blackjack can be found at:
https://bicyclecards.com/how-to-play/blackjack/
Things to know:
- An Ace counts as 1 or 11. Face cards count as 10.
- A blackjack (A and K/Q/J/10) pays out x1.5 unless the dealer also has a blackjack, wh... |
df28ce3e31efe10417cd698cca0b674ed72fbb7c | TheBiggerFish/Laserman | /space.py | 1,715 | 3.5 | 4 | from enum import Enum
from coord import Direction
class Object(Enum):
OPEN = 0
WALL = 1
ROCK = 2
MIRROR_1 = 3
MIRROR_2 = 4
class Space:
def __init__(self,object=Object.OPEN):
self.object = object
def __str__(self):
if self.object == Object.WALL:
return 'W'
... |
4be4488594d72d045d4c7249409a437eb00b2634 | NagahShinawy/book-store | /main.py | 1,138 | 3.5 | 4 | """
created by Nagaj at 04/05/2021
"""
from accounts.members import Author, User
from books.book import Book
def main():
user1 = User("user1", "user1@test.com")
bob = Author("UncleBob", "bob@test.com")
john = Author("john", "john@test.com")
# author2 = Author("author2", "author2@test.com")
# auth... |
32ba47e1eee85d68e144b478471b1c3fba29ca17 | StarWars-fan07/python-samples | /reversegamAA.py | 1,600 | 3.90625 | 4 | # Reversegam: a clone of Othello/Reversi
import random
import sys
WIDTH = 8
HEIGHT = 8
def drawBoard(board):
#Print the board passed to this function. Return None
print(' 12345678')
print(' +--------+')
for y in range(HEIGHT):
print('%s|' % (y+1), ends='')
for x in range(WIDTH):
... |
bf95406d36b1a3f78dbd44736f6e9c7ebddce427 | rebeccaz21/15-112-Term-Project | /add.py | 2,807 | 3.890625 | 4 | from tkinter import *
from tkinter import messagebox
from tkinter import simpledialog
#code taken from fall 2015 notes: http://www.kosbie.net/cmu/fall-16/15-112/notes/notes-tkinter-demos.html
#modified to fit project
#this file consists of all the buttons that are used in the project
#ask about where the user lives t... |
2458b6b8610d96ab39326415679d421a7edb4a2e | NPazylkhan/Python-working-with-words | /polindrom.py | 98 | 3.59375 | 4 | a = str(input())
b = a[::-1]
print(b)
k = int(len(a)/2)
print("yes" if a[0:k] == b[0:k] else "no") |
c73cf61e5a79744a8aaa15c9545bddc5b3b47692 | programmersteven/python_exercise | /prac_05/hex_colours.py | 496 | 4.3125 | 4 | COLOR_TO_CODE = {"AliceBlue": "#f0f8ff","blue1": "#0000ff","black":"#000000","brown":"#a52a2a",
"coral": "#ff7f50","DarkGoldenrod": "#b8860b","DarkOrchid": "#9932cc","DarkSeaGreen": "#8fbc8f",
"DimGray": "#696969","firebrick": "#b22222"}
color = input("Enter the color's name: ")
while ... |
88376961cbb2dc7e5ca7b88beb2bd34e76e51dc2 | tr-likelion/tR3 | /week1 hw/#3.py | 140 | 3.59375 | 4 | for i in range(2,10):
print "%d_Multiplication" %(i)
for j in range(1,10):
print "%d * %d =\t" %(i,j),i*j |
bd6e53f546391bcb92f4d36b4ba656dba973b054 | acedit/Python_kurs | /week1'5/sum_digits.py | 102 | 3.8125 | 4 | n=input("Enter n:")
n=int(n)
sum=0
while n>0:
cifra=n%10
sum=sum+cifra
n=n//10
print(sum)
|
f75f2d1bc5460b46b24357158ab367cb031207f5 | acedit/Python_kurs | /week1'5/factorial.py | 82 | 3.5625 | 4 | n=input("Enter n:")
n=int(n)
pr=1
i=1
while i<=n:
pr=pr*i
i=i+1
print(pr)
|
80e16146dd5b57e5930f167b33fa4157be5b51e3 | acedit/Python_kurs | /week1'5/1_to_n_by_2.py | 68 | 3.828125 | 4 | n=input("Enter n:")
n=int(n)
i=1
while i<n+1:
print(i)
i+=2
|
72f8cbcd7a7be2ee1921395e50f530bb309ebd14 | acedit/Python_kurs | /week5'5/sublist.py | 384 | 3.78125 | 4 | def sublist(list1, list2):
sublist=False
for i in range(0,len(list2)):
if list2[i]==list1[0]:
sublist=True
for j in range (1,len(list1)):
if i+j<len(list2):
if list1[j]!=list2[i+j]:
sublist=False
else:
... |
4cefc580c24cad53894e77c88f522d23eb4ebc41 | acedit/Python_kurs | /week3'3/largest_and_smallest.py | 555 | 3.515625 | 4 | #bugva ako ima 0 no ne mi se zanimava zashtoto nqmam vreme
def to_digits(n):
spisuk=[]
while n>0:
cifra=n%10
spisuk=[cifra]+spisuk
n=n//10
return spisuk
def spisuk_kum_chislo(spisuk):
chislo=0
for i in spisuk:
chislo=10*chislo+i
return chislo
def obrushtane_na_... |
e308ef069bd0889a75733e42d789157f26d25cb3 | LetheSec/Cryptography-Course-Design | /ClassicalCipher/Caesar.py | 1,903 | 3.75 | 4 | def Encrypt(m, k):
"""
凯撒密码加密
:param m: 明文
:param k: 密钥(移位量)
:return: 加密的结果
"""
k %= 26
c = ''
mlen = len(m)
for i in range(mlen):
if m[i].isupper():
c += chr((ord(m[i]) - ord('A') + k) % 26 + ord('A'))
elif m[i].islower():
c += chr((ord(m[... |
ccb58c3b3faee4d0b2a14e600c2881a3d5ecb362 | atravanam-git/Python | /DataStructures/tuplesCodeDemo_1.py | 1,133 | 4.6875 | 5 | """tuples have the same properties like list:
#==========================================================================
# 1. They allow duplicate values
# 2. They allow heterogeneous values
# 3. They preserve insertion order
# 4. But they are IMMUTABLE
# 5. tuple objects can be used as keys in Dictionaries
#=========... |
66a7a8a20302db6ef1887c0fec8e546059de9954 | atravanam-git/Python | /DataStructures/dictCodeDemo_3.py | 264 | 3.640625 | 4 | # declaring a dictionary object
dictA = dict()
# initialize dictionary values
dictA[100] = "Durga"
dictA[200] = "Praveen"
dictA[300] = "Reddy"
dictA[400] = "Govind"
dictA[500] = "Naveen"
print("Key\t" + "Values")
for k, v in dictA.items():
print(k, "\t", v) |
ea992d521c1151fcc536f9692ad1bd09582d090f | atravanam-git/Python | /FileOperations/pickle_unpickleCode.py | 1,142 | 4 | 4 | #=========================================================================
# from test.test_decimal import file
# Pickle and Unpickle Concept: (same like Serialization and De-serialization)
# 1.Import pickle module
# 2.Use dump() method to write object to dat file
# 3.Use load() method to read object from the dat file
... |
0160126d1a2e614c95b844adb1524a6982f50493 | atravanam-git/Python | /FunctionsDemo/globalvarDemo.py | 902 | 4.53125 | 5 | """
#==========================================================================
# 1. global vs local variables in functions
# 2. returning multiple values
# 3. positional args vs keyword args
# 4. var-args, variable length arguments
# 5. kwargs - keyword arguments
#======================================================... |
e2061fa47959c581e281523589bc59ea2168dd0c | kishore-s-15/MNIST-Digit-Recognizer | /data_utils.py | 2,082 | 3.609375 | 4 | # This script contains functions for loading the dataset and labels from the MNIST Dataset
# Importing the required libraries
import gzip
import random
import numpy as np
import matplotlib.pyplot as plt
def load_data(data_dir, verbose = False):
"""This function loads the data for the MNIST Dataset"""
# MNIST... |
87877c8594bebc496a90e34809c7a3cf0f83d3e9 | javatican/migulu_python | /list/list_test2.py | 570 | 3.796875 | 4 | s1 = [1,2,3,4,5,3]
s2 = ['John','Mary','Tom','Eddie','Helen']
# x in s
print(1 in s1)
print('Tom' in s2)
# x not in s
print('Sam' not in s1)
# use +
print(s1+s2)
#s*n or n*s
print(s1*3)
print(3*s2)
# s[i] , 若i為負值, 相當於len(s)+ i
print(s1[1])
print(s1[-1]) #相當於s1[5]
# s[i:j]
print(s1[1:3])
print(s1[:3])
print(s1[1:])
#... |
5b4005cce3caba34b983e5ec5d7c47ddafda854f | javatican/migulu_python | /class5/Box.py | 691 | 3.796875 | 4 | import datetime
class Box:
#三個資料(屬性) h, w, d (長寬高)
#行為(方法),calculate_volume() 計算體積, print_info()列印資訊
#建構子(__init__())
def __init__(self, h, w, d):
self.h = h
self.w = w
self.d = d
self.volume = self.h*self.w*self.d
def calculate_volume(self):
return self... |
65bbbdf892c60a333d96b50ed84298078800f87b | javatican/migulu_python | /class2/if4.py | 753 | 4.09375 | 4 | def is_upper(input='A'):
"""check if input is an upper case character """
if input>='A' and input <='Z':
return True
else:
return False
def is_lower(input):
if x>='a' and x<='z':
return True
else:
return False
def is_digit(input):
if x>='0' and ... |
1491034e0d2c3d1b20c36cf763c152cb91086e37 | javatican/migulu_python | /class1/str.py | 160 | 3.703125 | 4 | #coding=utf-8
str='Hello world!'
print(str)
print(str[0])
print(str[2:5]) #slice
print(str[:5])
print(str[2:])
print(str*2)
print(str+" Taiwan.") #字串串接 |
e4bfb3124771f4e47681eea576f01b734a4b1f4f | javatican/migulu_python | /class7/list_comprehension.py | 186 | 3.546875 | 4 | x = [1,2,3,4,5] #欲產生一個[11,12,13,14,15]
#1
y = []
for a in x:
y.append(a+10);
print(y)
#2
y = [a+10 for a in x]
print(y)
# 使用filter
z = [a for a in x if a%2]
print(z) |
52961e78f7d142032eee4753c323fc138a8090de | javatican/migulu_python | /class8/Cat.py | 620 | 3.609375 | 4 | from Pet import Pet
from Pet import animal_speak
class Cat(Pet):
def __init__(self, name, weight):
super().__init__(name, 'Cat')
self.weight = weight
def speak(self):
print("喵喵")
def show(self):
Pet.show(self)
print("weight=%f" % self.weight)
def __str__(self):
... |
397cf4e1582b4f6e5f30a51a5ef531231fdba1b2 | javatican/migulu_python | /class2/if3.py | 220 | 4.125 | 4 | x=-101
if x%2 and x>0:
print(x,"是正奇數")
elif x%2 and x<0:
print(x,"是負奇數")
elif x%2==0 and x>0:
print(x,"是正偶數")
elif x%2==0 and x<0:
print(x,"是負偶數")
else:
print(x,"是0") |
964c6e0588f5e3ca4aabb1cd861357f6d935a595 | cuongdv1/Practice-Python | /Python3/database/create_roster_db.py | 2,652 | 4.125 | 4 | """
Create a SQLite database using the data available in json stored locally.
json file contains the users, courses and the roles of the users.
"""
# Import required modules
import json # to parse json
import sqlite3 # to create sqlite db
import sys # to get coomand line arguments
# G... |
1b23f50c456417293a6da313f1c0eff9e6991594 | cuongdv1/Practice-Python | /Python3/web/beautifulsoup_ex.py | 991 | 3.515625 | 4 | # Third party Library
# Using Beautiful Soup : Remove Syntax errors from web pages
# crummy.com | Beautiful Soup
# Install from here | https://www.crummy.com/software/BeautifulSoup/
# OR #
# Download from 'Dr-Check'
# http://www.py4e.com/code3/bs4.zip
# Unzip in wroking directory
# Import urllib and Beautifu... |
e30756677e7d8094f46c14a43d8f5f01e706ae36 | cuongdv1/Practice-Python | /Python3/database/create_tracks_db_from_xml.py | 4,486 | 3.5625 | 4 | """
Create a Tracks Database from an exported xml music library
"""
import xml.etree.ElementTree as ETree
import sqlite3
def lookup(d, key):
found = False
for child in d:
if found : return child.text
if child.tag == 'key' and child.text == key :
found = True
retur... |
c6352125e3d704ed6102e557919443c6c85fd903 | cuongdv1/Practice-Python | /Python3/regex/regex_sum.py | 460 | 3.828125 | 4 | # Import Regular Expression module
import re
fname = "regex_sum_82164.txt"
# Open file
try:
fhand = open(fname)
except:
print("Error : Can't open file")
# Read file and compute sum
fdata = fhand.read()
sumtotal = 0
# Find all numbers: Start with a digit and
# find 1 or more digits
numlist = re... |
2bd7311b9d138e8472f2ef9ecd9d6bc6eac706e1 | mandrulevicius/coding-challenges | /fizzbuzzing.py | 7,082 | 3.984375 | 4 | # fizzbuzz with no ifs, no modulo??? should still be easily readable code?????
# for high performance, modulo with ints should be fine
# questions to ask (solution depending on answers):
# is this code going to be run many times a day/hour/second? (performance)
# is this code going to be run on different numbers? (sca... |
1fe7b0e0806796ef18ebecbaf7c042bea4a0f94f | YosukeKira/main | /Python/chapter2/2-4/inch-to-cm-input-ng.py | 116 | 3.609375 | 4 | per_inch = 2.54
inch = input("inch? ")
cm = inch * per_inch
desc = "{0}inch = {1}cm".format(inch,cm)
print(desc) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.