blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
a714cc89f57421868861bc42d0ae410b2091f387
hannypher/week-3-challenge-1
/lists_sort.py
524
3.8125
4
h=[1, 2, 3, 5.5, 8.2, 'x'] def list_sort(h): character = [] odds = [] evens = [] mydict = dict() for n in h: if isinstance(n, int): if n % 2 == 0: evens.append(n) else: odds.append(n) elif isinstance(n, str): ...
7b8d8928d6079153f70f5edb7867b3984195c65b
ramilabd/python-project-lvl1
/brain_games/cli.py
339
3.59375
4
# -*- coding:utf-8 -*- """Welcome user.""" import prompt def welcome_user(): """ Welcome to the game. Parameters are missing. Returns: None """ print('Welcome to the Brain Games!') name_user = prompt.string('May I have your name? ') print('Hello, {0}!'.format(name_user)) ...
42215e952d6efac0d0bd17af7f07f01ae770a737
ArseniySmirnov/Computer-Linguistics
/Словарь_1.py
1,057
3.53125
4
n = 0 a = ["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','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'] while (n == 0): word1 = str(input("Введите слово на русском языке: ")) s = [] s =...
81f5221c1c400989590349b8ea4e28c0dfe6894a
ictmaster/smart-house
/database.py
1,546
3.5
4
import sqlite3 import sys import json db_name = 'sqlite_database.db' def create_database(): con = sqlite3.connect(db_name) c = con.cursor() c.execute("""CREATE TABLE IF NOT EXISTS data ( id INTEGER PRIMARY KEY AUTOINCREMENT, value TEXT NOT NULL, ...
38436aa69fe97e73d86d8dad5b4b1b0753595041
aksh3004/Yelp-data-set-analysis
/yelping.py
17,787
3.515625
4
import json import operator import plotGraphs import numpy as np import pandas as pd class Yelping(object): def __init__(self, file): self.file = file def extractBusinessNames(self): """ From the given JSON file, extract the names of the businesses :return: the dictionary of b...
064ee2d208d72ac99652952ca30ba0dcbe196b11
Esekyi/printing-diamonds
/simpleMaths.py
475
4.03125
4
FirstNumber = int(input("What is the first number? > ")) SecondNumber = input("What is the second number? > ") print(FirstNumber, "+", SecondNumber, "= {}".format(int(FirstNumber) + int(SecondNumber))) print(FirstNumber, "*", SecondNumber, "= {}".format(int(FirstNumber) * int(SecondNumber))) print(FirstNumber, "-", S...
ed34e61e37564de442ead1690ecf9fe412e4d075
DJones0101/practice
/p/t5.py
978
4.28125
4
''' If you're given an array of numbers, find out the length of the longest consecutive subsequence in that array. For example, if the input is [2,1,6,9,4, 3], then your algorithm should return 4 because the longest subsequence in that array is [1,2,3,4]. ''' def longest_subseq(arr): # T: O(n ^ 2), S: O(n) hash...
73a1a22ae4731e0e83eb424b59a6b4c3f7be141c
irahkrishnan/python-programing
/begginer level/hello world .py
141
3.859375
4
num = input("Enter the N value\n") if(isinstance(num, int)): for i in range(num): print("Hell0\n") else: print("Invalid Input")
97752c167d51d9ada829263279feb61e97a9f774
irahkrishnan/python-programing
/begginer level/power of a num.py
171
4.15625
4
num = input("Enter the number ") power = input("Enter the power value") if(isinstance((num or power),(int,float))): print(pow(num,power)) else: print("Invalid Input")
bbd19f97e874efb59eb6b5d9f2cb9f95f8fee29b
smith-sanchez/t10_viilavicencio.carrion
/app03.py
897
3.765625
4
import libreria # Aplicacion para pedir el nombre de un dia def pedirDia(): # 1. Pedir nombre del dia # 2. Guardar los datos en el archivo info.txt dia = libreria.pedir_dia("Ingrese dia:") contenido=dia +"\n" libreria.guardar_datos("info.txt", contenido, "a") print("Se ingreso el nombre ...
f3216e91c4313596c5f63aa54ba52582c11abb16
luhanso/ME492
/EX1_P6.py
449
4.125
4
# Lucas Hanson - Exam 1 - Problem 6 Course = [] Grade = [] N = int(input("Enter in the number of courses taken last semester: ")) for i in range(N): Course.append(input("Enter course name: ")) Grade.append(int(input("Enter corresponding course grade: "))) print("REPORT CARD:") for j in range(N): print(C...
fac3342ed669fb78ba2b134e548b17a7ed3f8ccd
luhanso/ME492
/EX1_P5.py
209
3.671875
4
# Lucas Hanson - Exam 1 - Problem 5 CoefList = [5,4,3,2,1] x = 2 N = len(CoefList) SortList = sorted(CoefList) sum = 0 for i in range(N): poly = SortList[i]*x**i sum = sum + poly print('sum = '+ str(sum))
1cd35c8277e811b0379dfd51b688221cdf37f70e
Shillerm/pythontutor
/calculations/task_01.py
133
3.6875
4
# Дано натуральное число. Выведите его последнюю цифру. x = int(input()) print(x % 10)
1ed9ee20a01b6d661925b2604ee24fa4483cf516
Shillerm/pythontutor
/calculations/task_04.py
260
4.0625
4
# Дано положительное действительное число X. Выведите его первую цифру после десятичной точки. from math import floor x = float(input()) y = 10 * (x - int(x)) f = floor(y) print(f)
dbd8baa5ffb30b3aa4ac41df935cb3679e8666ef
Shillerm/pythontutor
/loop_while/task_08.py
388
4.15625
4
# Последовательность состоит из натуральных чисел и завершается числом 0. Определите значение наибольшего элемента # последовательности. max = -1 element = int(input()) while element != 0: if element > max: max = element element = int(input()) print(max)
7d1bc34e83771553f0923545586343ea69b91977
Shillerm/pythontutor
/calculations/task_13.py
530
3.765625
4
# С начала суток прошло H часов, M минут, S секунд (0 ≤ H < 12, 0 ≤ M < 60, 0 ≤ S < 60). По данным числам H, M, # S определите угол (в градусах), на который повернулаcь часовая стрелка с начала суток и выведите его в виде # действительного числа. H = int(input()) M = int(input()) S = int(input()) print((360 / 12 * H)...
f3f8d3bcc2ac850843fed14527ba667fcfd9b3b7
Shillerm/pythontutor
/loop_for/task_08.py
448
3.96875
4
# По данному натуральном n вычислите сумму 1!+2!+3!+...+n!. В решении этой задачи можно использовать только один # цикл. Пользоваться математической библиотекой math в этой задаче запрещено. factorial = 1 n = int(input()) sum = 0 for i in range(1, n + 1): factorial *= i sum += factorial print(sum)
1744eca8aace0e727b4757ec6ac208aa1a808c9c
sachinlodhi/Flask_Word_Guess
/test.py
118
3.953125
4
string = "Hello there what are you doing" str1 = "Hello there what are you diing" if string == str1: print('true')
731749c4be1f3892b9a7bb59a6aeec5ae0307aa4
eztwokey/laba5
/i2.py
505
3.9375
4
# !/usr/bin/env python3 # -*- coding: utf-8 -*- if __name__ == '__main__': # Даны два слова. # Определить, сколько начальных букв первого слова совпадает сначальными буквами второго слова. def fun(a, b): res = 0 for x, y in zip(a, b): if x != y: break ...
83680a2ff5fef16abb5723f79153ed3fe960c435
ulat/udacity_intro_to_machine_learning
/svm/svm_author_id.py
1,779
3.53125
4
#!/usr/bin/python """ This is the code to accompany the Lesson 2 (SVM) mini-project. Use a SVM to identify emails from the Enron corpus by their authors: Sara has label 0 Chris has label 1 """ import sys from sklearn.metrics import precision_recall_fscore_support, accuracy_score sys.path.append("../t...
268545cb79e3c9947aa55eadd756b302e1ad572f
chakrabortyanshu/Tutorials
/dev-lang/python/freecodecamp.org/IfStatementExample.py
218
4.25
4
is_male = True is_Tall = True # is_male = False if is_male: print("It is a male") else: print("It is not a male") if is_male or is_Tall: # and print("Y") elif not is_Tall: print("You are not tall")
0a960f65be64f74777adeb4bed251c56a0acf052
12Siva/AdventOfCode2018
/day2/day2.py
1,457
3.59375
4
from collections import Counter, defaultdict import difflib # Part 1 def part1(): """ :return: """ file_path = "input.txt" file = open(file_path, "r") ids = [line.strip("\n") for line in file] two_char_count = 0 three_char_count = 0 for id in ids: char_count = Counter(...
7e1fb17d3a899902133c84f0c3254cdefa27314b
Heracles93/gameUnix
/scripts/tictactoe.py
3,990
4
4
# -*- coding: utf-8 -*- """ Created on Wed Jan 30 09:52:47 2018 @author: Heracles93 """ def displayBoard(board): """ Display the board filled with the marker in place. <param board> : list of markers """ print("\n"*100) print("\t"+board[7]+"|"+board[8]+"|"+board[9]) print("\t-----") ...
5f72dd9f2401d7dab145fa069f93524fa28dddcc
tangFengKang/algorithm013
/Week_01/189.旋转数组.py
877
3.578125
4
''' @Description: @Version: 1.0 @Autor: TangFengKang @Date: 2020-07-03 12:32:10 @LastEditors: TangFengKang @LastEditTime: 2020-08-02 19:58:16 ''' # # @lc app=leetcode.cn id=189 lang=python3 # # [189] 旋转数组 # # @lc code=start class Solution: def rotate(self, nums: List[int], k: int) -> None: """ Do ...
7f90f4dee30dee1f29d9028512b973b76d11914c
UVvirus/factorial
/factorial.py
143
3.984375
4
n=int(input("enter a nummber:")) result=1 for i in range(n,0,-1): result=result*i print(result) """" n=5 5x4x3x2x1 """
d234d8b9a4030dc04592c70b3d2f1251c4ce3f99
Jacobsmith96/twitterScraper
/streaming/analyzeStream.py
2,875
3.59375
4
import json import pandas as pd import matplotlib.pyplot as plt #Open the files for sentiment analysis positives = open('positive.txt', 'r').read().split('\n') negatives = open('negative.txt', 'r').read().split('\n') #Define a function to count the number of words in each tweet def countWords(x): if x is not None...
be5a30046ea845cef2ecd6b2416cda7f9034e377
lynnwebber/aatest
/python/strings/stripjoin.py
791
3.75
4
#!/usr/bin/python # import os, sy def check4value(xarray, num): try: pos = xarray.index(str(num)) print "found it --> do nothing" print xarray except ValueError: print "not in the list adding it" xarray.append(str(num)) print xarray def main(): print "st...
f208d4b27f1814f270a7cce9ec42fb904cc4a38c
Elvis-Dodti/sorting_algorithms
/selection_sort.py
626
4.15625
4
def selection_sort(unordered_list: list): """ Sorts unordered lists. :param unordered_list: Unsorted list to sort. :return: Sorted list. """ for index in range(len(unordered_list)): min_index = index for j in range(index + 1, len(unordered_list)): if unordered_list[m...
a54850e73291fe0723cddfa713fe8b5075093b8b
sanjuprk/NLP
/spam-ham-classifier/step-wise-code/preprocessing.py
419
3.953125
4
import nltk from nltk import word_tokenize, WordNetLemmtizer from nltk.corpus import stopwords stoplist = stopwords.words('english') lemmatizer = WordNetLemmtizer() # in preprocessing we convert the sentence to tokens, tokens/words to lower case and then lemmatize the tokens def preprocess(sentence): return [le...
5cc9841279252682155489880ea669c8366d5f09
ankitkhandeparkar/wireless-servo-control-using-joystick
/server.py
2,290
3.5
4
## Author : ANKIT V KHANDEPARKAR import RPi.GPIO as GPIO # first of all import the socket library import socket import serial #not needed kept for future upgrade ;) incase i connect arduino(foolish of me to do so but learned a big lesson) import time import struct GPIO.setmode(GPIO.BOARD) #set the rpi boa...
f7449a2c53f8a2d35e47365b4128ee3afb81f1e0
Akshusharma7/Basic-Program-sorting-algo
/closure.py
1,287
4.4375
4
''' In simplest terms, a Closure is a function returned by a higher order function, whose return value depends on the data associated with the higher order function. ''' def multiple_of(x): def multiple(y): return x*y return multiple c1 = multiple_of(5) # 'c1' is a closure c2 = multiple_of(6) # 'c2' ...
4997214e68530d5babd73e47ffafc69ccdc52499
hejingy1/CSC290-Pong
/PongG.py
6,117
3.578125
4
import pygame pygame.init() win = pygame.display.set_mode((1300,700)) pygame.display.set_caption("Pong") player1x = 0 player1y = 300 player2x = 1280 player2y = 300 ballx = 650 bally = 350 ballSpeedy = 3 ballSpeedx = 3 width = 20 height = 100 speedy = 5 vel = 5 screen_h = 500 screen_w = 700 # class of setups clas...
4b8ae8fe1b123cfd41e4a1b5278fdd57b8232ade
LadyMarina/TicTacToe
/tictactoe.py
4,203
3.921875
4
#Tic Tac Toe game in python board= [" " for x in range(10)] def insertLetter(letter, pos): board[pos] = letter def spaceIsFree(pos): return board[pos] == " " #is gonna give a true or false value def printBoard(board): print(" | | " + " " +" | | ") print(" " + board[1] + " | " + board[2...
490e7c11b58dd380cbc7c1e4ebc901361a681810
RamParameswaran/NBA-Search
/visualize.py
440
3.515625
4
import pandas as pd """ Function to print query dataset Parameters ---------- n/a Returns ------- n/a """ def read_query_csv(): df = pd.read_csv("data/query.csv") df.columns = ['Query', 'Class'] print("Ranking Questions:", (df.Class == 1.0).sum()) print("Stat Questions:", (df.Class == 2.0).sum()) de...
6a810ab224d4ee33e7172496e0ec36d520ab724a
skolozali/IntroductionToProgramming
/Lab4/Lab4Ex_1.py
1,503
3.828125
4
# marks=[10,20,30,40] # total = maximum = 0.0 # size = len(marks) # # # if size == 0 : # print("The list is empty") # else : # for mark in marks: # total = total + mark # if mark > maximum : maximum = mark # print("The average is", round(total / size, # 1)) # print("The highest mark is", maximum) # v...
91dbd0532eba52169416ece97a003e521ca0c0eb
ZhongluShi/MachineLearning
/kNN/test_sklearn_kNN.py
532
3.71875
4
# 使用sklearn库中的kNN from sklearn.neighbors import KNeighborsClassifier from sklearn.model_selection import train_test_split from sklearn import datasets digits = datasets.load_digits() X = digits.data y = digits.target X_train,X_test,y_train,y_test = train_test_split(X,y) knn_clf = KNeighborsClassifier(3...
85422647eecfeafdba02ff7ada242fa60c2266d3
PriyankaJanaghar/guvi_codekata
/helloguvi.py
122
3.6875
4
def main(): n=int(raw_input()) i=0 while(i<n): i=i+1 print("hello") main()
d1e0ca53776ccceab50c3cce5dec2540d5e75393
AndriuEdu/python3Basico
/basico/Ciclicas.py
989
4
4
for i in range(0, 5): # range(2, 5): print("Iteración N° " + str(i)) for x in range(3): print("Iteración N° " + str(x)) if x == 1: print("Se corto la interación N° " + str(x)) break for x in range(3): if x == 1: continue print("Iteración N° " + str(x)) for x in "Mit0C0de"...
b5b338e35bd8fcbffc5c8dbc2aa788101e580fa8
an5456/hogwarts-httprunner
/tests/testcase/__init__.py
678
3.5625
4
# import csv # # from collections import defaultdict # # with open(filename, 'r') as handle: # reader = csv.DictReader(handle, ['name', 'miles', 'country']) # data = defaultdict(list) # # for line in reader: # data[line['name']).append(int(line['miles'])) # # for runner, distances in data.items(...
8693dcecf61219561941cdbce205c6520fd9f949
alxxiat/MiTP
/game.py
3,408
3.609375
4
from player import * from level import * class Game: def __init__(self, levels, player): self.levels = levels self.player = player self.current_level = 0 def run(self): while self.player.is_alive(): self.print_info() command = input()...
50fa6fa2cee64ef15c53dc9ebccc632b4523fe6d
TriusMalarky/Warcaster
/Warcaster/bin/cmd/new_item.py
115
3.59375
4
def new_item(data): print(">>New Item") data["name"]=input(" { What would you like to call the item?\n| ")
41af347f562502f3cc20bd7a004605e421d67e97
luguzman/ia-course
/tema3/utils/experience_memory.py
2,174
3.765625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Oct 16 17:48:47 2018 @author: juangabriel """ from collections import namedtuple import random Experience = namedtuple("Experience", ['obs', 'action', 'reward', 'next_obs', 'done']) class ExperienceMemory(object): """ Un buffer que simula la ...
fb0710a95247fe274b3aa1137a66e1465ea25ef0
Kento75/python-unittest-learn
/calc/test/test_example2-2-3.py
543
3.671875
4
import unittest from calc.calc import Calculator class MyTestCase(unittest.TestCase): @classmethod def setUpClass(cls): cls.calc = Calculator() print("create calculator") def test_add(self): self.assertEqual(self.calc.add(5, 2), 7) def test_sub(self): self.assertEqual...
8a58c6bff810bd5290c12d1e5b8341d25c2a5a7a
apkochi/apk_python
/python Lessons and code.py
962
4.34375
4
#============ print "Hello World" ================= print "Hello " #============ Lesson: Variables ================= summation = 32 + 12 subtraction = 55 - 10 #============ Lesson: Variables ================= # We've defined the variable "meal" here to be breakfast! meal = "An english muffin" # Prin...
547015755c6e76f10671eac2372f293c3f8080a6
jchigne/trabajo
/tipo_boleta03.py
543
3.84375
4
#INPUT cliente=input("Ingrese el nombre del cliente:") sacos_arroz=int(input("Ingrese Nr de sacos de arroz:")) pu_arroz=float(input("Ingrese precio unitario:")) # PROCESSING total = (pu_arroz* sacos_arroz) #VERIFICADOR compra=(total>11) # OUTPUT print("#######################") print("# BOLETA DE VENTA") print("####...
f9d0bc7c35b71a2f281592be4b609fa7cc594030
jchigne/trabajo
/Calculadora01.py
400
3.765625
4
#calculadora nro1 #Esta calculadora realiza el calculo del area del triangulo #Declaracion de variables base,altura,area_triangulo=0.0,0.0,0.0 #Calculadora base1=20 altura1=50 area_triangulo=(base1*altura1)/2 verificador=(area_triangulo==500) #Mostrar datos print("base =", base1) print("altura 1=", altura1) print(" ...
891b09fd95277e5cc6508ea3c00b6770d08c1986
jchigne/trabajo
/conversores_ENTEROS.py
760
4.3125
4
#1.comvertir el entero 20 en entero x="20" a= int(x) print(a,type(a)) #2.convertir el entero 80 en entero x= 80 a= int(x) print(a,type(a)) #3.comvertir el real 19.5 en entero x=19.5 a= int(x) print(a,type(a)) #4.convertir el real 189.32 en entero x=189.32 a= int(x) print(a,type(a)) #5.convertir el real 200.3 en ent...
e969c58066bf72dcd8f42ca9b515bf227806eb68
jchigne/trabajo
/calculadora10.py
356
3.546875
4
#calculadora nro10 #Esta calculadora realiza el calculo de la densidad #Declaracion de datos masa,volumen,densidad=0.0,0.0,0.0 #calculadora masa1=5000 volumen1=1000 densidad=(masa1/volumen1) verificador=(densidad==5) #mostrar datos print("masa=",masa1) print("volumen=",volumen1) print("densidad del cuuerpo=",densida...
cdb17c7ea32618c0a2e6e6d3ef49551ed66e11a2
jchigne/trabajo
/tipo_boleta12.py
595
3.828125
4
#INPUT cliente=input("Ingrese el nombre del cliente:") empresa=input("Ingrese el nombre de la empresa:") periodicos=int(input("Ingrese Nr de periodicos:")) pu=float(input("Ingrese precio unitario:")) # PROCESSING total = (pu* periodicos) #VERIFICADOR compra=(total>25) # OUTPUT print("#######################") print(...
0d0ecbe2e54ed9d13f04045b66d55f127ab0d9be
SunnyM17/SudokuSolver
/SudokuBackTracking.py
2,780
4.09375
4
''' Python grid solver using backtracking algorithm. Author: Sunny Mangat Date: July 17, 2019 ''' # Board is a 2D list that stores our sudoku board # 0 represent empty spots. board = [ [8,7,0,0,0,0,0,2,0], [0,0,9,8,0,6,7,1,0], [0,0,1,2,0,9,0,0,5], [0,0,5,0,0,8,0,7,0], [4,0,0,5,0,1,0,...
9bc1d1351d507ba9320e9cdbc5668f4e8d34eaea
Grover-py/lession1
/task_03.py
121
3.671875
4
n = int(input('Введите число: ')) n2 = str(n)+str(n) n3 = str(n)+str(n)+str(n) p = n+int(n2)+int(n3) print(p)
23e64cf0b9db79a8c680301c4a49809d0da01010
TaylorHurt/assignment-python-chapter-2
/app.py
2,592
4.125
4
# Chapter 2.1 and 2.2 Variables import math students_count = 1000 rating = 4.99 is_published = True course_name = "Python Programming" print(students_count) print(rating, is_published, course_name) print("." * 10) # Chapter 2.3 Strings course = "Python Programming" print(len(course)) print(course[0]) print(course[-1])...
6c643018e7694462fdeacfa3d966a69c386b6c41
anhdangoh/PythonPractice
/ex9.py
223
3.5
4
days = "Mon Tue Wed Thu Fri Sat Sun" months ="Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug\nSep\nOct\nNov\nDec" print "Here are the days: ", days print "Here are the months: ", months print """ I can print whatever I want. """
8eb90d3c5516b2db6a084c6ded438777e015b59c
nwweis/HY-Data-Analysis-Summer-2021
/part04-e16_split_date/src/split_date.py
1,258
3.578125
4
#!/usr/bin/env python3 import pandas as pd import numpy as np def split_date(): conDay = {"ma" : "Mon", "ti" : "Tue", 'ke' : 'Wed', 'to' : 'Thu', 'pe' :'Fri', 'la' : 'Sat', 'su' : 'Sun'} conMonth = {'tammi' :1, ...
9e020d65260054bdab8b96c0207626ffcca08e21
nwweis/HY-Data-Analysis-Summer-2021
/part02-e08_prepend/src/prepend.py
426
4.375
4
#!/usr/bin/env python3 class Prepend(object): """Prepend class function to do something""" def __init__(self, name): """Adds a name to the object""" self.name = name def write(self, s): """This is print statement""" print(f"{self.name}{s}") # Add the methods of the cla...
742c85ee78e5bcdb00e89e8f2ec24d2789ce4fa6
nwweis/HY-Data-Analysis-Summer-2021
/part01-e06_triple_square/src/triple_square.py
310
3.859375
4
#!/usr/bin/env python3 def main(): for i in range(1, 11): x = triple(i) y = square(i) if y > x: break print(f"triple({i})=={x} square({i})=={y}") def square(x): return x**2 def triple(x): return x*3 if __name__ == "__main__": main()
d438c978368f34d24de923e1d645abb5d63c4c98
nwweis/HY-Data-Analysis-Summer-2021
/part01-e19_sum_equation/src/sum_equation.py
264
3.609375
4
#!/usr/bin/env python3 def sum_equation(L): if not L: return "0 = 0" lString = list(map(str, L)) eq = " + ".join(lString) return(f"{eq} = {sum(L)}") def main(): print(sum_equation([1,5,7])) if __name__ == "__main__": main()
7093fc452c38faf8495e644208a9ab5ec4e35b88
shijingyu/Python_offer
/跑楼梯一步或者两步.py
350
3.71875
4
def climbStairs(n): if n == 1: return 1 if n == 2: return 2 return climbStairs(n-1) + climbStairs(n-2) #O(n) # 1, 2, 3, 5, 8, 13 def climbStairs2(n): if n == 1: return 1 res = [0 for i in range(n)] res[0], res[1] = 1, 2 for i in range(2, n): res[i] = res[i-1]...
2098494c621801c44318548fea24f5c316494eef
mahdimmr/raspberryPlays
/gpio_test.py
2,092
3.625
4
import RPi.GPIO as GPIO from time import sleep GPIO.setmode(GPIO.BCM) leds = [2, 3, 4, 17, 27, 22, 10, 9, 11, 5, 6, 13, 19, 26, 14, 15, 18, 23, 24, 25, 8, 7, 12, 16, 20, 21] leds1 = [2, 3, 4, 17, 27, 22, 10, 9] leds2 = [11, 5, 6, 13, 19, 26, 14, 15] leds3 = [18, 23, 24, 25, 8, 7, 12, 16] leds4 = [20, 21, 24, 25, 8, 7...
6ea07af4af9b60846944de22f6917a92327efaf5
TehnoBronik/Programming
/Lesson 1.0/cheker.py
527
3.96875
4
print ("vvedite viragenie") s = (input()) stack = [] for el in s: if el == "(" "[" "{" or el == ")" "]" "}": if not stack: stack.append(el) else: if el == "(" "[" "{": stack.append ("(" "[" "{") elif el == ")" "]" "}": if stack[-1] ...
27b4f81dd5345c95bf63055b19ba991d9c6371f3
TehnoBronik/Programming
/My programms/rlu.py
434
3.640625
4
print ("") print ("vvedite kefficenty po formyle") print ("") print ("┌ ax+by=c") print ("┤") print ("└ dx+ex=f") print ("") print ("a=") a= int (input()) print ("") print ("b=") b= int (input()) print ("") print ("c=") c= int (input()) print ("") print ("d=") d= int (input()) print ("") print ("e=") e= int (input()) p...
4f48ff449d8b09c4ffb80afd50eed9e98c5cc88c
TehnoBronik/Programming
/My programms/meshen.py
402
3.75
4
import random from datetime import datetime now = datetime.now() random.seed(now) print ("skolko vistrelov?") print ("") e=0 x=0 s= int(input()) for i in range (s): raz=random.uniform(0, 10) if raz<=3: x=10 e=e+10 elif raz<=5: x=5 e=e+5 elif raz<=6: x=1 e=...
23d8b0406ce1eac4f770e13d5b14c2bb3cbd240f
TehnoBronik/Programming
/Lesson 1.0/rand.py
149
3.625
4
import random import sort2 n = int(input("vvedite kol-vo")) A = [i for i in range (1, n+1)] random.shuffle(A) print(A) print(sort2.selectionsort(A))
462a7cb7c22baa0f0833334dd3391549c506904a
TehnoBronik/Programming
/HW1/sok.py
304
3.859375
4
print ("vvedite price soka") p1=float(input()) print ("vvedite obiom soka v litrah") v1=float(input()) print ("vvedite price soka po akcii") p2=float(input()) print ("vvedite obiom soka po akcii v litrah") v2=float(input()) if p1/v1>p2/v2: print ("vigodno") elif p1/v1<p2/v2: print ("nevigodno")
fdb96170ff39e3d3f4e56b84ea4bc57ae9c3b7a8
Xevion/exercism
/python/anagram/anagram.py
360
3.671875
4
def find_anagrams(word, candidates): word, lowercandidates = word.lower(), list(map(lambda item : item.lower(), candidates)) build = {char : word.count(char) for char in word.lower()} return [candidates[index] for index, candidate in enumerate(lowercandidates) if {char : candidate.count(char) for char in ca...
035b7ee33ef1dc1ed9c4166630906c17984ea750
Xevion/exercism
/python/acronym/acronym.py
141
3.765625
4
import string, re def abbreviate(words): return ''.join(word.strip(string.punctuation)[0] for word in re.split(r'[\s-]+', words)).upper()
ba61e0d61a91a4ec1c289a34dd0e7ce9ed8fc361
Xevion/exercism
/python/saddle-points/saddle_points.py
859
3.59375
4
def saddle_points(matrix): # Check a single point in the matrix for if it's a saddle point def saddle(point): row = matrix[point[0]] column = [row[point[1]] for row in matrix] return max(row) == row[point[1]] and min(column) == column[point[0]] # Raise a value error if the matrix len...
1ec52bb89c46f0665fe6c16d22155c88ac613f3f
Xevion/exercism
/python/crypto-square/crypto_square.py
826
3.75
4
import math, string def cipher_text(plain_text): # Normalize the input translation = str.maketrans({k : '' for k in string.punctuation}) plain_text = plain_text.translate(translation).replace(' ', '').lower() if len(plain_text) == 0: return '' # Calculate the dimensions of the crypto square (rectan...
08e51ab17cfe669e877b2ac612cdbeb0bf6d5694
c4road/Hybrid-Dictionary-Maker
/word_list.py
2,559
3.953125
4
import string import random # import word_filter # from password_maker_p import * def process_file(filename, skip_header): """Makes a histogram that contains the words from a file. filename: string skip_header: boolean, whether to skip the Gutenberg header Returns: map from each word to the number...
8740653b4073d23ddb8c9c79a36363e70383e6ab
liuhuanxg/untitled
/数据分析/day8/3、分治.py
2,041
3.953125
4
#分治:分而治之 #使用分治法能解决的问题一般具有以下几个特征: ''' (1)、该问题的规模缩小到一定程度就可以相对容易的解决 (2)、该问题可以分解为若干个规模较小的相同问题,即该问题具有最优子结构性质 (3)、利用该问题分解出的子问题的解可以合并为该问题的解 (4)、该问题所分解出的各个子问题是相互独立的,即子问题之间不包含公共的子问题 ''' #例题:给定一个顺序表,编写一个求出其最大值的分治算法 import time #基本子算法(子问题规模小于等于2时) def get_max(nums): if len(nums)<2: return nums[0] ...
bc8180260a0bdad94c2272535b5ed68cdd3efc60
liuhuanxg/untitled
/数据分析/day8/6、map函数.py
390
3.8125
4
# 表示:将迭代器当中的元素,依次作用在函数当中 # map(函数名,迭代器) def my_sq(num): return num**2 temp_list = [i for i in range(1,11)]#[1,2,3,4,....10] # result_list = [] # for value in temp_list: # new_value = my_sq(value) # result_list.append(new_value) # # print(result_list) result = list(map(my_sq,temp_list)) p...
25638068463b6bf193519b06ed05f42980a0fe39
liuhuanxg/untitled
/面试基础/常见标准库/3、必考知识/2、字符串操作.py
1,839
4.28125
4
#字符串常见操作和函数 str1='kkJHGse' print(dir(str1)) print(str1) print(str.capitalize(str1)) #Kkjhgse #Kkjhgse 将第一个字符转换为大写(如果第一个字符不是字母则不转化),其余字母转化为小写 print(str1.center(9)) #位于15个字符中间,两端用空格补充 print(str1.count('k')) #2 print(str1.encode()) #b'kkJHGse' print(str1.endswith('e')) #True print(str1.find('k')) ...
8a255c30d04768eb4e172110391da7433f62be42
liuhuanxg/untitled
/数据分析/day1/2、创建数组.py
1,618
3.578125
4
import numpy as np ''' 1、使用array函数来创建 格式: np.array(object,dtype=None,copy=True,oreder='K',subok=False,ndmin=0) objece:接受array。表示想要创建的数据,无默认值 dtype: 接受data-type.表示数组所需的数据类型。如果未给定,则选择保存对象所需的最小类型。默认为None ndmin:接收int。指定生成数据应该具有的最小维数,默认为None ''' a1=np.array([1,2,3,4]) print(a1,a1.dtype) #[1 2 3 4] int32 a2=np....
a04cf9b30b2b9fa7ec7581b46bc0ff467cea3d6f
liuhuanxg/untitled
/面试基础/常见标准库/2、python底层/2、python语言特点.py
1,309
3.625
4
# 1、python是一种解释型语言,python代码在运行之前不需要编译。其他解释型语言还包括PHP和Ruby # # 2、python是动态类型语言,指的是在声明变量时,不需要说明变量的类型。可以直接编写。 # # 3、python适合面向对象的编程,支持通过组合与继承的方式定义类。python中没有访问说明符。 # # 4、在Python语言中,函数是第一类对象(first-class objects)。这指的是它们可以被指定给变量,函数既能返回函数类型,也可以接受函数作为输入。类(class)也是第一类对象。 # # 5、Python代码编写快,但是运行速度比编译语言通常要慢。好在Python允许加入基于C语...
e6f4651959ea15ae86f06eb74f7c2c50f855409a
liuhuanxg/untitled
/排序/1、简单选择排序.py
1,097
3.8125
4
""" 基本思想:在要排序的一组数中,选出最小(或最大)的一个数与第一个位置的数交换;然后在剩下的数当中再找最小(或者最大)的与第2个位置的数交换,依次类推,直到第n-1个元素(倒数第二个数)和第n个元素(最后一个元素)比较为止。 """ # 时间复杂度平均O(n2),最好为O(n2),最坏为O(n2),空间复杂度为:O(1),不稳定排序 list1=[9,6,8,4,7] print(list(filter(lambda x:True if x%2==1 else False ,list1))) def select_sort(alist): ''' :param alist: 将要排序的列表 :re...
9d21b789231eafe5df66bbae35ee3a216d55c02d
shikma19-meet/yl1201718
/lab3/lab6.py
1,512
4.0625
4
from turtle import * import random import math class Ball (Turtle): def __init__(self,radius,color,speed): Turtle.__init__(self) self.shape("circle") self.shapesize(radius/10) self.radius = radius self.color(color) self.speed(speed) #def random_color(): # r = random.randint(0,256) # b = random.r...
3ef8e5f56f7f6a695513e50ebfea0371f8016fc8
MarianoEcheconea/veintePalabras
/include/history.py
491
3.828125
4
class History: """ clase para manejar las historias """ #variables history = "" #funciones def __init__(self): a_file = open("data/history.txt", encoding="utf-8") self.setHistory(a_file.read()) def __iter__(self): pass def __next__(self): pass def ...
c0268c416e0ccc28559203a036d1e75cd734264c
azharcs/Learn-Python-the-Hard-Way
/ex19.1.py
478
3.75
4
def bluth (name_of_actor, age_of_actor, relation): print "The actor's name is %s !" % name_of_actor print "The age of %s is %d !" % (name_of_actor, age_of_actor) print "The %s's relation is %s !" % (name_of_actor, relation) print "Thank you for all your help, It was indeed helpful!" print "Ver ...
c1e6574e4132e50b722c13f8cb20c85bc3ebf2b3
mellow3607/DRILL
/04/grid.py
541
3.828125
4
import turtle turtle.penup() turtle.goto(-200,-200) #turtle.pendown() #turtle.forward(500) count = 0 x = -200 y = -200 while (count < 6 ) : turtle.pendown() turtle.forward(500) turtle.penup() y = y +100 turtle.goto(x,y) count = count + 1 turtle.left(90) turtle.penup() turtle.goto(-200,-200) ...
0311c422c7ba1b39204037239c241f37c6fb9dae
chenpenfree/data-structures-algorithms
/sort_algorithms/tree.py
10,151
4.09375
4
import queue class Node: """ 树的节点 """ def __init__(self, data): self.data = data self.left = None self.right = None class BinarySearchTree: """ 二叉查找树 """ def __init__(self): self.__tree = None def insert(self, data): """ 插入数据 ...
0a9d7b8b987ab032b73588d023c3a407962d3dec
Chippers255/regex_gp
/src/node.py
632
3.671875
4
import sets class Node(object): def __init__(self, depth, root=False): self.depth = depth if root: self.value = '__' self.num_children = 2 else: self.value, self.num_children = sets.random_value() self.left = None self.right = None ...
efc1fcd6a766f3ab8d6dbbe2c9d930736ec2f542
Stevinson/HBAdissertation
/src/game/othello.py
9,254
3.71875
4
""""" Controller class for the Othello board game. Adapted from Andy Salerno (2016) """ from copy import deepcopy from typing import Tuple from agents.random_agent import RandomAgent from constants import COLOUR_STR, OPPONENT from game.board import BLACK, EMPTY, WHITE, Board from util import * class Othello: "...
09d5d64a3f575248ae934982177666e07c873186
chetanadhikary/pythonLearning
/day1/if_2.py
149
4.125
4
email_str = input('Enter your email ID : ') if '@' in email_str: print('Its an valid email ID') else: print('Entered email ID is not valid')
9c65bf648b6bf414ffbd142bb22383406c00a4df
WuraolaS/OOP_bank_account
/Bank_Account.py
1,798
4.28125
4
#This is an OOP python project to create a Bank Account #variables are: #first name #last name #account number #starting balance #current balance #Methods #withdraw #deposit #interaccount transfer # Bank Account has a checkings and savings account # Checkings Account is a bank account - it inherits the bank accout cl...
0e4fd4fc8f24cbadb72f7ef4afbd784f7389fc9f
ccg/TwitterOAuth
/twitter_oauth/__init__.py
5,666
3.546875
4
#!/usr/bin/env python """twitter_client.TwitterClient is a class for creating an OAuth-based Twitter client.""" # TODO unittest or doctest # TODO abstraction for API URLs or just type out the whole thing each time? # TODO test with desktopRW app import urllib import urllib2 import webbrowser import oauth.oauth as oa...
6b9f270e726a31ead883b7d235a64b00d8625c2a
kuzovkov/python_labs
/exp/ofop/func.py
162
3.671875
4
from math import sqrt formula = 'f(x)=0.7*x2-sqrt(3)*x +4.8' a = 0 b = 2 eps = 0.0001 def function( x ): return 0.7 * x * x - sqrt( 3 ) * x + 4.8
b16601487a6973482362106a7151dfa3e0bdc8ca
kuzovkov/python_labs
/4/task4.1.py
795
4.03125
4
# # def fact_1(n): n=int(n) f=1 for i in range(1,n+1): f=f*i return f # def fact_2(n): if n>1: return n*fact_2(n-1) else: return 1 # reduce def fact_3(n): def mul(x,y): return x*y ls=range(1,n+1) return reduce(mul,ls)...
1053d61866c54c1c0d6d92a1d7adbc02fd950314
kuzovkov/python_labs
/web/torrent_search/sort.py
1,090
3.53125
4
# ls1=[ ['dfgee1w','hg1fd','wer1ty','er1ty','asd1fg'], ['afgee2w','hg2fd','wer2ty','er2ty','dsd2fg'], ['dfgee3w','ag3fd','wer3ty','ert3y','asdf3g'], ['wfgee4w','hg4fd','cer4ty','art4y','dsd4fg'], ] def printList(ls): for row in ls: print row print "-"*60 def sortList(ls,inde...
11240302f3e29f9d9c0bcbdf5222e8fef4ad5603
kuzovkov/python_labs
/6/task6.v1.py
7,043
3.578125
4
#coding=utf-8 #Кузовков Александр Владимирович from Tkinter import * from tkFont import * s='' x=0 y=0 z=0 digit=10 op='0' new=False app=Tk() app.title("Калькулятор") app.geometry('300x300') app.resizable(0,0) #текстовое поле pole=Entry(app,bg="white",state="readonly",readonlybackground="white",...
e3d16a9423402f9cff398281d6d9644da8f54b58
robinguo/python-network-data
/week-6/extracting-data-from-json.py
338
3.75
4
import json import urllib url = raw_input("Enter location: ") print "Retrieving", url data = urllib.urlopen(url).read() print "Retrieved", len(data), " characters" comments = json.loads(data).get("comments") sum = 0 count = 0 for comment in comments: sum += comment.get("count") count += 1 print "Count", count...
a001594831442b36b68cd79a672c91ca1b4290a8
bjolley74/aoc_new_year
/myerrors.py
914
4.125
4
"""my error classes""" class ArgumentError(Exception): """ ArgumentError is raised when aoc_new_year.py is given an unexpected argument. Expected arguments include '-h', '--help', '-v', '--version', 'y:1234',and/or 'd:filepath/'. Any other arguments provided will result in an ArgumentError """ ...
da139d0f6abcf8b2585b1e68679b0d1a09f28fc6
arulantran/disk-scheduling-gui-python
/fcfs.py
730
3.640625
4
def fcfs_fun (num_list, head): next_head = head total = 0 print('Current position --> Next position') for num in num_list: temp = abs(next_head - num) print('{} --> {}'.format(next_head, num)) next_head = num total += temp print('Total seek time is : {}'.format(t...
b937265abc2c92a0ec5244f6fef54c10f6f43a9d
jiapei100/Stereo
/micropython/tests/basics/list_index.py
631
3.84375
4
a = [1, 2, 3] print(a.index(1)) print(a.index(2)) print(a.index(3)) print(a.index(3, 2)) print(a.index(1, -100)) print(a.index(1, False)) try: print(a.index(1, True)) except ValueError: print("Raised ValueError") else: print("Did not raise ValueError") try: print(a.index(3, 2, 2)) exc...
aa6cea2f8e2f2ba41736b5ebd0e7b97a54021e0d
jiapei100/Stereo
/micropython/tests/basics/exceptpoly.py
7,395
3.546875
4
try: raise ArithmeticError except Exception: print("Caught ArithmeticError via Exception") try: raise ArithmeticError except ArithmeticError: print("Caught ArithmeticError") try: raise AssertionError except Exception: print("Caught AssertionError via Exception") try: raise...
7772cdd997837b859a88024594c92cacaad6b3fa
jiapei100/Stereo
/micropython/tests/basics/class_number.py
281
3.859375
4
# test class with __add__ and __sub__ methods class C: def __init__(self, value): self.value = value def __add__(self, rhs): print(self.value, '+', rhs) def __sub__(self, rhs): print(self.value, '-', rhs) c = C(0) c + 1 c - 2
9e98de1ee38711beb581cbe6c6fca9bc2d43e534
jiapei100/Stereo
/micropython/tests/basics/builtin_minmax.py
586
3.703125
4
# test builtin min and max functions print(min(0,1)) print(min(1,0)) print(min(0,-1)) print(min(-1,0)) print(max(0,1)) print(max(1,0)) print(max(0,-1)) print(max(-1,0)) print(min([1,2,4,0,-1,2])) print(max([1,2,4,0,-1,2])) # test with key function lst = [2, 1, 3, 4] print(min(lst, key=lambda x:x)) ...
917f426d253a2603cc8bf8c4d93a95c8e2998edf
jiapei100/Stereo
/micropython/tests/basics/class3.py
359
3.671875
4
# inheritance class A: def a(): print('A.a() called') class B(A): pass print(type(A)) print(type(B)) print(issubclass(A, A)) print(issubclass(A, B)) print(issubclass(B, A)) print(issubclass(B, B)) print(isinstance(A(), A)) print(isinstance(A(), B)) print(isinstance(B(), A)) prin...
2ffccf114bffa8005d316dd9dc31129b8933c71d
jiapei100/Stereo
/micropython/tests/bytecode/mp-tests/scope3.py
163
3.71875
4
# test nested functions and scope def f(x): def f2(y): return y + x print(f2(x)) return f2 x=f(2) print(x, x(5)) f=123 print(f(f))
69e06b483fb71cca3bebb25724623802b1197e9a
jiapei100/Stereo
/micropython/tests/basics/except_match_tuple.py
337
3.765625
4
# test exception matching against a tuple try: fail except (Exception,): print('except 1') try: fail except (Exception, Exception): print('except 2') try: fail except (TypeError, NameError): print('except 3') try: fail except (TypeError, ValueError, Exception): pr...
d46ed419c171915f1174ff918be19c6a82033c46
jiapei100/Stereo
/micropython/tests/basics/bytes_mult.py
259
3.859375
4
# basic multiplication print(b'0' * 5) # check negative, 0, positive; lhs and rhs multiplication for i in (-4, -2, 0, 2, 4): print(i * b'12') print(b'12' * i) # check that we don't modify existing object a = b'123' c = a * 3 print(a, c)