blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
d1c014d0af98af413e96c2c62526bdb693e73d81
zanariah8/Starting_Out_with_Python
/chapter_05/q10.py
274
4.1875
4
# feet to inches def main(): number_feet = float(input("Enter a number of feet: ")) feet_to_inches(number_feet) def feet_to_inches(feet): inches = feet * 12 print(feet, "feet equals to", inches, "inches") return inches # call the main function main()
ca09e1f9fe10eb9cffd580b142690209b586143e
BaiKongQue/Rent-Calculator-Square-Footage
/RentCalculator.py
9,040
3.953125
4
class RentCalculator: """ API to interact and calculate how much each person pays what for rent based on the square footage of the rooms. """ def __init__(self): self._data = {} return # PRIVATE # def _clear(self): """ Reset and clear the current data being h...
a15f048d079f9fcbcd338e461dd40411256880c1
partho-maple/coding-interview-gym
/leetcode.com/python/114_Flatten_Binary_Tree_to_Linked_List.py
891
3.84375
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def flatten(self, root): """ :type root: TreeNode :rtype: None Do not return anything, modify roo...
9b2b644ef8a8e1d1eca1ecbbdc8830073f145880
eronekogin/leetcode
/2020/binary_tree_paths.py
848
3.921875
4
""" https://leetcode.com/problems/binary-tree-paths/ """ from test_helper import TreeNode from typing import List class Solution: def binaryTreePaths(self, root: TreeNode) -> List[str]: rslt = [] def calc_path(currNode: TreeNode, path: List[str]): if not currNode: re...
9d0d6db38df5fc6d2b5e4a898091236ab61eb669
ketannakum/Dogs-Image-Classify
/home/get_pet_labels.py
6,553
3.546875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # */AIPND-revision/intropyproject-classify-pet-images/get_pet_labels.py # # PROGRAMMER: KETAN N. # DATE CREATED: MAY 19th, 2021 # REVISED DATE: MAY 31st, 2021 # PURPOSE:...
e2a7cb38c89aab3a10c55759545cb9dd427fb5e0
Khai-Ngo/Steno
/steno/image.py
2,688
3.546875
4
import math from steno import database as db import cv2 """ This module helps us in performing image stenography on all formats of image files. link - https://tinyurl.com/ya95agjj """ def encrypt_image(img_path: str, message: str, new_path: str): # load the image img = cv2.imread(img_path) # break the i...
0817974274689e26d51e65825bbeefccba9db3a0
skiman93/python_scripting_-l1-assignments
/python_scripting_-l1-assignments/ex2.py
548
3.765625
4
import sys def isWhiteLine(f): file = open(f) array = file.readlines() # Checks to see if the file only contains whitespace if all('' == s or s.isspace() for s in array): return True # If not only white space, non-blank lines are printed to the cmd prompt for i in range(len(array)): if not all...
4e058d7439afa7010d4873c2dbb8e998e9975c90
Hayden-Bailey/Sandbox
/password_entry.py
215
4
4
""" Hayden Bailey """ password = input('Input password (min 7 characters): ') while len(password) <= 6: password = input('Incorrect length. Input password: ') for char in range(len(password)): print('*', end='')
21830c1e8a9d7254d0e8f1b67f319f3cb797228e
Alexrg/Python_challenges
/mini_projects/memory_game.py
4,863
4.25
4
import simplegui import random """ Memory is a card game in which the player deals out a set of cards face down. In Memory, a turn (or a move) consists of the player flipping over two cards. If they match, the player leaves them face up. If they don't match, the player flips the cards back face down. The goal of Memor...
88fccb796920e532aa56485a08c44abd7f2b887a
timeaut777/repo
/venv/калории.py
1,095
3.75
4
a = int(input('Введите Ваш рост в см: ')) b = int(input('Введите Ваш вес в кг: ')) bel = 2 yg = 2 zh = 1 bel_k = 4 yg_k = 4 zh_k = 9 imt = b / (a/100)**2 print('Ваш индекс массы тела = ', imt ) if imt <= 16: print('Выраженный дефицит массы тела') elif 18.5 > imt > 16: print('Недостаточная (дефицит) масса те...
1e1d37b22de10e5d539d8479a487c5d2e0a867d6
3gx/python-mix
/pmatch/tree.py
333
3.734375
4
from typing import List, Union from dataclasses import dataclass Tree = Union["Leaf", "Node"] @dataclass class Leaf: pass @dataclass class Node: value: int left: Tree right: Tree tree = Node( 32, Node(34, Leaf(), Node(33, Leaf(), Leaf())), Node(44, Node(77, Leaf(), Leaf()), Leaf()), )...
879a4cf28f0c767ee945e03ece26da9edd1dae9d
olcostafilipe/cracking_the_coding
/chapter01/question_06.py
943
4.40625
4
""" Question 06: String comprehension Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2blc5a3. If the "compressed" string would not become smaller than the original string, your method should return the original string. ""...
1a6d60038b2a220c0b033a105da41b3653df3bd4
Rafapearl/blueTurma2B
/Exercicios_aula6/Exercicio2_aula6.py
407
4.1875
4
## 2 - Faça um programa, com uma função que necessite de um argumento. A função retorna o valor de caractere # ‘P’, se seu argumento for positivo, ‘N’, se seu argumento for negativo e ‘0’ se for 0. '''def posinega(x=0): x = int(input("Digite aqui o valor desajado: ")) if x >0: print("P") elif x<0:...
4407d44d5de54e48c5781d66cbb3171b2cb91fc9
shifalik/practice
/shifali/test36.py
670
4.03125
4
''' Created on Jan 30, 2018 @author: shifa ''' #generator #function that produces or yields a sequence of values #using yield method #when generator function is called returns a generator #object without even beginning execution of the function #below generates an iterator for all FIbonacci numbers import sys de...
44866e08babd837f19c12b119533d71e1d3ff836
Orcha02/AirBnB_clone
/tests/test_models/test_user.py
4,101
3.578125
4
#!/usr/bin/python3 """New testing module""" import pep8 import unittest from models.base_model import BaseModel from models.user import User class TestMyUser(unittest.TestCase): """Class TestMyUser to test class User""" def setUp(self): """setting up each test""" self.my_user = User() ...
21d42168486cbf035a37b70f437b447e6ef7fec9
ccamp032/CS183-UNIX-System-Administration
/hw1/hw1.py
384
3.65625
4
#! /usr/bin/python import sys # import sys to use sys.argv # sys.argv: a list of strings which the command line is used to execute the script # The files is counted as a argument # Open and read the arguments ( filenames ) and print the filenames contents for i in range(1,len(sys.argv)): with open(sys.argv[i],...
08e453872be8f3244bbdf82a87e02a59c8551d68
QI1002/exampool
/Cracking_the_Coding_Interview/5-6.py
264
4.09375
4
def swap(a,b): a = a ^ b b = a ^ b a = a ^ b def swapBits(a): odd = a & 0xaaaaaaaa even = a & 0x55555555 odd >>= 1 even <<= 1 return (odd | even) a = 0x5aa5 print("{0} swap bits = {1}".format(bin(a), bin(swapBits(a))))
051218b9a3ed86b64ee12b7119375d9f92dd3de0
the-brainiac/coursera-assignments
/pythonDataAnalysis/isp_csvfiles_template.py
3,854
4.5625
5
""" Project for Week 3 of "Python Data Analysis". Read and write CSV files using a dictionary of dictionaries. Be sure to read the project description page for further information about the expected behavior of the program. """ import csv def read_csv_fieldnames(filename, separator, quote): """ Inputs: ...
fbf75820435fdec1bb02cd46468ab8dc6d98b8ce
shanavas786/coding-fu
/adventofcode/2019/python/day01.py
1,378
4.3125
4
#!/usr/bin/env python3 # Fuel required to launch a given module is based on its mass. Specifically, # to find the fuel required for a module, take its mass, divide by three, round down, # and subtract 2. # # For example: # # For a mass of 12, divide by 3 and round down to get 4, then subtract 2 to get 2. # For a mass ...
5efebdaf81205510a53b146fef7549d2b768d2fc
Yorali/Python-Beginner-Practice
/integers_and_floats.py
1,291
4.25
4
num = 7 num2 = 3.14 # 1.) Show data type of argument print(type(num)) print(type(num2)) # Arithmetic Operators: # Addition: 5 + 4 # Subtraction: 5 - 4 # Multiplication: 5 * 4 # Division: 5 / 4 # Floor division: 5 // 4 Prevents decimal drop in older Python # Exponent: 5 ** 4 # Modulu...
27c2bf3e73c2a52d924af511796bed2fe77cb54e
mochapup/LPTHW
/ex5.py
583
3.921875
4
my_name = 'Charles A. M.' my_age = 24 #Real age. my_height = 74 #inches my_weight = 184 #lbs my_eyes = 'Green' my_teeth = 'White' my_hair = 'Brown' print(f"Let's talk about {my_name}.") print(f"He's {my_height} inches tall.") print(f"He's {my_weight} pounds heavy.") print("Actually that's not too heavy.") print(f"He...
1b9cf0054a9ff9d367d8301a0314b541672f8d01
Elena-May/MIT-Problem-Sets
/ps1/ProblemSet1a.py
1,215
4.1875
4
#how many months will it take to save for your dream house portion_down_payment = 0.25 current_savings = 0 r = 0.04 num_of_months = 0 annual_salary = float(input('Enter your annual salary: ')) portion_saved = float(input('Enter the percent of you salary to save, as a decimal: ')) total_cost = float(input('Enter the c...
0be7e476c5c89b8bad880009afe548401fef3447
bthalpin/user-input
/user_input.py
1,900
4.5
4
def check_input_include(input_options, input_text = 'Please enter one of the following options', input_error = 'That is not a valid entry. ', display=True): ''' This function asks the user for input and checks if the input entered is valid. You must enter a list of the valid input_options. You can then ...
f782fb681a6b1ee08693a3ef79cb60634bb0692f
zalameedi/Algorithms
/Python/sequentialsearch.py
737
3.8125
4
#Sequential search implementation import sys import os main_L = [] i=0 for i in range(0,1000): main_L.append(i) def sequentialSearch(L, x): found = False index = 0 ls_size = len(L) while (index < ls_size): try: if(L[index] == x): found = True re...
62f3a3686e3027ba4a26ad4d0160d6f16e031122
Govorun11/beetroot
/lesson24/task1.py
1,244
3.953125
4
class Node: def __init__(self, data, next_node): self.data = data self.next_node = next_node class LinkedList: def __init__(self, root=None): self.root = root self.size = 0 def add(self, data): new_node = Node(data, self.root) self.root = new_node ...
6c4c4c8ad876244278778e128f990e5ba6b6477b
RishikaMachina/Linked-List-1
/Problem_3.py
1,250
3.640625
4
# Runs on leetcode # Runtime - O(n) # Memory - O(1) class Solution: def detectCycle(self, head: ListNode) -> ListNode: if not head: return None slow = fast = head slow = slow.next try: fast = fast.next.next except AttributeError: ...
0f54ee3f227451c5f8503422aa249e0e163040cc
nandit123/Competitive-Programming-Practice
/Python Practice/code2.py
252
3.71875
4
x = 50 def func(): global x print('x is', x) x = 2 print('Changed global x to', x) func() print('Value of x is', x) list1 = [1,2,3,4,5] list2 = [2*i for i in list1 if i >= 3] print('list 2 is',list2) x=list2.pop() print(x) print(list2)
cfe138fc60f7c73b5c10c8ab1a20b74155a3be20
pobalasumanth/data-cleaning-and-exploration
/CODE/DATA EXPLORATION/anagram.py
1,865
3.890625
4
# -*- coding: utf-8 -*- """ Created on Sun Feb 3 14:00:28 2019 @author: suman """ # -*- coding: utf-8 -*- """ Created on Wed Jan 30 21:45:05 2019 @author: sumanth """ def init_words(fname): words = {} with open(fname) as f: for line in f.readlines(): word = line.strip() words[word] = 1 ...
9004d52c920e81938bdbc5cc90ec5c6efd16c9fe
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/difference-of-squares/50e52c55ce0147e9876735d27a1984cf.py
200
3.9375
4
def difference(n): return square_of_sum(n) - sum_of_squares(n) def square_of_sum(n): return sum(d for d in range(1, n+1))**2 def sum_of_squares(n): return sum(d**2 for d in range(1, n+1))
89d8720bdb51a102396a67f29996068903fad31b
alex3kv/PythonAlgorithms
/Lesson8/Task2.py
1,589
3.71875
4
''' Доработать алгоритм Дейкстры (рассматривался на уроке), чтобы он дополнительно возвращал список вершин, которые необходимо обойти. ''' def dijkstra(graph, start): lenght = len(graph) is_visited = [False] * lenght cost = { i: [float("inf"),[]] for i in range(lenght)} parent = [-1] * lenght cost...
e91d986155757e0767bdc9318ead3ee9f84c808e
cem271/cem-python
/Standalone/primes.py
557
4.03125
4
# Really basic function that figures out how many prime numbers there are between any two numbers. def prime(y,z): #y = 0 first_y = y first_z = z check = True primes = [] while check: x = 2 y = int((y ** 0.5)+1) prime = True while x < y: if y % x == 0: prime = False break x+=1 if y == 0 o...
44b6417c6d55ad49d89653622dcc4005e776bfdb
ethanmatthews/KCC-Intro-Mon-Night
/matthews-exercise6.py
904
4.0625
4
from helpers import * import random def createList(length): numList = [] for i in range(length): ranNum = random.randint(0,100) numList.append(ranNum) numList.sort() return numList greaterThanList = [] def largerTest(listNum, givenNum): if listNum > givenNum: greaterTha...
a8a3a26880518b640bfcf1b40cc808494a7aa45f
nikhilcusc/LearningRepo
/LCP/P703/direct.py
118
3.765625
4
def f1(nums,val): nums.append(val) nums.sort(reverse=True) print(nums) lf1 = [4,5,8,2] print(f1(lf1,3))
4ef0bfbcb5178fc6b2c26906ccb8ab3429a0fd26
siowyisheng/rl-learning
/my-rl/environments/tictactoe_env.py
2,050
3.890625
4
import random class TicTacToeEnv: """ A game of tic tac toe. """ initial_state = (0, 0, 0, 0, 0, 0, 0, 0, 0) def __init__(self): self.state = self.initial_state @property def action_space(self): return [i for i, x in enumerate(self.state) if x == 0] def step(self, s...
1bf3e65359ff94e80e81c6b4762f6c6ea1ae8d5d
thomasmari/CZK_project
/Python/norm.py
770
3.53125
4
import matplotlib.pyplot as plt from array import array import math def read_file(filename): file = open(filename, "r") a = [] for line in file: a.append(str(line).rstrip()) return a def read_float(filename): file = open(filename, "r") a = [] for line in file: a.append(float(line)) return a def diff_arr...
0ba5a4ac87bcac05537ffb1bac6cab634b0bd9ec
jay6413682/Leetcode
/Jump_Game_II_45.py
4,319
3.578125
4
class Solution: def maxSubArray(self, nums: List[int]) -> int: """ 暴力法: https://leetcode-cn.com/problems/maximum-subarray/solution/zui-da-zi-xu-he-cshi-xian-si-chong-jie-fa-bao-li-f/ """ i = 0 max_sum = nums[0] while i < len(nums): j = i while j < len(nums): ...
81d77b625b0003698aaa8e9c1a1e2c963cafffe5
soizensun/python-lab-solution
/premid_14.py
755
3.78125
4
count = 0 s = '' target = 3434534 while True: one = int(input("")) two = int(input("")) if one <= 0 or one > 6 or two <= 0 or two > 6: print("ERROR") else: count += 1 # print(s) summ = one + two if summ == target: s = 'W' if summ == 4 or summ == 5 or summ == 6...
b4a4f14aa860a52d0f8e8e47910a5a29a2521341
phillikus/100-days-of-code
/day47/ransom_note.py
704
3.609375
4
#!/bin/python3 def check_magazine(magazine, note): magazine_items = {} for i in range(len(magazine)): item = magazine[i] if item in magazine_items: magazine_items[item] += 1 else: magazine_items[item] = 1 for i in range(len(note)): item = note[i] ...
bc0123797d2e332a6c8ec67c946f7340d8b5efa6
phaniallamsetty/Hadoop_Mincemeat
/mathstats.py
1,150
3.5625
4
#importing mincemeat and sys import mincemeat import sys #Accepting the file name as a command line argument and reading the data from it inp_file = sys.argv[1] file = open(inp_file,'r') data = list(file) file.close() #Defining a counter to count the number of numbers in the file counter = 0 # The data source can b...
a63ddebe8b6bce628f4f45807fe5140566875232
dryprojects/CodeSnippet
/sort_algorithms/bubble_sort.py
439
4.0625
4
#!usr/bin/env python #-*- coding:utf-8 -*- """ @author: nico @file: bubble_sort.py @time: 2018/09/27 """ def bubble_sort(l:list): for cursor1 in range(len(l)): for cursor2 in range(cursor1 + 1, len(l)): if l[cursor1] > l[cursor2]: l[cursor1], l[cursor2] = l[...
cb110cdb71af8de972cb3ee7818665f732942155
Davitkhachikyan/HTI-1-Practical-Group-2-Davit-Khachikyan
/homework_1/age.py
128
3.828125
4
year = input("Enter year: ") if year[-2:] == "00": age = int(year) // 100 else: age = int(year) // 100 + 1 print(age)
3a77e140c9666dd2e8416eba37ee81ae59f548c5
Mahendrarrao/Python-sample-programs
/week311.py
148
3.9375
4
fname = input("enter filename") fhand = open(fname) for line in fhand: line = line.rstrip() upper_case = line.upper() print(upper_case)
d39e7556c32ce74cfec8242ef0c676132e123a06
csw279/new
/practice code/format.py
385
3.84375
4
'''print('%2d-%02d' % (3, 1)) print('%2d'%(3)) print('%.2f' % 3.1415926)''' # % 的格式化用法 a=input('请输入姓名:') b=eval(input('请输入身高:')) print('我的名字叫做%s,我身高%d'%(a,b)) #.format()的用法,他会传入参数依次替换占位符{} a=input('请输入姓名:') b=eval(input('请输入身高:')) print('我的名字叫{},我身高{}'.format(a,b))
629f0e4340a047b195cbbc4a64e957963d6090f6
guillox/Practica_python
/2014/tp3/tp3ej10c.py
653
3.78125
4
__author__ = 'guillermo' """idem anterior pero de otra forma""" import math class Punto: # Clase punto def __init__(self, x, y): self.y = y self.x = x def reiniciar(self): # metodo reiniciar self.mover(0, 0) def calcular_distancia(self, otro_punto): # metodo reiniciar ...
37b0554e47a1740a2d42db133ccba5b380938085
jordanpippen23/python_work
/matplotlib/examples/colormapnorms.py
2,223
3.9375
4
""" Colormap Normalization ====================== Objects that use colormaps by default linearly map the colors in the colormap from data values *vmin* to *vmax*. For example:: pcm = ax.pcolormesh(x, y, Z, vmin=-1., vmax=1., cmap='RdBu_r') will map the data in *Z* linearly from -1 to +1, so *Z=0* will give a co...
feb172c8a38e7019f3c4708c4d5200e2ebe546ef
yideng333/Code_Interview
/Code_interview/17.py
575
3.703125
4
''' 打印从1到最大的n位数 ''' def print_max_n(n): number = ['0' for i in range(n)] print_help(0, n, number) def print_help(begin, length, number): if begin == length: # print(number) print_with_nozero(number) return for i in range(10): number[begin] = str(i) print_help...
68aa1d2459a62219cebf03d79353dc11eb342ab6
YaraBader/python-applecation
/Ryans+Notes+Coding+Exercise+7+Print+Odds+up+to+20.py
267
3.859375
4
''' Print Odds up to 20 To solve this problem print out all off values from 1 up to 20 on separate lines ''' for i in range(1,21): # odd is when the modulus of 2 is equal to 1 # even is when the modulus of 2 is equal to 0 if i % 2 == 1: print(i)
9e149a45b62bd104095881ec6b7eb0ceac157f50
rkp872/Python
/3)Conditional/EmployeeWork.py
760
4.4375
4
# Ask user to enter age, sex ( M or F ), marital status ( Y or N ) and then using following rules print their place of service. # if employee is female, then she will work only in urban areas. # if employee is a male and age is in between 20 to 40 then he may work in anywhere # if employee is male and age is in ...
b81cffb288224be1cebd489adb825412c9482355
bashikan/python
/リスト.py
1,786
3.578125
4
#txt1 # x=[3,15,123] # print(x[1]) #txt2 # x=["3","ABCabc",12345,[10,20,"ABC"],333] # print(x[3][1]) #txt3 # x=[] #txt4 # x=[] # y=[225,13,50,1002,133,99] # x+=y # print(max(x),min(y)) #txt5 # x=[] # y=[225,13,50,1002,133,99] # x+=y # nx=sorted(x) # print(nx) #txt6 # x=[] # y=[225,13,50,1002,133,99] # x+=y # nx=so...
ef1504a9a7343c95682c956b9748be1d243f8cb9
turnip314/TurnipTex
/Parsing/Tokenizer.py
1,397
3.65625
4
class Tokenizer: def __init__(self, dfa): self.dfa = dfa def maximal_munch_scan(self, input_string): """ Uses the maximal munch algorithm to fetch a list of tokens whose lexeme satisfy the DFA :param input_string: String :return: List[Token] """ from Pars...
21e24232a83aae7f786819862a60239bede823ec
JefVerschuere/TikTakToe
/TicTac.py
5,465
3.828125
4
import random import sys def hasGameEnded(board) : #Checks the horizontal lines for X if board['top-L'] == 'X' and board['top-M'] == 'X' and board['top-R'] == 'X' : print("X was Won!!!!") return True if board['mid-L'] == 'X' and board['mid-M'] == 'X' and board['mid-R'] == '...
8959bf57a0fd94f508cc84fe44d7dc55ee35c018
lilyfromseattle/Lilys-Library
/lilyslibrary.py
2,461
4.125
4
booklist = [] shelflist = [] class Library(object): def __init__(self, library_name): self.name = library_name def print_all_books(self): for item in booklist: print item.title + " by " + item.author #Prints the title and author of all the books in the library def number_of_bo...
6ffeb94795f22e7b39bc9a3007e9afd638e24b97
983bot/pyneng
/18_db/task_18_3/create_db.py
753
3.578125
4
# -*- coding: utf-8 -*-import sqlite3 import sqlite3 import os dbfilename = 'dhcp_snooping.db' def connect_db(dbname): db_exists = os.path.exists(dbname) conn=sqlite3.connect(dbname) if db_exists: print(f'connecting to database {dbname}') print('-'*60) return conn else: w...
e9dd8cc4050b1723a7e13048159c9537b1511951
rezoanahmed/uri_solutions_python
/1116.py
219
3.59375
4
N = int(input()) for i in range(N): X,Y=list(map(int,input().split())) if(Y==0): print('divisao impossivel') elif(X==0): print(0.0) else: result = X/Y print('%.1f'%result)
964368c332d03d4b964eba5341fc8da443c99e01
alexandraback/datacollection
/solutions_1482494_0/Python/jgaten/b.py
1,893
3.5625
4
#!/usr/local/bin/python import sys def count_stars(levels): return sum(x[2] for x in levels) def complete_stage1(levels, stars): potentials = [] for i, level in enumerate(levels): if level[0] <= stars and level[2] == 0: potentials.append((i, level)) if potentials: print "c...
66bd324ce68ab79581699cad5c5ca6f8843f94fc
Code-Institute-Submissions/connect-4
/run.py
20,935
3.71875
4
from termcolor import colored, cprint from random import randint import time class Player: """ Player class, Creates player, sets player name, counter color, player type (Real or Computer) """ def __init__(self, name, counter_color, player_type): self.name = name self.color = coun...
1ac85f5b0ad8264357696807482a7aee56889454
lalit97/DSA
/Tree/Tree HR/que6.py
844
3.5
4
''' https://www.hackerearth.com/practice/data-structures/trees/binary-search-tree/practice-problems/algorithm/b-sequence-f919fc86/ ''' n = int(input()) lis = list(map(int, input().split())) max_item, max_index = 0, 0 for i in range(n): if lis[i] > max_item: max_item = lis[i] max_index = i increas...
962096f9e739e002cfe3b802e502a5d5109aa16c
xianjinseow92/Curriculum-Wk-1-12-
/Week 1/Day 1/day-1-materials/pair-demo.py
613
3.578125
4
from __future__ import print_function, division """ >>> pairs_for(['Andrea', 'Bob', 'Cassandra', 'Doug']) # [[('Bob', 'Cassandra'), ('Andrea', 'Doug')], # [('Andrea', 'Bob'), ('Cassandra', 'Doug')], # [('Andrea', 'Cassandra'), ('Bob', 'Doug')]] """ def pairs_for(names): n = len(names) assert n % 2 == 0 ...
23410120345c5649ef4641d5455876ca047437e9
Sergaebi/DS-and-A-class
/DataStructures/Queue_LinkedList.py
1,140
3.796875
4
class Node: def __init__(self, data, next_node): self.data = data self.next_node = next_node class QueueLinkedList: def __init__(self): self.first = None self.last = None self.__size = 0 def enqueue(self, data): node = Node(data, None) if self.las...
2bd36a5cf9687a0f1833b3b3017e0898defdfd58
guoylyy/uband-python-s1-july
/B21056/checkin10/karen-HW16-1.py
474
3.890625
4
#!/usr/bin/python #-*- coding: utf-8 -*- #@author:xxx import turtle def main(): #设置一个画面 windows=turtle.Screen() #设置背景 windows.bgcolor('pink') #生成黄色的乌龟 bran=turtle.Turtle()#后面的T一定要大写 bran.shape('turtle') bran.color('purple') #设置速度 bran.speed(1) for i in range(1,20): bran.forward(100) ...
47be3307c6da518d114c2a667dc4ebec2aabd432
prateek1998/Coding-Problems
/First Neural Network.py
1,254
3.640625
4
#created by prateek saini #check it in the link "https://stackabuse.com/creating-a-neural-network-from-scratch-in-python/" import math import numpy as np feature_set = np.array([[0,1,0],[0,0,1],[1,0,0],[1,1,0],[1,1,1]]) labels = np.array([[1,0,0,1,1]]) labels = labels.reshape(5,1) np.random.seed(42) weights...
446dbc4c05f023ad83b0320cea667fbc05342a31
gilgameshzzz/learn
/day6Python字典/day6-字典/dict/03-字段.py
4,277
4.1875
4
"""__author__ = 余婷""" """ 字典也是一种容器类型的数据类型(序列),存的数据是以键值对的形式出现的,字典中的元素全部都是键值对 字典是可变的(可是增删改),但是是无序的(不能使用下标) 键是唯一的 键值对: 键:值(key:value); 键值对中key是形式,值才是真正要存的内容 键:理论上可以是任何不可变的数据类型,但是实际开发的时候一般使用字符串作为key 值:可以是任意数据类型数据 """ # 1.声明一个字典 """a.创建一个字典变量""" dict1 = {} # 创建一个空的字典 print(type(dict1)) dict2 = {'a': 1, 'b': 'abc', 10: ...
cf76e0a73d4bf78dc609ed6dd67a6254a1586b89
coryskeers/pypy
/dbaccessor.py
2,139
3.5625
4
import sqlite3 import re class DBAccessor: def __init__(self): self.connect() self.phonemes = ['AA', 'AE', 'AH', 'AO', 'AW', 'AY', 'EH', 'ER', 'EY', 'IH', 'IY', 'OW', 'OY', 'UH', 'UW', 'B', 'D', 'G', 'K', 'P', 'T'...
22bddaead4e16d572f589bfbcd44fa06779ddc72
mothermary5951/videau
/dumpversion_hashmap.py
7,612
4.125
4
def new(num_buckets=256): # creates a new function with the potential for 256 (2 to the 7th) containers """Initializes a Map with the given number of buckets.""" # python uses 'map' instead of 'dictionary' aMap = [] ...
b390608f92c777a594257bcb8074fab0e64216da
famasya/projects
/Learn/fileio.py
157
3.53125
4
def Main(): f = open("file.txt","w") word = raw_input("insert any word : ") f.write(word) f.close() if __name__ == "__main__": Main()
5f3fef50a9bd2af96d5a1c5d2426ae504b77fdd0
huang-jingwei/Coding-Interview-Guide
/chap3/06.在二叉树中找到累加和为指定值的最长路径长度/06_pathSum.py
1,493
3.640625
4
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None import copy class Solution: def __init__(self): self.treePath = [] # 用来存放可行解集 def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]...
a7764519916971bbb75b7f728185d05ec3f4536b
dlsrks1218/python_study
/day5/book.py
1,286
4.03125
4
from typing import List, Any class Book: def __init__(self, title: str, authors: List[str], publisher: str, isbn: str, price: float) -> None: self.title = title # 호출자가 추후 리스트를 수정할 경우를 대비해 저자 리스트를 복사 self.authors = authors[:] self.publisher = publisher self.isbn = isbn ...
11bba9cb1f6ffcc205ad453f4e5cdd55a71b69fa
captainjack331089/Automate-Boring-Stuff-with-Python
/Python Programming/Projects/addBullets.py
1,532
4.4375
4
#coding: utf-8 #Adds Wikipedia bullet points to the start # of each line of text on the clipboard. """ When editing a Wikipedia article, you can create a bulleted list by putting each list item on its own line and placing a star in front. But say you have a really large list that you want to add bullet points to. You c...
afb1f2a470f0c147e5247592e35e81a7dcdd6034
firewebteam/main-repository
/J.Karasek/figury_vol2.py
1,321
3.84375
4
class Figury: def __init__(self, figure, x, y, color): self.figure = figure self.x = x self.y = y self.color = color print("Powstała figura:", self.figure) def figure_color(self): print("Ta figura ma kolor", self.color) def figure_area(self): ...
7aa04a7e703ecfcf320b6e93eb0545b8bd039473
caoxiang104/-offer
/53.py
1,570
3.796875
4
# -*- coding:utf-8 -*- """ 请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。 例如,字符串"+100","5e2","-123","3.1416"和"-1E-16"都 表示数值。 但是"12e","1a3.14","1.2.3","+-5"和"12e+4.3" 都不是。 """ class Solution: # s字符串 def isNumeric(self, s): # write code here\ index1 = 0 # "."判断指示 for i in range(len(s)): if ...
beaf5146bafaa1e04f593d5623e570271a141e98
eflipe/python-exercises
/udemy-py/variables_estaticas.py
518
3.734375
4
class MiClase: variable_clase = "Variable de claseee" def __init__(self, variable_instancia): self.variable_instancia = variable_instancia print(MiClase.variable_clase) # no funciona porque no se creo un objeto obj1 = MiClase("Varibale instancia desde objeto") MiClase.variable_instancia = "Modificand...
884c0cf5e9f2eaa1fa20b0f12a6a19387b0ae456
chn650/Rosalind
/Algorithmic_Heights/FIBO.py
232
3.671875
4
#Python 2.7.5 def FibonacciNumbers(n): f=[0]*(n+1) f[1] =1 for i in range(2,n+1): f[i] = f[i-1]+f[i-2] return f[n] n = int(raw_input("Positivive integer n: ")) print "F%s: " %(n), FibonacciNumbers(n)
9303638a6a4a32a196301728814277dde55d87ce
Edouard360/Halite-Python-RL
/tests/path_test.py
702
3.546875
4
"""Test the path_to function""" import unittest from public.util.path import path_to class PathTo(unittest.TestCase): """ Tests the path_to function """ def test_path_to(self): """ Test the path_to function """ self.assertTrue(path_to((0, 0), (0, 4), 5, 5) == (0, -1)) ...
bd75eb24527bf7e4fe9e7e1028e564ac6a5f1adf
KathyCriollo/Deber-Semana_nueve
/Reloj.py
267
3.828125
4
# -*- coding: utf-8 -*- import time fecha_hora = time.strftime("%c") print ("Fecha y hora " + time.strftime("%c")) #Fecha y hora print ("Fecha " + time.strftime("%x")) #tiempo print ("Hora " + time.strftime("%X")) #hora print ("Fecha y hora son: %s" % fecha_hora )
fa6648f06b92cd30e6b9f2dbe868436e3e12ca16
water-lilies/CodingTest
/Programmers/K번째수.py
1,196
3.6875
4
''' 배열 array의 i번째 숫자부터 j번째 숫자까지 자르고 정렬했을 때, k번째에 있는 수를 구하려 합니다. 예를 들어 array가 [1, 5, 2, 6, 3, 7, 4], i = 2, j = 5, k = 3이라면 1. array의 2번째부터 5번째까지 자르면 [5, 2, 6, 3]입니다. 2. 1에서 나온 배열을 정렬하면 [2, 3, 5, 6]입니다. 3. 2에서 나온 배열의 3번째 숫자는 5입니다. 배열 array, [i, j, k]를 원소로 가진 2차원 배열 commands가 매개변수로 주어질 때, commands의 모든 원소에 대해 앞서 설명한 연...
99920b17c0e6dff72f784b3c14da3cc80d0e7475
mkvenkatesh/Random-Programming-Exercises
/binary_search_iterative.py
898
3.890625
4
""" Binary Search - Iterative Approach Given a sorted array, return the index of the element that needs to be searched. Return -1 if no match is found Worst case - O(log N) Time complexity - O(1) # Algorithm while True: if start > end: break mid = start + end/2 if key is in mid return elif...
8ef281ae60f6bc9791f48e7eb317fef1a85d3a2a
Hoyo-yu/Learning
/python/learns/day03-函数/function.py
1,451
3.546875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # Author:Mario def func1(): # 函数 """ 函数体 """ print("in the func1") return 0 def func2(): # 过程 """ 函数体 """ print("in the func2") def func3(): # 函数 """ 函数体 """ print("in the func1") return 1, "hello", ["lhy", "kk...
04ee8f4d0de213b4ba0a3afbc04c2097356696aa
BD20171998/holbertonschool-low_level_programming
/0x1C-makefiles/5-island_perimeter.py
743
3.53125
4
#!/usr/bin/python3 def island_perimeter(grid): if grid == [[1]]: return 1 if grid == [0] or grid == [[0]]: return 0 perm = 0 for i in range(len(grid)): for j in range(len(grid[i])): if grid[i][j] == 0: continue if grid[i][j] == 1 and...
90f7bf130fd51ef3677751760acfa5fe31831211
tungvx/deploy
/Django-0.90/tests/testapp/models/m2m_intermediary.py
1,923
3.703125
4
""" 9. Many-to-many relationships via an intermediary table For many-to-many relationships that need extra fields on the intermediary table, use an intermediary model. In this example, an ``Article`` can have multiple ``Reporter``s, and each ``Article``-``Reporter`` combination (a ``Writer``) has a ``position`` field...
6cf86aeefea46ae001896a836b39bd76b3063be6
SoniaSanchezSoto/Python-practice
/condicionales2.py
560
4.03125
4
'''print("Verificación de acceso") edad_usuario=int(input("Introduce tu edad, por favor: ")) if edad_usuario<18: print("No puedes pasar") elif edad_usuario>100: print("Edad Incorrecta") else: print("Puedes pasar") print("El programa ha finalizado")''' print("Verificación de acceso") Nota_alumno=int(inpu...
b72ad25729a633016fbeb51c0246c3972eeedd5b
imanfaraji/python_codes
/practice/interviews/old/__1_date_sort.py
1,275
3.75
4
# Date sort: inputList = ["01-05-2016", "05-08-2016", "07-09-2015", "02-24-2014", "09-30-2012", "01-09-2017"] print (inputList) def mySwap(mylst,idx1, idx2): temp = mylst[idx1] mylst[idx1] = mylst[idx2] mylst[idx2] = temp def getDay(myDate): return myDate[3:5] def getMonth(myDate): return myDate[...
4fdc65393c3a6b33db8ba059a179aa1bc6a719a4
maakolk/Majo
/polarCoordinates/polarCoordinates.py
779
3.875
4
""" https://matplotlib.org/examples/pylab_examples/polar_demo.html Demo of a line plot on a polar axis. """ import numpy as np import matplotlib.pyplot as plt # r = np.arange(0, 2, 0.01) # theta = 2 * np.pi * r alpha = 30.0 alphaRad = 2 * np.pi * alpha / 360. r = [0.0001, 2.0] theta = [alphaRad, alphaRad] ax = plt...
fb8657801ae619ef6b80d884e869d4d0c87b6ba4
NAIST-SD-PBL-PAL/Teddy-plus
/evaluation/npi-code-formatting_2.py
746
3.609375
4
import csv import re # Current evaluation values mean_avg_prec = 0.0;avg_reca = 0.0;avg_mrr = 0.0; # Possible evaluation values in the future avg_accuracy = 0.0;avg_sensitivity = 0.0; local_file = []; print('Enter csv file name: '); file_name = input(); with open(file_name, newline='') as csvfile: csvreader = csv...
08f712fc6c0f442b0170ee87b44139ce27a6152b
wangzhongjian5920/-
/string_new.py
269
3.796875
4
# -*- coding: utf-8 -*- """ Created on Thu Sep 20 17:48:36 2018 @author: Administrator """ string_a = list(input().strip()) string_b = list(input().strip()) string_c = [string_a[i] for i in range(len(string_a)) if string_a[i] not in string_b] print(''.join(string_c))
aa6cf1b7b7180c938be13cb74af56767ff6b8a9f
syurskyi/Python_Topics
/045_functions/005_decorators/_exercises/_templates/The_Modern_Python_3_Bootcamp/279. Higher Order Functions_higher-order.py
260
3.875
4
# We can pass funcs as args to other funcs def sum(n, func): total = 0 for num in range(1, n+1): total += func(num) return total def square(x): return x*x def cube(x): return x*x*x print(sum(3, cube)) print(sum(3, square))
72cf12b9d9a1d8ef7e5a67fcb4116ec9380747de
bharathtintitn/HackerRankProblems
/HackerRankProblems/searchMatrix.py
917
3.78125
4
import pdb class Solution(object): def searchMatrix(self, matrix, target): if not matrix: return False lo, hi = 0, len(matrix)*len(matrix[0]) - 1 print lo, hi rlen = len(matrix[0]) while lo <= hi: mid = (lo+hi)/2 row = mid//rlen ...
939b12c719ec73bdbb0714dcb67faf903b4fd14e
Sravaniram/Python-Programming
/Code Kata/nearest greater multiple of 10.py
80
3.71875
4
a=int(raw_input()) if a%10==0: print a else: while(a%10!=0): a=a+1 print a
99a8aee3031dc496e3864620cd1551afbec35aeb
CosmosShadow/MLPythonLib
/samples/thread/producer_consumer.py
1,191
3.953125
4
# coding: utf-8 # 多线程: 生产、消费模式 from Queue import Queue import random import threading import time lock = threading.Lock() running = True #Producer thread class Producer(threading.Thread): def __init__(self, t_name, queue): threading.Thread.__init__(self, name=t_name) self.data = queue def run(self): global ...
3c038b34b1eeed045e5eea31c6857b08ab459a5b
7sagar/snakegame
/Snake game/Snakegame.py
7,404
3.5625
4
# from turtle import * # from random import randrange # from freegames import square,vector # food=vector(0,0) # snake=[vector(10,0)] # aim=vector(0,-10) # # def change(x,y): # aim.x=x # aim.y=y # # def inside(head): # return-200<head.x<190 and -200 <head.y < 190 # # # def randrage(param, pa...
651a3a20c37d40ad31507eeb61d96a2dec6341f6
kioplato/leetcode
/problem414.py
896
4
4
def listify(string): list = [] for char in string: if char != ' ' and char != '[' and char != ']' and char != ',': list.append(int(char)) return list def thirdMax(list): first_max = None second_max = None third_max = None for member in list: if member > first_max...
6a746517376077e688a06e644d73d5896096ae67
biam05/FPRO_MIEIC
/play/exceptions/reciprocals.py
307
3.640625
4
# -*- coding: utf-8 -*- """ Created on Mon Jan 7 19:48:45 2019 @author: biam05 """ def reciprocals(alist): new_list = [] for n in alist: try: new_list.append(1/n) except TypeError: pass except ZeroDivisionError: pass return new_list
9987bff8aa40a92b0af239db5179d9ae48883c2f
CircleZ3791117/CodingPractice
/source_code/LC107_BinaryTreeLevelOrderTraversalII.py
1,347
4.15625
4
# -*- coding: utf-8 -*- """ Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root). For example: Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its bottom-up level order traversal as: [...
aab0d60848527f4f1256fe6aa71e636ac6b3e32f
Ixeldr7/PythonChess
/move.py
371
3.65625
4
class Move: def __init__(self): self.moveFrom = [] self.moveTo = [] self.makeMove = False def clear(self): self.moveFrom = [] self.moveTo = [] self.makeMove = False def addMove(self, move): if not self.moveFrom: self.moveFrom = move else: if self.moveFrom == move: self.clear() else:...
947fde1c6b1298ae8f746be05158dea971a9041d
priyamshah112/Data_Analysis-Mining
/DASUT/DASUT-Analytics-master/PROJECT/Search_Process/search4final3.py
26,244
3.734375
4
#ANALYSIS STEP-1 (To get user data and count them category wise in our database) """Problem Definition:To get a users personality based on number of app of particular category he uses. Abstract:The following code is analysis of a persons android app list ,the apps of user are category wise arranged and counted to ge...
59767c9e686ca392de1268083d20c249ca745ae7
ivn-svn/Python-Advanced-SoftUni
/Functions-Advanced/Lab/02. rounding.py
158
3.828125
4
def round_nums(nums): return [round(num) for num in nums] nums = [float(el) for el in input().split()] #turn elements into floats print(round_nums(nums))
9b0e45e0f1b67f848128832c5696dae1889240ac
andersonmoura87/aulas_python
/Testes/Teste3.py
251
3.875
4
#Tabuada num = int(input("Qual tabudada você quer saber? ")) print("-"*15) print("TABUADA") print("-"*15) num1 = 0 while num1 < 10: num1 += 1 resultado = num * num1 print("{} X {} = {}".format(num, num1, resultado)) print("-"*15)
3ff9f523ebfc3193168c9e2eb2fe18a9c258593c
AlexGalhardo/Learning-Python
/Book Introdução Programação com Python/11 - Banco de dados/11.01 - Exemplo de uso do SQLIte em Python.py
975
3.515625
4
############################################################################## # Parte do livro Introdução à Programação com Python # Autor: Nilo Ney Coutinho Menezes # Editora Novatec (c) 2010-2014 # Primeira edição - Novembro/2010 - ISBN 978-85-7522-250-8 # Primeira reimpressão - Outubro/2011 # Segunda reimpressão - ...
567823eec90c5313fe10848304096ba87960b970
swsuggs/Labs
/Python/Arrays/solutions.py
7,056
4.3125
4
#solutions.py """Volume 1 Lab 2: NumPy and SciPy Written Summer 2015 (Tanner Christensen) """ import numpy as np from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D # student's file should be called solutions.py # Problem 1: Perform matrix multiplication A = np.array([[2,4,0],[-3,1,-1],[0,3...
a121a054213c61b008d6ced254cb8ef0f443aa99
shasan06/question
/number_of_above_averages.py
272
3.59375
4
def number_of_above_averages(n,m,A): sum=0 count=0 for elem in A: for i in elem: sum+=i average=sum/(n*m) for elem in A: for j in elem: if average<j: count+=1 return count
57c7bd9f0660d9fcf67453640d8a9f0fd99d297b
eMostyn/Project-Euler-Problems
/problem 56.py
730
3.8125
4
#Function to compute problem def compute(): #Holds maximal digit sum so far maxi = 0 #For each a <100 for i in range(0,100): #For each b <100 for j in range(0,100): #Generate number num = i**j #Set maxi to be the largest of the current maxi and the dig...