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
f233bd8b8536dbaaf4810839f262f93a0ede3113
ridwanrahman/datastructures
/problems/LinkedListProblem1.py
269
3.953125
4
#Find the nth node from the end of a linkedlist from singlylinkedlist.linkedlist import LinkedList ll = LinkedList() ll.insertAtBeginning(1) ll.insertAtBeginning(2) ll.insertAtBeginning(3) ll.insertAtBeginning(4) ll.insertAtBeginning(5) ll.print_list() ll.problem1(2)
0aeeacda2573821d2b0edd60f5b0a0ce21055d3a
ridwanrahman/datastructures
/linkedlist/DoublyLinkedList/Node.py
1,164
3.9375
4
class Node: # if the data is not given by the user its taken as None def __init__(self,data=None, next=None, prev=None): self.data = data self.next = next self.prev = prev #method for setting the data field of the node def setData(self, data): self.data = data #method...
aa937c560f8049ac5ffc1edce9b62300e3486983
ridwanrahman/datastructures
/problems/LinkedListProblem2.py
306
3.78125
4
# Insert a node in a sorted linked list from singlylinkedlist.linkedlist import LinkedList ll = LinkedList() # ll.insertAtBeginning(2) # ll.insertAtBeginning(3) # ll.insertAtBeginning(4) ll.insertSorted(78) ll.insertSorted(100) ll.insertSorted(90) ll.insertSorted(9) ll.insertSorted(900) ll.print_list()
e445b580d8a29dd6c0cb49f5f428768d25665820
shiyamvasanthan/Connect4
/connect4.py
6,332
3.84375
4
import pygame #Initialize pygame pygame.init() #Setup the window window = pygame.display.set_mode((700, 700)) window.fill((255, 255, 255)) pygame.display.set_caption('Connect 4') #Game Colors black = (0, 0, 0) blue = (51, 102, 255) white = (255, 255, 255) red = (220, 0, 0) yellow = (253, 222, 42) #...
c64862771718eb552065ec138819293274a82edc
chalsea2000/cse163
/get_data.py
6,588
3.984375
4
''' Matthew Khoo, Chalsea Chen, Chenyu Hu CSE 163 Proj This python file contains all the methods to extract data we want from the Youtube API to answer our research questions. It does all of the data processing and transforms the final dataframes into csv files to be used in the plot_visualizations.py file to create va...
bcfbc9daa97fa0b1fc9bd43aab58d20ac0ec824d
lavindude/Session-Activities
/test.py
165
3.71875
4
# pi = [5, 6, 7, "github"] # print(pi[3]) pi = [{"Apple" : [4, 7, 9], "Banana" : "a yellow fruit"}, {"Freshavacado" : "fresh avacados"}] print(pi[0]['Apple'][0])
f6c154a48782ea8141868447b3a0b4e33f6b5ba8
dancual/pythonpackagesample
/ie_mbdbl2017_C_yahoo_ks_datareader/check_dates.py
4,105
3.84375
4
def check_dates(tic,t_date): import requests if(t_date == "min"): j_date = requests.get("https://daniserrano.pythonanywhere.com/GroupC/" + tic + "/mindate") else: j_date = requests.get("https://daniserrano.pythonanywhere.com/GroupC/" + tic + "/maxdate") return j_date def check_...
3c804e5b14d19ae6ae8c99e9cf615ded310fe09e
KaseyHarvey98/python3_journey
/Unit1/Unit1.3.py
193
4.28125
4
word = 'substantiate' substrings = ['ate', 'state', 'a', 'substantiate', 'it', 'tan'] for substring in substrings: if substring in word: print(substring, 'is a substring of', word)
ce4c48af06e6510760b72c57ee477a6f188471b2
KaseyHarvey98/python3_journey
/Unit2/Unit2.5.py
129
3.71875
4
students = ['Ed', 'Ted', 'Fred', 'Jennifer'] output = [ ] for student in students: output.append(len(student)) print(output)
1acbd2d10843fa2b929d11f6542ee0fbf72cf37c
KaseyHarvey98/python3_journey
/Unit1/Unit1.5.py
88
3.65625
4
numbers = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] for number in numbers: print(number)
7ace955013d9286576220f54ea864a9f26c62034
KaseyHarvey98/python3_journey
/Unit3/test3.py
1,032
3.84375
4
def cleanedup(s): alphabet = '@abcdefghijklmnopqrstuvwxyz' cleantext = '' for character in s.lower(): if character in alphabet: cleantext += character else: cleantext += ' ' return cleantext lines = 0 longest = 0 usernames = {} with open('elon-musk.txt') as book:...
afe0c94d929e04f51a6a0c0095effaa8d924d0d3
KaseyHarvey98/python3_journey
/Unit6/Unit6.1.py
124
3.8125
4
def lengths(strings): return[len(s) for s in strings] names = ['Ed', 'Ted', 'Fred', 'Jennifer'] print(lengths(names))
d992b83b1b19c83050c294012fed71fee235ca0d
movingroovin/Rental591Crawler
/python101.py
1,296
3.953125
4
x = range(10) for i in x: print(i) # 下載: vscode/ python官網/ python 外掛(vscode) # pip: https://matthung0807.blogspot.com/2019/08/windows-pythonpip.html # 數字: 1 # 字串: "1" # 布林: True/ False # 列表List: [],從0開始數 # 字典Dict: {},用冒號: 對應key: value # python 101: https://blog.techbridge.cc/2016/12/17/python101-tutorial/ # htt...
b47b4aa1615c0e18d6f0257b10c02cbb8d26a2a3
RashidLadj/Sudoku_Augmented_Solver
/src/modelsCNN/Sudokunet.py
2,029
3.671875
4
# import the necessary packages from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Conv2D from tensorflow.keras.layers import MaxPooling2D from tensorflow.keras.layers import Activation from tensorflow.keras.layers import Flatten from tensorflow.keras.layers import Dense from tensorflow....
7f67769a9718b3548b4cc0e089b9a5bd4e9e7be0
wonderjeo/Python_Learn
/Exercise17.py
1,439
3.796875
4
# -*- coding: utf-8 -*- """ Created on Sat Jan 12 16:22:50 2019 @author: 45570 """ class Frac: def __init__(self, num, denum): import math gcd = math.gcd(num, denum) self.__num = num // gcd self.__denum = denum // gcd def __str__(self): return f'{self.getNum...
8ec72d8b155eea55b5f30ca30894377664cf2852
wonderjeo/Python_Learn
/Exercise6.py
306
3.71875
4
# -*- coding: utf-8 -*- """ Created on Mon Jan 7 21:10:52 2019 @author: 45570 """ n = int(input("Please input a number:")) for i in range(2, n+1): flag = 1 for x in range(2, int(i ** 0.5 + 1)): if i % x == 0: flag = 0 if flag == 1: print(i, end=" ")
4e2d093896fd0924c425084954e97ac5689b7f67
ParkerLLF/LanQiaoCode_Python
/数学问题/全排列.py
520
3.515625
4
# # 方法一 # ''' # 输入: # 1 2 3 # 输出: # (1, 2, 3) # (1, 3, 2) # (2, 1, 3) # (2, 3, 1) # (3, 1, 2) # (3, 2, 1) # ''' # import itertools # n = list(map(int, input().split())) # list = list(itertools.permutations(n)) # for i in range(len(list)): # print(list[i]) # 方法二 nums = [1, 2, 3] res = [] def backtrack(nums, tmp): ...
0c6964d85eb8106cd01128e43406f0170e84ce17
ParkerLLF/LanQiaoCode_Python
/数学问题/质数最优.py
1,611
3.671875
4
class Solution(object): def countPrimes(self, n): """ :type n: int :rtype: int """ # 方法一 ''' def isPrime(n): if n == 2: return True for i in range(2, n): if n % i == 0: re...
18a84fb0893f69a518351d9dd1c493b935c30dc1
ParkerLLF/LanQiaoCode_Python
/蓝桥杯模拟赛oj6/解决NPC问题.py
419
3.78125
4
import datetime for i in range(2, 3000): today1 = datetime.datetime(i,1,1) today2 = datetime.datetime(i+1,1,1) resultDay = today1 + datetime.timedelta(days=300) resultDay2 = today2 + datetime.timedelta(days=200) if resultDay.weekday() == 1 and resultDay2.weekday() == 1: today3 = datetime.dat...
1d69066e84197b4223ba8a0a169bdc6a9ab906f2
ParkerLLF/LanQiaoCode_Python
/数学问题/闰年.py
253
3.9375
4
def is_leapyear(num): if num % 4 == 0 and num % 100 != 0 or num % 400 == 0: return True return False if __name__ == '__main__': num = int(input()) if is_leapyear(num): print('yes') else: print('no')
3e62e775314af0e807407baf7173df7b34a24595
ParkerLLF/LanQiaoCode_Python
/蓝桥杯官网试题/基础练习/字符串对比.py
302
3.8125
4
def solve(str1, str2): if len(str1) != len(str2): return 1 else: if str1 == str2: return 2 elif str1.lower() != str2.lower(): return 4 return 3 if __name__ == '__main__': str1 = input() str2 = input() print(solve(str1, str2))
1df187eef80a7d3025acec9442b3779af8f039bc
marinajukova/HSE_programming
/pretest/dictionaries/1.py
1,658
3.609375
4
## Программа должна прочитать текст, создать частотный список слов в этом тексте, используя слова в качестве ключей словаря, ## а частотность в качестве значений. После этого нужно распечатать самое частотное слово в тексте. ## Найти среднее значение частотности слов в тексте и распечатать его. def process(fname): ...
0756e449257b77a7a31d4e1f88edf6a9142c95ec
marinajukova/HSE_programming
/CWs/CW8.py
3,446
3.703125
4
##1) Написать фкнкцию opentext(): ## - открывать файл с названием fname ## with open() ## - перевести текст в нижний регистр ## text.lower() ## - делить текст на слова (между пробелами и знаками препинания) ## text.split() ## - удалить от слов знаки препинания ## ...
afa47901b1223d862347a4505f936b2f829cce3b
marinajukova/HSE_programming
/pretest/regular expressions/8.py
675
3.609375
4
## Нужно открыть текстовый файл и найти в тексте все даты формата дд.мм.гг. ## При этом программа не должна распознавать несуществующие даты, типа 45.02.93 или 00.14.11. import re def main(): with open('dates.txt', 'r', encoding = 'utf-8') as f: text = f.read() dates = re.findall('(?:(?:0|1|2)|3(?:0|1...
eeab7b191a4832007d165c8ba0e1d7f61c61ce7d
marinajukova/HSE_programming
/hw5/3.py
1,097
3.96875
4
##Вариант 3. Программа должна открывать файл с русским текстом в utf-8 и сообщать про него следующую информацию: ##во сколько раз слов длины 3 больше, чем слов длины 1 (если слов длины 1 нет вообще, программа должна об этом сообщить) ## !!! Программа работает только с utf-8 без BOM !!! words = [] with open('text.txt'...
caa33fdad5d9812eb473d03a497c46d6a0ad71f2
YasirQR/Interactive-Programming-with-python
/guess_number.py
1,963
4.21875
4
# template for "Guess the number" mini-project # input will come from buttons and an input field # all output for the game will be printed in the console import math import random import simplegui num_range = 100 count = 0 stop = 7 # helper function to start and restart the game def new_game(): #...
11202605be39d3662b9f284d6c32fbbb595d7717
FriesW/ConnectMaze
/Node.py
2,195
3.546875
4
class Node: TOP = 0 RIGHT = 1 BOTTOM = 2 LEFT = 3 __all = [ TOP, RIGHT, BOTTOM, LEFT ] __inverse = [ BOTTOM, LEFT, TOP, RIGHT ] def __init__(self): self.nodes = self.__init_array(4, None) self.connects = self.__init_array(4, False) self.group_id = object() def __init_array(self, l, v): ...
c1acca7e8b25fd0caf4fd92ca244957f90c217fe
swenker/studio
/python/basic/DigitalSequence.py
726
3.875
4
""" get the index left to which the sum is equal to the right part. """ def getIndex(a): if (len(a)<2): return -1 if len(a)==3: if a[0]==a[2]: return 1 else: return -1 total=0 for i in a: total +=i ...
2efd586bcf0773cb39512aaec89f9165d3740b34
swenker/studio
/python/basic/lesson/bp/cpucontrol.py
582
3.609375
4
__author__ = 'samsung' import time def test(): i=0 while(True): if(i %2==0): i+=1 print i else: time.sleep(1) def test2(): i=2 while(True): i*=i time.sleep(1) #print i def test3(): while(True): ...
aa59b20bc1fdd1426bcf8e268e1408800ee57c0e
raghavgupta00/Evalueserve-Intern-project-2019
/Scraping university URL.py
4,177
3.703125
4
# -*- coding: utf-8 -*- """ Created on Thu Jul 25 12:33:57 2019 @author: Raghav Gupta A script to scrape the homepage of various universities stored in an excel file. The first non-advertised page is pulled and stored in a list, which is then appended to the dataframe of the universities. These will be us...
359280747938d7b721b3384adddb5184c46d1542
Hari-Priya-P/Image-Colorizer
/read_dataset.py
2,894
3.765625
4
# load and display an image with Matplotlib from matplotlib import image from matplotlib import pyplot import conv as conv from conv import conv_block import backprop as bp import numpy as np def normalize_output_layer(output): num_layers = output.shape[2] normalized_output = np.zeros(output.shape) for l ...
2547ab4983c2a05865b162253774f22e3afb2f21
pcaressa/temp
/put_parenthesis.py
4,405
3.734375
4
# put_parenthesys.py """ Expressions are represented as lists: [b1, o1, b2, o2, ...] where bi are 'true', 'false' or subexpressions and oi are 'and', 'or', 'xor'. """ def find_all(token_list): """ Associates in all possible ways parentheses in the token_list expression. TODO""" ...
1c10a0791d3585aa56a5b6c88d133b7ea98a8b24
haydenbanting/LawnBot
/Mapping/mapping_functions/matrix_builder.py
2,029
4.25
4
''' Function for creating matricies for map routing algorithms Author: Kristian Melo Version: 15 Jan 2018 ''' ######################################################################################################################## ##Imports ##############################################################################...
1cb887a99ffa1094a0f32f97776aaf5e14182421
haydenbanting/LawnBot
/Mapping/mapping_functions/plotting_functions.py
3,148
3.84375
4
''' This function plots a graphical representation of the lawn used for testing simulations Author: Kristian Melo Version: 18 Jan 2018 ''' ######################################################################################################################## ##Imports #################################################...
f11223039ef7b2745dacc917e4ca408d88e210a2
ndnmonkey/simple_algorithms
/插入排序.py
431
3.84375
4
def charu(list): num = len(list) for i in range(1,num): for j in range(0,i): print("i=",i,"j=",j," list[i]=",list[i],"list[j]=",list[j]) if list[i] < list[j]: temp = list[i] list.remove(list[i]) list.insert(j,temp) ...
dfd01eee5643db01f235f8475666b83be4ec71e5
dyladan/school-notes
/algo/shellsort.py
429
3.5625
4
gaps = [23, 10, 5, 1] def shellSort(lst): for gap in gaps: for i in range(gap): gapISort(lst, i, gap) return lst def gapISort(lst,start,gap): for i in range(start+gap, len(lst), gap): v = lst[i] p = i while p >= gap and lst[p-gap] > v: lst[p] = lst[p...
bff0820d190ac9d1e50e0009dcf84608a76a2aaf
freedom357/freedom357.github.io
/lab001.py
1,061
3.75
4
""" This script will Anonymize the data in original_data.csv file to Anonymized form in anonymized_data csv file """ import csv #Brad from faker import Faker #Luck from collections import defaultdict #Brad def anonymize(): #Luck # Load the faker and its providers faker = Faker() #Brad # Create map...
22cee07f314c33d643c68081ee0575b51d59f518
deycyrubi/ProyectoUnidad3
/DistanciaEuclidea.py
1,445
4.15625
4
""" >>> numero = DistanciaEuclidea(2,2,4,4,) >>> numero.CalDistancia() >>> numero.getDistancia() 2.8284271247461903 """ #Se declara la palabra reservada math para la resolución del problema import math #Se declara la clase la cual lleva por nombre el problema a resolver class DistanciaEuclidea: """Se declaran los...
66d85d4d119be319d62c133c1456c91a630291db
10zink/MyPythonCode
/HotDog/hotdog.py
1,624
4.1875
4
import time import random import Epic # Programmed by Tenzin Khunkhyen # 3/5/17 for my Python Class # HotDogContest #function that checks the user's guess with the actual winner and then returns a prompt. def correct(guess, winner): if guess.lower() == winner.lower(): statement = "\nYou gusses right, ...
0b18e86b3b5c414604e6cf3e35618770998043a9
10zink/MyPythonCode
/Exam5/Store.py
1,448
4.46875
4
import json import Epic # Programmed by Tenzin Khunkhyen # 4/16/17 for my Python Class # This program is for Exam 5 # This program just reads a json file and then prints information from a dictionary based on either # a category search or a keyword search. #This function reads the json file and converts it into a ...
c601c685111500976d62442a4e2be11bb928ee77
justdave001/Algorithms-and-data-structures
/SelectionSort.py
524
4.1875
4
""" Sort array using brute force (comparing value in array with sucessive values and then picking the lowest value """ #Time complexity = O(n^2) #Space complexity = O(1) def selection_sort(array): for i in range(len(array)): for j in range(i+1, len(array)): if array[i] > array[j]: ...
368cf7abc1c59791edea7709d6d8618f80615e1c
saunak1994/DigitRecognitionNN
/CNNTrain.py
2,154
3.53125
4
#Script for data acquisition and training the CNN model import keras from keras.models import Sequential from keras.layers.core import Dense, Dropout, Activation, Flatten from keras.layers.convolutional import Convolution2D, MaxPooling2D from sklearn.model_selection import train_test_split import pandas as pd im...
a7ad40a3f56933742bde8e5390cf4c2a731ae5ad
hm77/Project200k
/sg22/May21_Question2_maxContainer.py
330
3.6875
4
import sys def maxContainer(height): Result=[] for i in range(0,len(height)): for j in range(i+1,len(height)): area=(j-i)*min(height[i],height[j]) Result.append(area) return Result if __name__ == '__main__': height=[1,1] Result=maxContainer(height) print ma...
f8edc77d0d361df8ad4a585141f459007c91c190
bxio/SEng360
/L2/lab2_orig.py
1,291
3.765625
4
''' purpose encrypt P using Vernam cipher with key K preconditions P string of A..Z K: non-empty list of int in 0..25 len(P) <= len(K) ''' def vernam_encrypt(P,K): pass # put your implementation here and REMOVE THIS LINE ''' purpose decrypt C using Vernam cipher with key K preconditions C string of A..Z K: non...
3c8df58e0135bd806acd5735d66bf42e718cd49d
signoreankit/PythonLearn
/numbers.py
551
4.1875
4
""" Integer - Whole numbers, eg: 0, 43,77 etc. Floating point numbers - Numbers with a decimal """ # Addition print('Addition', 2+2) # Subtraction print('Subtraction', 3-2) # Division print('Division', 3/4) # Multiplication print('Multiplication', 5*7) # Modulo or Mod operator - returns the remained after ...
2e704c033d833d5ec31838c11fcae15b15592de8
hierynomus/code-challenges
/2015-adventofcode.com/day22.py
5,602
3.8125
4
from collections import namedtuple Player = namedtuple('Player', ['hp', 'armor', 'mana', 'Shield', 'Poison', 'Recharge']) Boss = namedtuple('Boss', ['hp', 'damage']) def memoize(f): """ Memoization decorator for functions taking one or more arguments. """ class memodict(dict): def __init__(self, f): ...
fdc172d21be16fc8cbf4f991dc5b9a3bc5c9dd42
hierynomus/code-challenges
/2015-adventofcode.com/day17.py
817
3.515625
4
from itertools import chain, combinations def powerset(iterable): "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)" s = list(iterable) return chain.from_iterable(combinations(s, r) for r in range(len(s) + 1)) target = 150 containers = [] with open('day17.in', 'r') as f: for l in ...
f3f830c9c5732f78e29fff2e52d2af1c21c76fcd
JeuneRR/3laba
/1.py
192
3.765625
4
a=input("Ваше имя?") b=input("Какой Ваш любимый предмет в школе?") c=input("В каком классе Вы учитесь?") print(a, b, c, sep="\n")
223070725f14bb3d977bb67a41830942263aacd7
Hazel-K/Python3
/code05/main.py
773
4.21875
4
# num_tuple = (1, 2, 3) # num_tuple[0] = 0 #TypeError: 'tuple' object does not support item assignment # del num_tuple[0] #TypeError: 'tuple' object does not support item assignment # print(num_tuple) # 튜플 형태의 값은 수정 삭제가 불가능 # num_set = {1, 1, 2, 2, 3, 3} # {1,2,3} 중복 제거됨 # num_set.add(4) # print(num_set) # 순서를 갖지 않으므로...
22babd2c5940cbdc09b1909ad16df2bca5d6e9e8
Shalin21/PyEulerProblems
/[2]Even_Fibonacci_numbers/main.py
197
3.546875
4
first = 1 second = 2 num = first + second finalSum = 2 while num < 4000000: first = second second = num num = first + second if num % 2 == 0: finalSum += num print(finalSum)
927f4a0d3f15f4b3d3356df84a3e6b07310c02e6
AlikasE2E/Alikas_courses
/Homework/4. Task 4.py
514
4.03125
4
# Даны три числа a, b, c. Определите, существует ли треугольник с такими сторонами. Если # треугольник существует, выведите строку YES, иначе выведите строку NO. print("Введите длины сторон треугольника:") a = float(input("a = ")) b = float(input("b = ")) c = float(input("c = ")) if a + b > c and a + c > b and b + c >...
1d9f00fcc53c2e66c8ff129621c9c49a3ef7ebaf
AlikasE2E/Alikas_courses
/Homework/10. Task 10.py
1,052
3.71875
4
# У вас есть список чисел. # 1. Напишите цикл, который выводит на экран и удаляет с начала элементы списка, пока он не # останется пустым b = [] i = 0 while i < len(a): if 35 < a[i] < 65: b.append(a[i]) del a[i] else: i += 1 # 2. ** Как сделать это же задание со строкой: напишите цикл, ...
47441f2588de4d832de4caadfb0a0aad54ab78da
timpogue/3dpy-with-Leap-Motion
/3d.py
13,070
3.515625
4
import pygame import math import numpy import Leap, sys import LeapMotionController def square((x, z), (w, d)): return [[nx, nz] for nx in (x, x + w) for nz in (z, z + d)] def circle((cx, cy, cz), (cr, res)): circle = Wireframe() theta = 0 step = 2 * numpy.pi / res while theta < 2 * numpy.pi: ...
b829a56397de56a571604b1fae51e8ec449511ed
snord883/Data-Structures-and-Algorithms-specialization
/1. Algorithmic Toolbox/coursera resources/week3_greedy_algorithms/3_car_fueling/car_fueling.py
1,365
3.796875
4
# python3 import sys def determine_farthest_reachable_station(distance, current_spot, tank, stops): # 1500, 0, 400, [100,200,600,800,1000,1400] current_farthest_reachable_station = current_spot while tank>0: try: if stops[0]<=current_farthest_reachable_station + tank: ta...
1d52c5b2646da21cf812bafc2a932750096b00d8
snord883/Data-Structures-and-Algorithms-specialization
/1. Algorithmic Toolbox/coursera resources/week5_dynamic_programming1/2_primitive_calculator/primitive_calculator.py
1,712
3.8125
4
# Uses python3 import sys # def incorrect_optimal_sequence(n): # sequence = [] # while n >= 1: # sequence.append(n) # if n % 3 == 0: # n = n // 3 # elif n % 2 == 0: # n = n // 2 # else: # n = n - 1 # return reversed(sequence) # def optima...
398e3b327caa383cfb8dd4515979d6300d3e52f3
jxvo/holbertonschool-higher_level_programming
/0x0B-python-input_output/14-pascal_triangle.py~
298
3.5625
4
#!/usr/bin/python3 def pascal_triangle(n): list_init = [1] for idx in range(n): new_list = [] new_list.append(list_init[0]) for idx in range (len(list_init) - 1): new_list.append(list_init[i] + list_init[idx + 1]) new_list.append(list_init[-1])
9f4c114646ad29c50d6f31b6f8693f2cf5f9e417
jxvo/holbertonschool-higher_level_programming
/0x07-python-test_driven_development/2-matrix_divided.py
900
3.6875
4
#!/usr/bin/python3 def matrix_divided(matrix, div): """all elements of matrix (list of lists) are divided by div""" __long_error = "matrix must be a matrix (list of lists) of integers/floats" if len(matrix) < 1: raise TypeError(__long_error) if not isinstance(div, (float, int)): raise ...
4ee85ed30b2a6ef8718fa9ae665a4b970f8401de
jxvo/holbertonschool-higher_level_programming
/0x0F-python-object_relational_mapping/relationship_state.py
741
3.53125
4
#!/usr/bin/python3 """Module for State class""" from sqlalchemy import Column, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship Base = declarative_base() class State(Base): """A U.S. state stored in a database Attributes: cities (List[C...
971462380281501f02852126640635fc659a79aa
jxvo/holbertonschool-higher_level_programming
/0x0A-python-inheritance/101-add_attribute.py~
204
3.5
4
#!/usr/bin/python3 """Advanced Task 13""" def add_attribute(obj, attr, value): if isinstance(obj, type): setattr(obj, attr, value) else: raise TypeError("can't add new attribute")
7a53b991ed0f8ed2c37e1844d9d85ac45507f463
jxvo/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/1-search_replace.py
135
4.125
4
#!/usr/bin/python3 def search_replace(my_list, search, replace): return list(replace if search is num else num for num in my_list)
e070b77ccd02b5ca594ae2eeb49a9d96039e138b
jxvo/holbertonschool-higher_level_programming
/0x0C-python-almost_a_circle/models/base.py~
438
3.71875
4
#!/usr/bin/python3 """Base model""" import json import os.path import turtle class Base: """Base class contains methods and id for all data models""" __nb_objects = 0 def __init__(self, id=None): """Initialize an instance of Base id: set to total number of objects created if not provided ...
39c7e7c415bdd87436e46e1180b7305c49797716
NadaIhabAhmed/BigData
/support.py
5,356
3.609375
4
def SupportCount(arry_x,mim): count_arry=[] cou=0 for x in arry_x : if x not in (item[0] for item in count_arry): cou=arry_x.count(x) Support=cou/len(arry_x) if(Support>=mim): E=(x,Support) count_arry.append(E) return count_arry...
82dd3b338d45c319c67e3141a2e77bd006eaa76d
tjrobinson/LeoPython
/game-test.py
183
3.71875
4
player = "Pv" score = 0 scorearned = 0 something = True choice = input("what is 23x3") answer = "69" if something: scorearned = scorearned+1 print("+1 point") choice == answer
3b6559c4f2511789a65a458111ba32103cf340a6
tjrobinson/LeoPython
/codes.py
2,373
4.21875
4
for x in range(0,2): userchoice = input("Do you want to encrypt or decrypt?") userchoice = userchoice.lower() if userchoice == "encrypt": Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ" StringToEncrypt = input("Please enter a message to encrypt: ") StringToEncrypt =...
c98df6385aff876909090809922dae44f14f05f6
tjrobinson/LeoPython
/pygamezero/food.py
920
3.84375
4
import time import random leoeaten = 0 daddyeaten = 0 mummyeaten = 0 minutes = random.randint(0,5) if minutes != 0: if minutes > 1: print("They have just over", minutes, "minutes!") else: print("They have just over", minutes, "minute!") for x in range(minutes): if minutes != 0: def...
44d05ed22e742656562ce9179d63dee9cc2d8980
redjax/practice-python-exercises
/06-string-lists.py
567
4.375
4
""" Ask the user for a string and print out whether this string is a palindrome or not. (A palindrome is a string that reads the same forwards and backwards.) """ test = [0, 1, 2, 3, 4, 5] # print(test[::-1]) word_input = input("Enter a word, we'll tell you if it's a palindrome: ") def reverse_word(word): reve...
654c701225cb85fa87bbe93e2d25bbcf8f6a6554
WillRosen/EducationalRoboticArm
/ERA-Python/ERA/ERA/Example_IK_Keyboard.py
4,882
3.8125
4
import pygame import ERA #This code will allow the user to use the Inverse Kinematic controls, #but using the computer's keyboard #These values will store the values we want to send to the robotic arm xVal=0 yVal=100 zVal=100 gripVal=90 #These values are used to change the values above xChanger=0 yCha...
5db51eba70afd52e05207809ac0a3e5cbf454306
Deniska10K/stepik
/6.3-string_data_type/7.are_we_resting.py
706
4.0625
4
""" Напишите программу, которая считывает одну строку, после чего выводит «YES», если в введённой строке есть подстрока «суббота» или «воскресенье», и «NO» в противном случае. Формат входных данных На вход программе подается одна строка. Формат выходных данных Программа должна вывести текст в соответствии с условием ...
4ec9a5d7104332c729e155cfad8949baed4f686b
Deniska10K/stepik
/4.3-nested_and_cascading_conditions/4.number_of_days.py
895
3.796875
4
""" Дан порядковый номер месяца(1,2,…, 12). Напишите программу, которая выводит на экран количество дней в этом месяце. Принять, что год является невисокосным. Примечание. Постарайтесь написать программу, так чтобы в ней было не более трех условий. Формат входных данных На вход программе подаётся одно целое число – п...
d1a6dcf4f6b6600117789e857ad84636cb1788e6
Deniska10K/stepik
/2.2-print_and_input_commands/4.star_triangle.py
216
4.125
4
""" Напишите программу, которая выводит указанный треугольник, состоящий из звездочек (*). """ print('\n'.join(['*' * i for i in range(1, 8)]))
abde6bffef26afe110d05c19e45f8a4b34b8eb8f
Deniska10K/stepik
/4.3-nested_and_cascading_conditions/5.weighing_ceremony.py
1,007
4.34375
4
""" Известен вес боксера-любителя (целое число). Известно, что вес таков, что боксер может быть отнесён к одной из трех весовых категорий: Легкий вес – до 60 кг; Первый полусредний вес – до 64 кг; Полусредний вес – до 69 кг. Напишите программу, определяющую, в какой категории будет выступать данный боксер...
ec5e93dd759250bef6aa51d6e7cb1d855ac7cd3c
Deniska10K/stepik
/4.2-logical_operations/3.accessory_3.py
621
4.21875
4
""" Напишите программу, которая принимает целое число x и определяет, принадлежит ли данное число указанным промежуткам. Формат входных данных На вход программе подаётся целое число x. Формат выходных данных Программа должна вывести текст в соответствии с условием задачи. """ n = int(input()) print("Принадлежит" if ...
984fc34aa01a3ea9ed8cbdd3d8b44d19521b64c2
Deniska10K/stepik
/4.2-logical_operations/4.beautiful_number.py
869
4.0625
4
""" Назовем число красивым, если оно является четырехзначным и делится нацело на 7 или на 17. Напишите программу, определяющую, является ли введённое число красивым. Программа должна вывести «YES», если число является красивым, или «NO» в противном случае. Формат входных данных На вход программе подаётся натуральное ч...
39baba3140cfc6610e60228f6383c2ad3f3e2b6d
Deniska10K/stepik
/6.2-math_module/4.trigonometric_expression.py
1,172
4.21875
4
""" Напишите программу, вычисляющую значение тригонометрического выражения sin(x) + cos(x) + tan(x)^2 по заданному числу градусов x. Формат входных данных На вход программе подается одно вещественное число x измеряемое в градусах. Формат выходных данных Программа должна вывести одно число – значение тригонометрическо...
52b709291cc74e7102018d71c409c4c2c0c104df
Deniska10K/stepik
/6.2-math_module/5.floor_and_ceiling.py
653
4.34375
4
""" Напишите программу, вычисляющую значение ⌈x⌉ и ⌊x⌋ по заданному вещественному числу x. Формат входных данных На вход программе подается одно вещественное число xxx. Формат выходных данных Программа должна вывести одно число – значение указанного выражения. Примечание. ⌈x⌉ – потолок числа, ⌊x⌋ – пол числа. """ f...
44d1a4c1b852cf467408fc42ed5c155bfb5439e9
Deniska10K/stepik
/6.1-numeric_data_types_int_float/3.reverse_number.py
877
4.375
4
""" Напишите программу, которая считывает с клавиатуры одно число и выводит обратное ему. Если при этом введённое с клавиатуры число – ноль, то вывести «Обратного числа не существует» (без кавычек). Формат входных данных На вход программе подается одно действительное число. Формат выходных данных Программа должна выв...
510de01b1b80cc1684faaf2441dd5154bdd52b7c
zaydalameddine/Breast-Cancer-Classifier
/breastCancerClassifier.py
1,959
4.125
4
# importing a binary database from sklearn from sklearn.datasets import load_breast_cancer # importing the splitting function from sklearn.model_selection import train_test_split # importing the KNeighborsClassifier from sklearn.neighbors import KNeighborsClassifier import matplotlib.pyplot as plt # loading the databs...
b0a6d7b51978c4ed6691bc4542e63d63f90fc36a
mirandaday16/intent_chatbot
/formatting.py
301
4.25
4
# Capitalizes the first letter of every word in a string, e.g. for city names # Parameters: a place name (string) entered by the user def cap_first_letters(phrase): phrase_list = [word[0].upper() + word[1:] for word in phrase.split()] cap_phrase = " ".join(phrase_list) return cap_phrase
5bca5df3940cc80dedce54f7c34a1474a5720e3a
yojiyama7/python
/tutorial/str_list/str_join_tutorial.py
234
3.890625
4
words = ["place", "And", "pop", "TEXT", "TokeN", "ok", "jacK"] changed_words = [] for i, word in enumerate(words): changed_words.append(word.lower() if i % 2 else word.upper()) print(changed_words) print("".join(changed_words))
c3374f3b0952a7c34956878988485b9bb066ea0b
yojiyama7/python
/tutorial/popular/fizz_buzz.py
250
3.78125
4
for i in range(1, 101): if i % 15 == 0: print("FizzBuzz") elif i % 5 == 0: print("Buzz") elif i % 3 == 0: print("Fizz") else: print(i) # for i in range(100):print(i%3//2*"Fizz"+i%5//4*"Buzz"or-~i)
36ae8cdfa717928ca63d12bf3eb62312d89aae2a
yojiyama7/python
/tutorial/statement/with_tutorial.py
219
3.5625
4
with open("with_tutorial_country.txt", "w", encoding="utf-8") as f: # "w" は write の意 f.write("Japan China America England") with open("with_tutorial_country.txt", "r", encoding="utf-8") as f: print(f.read())
0a2fb74e0a829dd0d4e3fae7653b34aafbe19f5f
ThalesRod/jogo_do_welho
/jogo_da_velha.py
25,512
3.546875
4
import os def criaMatriz(matriz): for i in range(0,len(matriz)): if i%2==0: for c in range(0,11): if c==3 or c==7: matriz[i][c]='|' #switch(i) elif i==0: if c==1: matriz[i][c...
8a402737c9cdbd51387f112e9ea710356c8f29b3
VoKerrig/Study
/lesson_003/07_wall.py
941
3.625
4
# -*- coding: utf-8 -*- # (цикл for) import simple_draw as sd # Нарисовать стену из кирпичей. Размер кирпича - 100х50 # Использовать вложенные циклы for def horizon_line(): space = 0 for step in range(0, 1000, 50): space += step start = sd.get_point(0, 50 + step) end = sd.get_point(10...
983b00b28d296dbf180fdcc799ef3d3918eb0b57
Devanshi670/CS160
/05_Anagrams/perm.py
920
3.734375
4
import timeit import time class Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[len(self.items) - ...
b5aaf838216d9d85d43728e3d09ebf425cd277ce
imaimon1/algorithms-and-data-structures
/bucket_sort.py
457
3.53125
4
def bucket_sort(list,min,max): num_buckets=len(list) buckets = range( 0, num_buckets+1) delta = float(max-min)/float(num_buckets) out = [] for bucket in range(0,num_buckets+1): buckets[bucket] = [] for i in list: buckets[int((i-min)/delta)-1].append(i) for bucket in buckets: bucket.sort() for...
0e40f4e327a60970a56517bf0d98849997127b40
SergeevPG/CaesarCipherV2-master
/caesar.py
3,023
3.859375
4
def test_input_data(key_word, alphabet, key): if len(key_word) != len(set(key_word)): print("::: ERROR #2 :::\nLetters Into Key Word Must Be Unique\n::: ERROR #2 :::") return 1 elif len(key_word) < 2 or len(key_word) > len(alphabet): print(f"::: ERROR #3 :::\nLength Key Word Must Be [2,{...
f54dcb88c1a191ff3dbbdde9c59a6c1ad7e97293
MLBott/python-fundamentals-student
/permutation through AZ by index/permutation_through_AZ_by_index.py
413
3.859375
4
the_input = ['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'] def sample_swe_AZ_permutation(the_input): target_letter = 'PP' for item in the_input: print(the_input.index(item)) if target_letter not in the_input: print('Oh Well...') ...
adc452c82b5e6a0346987e640bcd8364578e0ac6
MLBott/python-fundamentals-student
/A1/243 assignment 1 Michael Bottom.py
1,909
4.125
4
""" Author: Michael Bottom Date: 1/14/2019 """ import math def lowestNumListSum(firstList, secondList): """ This function accepts two lists of numbers and returns the sum of the lowest numbers from each list. """ firstList.sort() secondList.sort() sumTwoLowest = firstList[0] + secondList...
0aa2bf8ce514de953eb93d59c82fd0a1025c3a47
MLBott/python-fundamentals-student
/find missing number 1 to 10/find_missing_number_1to10.py
257
3.9375
4
def find_missing_number(list_numbers): counter = 1 for i in list_numbers: if i == counter: counter += 1 else: return (i - 1) the_list = [1, 2, 3, 4, 5, 7, 8, 9, 10] print(find_missing_number(the_list))
908e58aecc7023605cb0698a99559ff63f1892b5
shafinnazmul/hackerrank-problem-solving
/minion_games.py
1,489
3.5625
4
def all_vowels(): return "AEIOU" def count_substr_by_pos(pos, length): return length - pos def sum_cum_count_substr(positions, length): cum_sum = 0 for pos in positions: cum_sum += count_substr_by_pos(pos, length) return cum_sum def get_vowel_positions(mystr): my_vowel_positions = ...
1c440c4d93f20aef2c33bd51c7f80b5d8a9612eb
wduffell/cmpt120duffell
/guessing-game.py
1,018
4.09375
4
# Introduction to Programming # Lab Assignment #5 # Author: Willow Duffell # Date: 2/26 #Define a variable to hold the name of an animal (this is the answer) def main(): guessedright = False answer = "pig" animalguess = input("I'm thinking of an animal... Try to guess it: ") animalguess = animalguess.low...
17b0ec0ed3f17ef53506c01582e284ef219984f6
jaideeprana/fizz-buzz-in-python
/fizzbuzz.py
846
3.71875
4
class FizzBuzz: def generate(self, number): result = [] for i in range(1, number + 1): result.append(self.__fizz_buzz_or_number(i)) return result def __fizz_buzz_or_number(self, number): if self.__is_multiple_of_three_and_five(number): return "FizzBuzz" ...
cd89bf2b39ba8673e0757503d3b0619bcc62b825
deepchem/deepchem
/deepchem/models/callbacks.py
4,414
3.5
4
""" Callback functions that can be invoked while fitting a KerasModel. """ import sys class ValidationCallback(object): """Performs validation while training a KerasModel. This is a callback that can be passed to fit(). It periodically computes a set of metrics over a validation set, writes them to a fi...
e4492f7ace23385df321ab2bf6fc9ea2659eb21c
UbiOps/base-connector
/ubiops_connector/utilities.py
1,297
3.5625
4
import json import os from .exceptions import ConnectorError def get_variable(variable_name, default_value=None): """ Get the environment variable with the given name. If the variable is not set and a default value is passed, use this value. :param str variable_name: the name of the variable :pa...
7f6226d20ad459b595cb291ae7a63dd3983b54ab
kratosxu/Crossin_study_publish
/字数统计.py
204
3.65625
4
import re article = open ('words.txt', 'r', encoding = 'utf-8') data = article.read() article.close() word_len = len(re.findall(r'\b[A-z]+\b', data)) print ('There are %i words in words.txt.' % word_len)
bc4d6a3910c4d52b3ac2141ae07884a8da47cd42
AdelMandour/python
/assignments/assign1/lab1_1.py
645
3.953125
4
def vowelsRemover(word): vowels=('a','e','i','o','u','A','E','I','O','U'); string=""; for i in word: if(not (i in vowels)): string+=i; return string; def vowelsRemoverlist(arr): vowels=('a','e','i','o','u','A','E','I','O','U'); string=""; unvowels=[]; for word in arr...
993fc1680d80170a6ddbc8464baae21aa1215c8d
sritar99/Ds-n-algos
/queue.py
820
4.21875
4
#Implementing queue's in python from exc import Empty class ArrayQueue: def __init__(self): self._data=[] self._front=0 self._rear=0 def length(self): return len(self._data) def is_empty(self): return self._front and self._rear == 0 def enque(self,n): self._data.append(n) self._rear+=1 def deque(...
19b24a12cac06e85860c5a8f9f8f9677c9403371
jbshep/conversational-python-legacy
/exercises/ch2/p2.3.py
184
4.15625
4
num = float(input("Enter a real number: ")) if num < 0.0: print("%.2 is negative." % num) else: print("The number is 0.0.") elif num > 0.0: print("%.2 is positive." % num)
9eb9724cedcadd52f293fe20ee4fff86a454b25d
louis172000/PYTHON_2
/TP12/Ex4.py
432
3.65625
4
def listSum(L): if len(L) == 0: return 0 elif len(L) == 1: return L[0] else: n = L[0]+L[len(L)-1] # additionne le dernier et le premier L[0] = n # remplace le preier par l'addition des deux del L[len(L)-1] # supprime le dernier ...
511e2e587855bf416ae901434474e77075995742
louis172000/PYTHON_2
/TP12/Ex 3.py
216
3.53125
4
def pow(nb, puiss): if puiss == 1: return nb elif puiss == 0: return 1 return nb*(pow(nb, puiss-1)) print(pow(42, 0)) # 1 print(pow(1, 10)) # 1 print(pow(2, 5)) # 32 print(pow(7, 2)) # 49