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 |
|---|---|---|---|---|---|---|
fe17fb35f1fd90379c4d8db8d6da145853afa108 | janaslo/pyladies | /04_while_funkce/zelva_kytka.py | 3,193 | 3.671875 | 4 |
from random import randrange
from turtle import *
def nakresli_zahradku(pocet_kytek=3):
"""Vykreslí zahrádku složenou z kytek, které mají náhodně vybrané
vlastnosti.
"""
posun = 300 # mezera mezi kytkami
x, y = -(pocet_kytek//2 * posun) , -250 # vychozi pozice ... |
213100e34315da40ea9cef619a4a390362dac64d | janaslo/pyladies | /07_seznamy/opakovani_palindrom.py | 946 | 3.53125 | 4 |
def je_palindrom(retezec):
"""Tato funkce zjistí, zda je vstupní řetězec palindrom
(tj. čte se stejně zepředu i zezadu), a vrátí příslušnou
logickou hodnotu (True/False).
"""
pass # nahraď svým kódem
# Základní otestování funkce
palindromy_skupiny = [
("aha", "abba", "radar"), # pokud p... |
0591873e2928280f791a0f386347c3fb297bd4ab | larissaOjeda/BDnR | /Tarea1_Conjunta.py | 13,785 | 3.984375 | 4 | #----------------------Ejercicio 1a---------------------------------------
def desplaza_lista(k, lista):
"""
Parameters
----------
k : int
cantidad de lugares a desplazar (un valor positivo indica desplazar a la derecha; un valor negativo, a la izquierda.)
lista : list
lista que se ... |
5960ef45352fa254d26ad3cd8a6745a5fdb96533 | HenriqueEichstadt/MeusCursos | /Python/PythonFundamentos/Cap02/DSA-Python-Cap02-05-Dicionarios.py | 1,743 | 3.875 | 4 | # ## Dicionários
# Isso é uma lista
estudantes_lst = ["Mateus", 24, "Fernanda", 22, "Tamires", 26, "Cristiano", 25]
estudantes_lst
# Isso é um dicionário
estudantes_dict = {"Mateus":24, "Fernanda":22, "Tamires":26, "Cristiano":25}
estudantes_dict
estudantes_dict["Mateus"]
estudantes_dict["Pedro"] = 23
estudantes_d... |
aebf2c565ac04e903da16fe7c96d812824c21d60 | HenriqueEichstadt/MeusCursos | /Python/PythonFundamentos/Cap03/DSA-Python-Cap03-05-Metodos.py | 482 | 4.15625 | 4 |
# # Métodos
# Criando uma lista
lst = [100, -2, 12, 65, 0]
# Usando um método do objeto lista
lst.append(10)
# Imprimindo a lista
lst
# Usando um método do objeto lista
lst.count(10)
# A função help() explica como utilizar cada método de um objeto
help(lst.count)
# A função dir() mostra todos os métodos e atr... |
6a0a861d93f7cddfee4374de6e37cc0c9a9545dd | HenriqueEichstadt/MeusCursos | /Python/PythonFundamentos/Cap02/DSA-Python-Cap02-Exercicios.py | 1,877 | 4.0625 | 4 | #!/usr/bin/env python
# coding: utf-8
# # <font color='blue'>Data Science Academy - Python Fundamentos - Capítulo 2</font>
#
# ## Download: http://github.com/dsacademybr
# In[ ]:
# Versão da Linguagem Python
from platform import python_version
print('Versão da Linguagem Python Usada Neste Jupyter Notebook:', pytho... |
8a39545055bd1b810c9a0a32a60092c942359dfb | HuuThin/C4T06 | /what is life/session8.py | 6,920 | 3.875 | 4 | # C4T List Create
# 0
array = ["apple", "banana", "orange"]
array.append("grapefruit")
print(array)
# 1
array = ["apple", "banana", "orange"]
fav = input("Add a thing you like!\nThing: ")
array.append(fav)
print("New list of your favourite fruits!\n{0}".format(array))
# C4T List read & index... |
b32ac48d1f1ef2c1f93776a0a8c7544909061e4a | Maarten1999/Minor_ML3_Snake_AI | /path_finding/bfs_v2/bfs.py | 520 | 3.6875 | 4 | import collections
def bfs(grid, start, goal, width, height, wall):
queue = collections.deque([[start]])
seen = set([start])
while queue:
path = queue.popleft()
x, y = path[-1]
if grid[y][x] == goal:
return path
for x2, y2 in ((x + 1, y), (x - 1, y), (x, y + 1),... |
508e4a3139bca354467178cbc2687416924599ea | Harpreetkaurpanesar25/python.py | /anagram.py | 267 | 4.1875 | 4 | #an anagram of a string is another string that contains same char, only the order of characters are different
def anagram(s1,s2):
if sorted(s1)==sorted(s2):
print("yes")
else:
print("no")
s1=str(input(""))
s2=str(input(""))
anagram(s1,s2)
|
538b370422f830f38bc1ffd8fda456d842c8c7a2 | Matar-mona/NN | /Assignment_1/task4.py | 1,639 | 3.59375 | 4 | import matplotlib.pyplot as plt
import numpy as np
def train_multiclass_perceptron(train_x, train_y, learning_rate=0.01):
'''
Train a multiclass perceptron given a learning rate
'''
w = np.random.randn(10,257)*0.01
w[:,0] = 1
missclass = 10
iterations = 0
accuracy = 0
acc = []
#iterate until there are no ca... |
7c1e7a4e0aef36a5f9c869d57d06f31cf9508976 | thelfensdrfer/machine-learning-hpc | /1-examples/nn/index.py | 3,696 | 3.8125 | 4 | import tensorflow as tf
from tensorflow import keras
import numpy as np
import matplotlib.pyplot as plt
# Import fashion mnist dataset (https://github.com/zalandoresearch/fashion-mnist)
# 10 categories of grayscaled clothes
fashion_mnist = keras.datasets.fashion_mnist
# Class names [0-9]
class_names = ['T-shirt/top'... |
a6ce7d039cb2830253741dea89477d0414b8c943 | SophieGarden/DataScience_NanoDegree | /Project2_flower_species_image_classifier/train.py | 10,185 | 3.71875 | 4 | '''
Train a new network on a data set with train.py
Basic usage: python train.py data_directory
Prints out training loss, validation loss, and validation accuracy as the network trains
Options:
Set directory to save checkpoints: python train.py data_dir --save_dir save_directory
Choose architecture: python train.py da... |
e8205c6ea0fe16db69c4e89443128c2d99efd91f | vax521/algorithms | /basic_algorithm/DivideAndConquer/NearestPointsPairs.py | 1,886 | 3.671875 | 4 | # 分治法 最近点对问题
import math
import random
def get_distance(pairs):
return math.sqrt((pairs[0][0]-pairs[1][0])**2+(pairs[0][1]-pairs[1][1])**2)
def candidateDot(u,right,dis,mid_x):
#遍历right(已按横坐标升序排序)。
# 若横坐标小于med_x-dis则进入下一次循环;
# 若横坐标大于med_x+dis则跳出循环.
# 若点的纵坐标好是否落在在[u[1]-dis,u[1]+dis],则返回这个点
... |
35806701d6c21fe9908a57daa161b94f6a9ea658 | vax521/algorithms | /basic_algorithm/Recursive/primeFactor.py | 265 | 3.6875 | 4 | result = []
def PrimeFactor(n):
for i in range(2,int(n/2+1)):
if n % i == 0:
result.append(i)
return PrimeFactor(n/i)
result.append(int(n))
if __name__ == '__main__':
PrimeFactor(90)
print("90的质因数:",result)
|
1aa1dea1e73ee4f0b8d1459d5be6003bbe1a76b4 | melardev/PythonFilesytemSnippets | /pathlib_usage.py | 606 | 3.53125 | 4 | '''
Usage of pathlib, available since Python 3.4
'''
from pathlib import Path
file_path = Path('C:/windows')
print('About C:/Windows')
print('exists? %r' % file_path.exists())
print('is dir? %r' % file_path.is_dir())
print('About C:/Windows / System32')
file_path_changed = file_path / 'System32'
print('exists? %r' % f... |
4bba6f0b37928a27e54e8c6214a31293446dfd56 | yousef19-meet/meet2017y1lab3 | /Ages.py | 114 | 3.6875 | 4 | print("person1:put your age=")
age=input()
print("person2:put your age=")
age1=input()
print(int(age)+int(age1))
|
9eafd04ecb4a611f4d47556d0727fd731fd6327b | teayes/Python | /Experiments/Exp8.py | 3,367 | 4.03125 | 4 | from sqlite3 import Error, connect
def connection():
try:
con = connect('Experiments/Student.db')
print("Connection Established")
return con
except Error:
print(Error)
def table(con):
query = "CREATE TABLE if not exists information(USN text PRIMARY KEY,Name text,Departme... |
56c6c4417ca6f8dd1bc1880957484ed343b2a81d | teayes/Python | /Experiments/Exp6.py | 731 | 4.15625 | 4 | class stringValidation:
def __init__(self):
self.open= ["[", "{", "("]
self.close= ["]", "}", ")"]
def validate(self,string):
stack = []
for char in string:
if char in self.open:
stack.append(char)
elif char in self.close:
p... |
9ee3836741e61b13fd337dc58d6127ee82393fb5 | leonoverweel/graph-coloring | /python/coloring/luby_jones_smallest.py | 3,038 | 3.640625 | 4 | import random
class Coloring:
def __init__(self, graph=None):
self.graph = graph
self.vertices = graph.vertices
def color(self, verify=False, sort="id"):
"""Color the graph and return how many unique colors were used."""
colored = 0
colors = 0
# Sort
if sort == "id":
sorted_vertices = sort... |
06107927ab0e1efcdbf69c09596cbbfa86ece0e6 | leonoverweel/graph-coloring | /python/coloring/luby_jones.py | 1,976 | 3.640625 | 4 | import random
class Coloring:
def __init__(self, graph=None):
self.graph = graph
self.vertices = graph.vertices
def color(self, verify=False, sort="id"):
"""Color the graph and return how many unique colors were used."""
colored = 0
round = 0
# Sort
if sort == "id":
sorted_vertices = sorte... |
19f7fc83f5be9323340572cf75df46628cf4dd13 | juzen2003/LeetCode-python-practice | /9_PalindromeNumber.py | 462 | 3.71875 | 4 | # LeetCode #9 Palindrome Number
# Dave Chang
# 2016/12/30
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
temp = str(x)
# negative number can't be palindrome number, so no need to get rid of the signed
#if temp... |
8adca449b5fd09699f0c7b2266adcb7c8ebf8852 | juzen2003/LeetCode-python-practice | /2_AddTwoNumbers.py | 1,118 | 3.734375 | 4 | # LeetCode #2 Add Two Numbers
# Dave Chang
# 2016/12/23
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
... |
d481252616df3958e7a33dc38f486c39f07591f5 | alifmhmmd/InferenceEngine | /Sentence.py | 7,078 | 3.625 | 4 | import re # for regular expressions
import sys
class Sentence:
"""Implementation of General Sentence Structure for a General Knowledge Base.
Formats passed propositional logic in text to a structure that can be
solved using models.
"""
def __init__(self, sentence):
## fields ##
... |
4207e6f3c0ccba12cc56dcbe7e51beea425cda4f | QuantumTetra/OpenGL-Rendering-Engine | /res/textures/SortFunction.py | 448 | 3.75 | 4 | def sortBubble(L):
for i in range(0,len(L)):
for j in range(1,len(L)):
if L[j] < L[j-1]:
temp = L[j-1]
L[j-1] = L[j]
L[j] = temp
return L
def sortInsert(L):
for i in range(1,len(L)):
val = L[i]
pos = i
... |
77c6300b4d7a20a073b857c545c8d702eee86595 | AlexKasapis/Daily-Coding-Problems | /2019-02-23.py | 1,252 | 4.125 | 4 | # PROBLEM DESCRIPTION
# Given a sorted list of integers, square the elements and give the output in sorted order.
# For example, given [-9, -2, 0, 2, 3], return [0, 4, 4, 9, 81].
#
# SOLUTION
# Lets assume two pointers, pointing to the start and end of the list. The pointer which points to the number with the
# highest... |
4b0688e710cd0adac2a1dc9df843161cc81b201c | monjjjjj/20210617-File_Renamer | /argparse_test.py | 1,130 | 3.640625 | 4 | import argparse
import re
import os.path
import sys
def get_parser():
parser = argparse.ArgumentParser(description='Just a test!')
parser.add_argument("directory", help="Directory of files.")
parser.add_argument("pattern",
help="Please input the regular expression of the files. "
... |
cedd80fde4f5656663cb66d9e5921d8ee6a10ba0 | ramoncaceres/imbroglio | /imbroglio_lib.py | 2,115 | 4.0625 | 4 | #
# Maintains and navigates the text of Edward Gorey's
# "The Raging Tide: or, The Black Doll's Imbroglio".
#
class Page(object):
pass
class Book(object):
def __init__(self):
self.pages = dict()
def AddPage(self, pagenum, story, choice0, choice1):
page = Page()
page.story = story
page.choice0 = ... |
f580d20305727d45764691499ecf52094fdcb7ed | xuexiaolei1997/pytorch-official-code | /2_autograd.py | 1,986 | 3.515625 | 4 | # 关于pytorch的自动求导以及反向传递
import torch
# ------------------------------------------------------------------------------
# 创建一个张量,设置requires_grad=True 来跟踪与它相关的计算
x = torch.ones(2, 2, requires_grad=True)
print(x)
# tensor([[1., 1.],
# [1., 1.]], requires_grad=True)
# ---------------------------------------... |
1f2c595d20420137afb711fcf52365a95b502952 | judsondommer/DukeTip | /HangmanJudson.py | 3,276 | 4.125 | 4 | #Judson Dommer
from __future__ import print_function
import numpy
#This print the opening screen
print ('Welcome To Hangman!!')
print (' -----|')
print (' | O')
print (' | /-|-\\')
print (' | |')
print (' | /-\\')
print (' | /---\\')
print ('------')
#This line asks the player to trigger or end the game... |
2420786477543d7096d97e8f0d2895dacd9662cc | Sanjai-K/Python_Beginner_lvl_2 | /ipv4_to_ipv6.py | 673 | 3.921875 | 4 | #Pyhton code to convert given ipv4 address to ipvd address
import re
ipv4 = raw_input("enter the IP address :")
ipv6 = []
valid_ip = re.search('(([2][5][0-5]\.)|([2][0-4][0-9]\.)|([0-1]?[0-9]?[0-9]\.)){3}(([2][5][0-5])|([2][0-4][0-9])|([0-1]?[0-9]?[0-9]))$',ipv4)
if valid_ip:
ip_type = re.match('([\d]+).([\d]+).... |
f6dddf1f0f7a338df936f6e00ec07711a5bd9c74 | thatnepkid/itp_week_2 | /day_4/exercise.py | 3,258 | 4.5625 | 5 | #Testing Git
# ITP Week 1 Day 4 Exercise
#Write a basic calculator using the input function to complete the following tasks. Be sure to call your functions at the end, using the correct arguments.
# Easy:
# - A function that subtracts one integer from another
# - A function that multiplies three integers
# ... |
43d24f2afd816284a00e6ad93c6cee22e6eccf81 | seryogasx/VUZ | /maths/math/7sem/Петров_лаб1(eiler).py | 3,449 | 3.5 | 4 | from math import exp, fabs
from numpy import arange
import matplotlib.pyplot as plot
# размер шага
h1, h2 = 0.1, 0.01
# исходная функция (вариант 3)
def func(x, y):
return (y / x**2) + exp(x - 1 / x)
# результирующая функция
def funcOrigin(x):
return (0.367879 * exp(1))*exp(-1/x) + exp(x - (1/x))
# метод эйлера... |
fe27abad7c52adcf417aa5d1e01ff00e168993c1 | EldestHedge/MultiTool-APCSP | /MMultitool/Temp_Converter.py | 1,820 | 4.03125 | 4 | def TempConverter():
def TemperatureScript():
print ("[1] Know Celsius, Find Fahrenheit")
print ("[2] Know Celsius, Find Kelvin")
print ("[3] Know Fahrenheit, Find Celsius")
print ("[4] Know Fahrenheit, Find Kelvin")
print ("[5] Know Kelvin, Find Celsius")
print ("[6] Know Kelvin, Find Fahrenheit")
... |
6819269789d5982bed057e1e979a76dccbef9771 | Kbz2001/Final-Day- | /main.py | 3,087 | 4.625 | 5 | # Warm Up
#--------
# Use Turtle to draw any polygon on the screen.
# Refresher: What is a polygon?
# User enters the length of the sides and how many sides.
# Tip: Angle to turn by is 360/(number of sides)
# Ex. For a Triangle: 360/3 = 120
# Can be done with or without functions
# Try to use event handling! (Must use ... |
5522b96457ff9aab1daeff00d2546036d11ba948 | Tom-Sachs/covid-dashboard | /covid_dashboard/utils.py | 3,602 | 3.625 | 4 | import pandas as pd
import numpy as np
import datetime
### Color utils to create a custom color palette for plotting
def hex_to_RGB(hex):
''' "#FFFFFF" -> [255,255,255] '''
# Pass 16 to the integer function for change of base
return [int(hex[i:i+2], 16) for i in range(1,6,2)]
def RGB_to_hex(RGB):
''' [... |
29f8642c3cc74bb513fc50b7f841051872df997d | geekhub-python/strings-valiknet18 | /task4.py | 147 | 3.65625 | 4 | #!/usr/bin/env python3
print("Введите строку")
str = input()
str = str.split()
print("Результат:")
print(str[1] + str[0])
|
a20935db2deb52cd7ca07d7ac6186b42110528b1 | Wong-S/practice-1 | /march-practice/practice-test.py | 8,628 | 4.25 | 4 | # You are given two arrays of integers a and b of the same length, and an integer k. We will be iterating through array a from left to right, and simultaneously through array b from right to left, and looking at pairs (x, y), where x is from a and y is from b. Such a pair is called tiny if the concatenation xy is stric... |
9bc942a4085b5cab906b5655d1529a734959a96e | Wong-S/practice-1 | /array.py | 2,442 | 3.8125 | 4 | # Q1: Monotonic Array (896)
# An array A is monotone increasing if for all i <= j, A[i] <= A[j]. An array A is monotone decreasing if for all i <= j, A[i] >= A[j].
# Return true if and only if the given array A is monotonic.
# Test Cases:
# Input: [1,2,2,3]
# Output: true
# Example 2:
# Input: [6,5,4,4]
# Output:... |
b6619eedbb058b73b24e6eea8985edb12889b4cf | howls90/MDLA | /SKLearn/tutos/regressionLogistic.py | 919 | 3.59375 | 4 | from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
x,y = make_classification(n_samples=1000, n_features=4)
rlog = LogisticRegression()
# Dividiendo el dataset en entrenamiento y evaluacion
X_entrenamiento = X[:-200]
X_evaluacion = X[-200:]
y_entrenamiento = y[:-200]
... |
a2979d73752257c9a54a75d4e2b32f66409613d5 | rishavb123/DiffractionSimulation | /gaussian_quadrature.py | 3,980 | 3.859375 | 4 | """A file for choosing the points of the Gaussian Quadrature and calculating the weights"""
import numpy as np
from utils import one_hot
class GaussianQuadrature:
"""The gaussian quadrature class encapsulating all the methods"""
def __init__(self, N, method="closed form") -> None:
"""Creates an obje... |
a92584b3c8397bc7408e6b12f24c397a91e37300 | EHoggard/TryExcept1 | /Validation.py | 634 | 3.6875 | 4 | def account_number_validation(accountNumber):
if accountNumber:
try:
int(accountNumber)
if len(str(accountNumber)) == 10:
return True
else:
print("Invalid Account Type")
return False
... |
12404706673d1dfc33acabc52ba250789909496f | afrahaamer/PPLab | /VI Data Structures, Arrays, Vectors and Data Frames/3 Vectors/2 Basic Arithmetic operation/arithOperations.py | 1,094 | 4.3125 | 4 | # importing numpy
import numpy as np
# creating a 1-D list (Horizontal)
list1 = [5, 6, 9]
# creating a 1-D list (Horizontal)
list2 = [1, 2, 3]
# creating first vector
vector1 = np.array(list1)
# printing vector1
print("First Vector : " + str(vector1))
# creating secodn vector
vector2 = np.array(list2)
# printin... |
527835943216d348696b0ad6ed7f8ba521e5a56d | afrahaamer/PPLab | /III Regular Expressions/1 RegEx Functions/findall/Metacharachters/ends with.py | 241 | 4.21875 | 4 | # $ - Pattern ends with
# ^ - Pattern starts with
import re
t = "Hello, How are you World"
# Checks if string ends with World?
x = re.findall("World$",t)
print(x)
# Checks if string starts with Hello
x = re.findall("^Hello",t)
print(x)
|
b33dd638fe732ea4664acdbc175ca9666cfa93f5 | afrahaamer/PPLab | /I Python Basics/operators.py | 152 | 3.5 | 4 | x = 10 # 1010
y = 3 # 0011
print(x&y) # 0010 = 2
print(x|y) # 1011 = 11
print(x^y) # 1001 = 9
print(~y) # 1100
print(x>>1)# 0101 = 5
print(x<<1)# 20 |
ab74ae85033c835f0d0bc25991f2e961ea7988e7 | faiz-hasan11/MLH-Local-Hack-Day | /WeekLong/Translate/script.py | 359 | 3.796875 | 4 | import googletrans
from googletrans import Translator
translator = Translator()
print("AVAILABLE LANGUAGE FOR TRANSLATION FROM ENGLISH=>")
for i in googletrans.LANGUAGE:
print(i)
dest = input("ENTER THE LANGUAGE CODE YOU WANT QUOTE IN =>\n")
text = input("ENTER TEXT TO TRANSLATE\n")
print(translator.trans... |
dc6def38e0120e15de7b2636654bc447adab2532 | brendonthiede/hackerrank-python-challenge | /strings/05_designer_door_mat.py | 551 | 3.75 | 4 | import math
def get_row(row_number, width):
return ('.|.' * (row_number * 2 + 1)).center(width, '-')
def make_mat(height, width):
first_half = int(math.floor(height / 2))
mat = []
for i in range(0, first_half):
mat.append(get_row(i, width))
mat.append('WELCOME'.center(width, '-'))
for... |
748f220560f1574766dfc8408483f191c729b511 | musasaleem/unit_three | /d4_unit_three_warmups.py | 208 | 3.71875 | 4 | def area_of_rectangle(length, width):
"""
finding area of rectangle by multiplying length by width
:param length:
:param width:
:return:
"""
area = length * width
return area
|
1376ad30a48637d1ae0d9ff19fc9844618a7d671 | streiman/digitaltag2020-counter | /digitaltag20-count.py | 1,899 | 3.609375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from datetime import datetime
print("Digitaltag20-count: Wie viele Stunden Programm hatte der Digitaltag 2020?\n")
print("Lese die Website ein.")
# Die Website https://www.digitaltag.eu wurde im Browser geöffnet und das Aktionsprogramm angezeigt.
# Es wurden "Alle Verans... |
07bdd2976b0e3ac438c7e823dd99b427b003d224 | GanKnight/computing-work | /micropython/spot the error 4.py | 620 | 3.75 | 4 | from Microbit Import**
print("Roll the 12 sided die")
while True:
if button_b.was_pressed or button_b.was_pressed:
display.scroll(random.randint(1,12)
# qn 2
from microbit* import
while count< 3:
display.show(Image.RABBIT)
displa.show(Image.Sword)
if button_b was pressed():
display.... |
37d907faf4b6bb0ba7682d071be3d3c400f415f8 | ashmoreinc/Soundboard | /widgets.py | 1,584 | 3.65625 | 4 | import tkinter as tk
import threading
class GetInput:
"""Creates a new window to get the input from a question answer is saved to Data attribute"""
def __init__ (self, parent, title=None, question=None, font=None):
top = self.top = tk.Toplevel(parent)
if title:
top.title(s... |
998497d8b31a225b48bda7ce023d8994adf917ee | JoshuaRiddell/traffic_lights_workshop | /examples/04_light_change.py | 1,189 | 3.53125 | 4 | # import the GPIO module
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
def red_light_on():
# turn the light on
GPIO.output(light_red, True)
def red_light_off():
# turn the light off
GPIO.output(light_red, False)
def yellow_light_on():
# turn the light on
G... |
869264353a14ec47d71c5d8a0cb59e9919a91547 | Ashima0301/PathaPadha-DS-P-1 | /Assignment-1/swapping without using third variable.py | 287 | 3.953125 | 4 | x = int(input("Enter the 1st number : "))
y = int(input("Enter the 2nd number : "))
print ("Before swapping: ")
print("Value of x : ", x, " and y : ", y)
# Swap code
x = x + y
y = x - y
x = x - y
print ("After swapping: ")
print("Value of x : ", x, " and y : ", y)
|
1539e6b7d120f0975bf8a9236f1f7cf51c6424a1 | Ashima0301/PathaPadha-DS-P-1 | /Assignment-1/swapping using third variable.py | 267 | 3.953125 | 4 | x = int(input("Enter the 1st number : "))
y = int(input("Enter the 2nd number : "))
print ("Before swapping: ")
print("Value of x : ", x, " and y : ", y)
temp = x
x = y
y = temp
print ("After swapping: ")
print("Value of x : ", x, " and y : ", y)
|
48b68c9c273f0a5aed5dcbd8b0dc511cc895e0b4 | Dyndyn/python | /lab9.4.py | 1,594 | 3.84375 | 4 | #!/usr/bin/python
#-*- coding: utf-8 -*-
arabic = int(input("Enter arabic number: "))
roman = str(input("Enter roman number: "))
def toRomanNumber(arabicNumber):
if arabicNumber > 3999:
raise Exception('Number cannot be greater than 3999')
digitsSymbols = ["", "I", "II", "III", "IV", "V", "VI", "VII"... |
4455c5cd3fbda1bb34bbde3451c3897e14899c31 | Dyndyn/python | /lab3.1.py | 154 | 4 | 4 | #!/usr/bin/python
#-*- coding: utf-8 -*-
a = input("What's first number? ")
b = input("What's second number? ")
print('{} + {} = {}'.format(a, b, a+b))
|
e3036eec8a071b264c3dcd6191122fa90fb8f26b | Dyndyn/python | /lab7.6.py | 221 | 3.78125 | 4 | #!/usr/bin/python
#-*- coding: utf-8 -*-
s = input("enter the string? ")
def print_in_frame(s):
frame = "*" * (len(s) + 4)
result = frame + "\n* {} *\n" + frame
print(result.format(s))
print_in_frame(s)
|
4e12d55300c00ad5bef07832a1295e229f60e8d4 | Dyndyn/python | /12.2/lab12.2.py | 1,561 | 3.578125 | 4 | #!/usr/bin/python
#-*- coding: utf-8 -*-
import math
class Star:
def __init__(self, name, x=0, y=0):
self.name = name
self.x = x
self.y = y
def __str__(self) -> str:
return "%s %.2f %.2f" % (self.name ,self.x, self.y)
def _length(self) -> float:
return math.sqrt(s... |
786c1594b59ea950844d1e0017cb6259b37f48d5 | Dyndyn/python | /lab5.3.py | 575 | 3.953125 | 4 | #!/usr/bin/python
#-*- coding: utf-8 -*-
import random
print ("1 - камінь, 2 - ножиці, 3 - папір, 0 - завершити")
arr=["камінь","ножиці", "папір"]
while True:
choice = input("Ваш вибір? ")
if choice==0: break
rand = random.randint(1, 3)
print("Комп'ютер - " + arr[rand-1] + ", Ви - " + arr[choice - 1]... |
61127045c5e583d786236ff280f99ca496ffccb8 | SciPyCourse2020/notes | /02_Python_basics_2/more_basics.py | 152 | 4.125 | 4 | for i in range(10):
if i == 7:
continue
print(i)
if i % 2 == 0:
print('is even')
else:
print('is odd')
print(c)
|
40c9fbb9d09d335328e80190f8cf58ae208304c3 | nagy-serban-tunde/onlinebank | /datacollector/DataCleaning.py | 2,367 | 3.75 | 4 | import re # replaces given character by another character
"""This page is responsible for cleaning the data downloaded by WebScrepper"""
class DataCleaning(object):
def __init__(self,List_elements):
self.List_elements = List_elements
def redundant_list_removal(self,list):
temp_list = []
... |
fd730db31f1dca649242915e2848ae130e7625ec | adarshkushwah/Python-PROJ | /basic_pass_check.py | 209 | 3.78125 | 4 | user = input('Please enter your username : ')
passwd = input('Now please enter your password : ')
mask_pass_len = len(passwd) * '*'
print('Hi '+user+', your password is '+mask_pass_len+' characters long...') |
1df2907b981c94750a9ed6dfdedf344d71bd7b11 | sgerhardt/TakeStock | /src/QuarterlyReport.py | 7,296 | 3.5 | 4 | __author__ = 'Sean Gerhardt'
import datetime
import re
import bs4
import requests
def main():
pass
timeout = 3
def get_share_price(ticker=''):
"""
This function gets the share price for the given ticker symbol. It performs a request to the
nasdaq url and parses the response to find the share pri... |
aef4b1c7be43bd3d471b887a3f2b9d07a06e72dc | coreyclip/Python_challenge | /PyBoss/main.py | 4,310 | 4 | 4 | """
In this challenge, you get to be the boss.
You oversee hundreds of employees across the country developing Tuna 2.0,
a world-changing snack food based on canned tuna fish.
Alas, being the boss isn't all fun, games, and self-adulation.
The company recently decided to purchase a new HR system, and unfortunately f... |
3c7b761cd7c047f9dc89219b438e58d5f5fe72f4 | petr7555/SoloLearn-coding-challenges | /21_Reciprocal_letters.py | 424 | 3.984375 | 4 | def reciprocal(string):
reversed = []
for c in string:
if c.isalpha():
if c.upper() == c:
order = ord(c) - ord("A")
reversed.append(chr(ord("Z") - order))
else:
order = ord(c) - ord("a")
reversed.append(chr(ord("z") ... |
6153f7e1ab371141566961d67cf4e35b2af5977b | petr7555/SoloLearn-coding-challenges | /84_Strange_root.py | 231 | 3.984375 | 4 | def root(n):
square = list(str((n**2)))
square_root = list(str(round((n**(1/2)),3)))
for num in square:
if num in square_root:
return True
return False
print(root(11))
print(root(24))
|
8c36ec32ae88a6d607f57557b1e58e6d7b90ac29 | petr7555/SoloLearn-coding-challenges | /43_Garland_words.py | 404 | 3.953125 | 4 | def garland(word):
g = 0
for i in range(len(word)):
if word[:i] == word [-i:]:
g = i
return word[:g], g
words = "abracadabra", "tomato", "python", "a", "aa", "ab", "aaa", "aba", "aab"
for word in words:
gar = garland(word)
print("{} is {}a garland word {}".format(word, "not " *... |
e5fbb4b3abec0cd487d3b9001ba8d2726c72765d | petr7555/SoloLearn-coding-challenges | /79_Voodoo_primes.py | 390 | 3.921875 | 4 | def isPrime(n):
if n==2 or n==3:
return True
if n%2==0 or n<2:
return False
for i in range(3,int(n**0.5)+1,2):
if n%i==0:
return False
return True
def voodoo(n):
if not isPrime(n):
return False
if str(n) in str(1/n):
return True, str(1/n)
... |
f70e4623aa3c275e0b2e8aca39e5f2b8a195563b | petr7555/SoloLearn-coding-challenges | /68_The_Crypto-Cube.py | 2,149 | 3.90625 | 4 | import math, random
text = "Programming in Python is awesome!"
while len(text)%8 != 0:
text = text + " "
num_cubes = len(text)//8
cubes = [[text[j+i*8] for j in range(8)] for i in range(num_cubes)]
print("Number of cubes: {}".format(num_cubes))
for i in range(num_cubes):
print("Cube n. {}: {}".format(i+1, cube... |
f4fa2c9ca0b630f90a6d867d420b59b2ae6929ac | petr7555/SoloLearn-coding-challenges | /00_isPrime.py | 203 | 4 | 4 | def isPrime(n):
if n==2 or n==3:
return True
if n%2==0 or n<2:
return False
for i in range(3,int(n**0.5)+1,2):
if n%i==0:
return False
return True
|
0081f684df2da27757c1e3b56f73c0247f094085 | cangurdev/Hangman | /hangman.py | 1,915 | 3.859375 | 4 | from random import choice
from time import sleep
man = ['''
+---+
| |
|
|
|
|
=========''', '''
+---+
| |
O |
|
|
|
=========''', '''
+---+
| |
O |
| |
|
|
=========''', '''
+---+
| |
O |
/| |
|
|
=========''', ... |
36fded3321097f29e11247712dea2c3949178530 | chililily/reed-csci385-graphics | /hw04-render-it-flat/geom2d.py | 7,113 | 3.703125 | 4 | #
# geom2d.py
#
# Author: Jim Fix
# CSCI 385, Reed College, Fall 2017
#
# This defines three names:
#
# point2d: a class of locations in 2-space
# vector2d: a class of offsets between points within 2-space
# segment2d: a class of a line segment sitting in 2-space
# ORIGIN2D: a point at the origin
#
# The ... |
3284e8297a621441d01bd50af7b4b9ffc1aebf4b | a9ee8aa9ee8a/yzu_python_20210428 | /day03/雞兔同籠.py | 463 | 3.578125 | 4 | def getChk(y):
if 2 * (83 - y)+ 4 *y ==240:
return y
else:
return getChk(y+1)
Chk = getChk(0)
Rabbit = 83-Chk
print(Chk, Rabbit)
# 老師解法
def getChkAndRabbit(sum,feet):
'''
:param sum: 83
:param feet: 240
:return: chk,rabbit
'''
if feet/4 <= sum <= feet/2:
rabbit =... |
f7816303271a505c78694fb8a2e1cda97d5b4ffa | a9ee8aa9ee8a/yzu_python_20210428 | /day04/字串分析1.py | 993 | 4.09375 | 4 | # 字串分析
str = "she sell sea shell on the sea shore"
print(str)
# 去除左右空白
str = str.strip()
str = str.lstrip() #去除左邊空白
str = str.rstrip() #去除右邊空白
print(str)
print('字串長度:', len(str))
print('有幾個s:', str.count('s'))
print("on這個字的位置", str.find('on'))
print("off這個字的位置", str.find('off'))
print('有沒有sea這個字:', '有' if str.find('s... |
fe06906c6b2f30dbb0271d6064d13c5d76798f73 | SUNIL12273/SunilD | /Devops/Python/demo2.py | 138 | 3.90625 | 4 | a=10
b=20
if a < b:
print("a is the smallest number")
else:
print("b is the smallest number")
print("program is finished")
|
dbf266201aabcc295b27168cafe0fbc872ad70a9 | SethHarrison1/MAT4310 | /MAT4310/LE-Modified-Brent/main.py | 2,733 | 3.59375 | 4 | import math
def f(x):
return (x-1)*(x-2)*(x-3)*(x-4)*(x-5)*(x-6)*(x-7.0000000001) #function for which root is desired
def LE_brent(a,b,relerr, abserr):
# Calculates the root of an externally provided function f(x)
# in the interval [a,b]
# with specified relative and absolute error tolerances.
max_func_evals = ... |
d3dd0fcc49c34ee6949690b5763f1d75cc2d895a | SethHarrison1/MAT4310 | /MAT4310/Bisection-Secant-Newton/main.py | 1,593 | 3.625 | 4 | import math as m
def bisection(a, b, max_its, tol, f):
fa = f(a)
fb = f(b)
if fa*fb > 0:
return
d = b - a
for its in range(1, max_its+1):
d = d/2
m = a+d
fm = f(m)
print(m)
if fm == 0 or abs(d) < tol:
print("convergence")
print(its)
return
if fa * fm > 0:
a... |
a26016a7b9de1235577180ac3544036566ffda5a | SethHarrison1/MAT4310 | /MAT4310/Issue-with-Clocks-during-Gulf-War/main.py | 269 | 3.6875 | 4 | def step_calc():
dt = 0.0
for i in range(1,10001):
dt = dt + 1.0/10.0
dx = 0.0 + i/10.0
print(dt)
print(dt)
print(dx)
step_calc()
def step_calcProblem():
dt = 0.0
for i in range(1, 101):
dt = dt + 1.0/10.0
print(dt)
#step_calcProblem() |
b58bb641ba5f68443d02a66ee3ef9b9beb1d8492 | Barsha-Sunuwar/Day4 | /day4.py | 390 | 3.875 | 4 | biology=int(input("marks of biology"))
chemistry=int(input("marks of chemistry"))
physics=int(input("marks of physics"))
nepali=int(input("marks of nepali"))
math=int(input("marks of math"))
list=[biology,chemistry,physics,nepali,math]
print(list)
sum=(biology+chemistry+physics+nepali+math)
print(sum)
user=input("ente... |
312c35e0ee73ce3aa7b0836cf8f594d030ac1054 | MostDeadDeveloper/Python_Tutorial_Exercises | /exercise3.py | 357 | 4.21875 | 4 | # Challenge - Functions Exercise
# Create a function named tripleprint that takes a string as a parameter
# and prints that string 3 times in a row.
# So if I passed in the string "hello",
# it would print "hellohellohello"
def tripleprint(val):
print(val*3)
return val*3
#tripleprint("hello")
# ^ - r... |
e5627ec97a0514d059e8481a74f012e26b896626 | WangJie1994/Numpy_demo | /pandas选择数据.py | 481 | 3.671875 | 4 | import pandas as pd
import numpy as np
dates = pd.date_range('20130101', periods=6)
df = pd.DataFrame(np.arange(24).reshape((6,4)), index=dates, columns=['A','B','C','D'])
print(df)
print(df['A'], df.A)
print(df[0:3], df['20130102':'20130104'])
# select by label:loc
print(df.loc['20130102'])
print(df.loc[:,['A', 'B... |
eebf582f1c2c5f082206354e961b2c996355eda6 | pranavbharadwaj007/100-Days-of-Python | /Day 16 --- Coffee Machine (O.O.P.)/start/main.py | 350 | 3.78125 | 4 | from turtle import Turtle, Screen
timmy = Turtle()
screen = Screen()
timmy.color("red")
def fractal(n, l):
if n == 0:
return
timmy.forward(l)
timmy.left(45)
fractal(n - 1, l / 2)
timmy.right(90)
fractal(n - 1, l / 2)
timmy.left(45)
timmy.back(l)
timmy.back(200)
fractal(10... |
94f6bdf90b4574084f2e5eb8669c567e0ba251a2 | pranavbharadwaj007/100-Days-of-Python | /Day 25 + 26 --- US States Game/us-states-game-start/main.py | 927 | 3.53125 | 4 | import pandas
import turtle
screen = turtle.Screen()
screen.title("US States Game")
screen.bgpic("blank_states_img.gif")
data = pandas.read_csv("50_states.csv")
state_names = data.state.to_list()
guessed_states = []
while len(guessed_states) < len(state_names):
guess = turtle.textinput(title=f"{len(guess... |
59a7d5208cf8cb8b6c57f172c0e257d3df7f5f80 | pranavbharadwaj007/100-Days-of-Python | /Day 20 + 21 + 24 --- Snake/snake.py | 1,496 | 3.71875 | 4 | from turtle import Turtle
MOVE_DIST = 20
UP = 90
DOWN = 270
LEFT = 180
RIGHT = 0
class Snake:
def __init__(self):
self.segments = []
self.head = None
self.create_snake()
def reset(self):
for segment in self.segments:
segment.goto... |
0340d501babc4af06989c1455a8026e0b76c7cc8 | bchhun/Codes-Kata | /prime_factors.py | 1,509 | 4.21875 | 4 | #coding: utf-8
"""
Compute the prime factors of a given natural number.
Bernard says: What is a prime factor ? http://en.wikipedia.org/wiki/Prime_factor
Test Cases ([...] denotes a list)
primes(1) -> []
primes(2) -> [2]
primes(3) -> [3]
primes(4) -> [2,2]
primes(5) -> [5]
primes(6) -> [2,3]
primes(7) -> [7]
primes(8... |
3c776c4e4096b1e47bce46231adf85fb8fa59a24 | cyrne2/pong | /pong.py | 5,113 | 4.21875 | 4 | #Rice University Introduction to Interactive Programming (python)
#Implementation of classic arcade game Pong
#Produced in codeskulptor and works better in codeskultptor
#Imported simplieguitk to implement GUI components used in codeskulptor
import simpleguitk as simplegui
import random
# initialize globals - pos and... |
0588fe6779f07d81beba7e6cc6f4b615bc2694d6 | jet-c-21/SE-Practice | /Learning Python Design Patterns - 2e/Simple Factory/simple_factory.py | 666 | 3.828125 | 4 | """
author: Jet Chien
GitHub: https://github.com/jet-c-21
Create Date: 4/21/21
"""
# coding: utf-8
from abc import ABCMeta, abstractmethod
class Animal(metaclass=ABCMeta):
@abstractmethod
def do_say(self):
pass
class Dog(Animal):
def do_say(self):
print("Bhow Bhow!!")
class Cat(Animal)... |
feb9fc431f68a890b5da644445d950942333493e | tchu10/SDET | /SDET.py | 1,521 | 4.0625 | 4 | import unittest
class sentence_parse():
def parse(self,s):
#The purpose of this method is to parse a sentence and return both the longest word and the length of the word in characters
#The function return a tuple including the length of the word and the word itself (length,word)
#Assumptions... |
a2ca67c84f1145cea40c1829fdf1a42091929dc1 | alex-stybaev/leetcode | /lib/nodes.py | 1,405 | 3.734375 | 4 | import math
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def setNext(self, x):
self.next = x
class Solution(object):
def oddEvenList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
last_odd = head
... |
862ef457f1fbaa14cf5d9f6feea33c5a117954c4 | alex-stybaev/leetcode | /lib/first_unique_character.py | 701 | 3.734375 | 4 | class Solution(object):
def firstUniqChar(self, s):
"""
:type s: str
:rtype: int
"""
unique_chars = list()
deleted = set()
for char in s:
if char not in unique_chars and char not in deleted:
unique_chars.append(char)
el... |
15aa82a5637fb65f445cf0098de9e20de32906cc | pnordin/trimeol | /trimeol.py | 3,104 | 3.515625 | 4 | #!/usr/bin/python3
"""Remove all end of line whitespace and tabs in a given text file(s).
Usage:
trimeol.py [input_files]
If no input_files are supplied, the program reads from stdin.
"""
import os
import stat
import sys
import time
import binarycheck
def process_file(fname):
"""Remove all end of line wh... |
c3272a68e7f7705810f956609b24d6a6477d2faa | kimmvsrnglim/DigitalCrafts | /week2/print_triangle.py | 222 | 4.1875 | 4 | def triangle(height):
for x in range(0, height, 2):
space = " " * ((height - x)/2)
print space + "*" * (x + 1)
user_input = int(raw_input("What's the height of your triangle?"))
triangle (user_input)
|
ee0d216b772925a8a2713e8ed7be384cd2e4f5fd | xandhiller/learningPython | /stringTidbits.py | 454 | 4.40625 | 4 | print('Enter a string: ')
n = input()
print("\nLength of string is: " + str(len(n)))
print()
# Starting i at 1 because i determines the non-inclusive upper limit of string
# truncation.
for i in range(1, len(n)+1):
print("string[0:"+str(i)+"]: \t" + n[0:i])
print()
# Conclusions:
# The operator 'string[0:8]' ... |
d17e35ba2812c6b5803c09a83ee55467b25fef02 | xandhiller/learningPython | /Old/testinggui.py | 379 | 4.09375 | 4 | from tkinter import *
def main():
root = Tk()
root.minsize(width=300, height=100)
root.title("Hello GUI!")
button = Button(root, text = "Is this thing on?", height = 10, width = 30)
button.pack()
root.mainloop()
# Have to have this mainloop at the bottom in order for everything ... |
c0dcc11bc6eb5c83df214dff56c99984d1f089f2 | xandhiller/learningPython | /tracebackLogging.py | 304 | 3.953125 | 4 | #! python3
# Purpose: To demonstrate traceback logging.
import traceback
try:
raise Exception("This is the error message.")
except:
errorFile = open('errorInfo.txt', 'w')
errorFile.write(traceback.format_exc())
errorFile.close()
print('The traceback was written to errorInfo.txt')
|
b7f61be228c2dc47993337d657088183a203e8a2 | xandhiller/learningPython | /convDatesAmerToEur.py | 1,304 | 3.609375 | 4 | #! python3
# Purpose: Converts the dates of .txt files in the directory from an
# american format to a european format.
import os, re, sys, createDateFiles, shutil
# TODO: Make a regex to identify dates
# TODO: Use regex to work through the os.listdir(), selecting those that fit
# and then rename the file with shut... |
df43c2b9948e7f35d2c30e37fce19dee6f511257 | xandhiller/learningPython | /firstProg.py | 178 | 3.984375 | 4 | print ('Hello there! What\'s your name?')
name = input()
print ('It is nice to meet you ' + name)
print ('Did you know that you name is ' + str(len(name)) + ' characters long')
|
736c8634fb5f48fb26d99e2e1447d6df72b72550 | KoderKaran/SnakeSim | /main.py | 4,208 | 3.625 | 4 | import pygame as pg
import random as ra
import Specs as sp
import Snake as sn
import time as tm
import Food as fd
pg.init()
# ^^^ Initializes pygame
display = pg.display.set_mode((sp.WIDTH, sp.HEIGHT), pg.RESIZABLE | pg.DOUBLEBUF)
pg.display.set_caption('Snake Population Simulator')
# ^^^ Display initialization
cloc... |
cf330847cd2da4fc633e4dafeca2167582a40cdc | anpere/jigsaw | /main.py | 903 | 3.515625 | 4 | import argparse
import math
from PIL import Image, ImageDraw
def add(left, right):
"""
Returns an image that is the sum of left and right image
left: type TODO
right: type TODO
"""
return Image.blend(left, right)
if __name__ == '__main__':
#setup
parser.add_argument('--name', type=st... |
9b9533324115aa3884a37633270ca2e430b35734 | 0ndreu/Grok | /ArrayLen.py | 168 | 3.515625 | 4 | def get_arr_len(arr):
if len(arr) == 0:
return 0
else:
arr.pop(0)
return 1 + get_arr_len(arr)
a = [1]
f = int(get_arr_len(a))
print(f) |
cfd6202d98f4692ede70f3f1bb0950e4f5e56faa | luqmanrumaiz/University-Grading-System | /Part_I_Code.py | 2,718 | 3.640625 | 4 | # I declare that my work contains no examples of misconduct, such as plagiarism, or collusion.
# Any code taken from other sources is referenced within my code solution.
# Date: 2019/11/29
#initializing variables with boolean values False
pass_entered=False
defer_entered=False
fail_entered=False
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.