blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
bffa6576eebd0343e56aa5344025fd51877f093e
ikhwan/pythonkungfu
/case-study/mass-calc.py
1,089
4.25
4
#!/usr/bin/env python def arrayOperation(array, operation): a = int(0) for x in xrange(0, len(array)): # Handling error if type(array[x]) != int: return "The element is not a number" else: a += array[x] if (operation == "sum"): return a if(operat...
65993600e94e6f1be78c812166982e80d3c511bf
Dub4ek/Mit6.00x
/Week5/L9 Problem 1.py
263
3.921875
4
""" num = 3; L = [2, 0, 1, 5, 3, 4] val = 0 for i in range(0, num): val = L[L[val]] print val """ a = [1, 2, 3, 4, 0] b = [3, 0, 2, 4, 1] c = [3, 2, 4, 1, 5] def foo(L): val = L[0] while (True): print 'a' val = L[val] print foo(b)
a6713ea5a73faf51edfc89bca228702640bbc59b
holzschu/Carnets
/Library/lib/python3.7/site-packages/networkx/algorithms/voronoi.py
3,392
3.875
4
# voronoi.py - functions for computing the Voronoi partition of a graph # # Copyright 2016-2019 NetworkX developers. # # This file is part of NetworkX. # # NetworkX is distributed under a BSD license; see LICENSE.txt for more # information. """Functions for computing the Voronoi cells of a graph.""" import networkx as ...
7be82d5767aab87804288a9a45f8c8b7e526dfb8
AlexandruSerban321/python-beginner-scripts
/password_generatore.py
958
3.984375
4
from string import ascii_letters, punctuation, digits from random import choice def password_generatore(): characters = ascii_letters + punctuation + digits try: password_range = int( input("How long do you wish you password to be ( 8-16 recomandet )? ")) password = "".join(choice(...
9441109a2b8c824a9342bdf634721bb7047095cd
Maxim228337/pythonadvanced
/666.py
1,554
3.765625
4
#Настроение #Свойства class Critter(object): # total = 0 @staticmethod def status(): print('Общее число зверюшек',Critter.total) def __init__(self, name, hunger = 0, boredom = 0): self.__name = name self.hunger = hunger self.boredom = boredom Critter.total +...
138a7e932ef8367473bfb0ad3f5112f0bb4a3f0f
edwinnab/python_practice
/project1.py
390
4.21875
4
#imports random module import random #generates random number using the random method num = random.randint(0,35) print("randomly generated number:",num) #inputs a number from the user num1 = input("Guess a number:"); num1 = int() #loop for wrong input if num1 > 35 : print("number guessed is too high.") elif num1 < ...
c9c580cae58ba610b1d25b393b4174869489c25d
kRituraj/python-programming
/print-square-of-even-and-cube-of-odd.py
320
3.828125
4
from array import * MyArray = array("i",[1,2,3,4,5,6,7,8,9,10]) i = 0 even = 1 odd = 1 while (i < len(MyArray)): if (MyArray[i] %2 == 0): even = MyArray[i] * MyArray[i] print(even , end = " ") else: odd = MyArray[i] * MyArray[i] * MyArray[i] print(odd , end = " ") i = i + 1
75ac38c7e9d3a56bb1e68cd12b8e2d4a74d6881f
AdamFraserGitHub/heeschProblem
/prototypes/randomShapes/rotate square/server/compute.py
3,223
3.609375
4
from math import ceil from math import sin from math import cos from math import pi import numpy as np def matrixToList(matrix2Convert): ''' funct converts a 2d matrix to a 2d list ''' listReturn = [] for i in range(len(matrix2Convert)): # handles collums (neccesary to deal with points) li...
bdb1f5f4988e6011c7daa4c72362ee2f885e7212
Moris-Zhan/Udemy_Course
/Python/Complete Course/PyCharm/Module/guessGame.py
770
3.84375
4
import random rangeMin = 0 rangeMax = 100 guess = random.randint(rangeMin, rangeMax) t = (1,2,3,4,5,6,7) print(len(t)) # while True: # userGuess = input("Enter your guess number : ") # PlaceLowRange = "lower , In range %d ~ %d" # PlaceHighRange = "higher , In range %d ~ %d" # # if int(userGuess) > 1...
e4b1256d439a2330d7a0fcb1b9f65e72980485cc
HectorIGH/Competitive-Programming
/Leetcode Challenge/07_July_2020/Python/Week 3/7_Word Search.py
1,843
3.75
4
#Given a 2D board and a word, find if the word exists in the grid. # #The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once. # #Example: # #board = #[ # ['A','B','C','E'], # [...
d9e39c559a151d7c2334a83ad61b59beeade7b8c
arieli13/Practica
/classes/graphics.py
1,770
4.21875
4
"""Plots a csv file""" import matplotlib.pyplot as plt def separate_csv(path_file, separator): """Join each column of the csv in a single list each one.""" lines = [] with open(path_file, "r") as f: lines = f.readlines() header = lines[0].split(separator) lines = lines[1:] cols = [[]f...
0517fddd1e33f3e2a2dc34bc8cb30b91e73b2aa3
kkelikani/Week1-Project-CIS-Prog5-2020
/input +1.py
94
3.78125
4
first = int(input("Enter the first number: ")) sum = first + 1 print ("The sum is:", sum )
bb3c645a1758f42f56e6078c17e0e228521a9ee8
luizxx/projetos-git
/PA EM while.py
659
3.859375
4
pa = int (input('Digite a primeira PA ' )) razao = int (input('Digite a razão ' )) paf = int(input('Digite o final da sua pa. ' )) res = 'z' while res != '1' or res != '2' or res != 'l': if pa >0 or razao >0 : for c in range(pa,paf +1,razao): print(f'{c}',end=' = ') print('ACABOUU...
4341121e0b2894f972bf3be69d6ebb51563ed533
ashkan-abbasi66/python-comments
/ml/pandas_simple_examples/pivot_table_3.py
304
3.640625
4
# -*- coding: utf-8 -*- """ read from data file and create a dataframe """ import pandas as pd df = pd.read_csv('./data.csv') print (df,'\n\n') # Total sales per employee pivot = df.pivot_table(index=['Name of Employee'], values=['Sales'], aggfunc='sum') print (pivot,'\n\n')
e8ba826a94dc0cac6b35b77c9a9cfd6615844c3c
danielgunn/CodingBat
/python/Warmup1.py
5,064
3.671875
4
def sleep_in(weekday, vacation): return not weekday or vacation def monkey_trouble(a_smile, b_smile): return a_smile == b_smile def sum_double(a, b): if (a==b): return 2 * (a + b) return a + b def diff21(n): if (n > 21): return (n - 21) * 2 return (21 - n) def parrot_trouble(talking, hour): re...
d425f5c32e9469f0898891864ed43de17130b3fb
marcelohweb/python-study
/4-variaveis-tipos-de-dados/19-escopo_de_variaveis.py
531
4
4
""" Escopo de variáveis Dois casos de escopo: 1 - Variáveis globais -> Reconhecidas em todo o programa 2 - Variáveis globais -> Reconhecidas apenas no bloco onde foram declaradas Para declarar variáveis em python nome_da_variavel = valor_da_variavel Obs. Python é uma linguagem de tipagem dinâmica. Ao declarar uma...
ad37ae269ae3ecd7e31f769ffc7c1bd290e26248
Codeded87/Css_practice
/DataScience/classTest.py
534
3.953125
4
'''class Person: def __init__(self, first_name, last_name, age): #instance variable self.first_name = first_name self.last_name = last_name self.age = age def getData(self): print(self.first_name) p1 = Person("shiv","rudra",22) p1.getData() print(p1.last_name)''' ''' c...
577b4857f10b938f4b86190af1e5cf8d2b6346c7
jiangshen95/UbuntuLeetCode
/FractiontoRecurringDecimal.py
1,590
3.9375
4
class Solution: def fractionToDecimal(self, numerator, denominator): """ :type numerator: int :type denominator: int :rtype: str """ if numerator == 0: return "0" symbol = "" if (numerator < 0 or denominator < 0) and (not ...
5f1ea480ce74ba1363932cae006ccd2bcb31e411
theanik/CompetitiveProgramming
/codeforces/PetyaAndStrings.py
173
4
4
str1 = input() str2 = input() if str1.lower() == str2.lower(): print(0) elif str1.lower() > str2.lower(): print(1) elif str1.lower() < str2.lower(): print('-1')
5b6d73d1d772a12e78ad82928c31a758036b66b6
Jackieji00/csci1133
/repo-ji000011/hw2/ji000011_2D.py
2,609
3.875
4
def check(player): if player.lower() == 'p' or player.lower() == 'r' or player.lower() == 's': return True else: return False def rockPaperScissor(player1,player2): if player1.lower() == 'p': if player2.lower() == 'p': result = 'n' elif player2.lower() == 's': ...
3cc1bc0ab2c42b2eb0728467f90a5f01d0787195
youkaede77/Data-Structure-and-Algorithm
/剑指offer/24. 反转链表.py
2,112
4.125
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # author: wdf # datetime: 2/6/2020 10:07 PM # software: PyCharm # project name: Data Structure and Algorithm # file name: 24. 反转链表 # description: 翻转链表,并输出翻转后链表的头结点 # usage: class Node(): def __init__(self, val=None,...
5c73d167c0d7e55984242caf6c737709479a88a5
chen-min/learningPython
/nine/c1.py
518
3.671875
4
# coding=UTF-8 class Student(): name = '' age = 0 def __init__(self, name, age): #构造函数 #初始化对象的属性 name = name age = age print('student') #行为 与 特征 def do_homework(self): print('homework') # 实例化 student1 = Student('tom', 18) print(student1.name) # ...
4fd2df836ec1cfd29fb84d8fe5572bb31a5fe719
sony-zloi/hw_data_packing
/task_3.py
2,066
3.546875
4
import pickle import json from dataclasses import dataclass, field from typing import Dict, Any @dataclass class Stadium: """ Задание 3 Реализуйте класс «Стадион». Необходимо хранить в полях класса: - название стадиона, - дату открытия, - страну, - город, - вместимость. Реализуйте ...
7c91d69eb4f1ce21eea20b5eb4c2c2d62d4234f4
masonaviles/data-structures-and-algorithms
/python/code_challenges/ll_zip/ll_zip.py
1,468
4.40625
4
def zipLists(list1, list2): """ a function to zip the two linked lists together into one so that the nodes alternate between the two lists and return a reference to the head of the zipped list. Args: list1 (list): a linked list to zip in other ll list2 (list): a linked list to zip in other ll ...
f9f00fe7de7c666b6ba53daa0be0a2b95edab026
drlatt/python
/list_comprehension_sample.py
162
4.15625
4
# using a list comprehension to generate a list of the cubes from 3 through 30 threes = [value**3 for value in range(3,31)] for three in threes: print(three)
47758ad094e8cd5ce8dc25b2e1e22abaf864c485
vnatesh/Code_Eval_Solutions
/Moderate/reverse_groups.py
1,052
4.125
4
""" REVERSE GROUPS CHALLENGE DESCRIPTION: Given a list of numbers and a positive integer k, reverse the elements of the list, k items at a time. If the number of elements is not a multiple of k, then the remaining items in the end should be left as is. INPUT SAMPLE: Your program should accept as its first argumen...
0d548a1f792a84cd1264f4904149bf42276ecc60
ArthurJP/pythonLearning
/venv/OOP/Advanced.py
11,462
3.5
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __arthur__ = "张俊鹏" # 使用__slots__ class Student(object): pass s = Student() s.name = "Michael" print(s.name) def set_age(self, age): self.age = age from types import MethodType s.set_age = MethodType(set_age, s) # 给实例绑定一个方法 s.set_age(25) print(s.age) # 但是...
96d2f8c59d58b16773cd513ceb9c5a640b91f838
VaibhavRangare/python_basics_part1
/Pandas/DFOperations1.py
735
3.671875
4
import numpy as np import pandas as pd index = np.array([0,1,2,3,4,5,6]) columns = np.array(['Name','Age','Gender','Show']) data = [ ['John',10,'M','Kidzee'], ['Jinny',10,np.nan,'Kidone'], ['Castor',11,'M','Kidkill'], ['Troy',12,'M','Kidkill'], ['Angel',9,'F','Kidmoon'], ['Gretel',11...
cde8fbe48b5fd01b0351b64f1b1a9152f8b7d658
Abdelrahmanrezk/Sentiment-Behind-Reviews
/Sentiment_behind_reviews/features_extractions/categorical_one_hot_encoding.py
4,162
4.40625
4
#!/usr/bin/env python # coding: utf-8 # # One Hot Encoding # one hot encoding is used to encode categorical data and working as follow: # for each catecorial or word of data convert to integer number but binarry classifcation and each word is 0 or 1. # # Then, each integer value is represented as a binary vector tha...
39184c74599d7e273f6f06b1cddd0fa47c5d4e08
15902276147/my_python_practice
/python_practise/threading/queue_threading.py
1,733
3.703125
4
#coding:utf-8 from threading import Thread from time import sleep import queue """ def count_task(items,result_queue): number = 0 for x in items: number += x result_queue.put(number) if __name__ == "__main__": result_queue = queue.Queue() number_list = [x for x in range(100000)]...
25017c2178e5cf6613b37136d292e6a490d4d775
jy-hwang/CodeItPython
/a_i/dictionary.py
716
3.96875
4
lists = [3, 4, 1, 2, 7] print(lists[1]) # 사전 dict() # dictionary : key - value dict1 = {} print(type(dict1)) dict1[5] = 25 dict1[2] = 4 dict1[3] = 9 print(dict1) family = {} family['mom'] = 'grace' family['dad'] = 'chris' family['son'] = 'young' family['daughter'] = 'kay' print(family) print(family.keys()) pri...
6bd84d7109af8ad224739cf4a037cd53efb18831
akaIDIOT/2020-aoc
/07/handy-haversacks.py
1,252
3.515625
4
from collections import defaultdict import re def parse_rule(line): outer, inners = line.split(' bags contain ') inners = re.split(r' bags?[,\.]\s*', inners) inners = [inner.split(maxsplit=1) for inner in inners if inner and inner != 'no other'] inners = {color: int(num) for num, color in inners} ...
ce7a26a9b012df814ed5b6c47ee91db79dba1a4c
gabriellaec/desoft-analise-exercicios
/backup/user_352/ch149_2020_04_13_19_58_45_529367.py
1,075
3.9375
4
salario_bruto=float(input("qual o seu salário bruto?")) numero_dependentes=int(input("quantos dependentes você possui?")) def calculo_irrf(salario_bruto, numero_dependentes): if salario_bruto>6101.06: inss = 671.12 elif salario_bruto<=1045.00: inss = salario_bruto*0.075 elif salario_bruto>1...
52c9c3a109f4d30380900a929c0e077fcddd9775
saran87/machine-learning
/Titanic/predict_class.py
5,563
4.0625
4
#The first thing to do is to import the relevant packages # that I will need for my script, #these include the Numpy (for maths and arrays) #and csv for reading and writing csv files #If i want to use something from this I need to call #csv.[function] or np.[function] first import csv as csv import numpy as np #Op...
701e55fe7f01e2587964146accaea8a1da191c8e
c3rberuss/MetodosNumericos
/metodos_numericos/biseccion.py
2,162
3.6875
4
import math inferior = 0.0 superior = 0.0 ecuacion = "" tolerancioa = 0.0 resultado = 0.0 x = 0.0 def exp(x, expo): return math.pow(x, expo) def raiz(x, expo=2): return exp(x, 1/expo) def cos(x): return math.cos(x) def sen(x): return math.sin(x) def tan(x): return math.tan(x) def firstStep(ec...
62cb33844cc9807589e83f21e73f7faaee3856c2
dictator-x/practise_as
/algorithm/leetCode/0305_numbers_of_islands_II.py
1,405
3.71875
4
""" 305. Number of Islands II """ from typing import List class Solution: def numIslands2(self, m: int, n: int, positions: List[List[int]]) -> List[int]: ret = [] n_dis = [-1] * (m*n) directions = [(0,1),(0,-1),(1,0),(-1,0)] count = 0 def findRoot(idx): return ...
0f29975cfe38fda1dc90024bbf39aa2b797a99d0
av1234av/hello-world
/linked_list.py
1,427
4.09375
4
class Node(object): def __init__(self,val): self.next = None self.val = val class LinkedList(object): def __init__(self): self.head=None def add(self,n): if not self.head: self.head = n return p = self.head while p.next: ...
019a22fcbea8af03e7ce0c63f8f9470725d87c10
LeiLu199/assignment6
/pcl322/assignment6.py
1,241
3.84375
4
#Po-Chih Lin, pcl322 from interval.intervalClass import * from interval.intervalFunctions import * from interval.intervalExceptions import * """ Accept a list of intervals, and then insert the following inputted intervals merge any two if neccessary """ #Main function if __name__ == "__main__": #Input the list of ...
4ce781a3ff276681467214fa737ebee5342b82a7
nothingtosayy/Quiz-Using-Python
/main2.py
825
4.03125
4
# Quiz Logic q1 = """Who is our Prime Minister? a)Rahul Gandhi b)Chiranjeevi c)Narendra Modi""" q2 = """Whose nickname is king of Cricket? a)M.s Dhoni b)Virat Kohli c)Sachin""" q3 = """Who is called as Missile Man of India? a)Dr.A.P.J...
5b38eecd47ce16ab45f8312debf8f1b7fad26b8d
PolishDom/COM411
/basics/functions/sounds.py
177
3.609375
4
def loudsound(): sound = input("What word would you describe the sound?") print ("What did you just hear?") print (sound) print("That was a loud",sound) loudsound()
f38dc373075807aecaeef4472211b3fd0867ec8b
NeyBrito/Phyton
/Scripts-Python/pythontest/desafio29.py
267
3.671875
4
ca = float(input('Qual sua velocidade?')) if ca > 80: n1 = (ca - 80) * 7 print(' Você está acima do limite de velocidade. REDUZA!\n Você está sendo multado em {:.2f}'.format(n1)) else: print('Você está dentro do limite de velocidade. BOA VIAGEM!')
3f18a4c9dbad9d78cc61273876452fd9276c8c69
Semal80/Courses
/HomeWork6/hw6_4.py
389
4.15625
4
################################## # Leap Year # ################################## while True: try: a = int(input("Input a year:")) except ValueError: print("This is not number") continue if (a % 4 == 0) and (a % 100 != 0) or (a % 400 == 0): print("This...
7c26da8af224c3c6452198be5a2228fac2a84117
ezequielfrias20/exam-mutant
/src/mutant.py
3,210
3.796875
4
''' Funcion que permite ver si una persona es mutante o no, tiene como parametro una lista y devuelve True si es mutante o False si no lo es ''' def Mutant(adn): try: ''' Funcion que permite verificar si la matriz es correcta siendo NxN y que solo tenga las letras A T C G...
8fcf842e7d9df99ed8733d737ed68264c6d39616
zizle/MarketAnalyser
/utils/day.py
492
3.578125
4
# _*_ coding:utf-8 _*_ # @File : day.py # @Time : 2020-11-27 11:12 # @Author: zizle import datetime def generate_days_of_year(): """ 生成一年的每一月每一天 """ days_list = list() start_day = datetime.datetime.strptime("2020-01-01", "%Y-%m-%d") end_day = datetime.datetime.strptime("2020-12-31", "%Y-%m-%d") ...
2db0515918fc48d00d4cb1cb397fbfb3075a5a6f
nurnisi/algorithms-and-data-structures
/leetcode/0-250/275-859. Buddy Strings.py
688
3.65625
4
# 859. Buddy Strings class Solution: def buddyStrings(self, A: str, B: str) -> bool: if len(A) != len(B) or len(A) == 1: return False # create array of indices, where A and B differ # also count character occurences dif, count = [], [0] * 26 for i in range(len(A)): ...
a991c099f3823a5054fd3d2088df7e175f1ba190
ChangXiaodong/Leetcode-solutions
/4/542-01_Matrix.py
1,119
3.546875
4
class Solution(object): def dfs(self, matrix, access, res, steps, i, j): if i >= len(matrix) or j >= len(matrix[0]) or access[i][j] or matrix[i][j] == 0: return steps access[i][j] = True res = min(self.dfs(matrix, access, res, steps + 1, i + 1, j), res) res = min(self.dfs...
117d36eda839f670ca87311e52bf28735186e52c
MaiziXiao/Algorithms
/Leetcode 101/千奇百怪的排序算法/堆排序.py
1,330
3.578125
4
# 堆排序 # https://blog.csdn.net/Hk_john/article/details/79888992 # 堆排序(Heapsort)是指利用堆这种数据结构所设计的一种排序算法。 # 堆积是一个近似完全二叉树的结构,并同时满足堆积的性质:即子结点的键值或索引总是小于(或者大于)它的父节点。 # 堆是一种非线性结构,可以把堆看作一个数组,也可以被看作一个完全二叉树,通俗来讲堆其实就是利用完全二叉树的结构来维护的一维数组 # 按照堆的特点可以把堆分为大顶堆和小顶堆 # 大顶堆:每个结点的值都大于或等于其左右孩子结点的值 # 小顶堆:每个结点的值都小于或等于其左右孩子结点的值 # 将初始待排序关键字序列(R...
c6ae34192fe3596e5ddd6e64a26fb0ab1a6f1368
Vikas-ML/NUMPUZZ
/Game.py
755
3.859375
4
def numpuz(): print(" ","WELCOME IN OUR GAME") print() print(" ","1.PRESS 1 FOR EASY(2X2)") print(" ","2.PRESS 2 FOR MEDIUM(3X3)") print(" ","3.PRESS 3 FOR HARD(4X4)") ch=input("enter your choice= ") ...
e6e1b6c0cf62165d0fb6d36923ca28f6a303e8bb
amarotta1/um-programacion-i-2020
/59103- Marotta,Alejandro/Tp1/POO/ej18_ob.py
2,227
3.984375
4
""" Ejercicio 18 Modificar el programa del ejercicio 17 agregando un control de datos vacíos. Si por algún motivo alguno de los datos viene vacío o igual a "" debemos generar una excepción indicando que ocurrió un problema con la fuente de datos y notificar por pantalla. La excepción debe ser una excepción propia. ...
0659a4828be6a5d60ef0f045e4b64920cc3b56cd
ramasawmy/Python-program
/UserInputVowel.py
419
3.921875
4
y = input("enter a sentence:") vowels=0 consonant=0 digit=0 specailchar=0 for x in y: if x.isalpha(): if (x=="a" or x=="e" or x=="i" or x=="o" or x=="u"): vowels +=1 else: consonant+=1 elif x.isdigit(): digit+=1 else: specailchar+=1 print("vowels...
dee2975eb2b33f6a4a690f1ba1926d6d0e28f7d9
malewis5/Data-Structures-and-Algorithms-Python
/Fibonacci.py
710
3.921875
4
## Iterative Solution ## def iterFibonacci(n): if n < 0: return ValueError('Number must be positive.') fibs_list = [0,1] if n <= len(fibs_list) - 1: return fibs_list[n] else: while n > len(fibs_list) - 1: next_fib = fibs_list[-1] + fibs_list[-2] fibs_list.append(next_fib) return fibs_...
02c113d8b593c023e3c3061caf0ee84cc2ed600e
ipableras/PildorasInformaticasPython
/TrabajoConListas.py
472
4.3125
4
# Listas # doc python trabajadores =["Ana", "María", "Antonio", "Miguel"] print(trabajadores) print(len(trabajadores)) print(trabajadores.index("Antonio")) trabajadores.append("Juan") print(trabajadores) print(trabajadores[2]) print(trabajadores) print(trabajadores[-2]) print(trabajadores) print() # Borrar M...
31e8b552f313204a6da3d1b29705d51e6ac5bfd9
anhaidgroup/py_stringmatching
/py_stringmatching/tokenizer/qgram_tokenizer.py
8,314
3.5625
4
from six import string_types from six.moves import xrange from py_stringmatching import utils from py_stringmatching.tokenizer.definition_tokenizer import DefinitionTokenizer class QgramTokenizer(DefinitionTokenizer): """Returns tokens that are sequences of q consecutive characters. A qgram of an input ...
b935fc6ec8e15cd5bf8b4cfe2210bd8c84f8aec9
jchooker/py-functions-basic2
/functions-basic2.py
2,288
3.703125
4
from typing import Match import numpy as np #1 - Countdown def countdown(startNum): counted=[] for i in range(startNum,-1,-1): counted.append(i) return counted countVal = input("Enter a positive value from which to count down: ") print(countdown(int(countVal))) #2 - Print and return def printRetur...
e65caff977ee78c00d4df4e94006e79bba7f3a4e
Roopa07/Player-Set-1
/fact.py
100
3.703125
4
n=int(input()) fact=1 if fact==0: print("1") else: for i in range(1,n+1): fact *=i print(fact)
ba56ae77b75b720b5752ddb3d8bb5e80fd2d0d85
green-fox-academy/FulmenMinis
/week-03/day-03/triangles.py
1,177
3.875
4
from tkinter import * root = Tk() canvas = Canvas(root, width='400', height='600') canvas.pack() # 21 db egy oldalon ~25oldalszélesség # reproduce this: # [https://github.com/greenfox-academy/teaching-materials/blob/master/workshop/drawing/triangles/r5.png] def draw_triangles(x, y): black_line = canvas.create_lin...
712dbe61a0174df5e61bfd1ee8ffe692064a3703
gnperdue/Euler
/Code/Python/problem032/euler032.py
1,657
3.640625
4
#!/usr/bin/env python import numpy as np def has_unique_digits(num): list_of_digits = [] temp_num = num while temp_num > 0: last_digit = temp_num % 10 temp_num -= last_digit temp_num /= 10 list_of_digits.append(last_digit) return len(np.unique(list_of_digits)) == len(...
25c17300f23f76823cc19a06aafbf973b463a3be
Reetishchand/Leetcode-Problems
/01085_SumofDigitsintheMinimumNumber_Easy.py
865
3.765625
4
'''Given an array A of positive integers, let S be the sum of the digits of the minimal element of A. Return 0 if S is odd, otherwise return 1. Example 1: Input: [34,23,1,24,75,33,54,8] Output: 0 Explanation: The minimal element is 1, and the sum of those digits is S = 1 which is odd, so the answer is 0. Example 2: ...
8d776cda9da24e0f5e5d3daad0b22ad6d437d154
cjrzs/MyLeetCode
/列表根据指定格式分隔.py
1,730
3.671875
4
''' coding:utf8 @Time : 2020/3/4 1:58 @Author : cjr @File : 列表根据指定格式分隔.py 谨以此纪念第一个严格意义上自己开发的算法! 目的:将列表根据指定格式的字符串分隔成子列表并转换成指定格式 例如: 把列表根据以“-”开头的字符串为界限,分隔成不同的子列表,其中以“-”开头的字符串为字典的key,其后的所有元素为value 转换前:["-x", "1", "2", "3", "-q", "4", "5", "6", "-d", "7", "8"] 转换后:[{'-x': ['1', '2', '3']}, {'-q': ['4', '5', '6']}, {'-d': [...
377ca7d7cce5f531895c465566361fe2c7a482fc
nbrahman/Coursera
/Python for everybody/3. Using Python to Access Web Data/Week 6 Assignment 2/geojson.py
2,701
4.3125
4
# Calling a JSON API # In this assignment you will write a Python program somewhat similar to http://www.pythonlearn.com/code/geojson.py. The program will prompt for a location, contact a web service and retrieve JSON for the web service and parse that data, and retrieve the first place_id from the JSON. A place ID is ...
f5537c161322a6f9ca9156bf9400a61cc40097fc
KickItAndCode/Algorithms
/Recursion/WordSplit.py
1,314
4.125
4
# # Create a function called word_split() which takes in a string phrase and a set list_of_words. The function will then determine if it is possible to split the string in a way in which words can be made from the list of words. You can assume the phrase will only contain words found in the dictionary if it is complete...
1ebcbe231bd4b2209ea54e9182c3dd66712caf46
RafaelSerrate/C-digos-Python
/Exercicios/Aula 7 - exercicios/Exercicio 005.py
225
4.0625
4
n = int(input('Coloque um numero: ')) ant = n - 1 suc = n + 1 print('O antecessor do {} é {}, e o seu sucessor é {}'.format(n, ant, suc)) print('O antecessor do numero {} é {}, e o seu sucessor é {}'.format(n, n-1, n+1))
496f3fc343434dff3f3dde228a9a28595407eefc
subramaniam-kamaraj/codekata_full
/strings/find_non_repeating_character.py
534
4.09375
4
''' You are given a string ‘S’ consisting of lowercase Latin Letters. Find the first non repeating character in S. If you find all the characters are repeating print the answer as -1 Input Description: You are given a string ‘s’ Output Description: Print the first non occurring character if possible else -1. Samp...
a26f36c50ca118f6630e32efbcb134abfb27763a
stcybrdgs/myPython-refresher
/pythonEssential/classes_2.py
1,762
4.03125
4
# classes_2.py # class methods # # rem python does not have private variables, so there's no way to actually prevent # someone from using the class variables, but the self.__ is the conventional way to # indicate that the variable should be treated as a private variable and that it should # not be set or retreived outs...
01f6e2c889621f3774105906e66fd79b10a20e60
leeo1116/Algorithms
/LeetCode/Python/Original/039_combination_sum.py
691
3.5
4
class Solution(object): def combination_sum(self, candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ # candidates.sort() # return self.search(candidates, target) # def search(self, candidates, target): ...
495f26dfbadc0b6a3d820990d02f6c59fa9081a6
Woosiq92/Pythonworkspace
/4_string.py
3,527
3.9375
4
sentence = '파이썬' print(sentence) sentence2 = "파이썬은 쉬워요 " print(sentence2) sentence3 = """ 나는 파이썬이 , 쉬워요 """ # 총 네줄 출력 ( 줄바꿈 포함 ) print(sentence3) # 슬라이싱 woosik = "920308-1234567" # 리스트, 인덱스 개념 필요 print("성별 : " + woosik[7] ) print("년도 : " + woosik[0:2]) # 범위 개념 필요 , 0 ~ 2 직전 까지 print("월 : " + woosik[2:4]) p...
6dd41aaba81ad71b85d328bfbea3dc47ece10144
iverberk/advent-of-code-2018
/day-07/part1.py
240
3.53125
4
import networkx as nx G = nx.DiGraph() with open('input') as f: for line in f: instruction = line.strip().split() G.add_edge(instruction[1], instruction[7]) print("".join(list(nx.lexicographical_topological_sort(G))))
30b1efc4b2a8bc2632026f88eafe6322d544e6e5
is5pz3/automatic-client
/scripts/file_operations.py
1,012
3.59375
4
def read_hosts_from_temp(filename, mode): """ Retrieves list of hosts that were active in previous iteration of ranking algorithm. Args: filename: (str) Name of file to retrieve host names from. mode: (str) Opening file mode. Returns: prev_hosts: List of host names read from file. """ try: f = open(fi...
962ff630d86ec96b83d109ef0e7a6c85f9433d12
Thijsvanede/elliptic-curves
/ec/curves.py
6,134
4
4
from ec.points import Point import warnings class Curve(object): """Defines a curve as y² = x³ + a*x + b (mod n).""" def __init__(self, a, b, n=None): """Initialise curve as y² = x³ + a*x + b (mod n). Parameters ---------- a : float a value for curv...
c76e6a0be071923eaf8d46e5a9c24c07748a177b
raghubegur/PythonLearning
/codeSamples/errorHandling.py
232
3.765625
4
x = 42 y = 0 print() try: print(x / y) except ZeroDivisionError as e: print('Division by zero not allowed') else: print('Something else went wrong') finally: print('This is my clean up code') print()
d92f79a5ae2acfa74bf210a7df13b081ede7bfe5
shrivastava-himanshu/Leetcode_practice
/ReverseString.py
256
3.765625
4
def reverseString(s): # method 1 # return(s.reverse()) # method 2 p1 = 0 p2 = len(s) - 1 while p1 <= p2: s[p1], s[p2] = s[p2], s[p1] p1 += 1 p2 -= 1 return s print(reverseString(["h","e","l","l","o"]))
dd2719d89c36346de588f97e95ca670175e716b0
quamejnr/Python
/API/github_stars.py
438
3.53125
4
import requests import json # make an API call and store the response url = 'https://api.github.com/search/repositories?q=language:python&sort=stars' headers = {'Accept': 'application/vnd.github.v3+json'} r = requests.get(url, headers=headers) print(f'Status code: {r.status_code}\n') # Convert JSON to python dictiona...
761739a3a42fe843a0b1e240c5a785be3d4e3ab1
sandrastokka/phython
/Homework - 13.12.17/Find the lagrest number in a list.py
293
4.25
4
#Write a Python function to get the largest number from a list. temperatureThisWeek = [1, 2, 4, 1, 1, 3, 2,] #define function def findlargestnumber(): highest = max (temperatureThisWeek) print "the highest temperature this week is", highest, "celsius degrees" findlargestnumber()
c147550b95527860eb0d3fa7ef5b1ac76a402e32
Anton-L-GitHub/Learning
/Python/1_PROJECTS/Python_bok/Uppgifter/Kap13/uppg13-15.py
1,262
3.671875
4
class Hus: def __init__(self, l, b): self.längd = l self.bredd = b def kvadratiskt(self): return self.längd == self.bredd def yta(self): return self.längd * self.bredd __yta = yta # privat klassvariabel def __str__(self): y = self.__yta() retu...
44772b7ec57885f8472d51d02646c0c348db4396
Nouseva/proj1_14
/p1.py
6,618
3.984375
4
from p1_support import load_level, show_level, save_level_costs from math import inf, sqrt from heapq import heappop, heappush def dijkstras_shortest_path(initial_position, destination, graph, adj): """ Searches for a minimal cost path through a graph using Dijkstra's algorithm. Args: initial_positio...
3036f353d0956b61614c15ca8b0d1b4e02f4fa98
A6h15h3k806/Python
/Expected_WaitTime_Calculator/ExpectedWaitTime Calc.py
1,616
3.796875
4
import time average_list = [] t0 = int(time.time()) def timefy(x): print ('''Your Expected Waiting Time is''') s = x%60 print(str(s)+" sec") if x//60 >= 1: m = (x//60)%60 print(str(m)+" min") if (x//60)//60 >=1: h = ((x//60)//60)%60 ...
d693a11987b920f073c075fbca1f2f3649040a1b
lirenlin/DSA
/group_anagrams.py
376
4
4
def solution (array): dict_list = dict () for item in array: target = "".join (sorted (item)) if target in dict_list: dict_list[target].append (item) else: dict_list[target] = [item] result = [] for value in dict_list.values(): result += [sorted(value)] print result array = ["ea...
2387de53b769cec983984662a0bf9b3bf7a9bc7d
sriram161/Data-structures
/sort/insertion_sort.py
387
4.0625
4
def insertion_sort(a): """ Iterative apporach for insertion sort. """ n = len(a) for i in range(n): for j in range(i, 0, -1): if a[j-1] > a[j]: a[j-1], a[j] = a[j], a[j-1] else: break return a if __name__ == "__main__": a = [9, 3, ...
cf8c7bef193bad6e56f872378ea14b4d1a830783
adybose/hackerrank
/algorithms/implementation/kangaroo.py
481
3.78125
4
#!/bin/python3 # Link to the problem: https://www.hackerrank.com/challenges/kangaroo import sys def kangaroo(x1, v1, x2, v2): if v1 == v2: return 'NO' # since x1 < x2 else: j = (x1 - x2) // (v2 - v1) # if j > 0 and (x1 + (v1 * j) == x2 + (v2 * j)): return 'YES' else: ...
0505be87250bb2965051554cd084659dcbf32d39
xdc7/pythonworkout
/chapter-03/02-extra-02-sum-numeric.py
1,872
4.25
4
""" Write a function, sum_numeric , which takes any number of arguments. If the argument is or can be turned into an integer, then it should be added to the total. Those arguments which cannot be handled as integers should be ignored. The result is the sum of the numbers. Thus, sum_numeric(10, 20, 'a','30', 'bcd') woul...
928ae15ac66f5be28a1b695fd803db3d4c1c1ce0
luismglvieira/Python-and-OpenCV
/00 - Python3 Tutorials/17 - Python slice and negative index.py
668
3.75
4
# -*- coding: utf-8 -*- a = [0,1,2,3,4,5,6,7,8,9] b = (0,1,2,3,4,5,6,7,8,9) c = '0123456789' print("a[:] = " + str(a[:])) print("a[slice(0,5)] = " + str(a[slice(0,5)])) print("a[0:5] = " + str(a[0:5])) print() print("b[:] = " + str(b[:])) print("b[4:] = " + str(b[4:])) print("b[:6] = " + str(b[:6])) print() print("c[...
3810f617653938333eaa6527eafbb5fb54da5149
KotaCanchela/PythonCrashCourse
/8 Functions/8-3 8-4 T-Shirt.py
1,382
4.71875
5
# Write a function called make_shirt() # that accepts a size and the text of a message that should be printed on the shirt. # The function should print a sentence summarizing the size of the shirt and the message printed on it. # Call the function once using positional arguments to make a shirt. # Call the function a s...
8a2466eb7505828b1ae566721cdd5d850e7aa695
sammykol83/UdacityDataScienceNanoDegree
/Project - Array tool/sig_process_arrays/Array.py
1,450
3.546875
4
import numpy as np class Array: def __init__(self, num_of_elements = 8, spacing_m = 1e-3, az_res_deg = 0.5, az_span = np.array([-50, 50])): """ General 1D array of EQUALLY spaced elements (either UCA/ULA) Attributes: d (float) the spacing (in meters) between the elements...
99e7b8c61dc1a7786c31219cd88ebce9cbb2571f
XinJin96/Python-Programming
/guess game.py
1,095
3.890625
4
import random true=random.randint(0,99) count=0 left=0 print ("Number(0,100) guess game") print ("You will have 10 times to guess") print ("Guess out of range will game over immediately!") guess = int(input("guess a number:")) count=count+1 left=10-count while 0<=guess<=99: if count==10: if gues...
ac0fcbac231aa9c094c3ae0fb5659dff9a79d546
yuanning6/python-exercise
/004.py
545
3.5
4
# -*- coding: utf-8 -*- """ Created on Thu Oct 15 21:20:10 2020 @author: Iris """ f = float(input('请输入华氏温度:')) c = (f - 32) / 1.8 print('%.1f华氏度 = %.1f摄氏度' % (f,c)) print(f'{f:.1f}华氏度 = {c:.1f}摄氏度') radius = float(input('请输入圆的半径:')) perimeter = 2 * 3.1416 * radius area = 3.1416 * radius * radius print('周长:%.2f' ...
ae5e1333fb9f6e060d7564cc062257fa3e61b6cd
Sanchi02/Dojo
/PracticeComp/LargestNumber.py
482
3.5
4
def myCompare(): class K(object): def __init__(self, obj): self.obj = obj def __lt__(self, other): a, b = str(self.obj), str(other.obj) ab = a + b ba = b + a return (((int(ba) > int(ab)) - (int(ba) < int(ab))) < 0 ) return K # driver c...
e7bc7f8bffdcdd0ab74dfbd9ba9a27a9343fbb2f
S-Radhika/Best-enlist
/day 16.py
1,097
4.1875
4
#multiply argument x with y a=lambda x,y:x*y print(a(5,6)) #output ''' 30 ''' #create fibonacci series from functools import reduce fib = lambda n: reduce(lambda x, _: x+[x[-1]+x[-2]],range(n-2), [0, 1]) print(fib(5)) ''' output [0, 1, 1, 2, 3] ''' #counting even numbers in a list # list of numb...
c18536b1e7b760c9a8d3f86515a177b9c4a55343
Sk0uF/Algorithms
/py_algo/arrays_strings/competition/cyclic_shift.py
3,639
4.125
4
""" Codemonk link: https://www.hackerearth.com/problem/algorithm/maximum-binary-number-cb9a58c1/ A large binary number is represented by a string A of size N and comprises of 0s and 1s. You must perform a cyclic shift on this string. The cyclic shift operation is defined as follows: If the string A is [A0, A1, A2,...
cdb7e1872e1345d3fa00674c21dd607462d7644b
LeoGraciano/python
/FOR RANGE Numero Primo.py
196
3.90625
4
qp = 0 n = int(input("Digite um numero: ")) for p in range(1,n+1): if n % p == 0: qp += 1 if qp == 2: print ("Esse numero é primo") else: print ("Esse numero não é primo.")
81d403b3dc0a6e6ecb0fc74cfb2fe459ce642981
adsl305480885/leetcode-zhou
/242.有效的字母异位词.py
1,111
3.5
4
''' Author: Zhou Hao Date: 2021-02-23 21:15:45 LastEditors: Zhou Hao LastEditTime: 2021-02-23 21:37:52 Description: file content E-mail: 2294776770@qq.com ''' # # @lc app=leetcode.cn id=242 lang=python3 # # [242] 有效的字母异位词 # # @lc code=start class Solution: #排序 # def isAnagram(self, s: str, t: str) -> bool: ...
ee4492b84507e8311614c571f5df40c17b170ad7
kleyton67/algorithms_geral
/uri_1032.py
855
3.796875
4
#!/usr/bin/env python2 # -*- coding: utf-8 -*- ''' Kleyton Leite Problema do primo jposephus, deve ser considerado a primeira troca Arquivo uri_1032.py ''' import math def isprime(n): flag = True if n == 2: return flag for i in range(2, int(math.sqrt(n))+1, 1): if(n % i == 0):...
0bf7865f28e7b41a831c99bfc9cfcefb3d85a2f6
Vagacoder/PythonStudy
/w3schools/022-numpyArrayIterat.py
577
3.5
4
# # * Numpy array iterating #%% import numpy as np a1 = np.array([[1, 2, 3, 4],[5, 6, 7, 8]]) for x in a1: print(x) for y in x: print(y) # %% # * nditer() for x in np.nditer(a1): print(x) # %% # * Iterating array with different data types for x in np.nditer(a1, flags=['buffered'], op_dtypes...
5105f8ea113d412c48bb880de30f75eed5e1dfa2
Ricardo-oli/Projeto-3-
/at2.py
341
3.78125
4
print(input('Nome do time: ')) v = int(input('Vitórias: ')) d = int(input('Derrotas: ')) e = int(input('Empates: ')) total = v + d + e p = v * 3 + e vitorias = v * 3 pontos_perdidos = d * 3 print('Total de Partidas:', int(total),'Partidas') print('Total de Pontos:', p,'Pontos') print('Total de pontos perdidos...
114ad272c5959ba819ee1467f3e70243d50bd81e
jaywritescode/projecteuler-python
/tests/test_divisors.py
2,918
3.71875
4
from project import divisors import unittest class TestDivisors(unittest.TestCase): """ Test the divisors function from the library. """ def test_non_perfect_square_even(self): """ Test k where k is even and k != n ^ 2 for any integer n """ result = divisors.divisors(56...
f7f835f73b3cf34ae45e40dfea61dea43e46d305
St3pL3go/in-stock-bot
/src/csv_utils.py
2,889
3.625
4
import time import csv import os class ChatObject: """Class that creates an object from csv entry""" def __init__(self, l: list): self.id = int(l[0]) self.type = l[1] self.username = l[2] self.first_name = l[3] self.last_name = l[4] self.first_contact =...
3a3754958ceb8ca684a79cf14547ffd7fad44a3a
carlaoutput/python-class-
/enteros no negativos
1,755
3.875
4
#!/usr/bin/env python from types import * from math import * class IntSet: def __init__(self): # inicializaci´on self.c = 0L def __str__(self): # impresi´on del resultado c = self.c s = "{ " i = 0 while c != 0: j = 2**long(i) if c & j: s = s...
499c5d4ec3af637df1591e5362bfb41984a8b913
Iturriaga10/TC1028-Python
/Clase8/ej12.py
707
4.3125
4
''' Ejercicio 12 Escribir un programa en el que se pregunte al usuario por una frase y una letra, y muestre por pantalla el número de veces que aparece la letra en la frase. ''' frase = raw_input("Introduce una frase: ").lower() letra = raw_input("Introduce una letra: ").lower() contador = 0 for x in frase: if ...
850c989bd0430a6615beb809b75f443154527bf4
ptekspy/projects
/atm.py
2,189
3.625
4
import datetime class Atm: def __init__(self, name, pin): self.name = name self.pin = pin self.balance = 0 self.transactions = dict() self.transactions["Deposits"] = {} self.transactions["Withdrawals"] = {} if len(str(self.pin)) != 4: raise Value...
7b02df05eaabddb8146c8831605e5612218b439d
EndIFbiu/python-study
/20-模块和包/01-导入模.py
576
3.875
4
""" 模块(Module),是一个Python 文件,以.py 结尾,包含了Python 对象定义和Python语句 模块能定义函数,类和变量,模块里也能包含可执行的代码 """ """ # 1. 导⼊模块 import 模块名 import 模块名1, 模块名2... (不推荐) # 2. 调用功能 模块名.功能名() """ import math print(math.sqrt(9)) """ from 模块名 import 功能1, 功能2, 功能3... """ from math import sqrt # 不再需要前面写模块名.方法 print(sqrt(9)) """ fro...
68c99cb76a05a0136dfea5ad95b82602766a154a
rosekamallove/OOP
/PYTHON/Basics/b.py
157
3.640625
4
# Object Oriented Programming in Python string = "hello" # the .upper(maybeSomeParameter) is a method and anythig with a . is method print(string.upper())