blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
5faf3c2ec4ba589c8b6621731cc8180214fd7d16
michalkasiarz/learn-python-programming-masterclass
/stepping-into-the-world-of-python/SlicingIdioms.py
691
4.21875
4
# slicing idioms letters = "abcdefghijklmnopqrstuvwxyz" # reversing a sequence reversed_sequence = letters[::-1] print(reversed_sequence) # extracting specific number of last items from a sequence: 4 lastFourItems = letters[-4::] print(lastFourItems) # extracting the first item: two ways to do that firstItem = lett...
e50b5672638d9ae19c551556c159284c8eb7f999
swapnil-narwade/PythonProgramming
/Chapter 3/Ex.04_Magic_Date.py
245
4.25
4
day = int(input("Enter the day of Date")) month = int(input("Enter the month of Date")) year = int(input("Enter the year of Date")) date = 0 if (day * month) == year: print("this is a magic date") else: print("This is not a magic date")
43cd2d948b2c8ff12593082b579175e4b13ff68e
DerflaNehc/PythonPractice
/CH5_Array/arrayAddMultiply.py
1,579
4.09375
4
from typing import List from random import randint #These method works around overflow of large integers (for some programming languages) #Implement a function that takes an array representing an integer, D, and outputs the array D+1 def addOne(num:List[int]): #Consider the first digit if num[-1] == 9: ...
5b628712a93324bfd34a0e50513399221fc6eb56
anhcuonghuynhnguyen/Tkinter-Advance
/9.SetAndGetVar.py
1,329
4.1875
4
''' Tkinter supports some variables which are used to manipulate the values of Tkinter widgets. These variables work like normal variables. set() and get() methods are used to set and retrieve the values of these variables. The values of these variables can be set using set() method or by using constructor of thes...
f6f3b1072fa7e072d944436a4aae37323ffd1cac
cafenoctua/100knock2019
/aomi/chapter01/knock08.py
252
3.84375
4
def cipher(s): ans = "" for i in range(len(s)): if s[i] >= 'a' and s[i] <= 'z': ans += chr(219 - ord(s[i])) else: ans += s[i] return ans s = "abcdefgABCDEFG" print(cipher(s)) print(cipher(cipher(s)))
0b15bd849bb288cba87c6baa1e7ab63da5dc0bb3
HaoTruong/Python_FinalProject
/FinalProject_MineSweeper.py
8,498
3.515625
4
import pygame, random, time, sys # Define some colors BLACK = (0, 0, 0) WHITE = (255, 255, 255) GREEN = (0, 255, 0) RED = (255, 0, 0) # This sets the WIDTH and HEIGHT of each grid location WIDTH = 20 HEIGHT = 20 # This sets the margin between each cell MARGIN = 5 numGrid = 10 #Number of mines is...
0a6ad934945cc88ea627e66428ab7eed9f899814
herzenuni/herzenuni-sem3-assignment4-191217-AnnGoga
/Exam.py
519
3.625
4
#numbers = [1, 4, 10, -3, -8, 7, 15, 0, 31, 28, -10] numbers = [1, 9, -10, -20, -8, 7, 14, 0, 20, 20, -20] def exam(lst): min_1 = min(lst[0], lst[1]) max_1 = max(lst[0], lst[1]) min_2 = lst[0] * lst[1] max_2 = lst[0] * lst[1] min_3 = lst[0] * lst[1] * lst[2] for x in lst[2:]: min_3 = min(min_3, x *...
9588546c7a71a80619b0f3c1195998d05032cdea
zafar26/practise
/nomlogic.py
221
3.59375
4
n = 4 s = 'zafar' arr = [] for i in range(n): arr.append([]) for j in range(n): if i == j: arr[i].append(s[i]) else: arr[i].append('-') for i in arr: print(i)
ba450d47c2aab3321a58bb46ae6717a14dfa4b93
bzierk/janggiGame
/JanggiGUI.py
6,781
3.953125
4
# Author: Bryan Zierk # Date: 2/26/21 # Description: This program allows the user to play Janggi, a Korean board game similar to Xiangqi or Chinese Chess. # The game is played on a board which is 9 lines wide by 10 lines tall where pieces are placed at the intersection # of lines similar to Go. Players take turns movin...
0bf6e894c304cc1e39907e4ed762ce597a2047a5
DaniloDalessandro/PROGRAMAS-EM-PYHTON
/PYTHON BRASIL/LISTA 01/005.py
179
3.890625
4
# POR: DANILO COSTA # UNIVERSIDADE ESTADUAL DO MARANHÃO # GRADUANDO EM ENGENHARIA DE COMPUTAÇÃO n = float(input('DIGITE UM NUMERO: ')) n = n * 100 print('{} CENTIMENTOS'.format(n))
5807f314f71a1741dc78f3d6e855422b5a77922f
chenxuhl/Leetcode
/腾讯精选50题/12Binary_Tree_Maximum_Path_Sum/maxPathSum.py
1,537
3.765625
4
#124.二叉树中的最大路径和 #题目来源: """ https://leetcode-cn.com/problems/binary-tree-maximum-path-sum/ """ #题目描述: """ 给定一个非空二叉树,返回其最大路径和。 本题中,路径被定义为一条从树中任意节点出发,达到任意节点的序列。 该路径至少包含一个节点,且不一定经过根节点。 """ #示例1: """ 输入: [1,2,3] 1 / \ 2 3 输出: 6 """ #示例2: """ 输入: [-10,9,20,null,null,15,7] -10 / \ 9 20 / \...
75c21e8992fde36fc98b12ab6474bee8306689fd
tmosyc/aitech
/One_max.py
2,196
3.765625
4
import random import copy LIST_SIZE = 10 POPULATION_SIZE = 10 GENERATION = 25 MUTATE = 0.1 SELECT_RATE = 0.5 # calc_fitness, sort_fitness, selection, crossover, mutation def print_population(population): for individual in population: print(individual) print("----") def print_individual(individual): ...
9afed33695a1f62da47eaef47575305dacdd1d53
sinoyuco/leetcode_solutions
/string/one_away.py
765
3.578125
4
def one_away(str1,str2): maps = {} for i in range(len(str1)): if str1[i] in maps: maps[str1[i]] += 1 else: maps[str1[i]] = 1 for i in range(len(str2)): if str2[i] in maps: maps[str2[i]] -= 1 else: maps[str2[i]] = -1 p = []...
b07b45ad139753e3f7dc24fa3076b4bc5d4ae5a2
liu-yuxin98/Python
/chapter5/5.12.py
214
3.609375
4
def find(num): if num%5==0 and num%6==0: return 1 count=0 for i in range(0,1001): if find(i): print(format(i,"5.0f"),end=" ") count+=1 if(count%10)==0: print(" ")
648610eab5c44d275d1c10a8bd24b3dfa0fdec2d
CleitonSilvaT/URI_Python
/1-Iniciante/1959.py
236
3.609375
4
# -*- coding: utf-8 -*- if __name__ == '__main__': # Entrada entrada = input() valores = entrada.split(' ') # Calculando perimetro perimetro = int(valores[0]) * int(valores[1]) # Resultado print(perimetro)
8257fa758c43dd51a3149c3efa8251c30504b918
springle/PythonTweetMatch
/TweetMatch.py
3,023
3.59375
4
import random from TwitterAPI import TwitterAPI api = TwitterAPI('ha6n4e9gtH493V7fM8BI40ah4', 'TJNFLmXroylT0WVOohZnCAwp2gDHGWgzmnUDgKps4pKa2h42zy', '3845649433-jU8cxYET5DHYHSjzxfVwpntNYCX5ttvfUn8Fxx7', 'AOo8swxsjLhFoOUktJrlMHODVKzWjVh5KECcgU57d1Pci') twitterData = api.request('lists/statuses', {'owner_screen_name':'sam...
077de83c283d86bc0bcc375b632c714cbeb4c8ca
daniel-reich/turbo-robot
/vcFgGJHxhTwRiLK5d_15.py
667
4
4
""" Given a positive integer `n`, implement a function that finds the **smallest** number that is evenly divisible by the integers `1` through `n` inclusive. ### Examples smallest(1) ➞ 1 smallest(5) ➞ 60 smallest(10) ➞ 2520 smallest(20) ➞ 232792560 ### Notes N/A """ def smallest...
b9abd6cb208936fa16fc4b5dadcb346ff48ecd44
tuheenahmmed/week04
/8_exceptions&assertions_exercise_2.py
3,992
3.921875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jun 26 07:13:57 2018 @author: tuheenahmmed """ #number 01 def fancy_divide(numbers,index): try: denom = numbers[index] for i in range(len(numbers)): numbers[i] /= denom except IndexError: print("-1") else...
a6753aa63046bb13a06ed7489e6c5a97217296a2
mworrall1101/code-from-school
/summer16/Week09/table_to_dict.py
2,355
3.71875
4
# table_to_dict.py # # # # B. Bird - 06/28/2016 import sys #Create a new exception type (subclassed from 'Exception') #to represent duplicate key errors class DuplicateKeyError(Exception): #The __init__ method is the constructor #All instance methods take a parameter 'self' #as their first argument. #When the ins...
0db1ecc859a75d6b366ff9bbb8f0992e1e2348c6
levlab79/hometasks
/Berezianskii_Lev_dz_7/task_3.py
3,522
3.53125
4
# Задание 3. class Cell: def __init__(self, count): if count > 0: self._count = count else: raise ValueError('Количество ячеек клетки должно быть положительно.') def __add__(self, other): '''Сложение''' if self._check_class(other): return Ce...
86f4b627a34ecb015fd48957ade47f89a93ccd41
Kaushal28/SDE-Interview-Resources
/Design Patterns/decorator_pattern.py
2,379
4.6875
5
# Decorator is a structural design pattern. # Decorator pattern is used when the behaviour of a single or multiple # class objects is required be extended (not all class objects, otherwise # this can be done using subclass). It creates a wrapper like structure, # which wraps new functionalities over existing functiona...
37dc91bcf57a14b40fa9c76585fb55905a605447
zw543418882/CSCI-630
/AI HW1.py
568
4
4
import math def bfs(val, goal): path = [] while val != goal: for i in range(0, 3): if i == 0: val = math.sqrt(val) path.append(val) bfs(val,goal) elif i == 1: val = math.factorial(val) path...
91f0a2394536c6516380fbe9f41f133ccf522dd7
unboundthoughts/Simple_Banking_System
/Simple Banking System/task/banking/banking.py
7,159
3.59375
4
# Write your code here import random import sys import sqlite3 conn = sqlite3.connect('card.s3db') cur = conn.cursor() cur.execute(''' CREATE TABLE IF NOT EXISTS card ( id INTEGER , number TEXT , pin TEXT , balance INTEGER DEFAULT 0 ) ''') # check if table exists if not then create table conn.commit(...
c3a0d5bdd28b124991a0321e6e006b2e7393bcc2
um-computacion-tm/parcial-2021-11-03-celinalopez
/buscaminas.py
2,318
3.625
4
from random import randint class Buscaminas: def __init__(self, rows, cols, bombs): self.rows = rows self.cols = cols self.bombs = bombs self.initial_board = [['-' for x in range(self.rows)] for y in range(self.cols)] self.board = self.crear_tablero() def crear_tabler...
533d5a86fe6e1e89c1ee504ee052c1cc8bd96c1e
katryo/leetcode
/1268-search-suggestion-system/solution.py
866
3.5
4
from typing import List class Solution: def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]: trie = [{}, set()] for prod in products: cur = trie[0] for letter in prod: if not letter in cur: cur[letter] = [...
42abeb404c0418b7fe714111604f49c4a9513f13
Sirpy-Palaniswamy/HackerRank-Solutions
/Floor-Ceil-Rint.py
275
3.625
4
#Problem """ You are given a 1-D array, A. Your task is to print the Floor, Ceil and Rint of all the elements of A. """ #Code import numpy as np np.set_printoptions(sign=' ') arr = np.array(input().split(),float) print(np.floor(arr)) print(np.ceil(arr)) print(np.rint(arr))
1b663d4b9cd2e6bca1f19b665464621ac6a5573c
estansifer/chess
/src/py/timer.py
640
3.53125
4
import time class Timer: def __init__(self): self.intervals = [] self.cur = None def __enter__(self): self.cur = time.perf_counter() def __exit__(self, *args, **kwargs): x = time.perf_counter() - self.cur self.intervals.append(x) go = __enter__ stop = __ex...
c748e0fc29a84df1f2b582c1f2fe39926e21a7d5
Donghyun-34/KUCIS
/project/머신 러닝/파이썬/palindrome.py
414
4.09375
4
def is_palindrome(word): # 코드를 입력하세요. word_list = list(word) # word_list.reverse() revers_list = word_list[::-1] if word_list == revers_list: return True else: return False # 테스트 print(is_palindrome("racecar")) print(is_palindrome("stars")) print(is_palindrome("토마...
0421833541c8b9ace95a2377a0abe6f5368255fd
imraanishmail/pizza-ordering-application
/Assignment03.py
4,392
4.15625
4
def calcSubtotal(pizzas, drinkQuantity, dessert, delivery): subtotal = 0 subtotal += drinkQuantity * 3 # for drinks subtotal += 5 #for desserts if delivery == True: subtotal+= 10 for pizza in pizzas: if pizzas[pizza]["pizzaSize"] == "Small": subtotal+= 10 elif pizzas[pizza]["pizzaSize"] ...
060b2cc4c8e4f423083fe9322aece9ddf8bfb320
solka-git/Python-Orion-basic-
/homeworks/files_context_managers/HW#9_task2.py
603
3.828125
4
""" Task 2 в файлі task2 збережений список, відкрийте цей файл, прочитайте вміст, і знайдіть середнє арифметичне чисел що знаходяться в списку """ import pickle def arithmetic_mean(filename): with open(filename, "rb") as file: obj = pickle.load(file) summ = 0 for i in obj: sum...
f0880332bfac0bca5c41279c135425260c6bcb89
AkbarovEldar/PythonInterns
/python_loops.py
1,209
3.8125
4
# print("it's a number " + str(int_var)) # number=0 # nStr = "" # for i in range(1,10+1): # nStr+=str(i) # print(nStr) # number+=1 # print(number) # number = 1 # for i in range(10): # number+=i # print(i) # for i in range(1,10,2): # number+=2 # print(i) # # animals = ["cat", "dog...
eea5c1852df6952da8de358ea3ddc6836c3bd0fa
jackschlehr2/cse-20289-sp21-assignments
/homework04/rpn.py
1,544
3.78125
4
#!/usr/bin/env python3 import os import sys # Globals OPERATORS = {'+', '-', '*', '/'} # Functions def usage(status=0): ''' Display usage message and exit with status. ''' progname = os.path.basename(sys.argv[0]) print(f'''Usage: {progname} By default, {progname} will process expressions from standard...
406a82e51a3cd9690fdd1e3d221f5da1a0cf6e25
seckcoder/lang-learn
/python/regular_expression.py
263
3.84375
4
#!/usr/bin/env python import re m = re.search("c", "abcdef") if m: print 'search' m = re.match("c", "abcdef") if m: print 'match' m = re.match(r"(?P<first_name>\w+\?\w+) (?P<last_name>\w+)", "Is?sac Newton") if m: print m.group("first_name"), m.group("last_name")
d2d70636e10a742119a19ae80c3252740cf88d8c
Burakkylmz/Exception-Handling
/TypeOfException.py
356
3.734375
4
#Type of Exceptions # print "hello world" # SyntaxError: Missing parentheses in call to 'print'. Did you mean print("hello world")? # x = 5 / 0 # ZeroDivisionError: division by zero #lst = [1,2,3] #print(lst[3]) # IndexError: list index out of range # lst = [1,2] # lst + 2 # TypeError: can only conc...
ffe36017a8b3033e6a8c588e88397d5f221d9acc
romulets/adventofcode2019
/day_two/day_two.py
1,963
3.53125
4
__INSTRUCTION_ADD__ = 1 __INSTRUCTION_MULT__ = 2 __INSTRUCTION_EXIT__ = 99 def aggregate_memory(memory, instruction_pointer, agg_func): num1_address = memory[instruction_pointer + 1] num2_address = memory[instruction_pointer + 2] result_address = memory[instruction_pointer + 3] num1 = memory[num1...
2b144644ef399275e1dcffe9bcf678eb0611c209
Samwest5/kattis
/kattis/sibice.py
353
3.609375
4
import sys, math box = [] for i in sys.stdin: if len(i.split()) == 3: box.append([float(x) for x in i.split()]) else: box.append(float(i)) for i in range(1, len(box)): if(box[i] > box[0][1] and box[i] > box[0][2] and box[i] > math.sqrt(box[0][1]**2 + box[0][2]**2)): print('NE') els...
b01b6c39945f2f395e1cd19f7324d73e44d2a581
vini-2002/LeetCode-Solutions
/String/58. Length of Last Word/Solution.py
147
3.5
4
class Solution(object): def lengthOfLastWord(self, s): s=s.rstrip() words=s.split(" ") return len(words[len(words)-1])
4972c9ea9bcdf8aa8285455c27512301fc1240a5
mrbshaw/intergration
/Main.py
9,966
4.34375
4
""" This is my main file for this program. __author__ = Robert Shaw Jr. Code from Prof. Van. AND Python Activity 1 -13. """ # Trivia game based of the Wheel of time books. print("Welcome to My Trivia Game!") # A function is a segment of code that performs a single task. def run_pay(): """ to run this from menu. ...
2977d82f89b9b0022ea424098859a33f976d97b5
squash1205/DS-HW1and2
/Quiz2.3.py
330
3.625
4
def findLargestNum(toBeFind): i = 0 while i < len(toBeFind) - 1: if toBeFind[i] >= toBeFind[i + 1]: toBeFind[i + 1] = toBeFind[i] i = i + 1 print(toBeFind[len(toBeFind) - 1]) findLargestNum([1000, 1001, 857, 1]) findLargestNum([10000, 1000, 100, 10, 1, 0, -1]) findLargestNum([-...
9d7bff92bf045cbe9be24a0965dd7109e4c06c22
Yuri-Santiago/sor-python-ifce-p7
/Aula 02/atv03.py
470
4.1875
4
# Escrever um programa que informe ao usuário o maior e o menor elemento de uma lista e o valor médio dos elementos da # lista. Utilize uma lista com 10 elementos. lista = [2, 4, 7, 3, 1, 0, 6, 9, 5, 8] lista_ascendente = sorted(lista) print(f'{lista_ascendente}') print(f'O menor elemento é {lista_ascendente[0]} e o m...
b3bbe801f409e40a67e2cc476b9d6424fd5b69e6
missing-semicolon/advent-of-code-2018
/day11_chronal_charge.py
2,923
3.53125
4
from typing import Tuple, List SERIAL_NUMBER = 1308 def get_hundreds(x: int) -> int: if x < 100: return 0 else: return (x % 1000 - x % 100) // 100 def get_power_from_coord(coord: Tuple[int, int], serial_number=SERIAL_NUMBER) -> int: x, y = coord rack_id = x + 10 power_level = ra...
55be3b0f5cb4e75a5d327f27882f4eb4281b91f3
jnez71/airhockey
/control/controller.py
3,351
3.75
4
""" Basic Neural Network Controller A single layer neural network (NN) is used to generate a feedforward term for a typical state-feedback (PD) controller. The system is assumed to have error dynamics of the form, edot = f(x) - u, i.e. control-affine, holonomic, and time-invariant The input to the NN is the ful...
be327c926a1905af63a7aaf22e7decaf88f1d2a9
oscarfonsecaneira/Primer-Parcial
/punto2.py
495
3.875
4
import numpy as np import math def funcion (x): return math.log(x+2,math.exp(1)) + np.sin(x) def formula (x1,x2): return x1-((funcion(x1)*(x1-x2))/(funcion(x1)-funcion(x2))) def operacion(x,x1,x2,E): if funcion(x) > E or funcion(x) < 0: x2 = x1 x1 = x x = formula(x1,x2) return operacion(x,x1,x2...
9de873415c2777456c3d4d3886b86893e46635a1
preethamsridhar/Algorithms
/PermuteString.py
557
3.921875
4
noOfPermute = 0 def permute(word, low, high): global noOfPermute # to count the number of permutations of the string if low == high: print("".join(n for n in word)) noOfPermute +=1 else: for i in range(low, high): word[i], word[low] = word[low], word[i] # swap ...
d443b954222519ed2f8278025027493ea454a484
NullOsama/Integrals
/riemann.py
3,256
3.953125
4
import numpy as np import matplotlib.pyplot as plt from .integrate import Integrate class Riemann(Integrate): """ Compute the Riemann sum of f(x) over the interval [a,b]. Parameters ---------- f : function A single variable function f(x), ex: lambda x:np.exp(x**2) """ def _...
bbc1f4983b06b20e937ba5191d6e94dcde2a9bf6
0xJeremy/data-structures-and-algorithms
/algorithms/knapsack.py
357
3.734375
4
def _knapSack(W, weight, value, n): if n == 0 or W == 0: return 0 if(weight[n-1] > W): return _knapSack(W, weight, value, n-1) else: return max(value[n-1] + _knapSack(W-weight[n-1], weight, value, n-1), _knapSack(W, weight, value, n-1)) def KnapSack(maxWeight, weights, values): return _knapSack(max...
3398d10862861ed4c5c6cf5467256416736d0f30
jasperlankhorst/dataprocessing
/homework/week_4/convertCSV2JSON.py
970
3.875
4
#!/usr/bin/env python # Name: Jasper Lankhorst # Student number: 10885803 import csv import json from io import StringIO INPUT = "data.csv" OUTPUT = "data.json" INDEX = "AUS" MEASURE = "KTOE" def tojson(input_csv, output_json): """ Converts a CSV (or .txt, as long as it's comma separated) to a JSON file, ...
0ab9f73b307f7571adf005ea5e1ca79444baa03c
ericd9799/PythonPractice
/listPrintLess.py
387
3.9375
4
#! /usr/bin/python3 import random def main(): a = [] b = [] listSize =int(input("Enter size of list: ")) compare = int(input("Enter integer to compare to: ")) for x in range(listSize): a.insert(x, random.randrange(100)) print("List a: "+str(a)) for x in a: if x < compare: print(x) b.append(x) ...
cbfe050263721a2c3f92ede3080df8f5db6bf27b
GGL12/myStudy
/leetcode/leetcode/226.反转二叉树.py
725
3.796875
4
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def invertTree(self, root): #递归 if not root: return None left = self.invertTree(root.left) right = self.invertTree(root.right) root....
95e179c9e4aad9081fa4d38a333f95c75d8b94bf
torenord/euler
/problem7.py
330
3.875
4
#!/usr/bin/env python3 # Problem 7: 10001st prime # By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we # can see that the 6th prime is 13. # What is the 10 001st prime number? from problem3 import primes def problem7(): return list(primes(104743))[10000] if __name__ == '__main__': print(pr...
31d9f3a2cb3d621a6176cf2aa8b47776bad0790b
oliver-ode/Algorithmic-Coding
/ProjectEuler/problem52.py
464
3.5625
4
num = 1 nums = [] digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] while True: nums.clear() pos = True nums.append(num) for multi in range(2, 7): nums.append(num*multi) for digit in digits: for i in range(0, 5): if str(nums[i]).count(str(digit))!=str(nums[i+1]).count(str(digit)): ...
6dee6c0b23b41b0d00c08f91fb09155b330a348d
IntroProgramacion-P-Oct20-Feb21/trabajofinal-1bim-JamilErasmo
/semana 4/ejercicios-clase-04-1bim-JamilErasmo/Ejemplo02/Ejemplo03.py
238
3.84375
4
nombre = input("Ingrese nombre del estudiante: ") apellido = input("Ingrese el apellido del estudiante: ") nacimiento = input("Ingrese la fecha de nacimiento: ") print("Datos del estudiante\n%s\n%s\n%s\n" %(nombre, apellido, nacimiento))
5c1e6bb41a3b3d2b99a9530e55db68c8dbdc354a
PSAB/Python-Machine-Learning
/Machine Learning A-Z Template Folder/Part 2 - Regression/Section 4 - Simple Linear Regression/simple_linear_regression.py
2,269
3.9375
4
# #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Mar 21 14:48:55 2018 @author: johnyorangeseed """ import numpy as np import matplotlib.pyplot as plt import pandas as pd #import and section the datasets dataset = pd.read_csv('Salary_Data.csv') X = dataset.iloc[:, :-1].values Y = dataset.iloc[:, 1]...
61ccc186ca8318142f263c2989bdc47ec20b807f
aimeirabahaye/Project-Euler
/55.py
370
3.515625
4
def palyndrome(n): x = str(n) if x == x[::-1]: return True else: return False def lychrel(n): count = 1 while count <= 50: x = str(n) reverse_ = x[::-1] a = int(reverse_) + n if palyndrome(a) == True: return False else: n = a count += 1 return True number = 0 for n in range(1,10000): ...
a238a2331aa2932340848983499a9ea2a9ca3257
wenkejiang/Python-Study
/self_idempotent.py
1,131
3.609375
4
# -*- coding: utf-8 -*- """ @Time : 2020/10/30 11:58 上午 @Auth : 姜文科 @File :self_idempotent.py @IDE :PyCharm @Motto:ABC(Always Be Coding) """ import os import time class SelfIdempotent(object): def make_self_num(self): for num in range(100, 1000): low = num % 10 mid = num // 10 % 1...
5edf79b616fc0566c8a2c8ee26571252ce31fab7
gabopotestades/python_mini_projects
/Hackerrank/Math/Triangle Quest 2.py
124
3.734375
4
#Get n inputs for n in range(1, int(input()) + 1): #Print each palindrome using this formula print(((10**n)//9)**2)
ff5092f03156d7b27b76cb9ab5ba1d03c7b31c19
rafaelperazzo/programacao-web
/moodledata/vpl_data/2/usersdata/91/976/submittedfiles/poligono.py
124
3.890625
4
# -*- coding: utf-8 -*- from __future__ import division n= input('Digite oo valor de n:') nd=(n*(n-3)/2) print ('%.1f'%nd)
9e08c7cdcde8204fbb79f293d2c6e6551e11d445
ayush879/python
/17.py
276
4.1875
4
#17) Replaces the substring with the pattern and counts how many times it has done the same. import re string = input("Enter a string : ") string_replace = input("Enter a replace string : ") pattern = input("enter the pattern") print(re.sub(pattern, string_replace, string))
dd565736db8b29c76a20a658cac9087924af475e
19973466719/Python--
/51CTO课程/day5/函数/函数的返回值.py
199
3.75
4
#编写函数,实现功能,给函数两个数,返回这两个数的和 def mysum(num1,num2): sum=num1+num2 return sum #执行return之后,函数结束了 res=mysum(1,2) print(res)
b1c15ee5fb9a7b9a89eaeb723ccc8474600814e8
CmdrFop/Practical2
/division.py
2,111
3.796875
4
groups = ['0', '1', '2', '3'] elements = groups group = '0123' cost = [3, -2, 6, -3] max_divisions = 2 def recursion_solution(group, cost, max_divisions, elements): # If we meet the base case we return the cost for this single item if len(group) == 1: return cost[int(group)], [group], 1 # Create 2...
cfe93079e1081043411e5e1d47655a0f48e7fea4
DudeMSK/module-1
/Module_1.py
645
3.546875
4
def readWords(filename): with open(filename) as f: for line in f: words = ''.join(s for s in line if s.isalpha() or s.isspace()) for word in words.split(): yield word.lower() list = [] dict = {} i = 0 for word in readWords(input()): list.append(word)...
0b151ab4cdff6cade6a6f4ee7875a952b1d777fe
t2y/python-study
/LanguageProcessing/100-knocks-2015/chapter1/05.py
604
3.78125
4
""" 05. n-gram 与えられたシーケンス(文字列やリストなど)からn-gramを作る関数を作成せよ.この関数を用い,"I am an NLPer"という文から単語bi-gram,文字bi-gramを得よ. """ def char_bi_gram(s): length = len(s) if length < 2: yield s return for i, c in enumerate(s): yield c + s[i + 1] if i == length - 2: break def word_bi...
543c829911775e3e9ff7a87ceb78cff3434e0a77
Tmk10/Hacker-Rank
/word_order.py
237
3.75
4
from collections import OrderedDict word_dict = OrderedDict() for _ in range(int(input())): temp_word = input() word_dict[temp_word] = word_dict.setdefault(temp_word, 0) + 1 print(len(word_dict)) print(*word_dict.values())
bb3f48437f278ea5dc68406fd1493ce8fd186356
Rumate911/PYTHON_18022020_2
/ua/univer/base/Bank_0303/__main__.py
1,228
3.921875
4
def calculate_complex_rate(rate,money,period): month_sum = money for i in range(1,period+1): month_sum = round(month_sum + month_sum*(rate/100/12),2) print(i,month_sum) return month_sum def calculate_simple_rate(rate,money,period): for i in range(1,period+1): result_sum = round...
b8a26594371e5adabdb5e5801be7004e0fcfc29e
aditya618/Tik-Tac-Toe
/tik-tak-toe.py
6,504
4.09375
4
first_row = [' ', ' ', ' '] second_row = [' ', ' ', ' '] third_row = [' ', ' ', ' '] chosen_pattern = 'X' def game_display(first_row, second_row, third_row): print(f' {first_row[0]} | {first_row[1]} | {first_row[2]}') print('-----------') print(f' {second_row[0]} | {second_row[1]} | {second_r...
7921023b2e11096e1a12feafbd3d691004265897
Ikshitkate/java-html-5-new-project
/python/fibonacci.py
642
4.15625
4
#I've included while loop and try except so that invalid inputs can be detected and error message printed while True: num = input("Enter the Number:") try: n = int(num) break except: print("Invalid Input. You can enter only positive integers.") n1, n2 = 0, 1 #In the following line th...
7931d2e0254a0d6bfd3a475e72d4d522102fb4ce
FZamberlam/MITx-6.00.1x-Python
/Week_1_-_Python_Basics/Exercises/bisection_search.py
787
3.859375
4
# -*- coding: utf-8 -*- """ Created on Sat Sep 5 06:23:30 2020 @author: Zamberlam """ print('Please think of a number between 0 and 100!') low = 0 high = 100 guess = False while not guess: ans = (high + low) // 2 print('\nIs your secret number ' + str(ans) + '?') user_input = input("Enter 'h...
daa48c4f0b5c89be6300556c73c31c514cd96833
lucas-sigma/Python-Brasil-Resposta-Exercicios
/Estrutura-Repeticao/ex17.py
224
4.09375
4
''' Faça um programa que calcule o fatorial de um número inteiro fornecido pelo usuário. Ex.: 5! = 5.4.3.2.1 = 120 ''' n, fatorial = int(input('Numero: ')), 1 for i in range(n, 1, -1): fatorial *= i print(fatorial)
e72bea66f7fab71ec75f4086aa0fc41c46eef8fe
mmardene1982/Python-course
/Excersizes/Our First Database.py
920
3.578125
4
import sqlite3 conn= sqlite3.connect('Ages.sqlite') cur = conn.cursor() cur.execute("DROP TABLE IF EXISTS Ages") cur.execute("CREATE TABLE Ages (name VARCHAR(128), age INTEGER)") conn.commit() for i in range(4): name= input('Enter name: ') age= input('Enter age: ') age= int(age) sqlcommand= '''INSERT...
272780efde967884d599ef1d3692a521c6080057
amakaa/dev-challenge
/chapter2_exercises.py
930
3.734375
4
# Exercises for chapter 2: # Name: Amaka Atoyebi #2.1 print 5 x = 5 print x + 1 #2.2 val1 = 01 val2 = 010 val3 = 0100 val4 = 01000 print (val1) print (val2) print (val3) print (val4) #2.3 # 8 # 8.5 # 4.0 # 11 #..... #2.4 #1 pi = 3.14 r = 5**3 vol = (4*pi*r)/3 print (vol) #2 cp = 24.95 perc = .4 first = 3 ...
db45cb311ebbb41e0b6520925d71c2f3afd1453b
davecampbell13/gocode
/blog-model/webserver-3.py
2,918
4.3125
4
''' Phase three: Templating Templating allows a program to replace data dynamically in an html file. Ex: A blog page, we wouldn't write a whole new html file for every blog page. We want to write the html part, and styling just once, then just inject the different blog data into that page. 1) Add the following l...
08e613c3d9ad403efc18fc095e70806ca1140550
GabitovRuslan/Home_work_OOP
/main.py
5,828
3.828125
4
class Geese: animal_list = [] def __init__(self, name, weight, food, eggs=0, feed=0): self.name = name self.weight = weight self.food = food self.feed = feed self.eggs = eggs self.animal_list.append(self) def feed_animal(self, food): satiety = 100 ...
d60810490c33b18b8e2322a3413997df77213211
herofyf/python_examples
/Numpy_Example_List.py
888
3.53125
4
import numpy as np # http://scipy.github.io/old-wiki/pages/Numpy_Example_List test_case = 3 if (test_case == 1): A = np.arange(3, 15).reshape(3, 4) for item in A: print(item) for item in A.flat: print(item) elif test_case == 2: A = np.ones((2,2)) B = np.random.randin...
0ae5eb259422ed9687093e46c88f90ef494acf9b
pchen12567/Leetcode
/Algorithm_Sort/InsertionSort/insertion_sort.py
760
3.96875
4
def insertionSort(nums): # 遍历 len(nums)-1 次 for i in range(len(nums) - 1): # curNum 保存当前待插入的数 curNum = nums[i + 1] # preIndex 保存前一个数的索引 preIndex = i # 将比 curNum 大的元素向后移动 while curNum < nums[preIndex] and preIndex >= 0: nums[preIndex + 1] = nums[preInde...
b4fb9bf19ef5e243a251b68417bb54a471afa341
rafaelprogrammer/curso-python3
/guppe/basico/ententendo_ranges.py
232
4.28125
4
""" Entendendo o Range """ for num in range(11): print(num) for num in range(1, 11): print(num) for num in range(1, 11, 2): print(num) for num in range(11, 0, -1): print(num) lista = list(range(11)) print(lista)
3f74e38c3359bf410b24887aaf925c23a87e30cd
ltsdw/Uri-Online-Judge
/python/iniciante/1079.py
243
3.609375
4
''' title: Médias Ponderadas number of the problem: 1079 date: 07/03/2018 author: ltsdw ''' for _ in range(0, int(input())): n1, n2, n3 = map(float, input().split()) media = ((n1*2) + (n2*3) + (n3*5)) / 10 print(f'{media:.1f}')
74cf862c3e77ccb9d510026afcb951083436b292
Graciarp/PemrogramanGUI_Teori_Praktikum
/PRAKTIKUM/Pertemuan 3/Person.py
853
3.78125
4
# DEKLARASI CLASS class Person : # Constructor def __init__(self, fname, lname): self.firstname = fname self.lastname = lname #------------------------------------------------------------------------# # CONSTRUCTOR # # ...
5264f83c701d08c0829868102571bb80c4c490cf
techtalktamizha/PythonTutorial
/comprehensions.py
279
3.84375
4
import sys print(sys.version) ''' values = range(100) evens = [] for no in values: if no%2 == 0: evens.append(no) print(evens) print([no for no in values if no%2 == 0 ]) ''' dictcomp = {x:x*3 for x in "arockia"} setcomp = {x for x in [1,2,3,3]} print(dictcomp) print(setcomp)
6a73fa0447e6f5eea833c08247e8fc7bb33968cb
charpdev/tests
/main.py
515
3.53125
4
import unittest from FizzBuzz import FizzBuzz import sys class FizzBuzzTest(unittest.TestCase): def test_ExpectFizz_When_3_Is_Input(self): self.assertEqual(FizzBuzz(3), 'Fizz') def test_ExpectBuzz_When_5_Is_Input(self): self.assertEqual(FizzBuzz(5), 'Buzz') def test_ExpectFizzBuzz_When_...
3342967e5a2a6b0ec118ff68e35deeb979edbcce
amirmirzaeimoghadam/PYTHON
/Ex5/073.py
281
3.734375
4
dict_food={} for i in range(0,4): dict_food[i] = input("plz enter your favorite foods:") print (dict_food) food_del = input('Which one do you want to get rid of? ') for i in range(0,4): if dict_food[i]== food_del : dict_food.pop(i) print(dict_food)
7b0c24adb446ea87d8953aea69e17a395322508b
pedrovarangot/project_euler
/30/sum_powers.py
219
4.1875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Aug 31 19:10:18 2017 @author: peter """ def sum_power_digits(n, p): sum = 0 for d in str(n): sum += int(d)**p return sum
113fe99124ec7490fbb00ef570b7560744002c84
rpatel1291/SSW567-Assignment4a
/Main.py
1,207
4.0625
4
import requests import json ''' Created on Sunday Sept 22, 2019 @author: Ravi Patel @cwid: 10432313 ''' def isValid(username): ''' The function of this method is to use requests to call the github api to check the username is a valid username. :param username: :return: boolean value ''...
10429a8dee213272430b6695c46f43e4c3e635ed
CodyThomasCrump/funtions_tutorial
/functions.py
611
3.984375
4
def area(width, height): result = width * height return result result = area(5, 6) print(result) result = area(7, 3) print(result) result = area(102, 57) print(result) def subtract(num1, num2): result = num1 - num2 return result result = subtract(8, 6) print(result) result = subtract(4, 6) print(re...
1b27a8edb4c4c33a445ee44f212e9e91044f61d7
mikewarren02/PythonReview
/fizz-buzz.py
298
4.03125
4
def fizz_buzz(): number = int(input("What number did you select: ")) if number % 3 == 0 and number % 5 == 0: print("Fizz Buzz") elif number % 5 == 0: print("Buzz") elif number % 3 == 0: print("Fizz ") else: print("Not an option") fizz_buzz()
6ba7dff7b257231984293cefe984c60c8b41bdf6
Utsav-Raut/python_tutorials
/python-sdet/python_csv/demo.py
265
3.578125
4
import csv with open(r'demo.csv', 'r') as csvfile: reader=csv.reader(csvfile) for i in reader: header=i print(header) print(header[1:]) print(len(header[1:])) print(header[0].split(':')) print(len(header[0].split(':')[1:]))
0a2762d6bec71934b095ff0afab36a271b933dd4
vickyaral/python-training
/7-iterators/binarytree.py
1,743
3.875
4
class BinaryTreeInorderIterator: def __init__(self, root): self.stack = [] self.node = root def __next__(self): try: while self.node: self.stack.append(self.node) self.node = self.node.left top = self.stack.pop() val =...
1fe909b09afd329a0081e44df961a6bb5c8579a1
dajkatal/Codewars
/Python/Replace With Alphabet Position.py
250
3.734375
4
def alphabet_position(text): text = text.lower(); alphabet = {chr(i): i for i in range(97, 123)}; stng = '' for letter in text: if alphabet.get(letter, False): stng += ' {}'.format(alphabet[letter]-96) return stng[1:]
d51e4e6f5327e421ec111d31b31b1365457eb5fe
sresis/practice-problems
/validate-ip/validate-ip.py
1,152
3.96875
4
""" Edge cases: Input: '200.50.252' -> False Input: '23.23.23.23.23' -> False Input: '12.12.12.x' -> False Input: '400.2.2.2' -> False Input: '0.0.0.00' _> False Approaches: - splitting the string by '.' and then iterating through the array - validate that length of list == 4 - check each item use and convert to ...
96e0e886540f45fc9d779db428398f9f339e0169
coderZsq/coderZsq.practice.data
/study-notes/py-collection/10_绘图/06_练习.py
418
3.671875
4
import turtle as t import random as r t.pensize(10) t.colormode(255) t.hideturtle() for i in range(1, 6): # 设置画笔颜色 t.color( r.randint(0, 255), r.randint(0, 255), r.randint(0, 255) ) # 半径 radius = 30 * i # 修改一下起点 t.penup() t.sety(-radius) ...
a02b9cdba68ac7daebb2a6d8df2325ea2a36ed4f
SaiSudhaV/coding_platforms
/bst_iterator.py
784
4.0625
4
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class BSTIterator: # @param root, a binary search tree's root node def __init__(self, root): self.arr = [] push(self.arr, root) ...
08b3484893b13da7675046544b29d140fb2a69df
Oashpak/Lv-625.PythonCore
/HW6/yantoniv/Simple: Find The Distance Between Two Points.py
102
3.53125
4
def distance(x1, y1, x2, y2): return float("{0:.2f}".format(((x2-x1)**2+(y2-y1)**2)**(0.5)))
b817825e57b6ad6c2cd9ee36414fb3003f73d757
Nikitaprk/newbee_practive_day_1
/Statistics.py
1,846
3.875
4
str ="01|15|59, 1|47|16, 01|17|20, 1|32|34, 2|17|17" def first(str): str = str.replace(' ', '') str = str.split(',') # сплитим по запятым, получается список из 3 значений first_nums = [] for n in range(len(str)): # цикл для выделения 1 значений из всего списка x = str[n].replace('|', ' ') #...
7bfbcef205863dc0de8b30334a42683b854309e6
ynu/ynu_send_mail
/others/sendmail.py
712
3.78125
4
"""The first step is to create an SMTP object, each object is used for connection with one server.""" import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText msg = MIMEMultipart() msg['From'] = "sfjb-client@ynu.edu.cn" msg['To'] = "liudonghua@ynu.edu.cn" msg['Subject'] = "P...
6d5fed7257cf09fbaf05a38054eeb5a53485b08a
antoniusf/Aplyval
/lambdabox.py
11,664
3.59375
4
import pyglet, math from pyglet.gl import * import shader from triangle import Triangle class vec2: def __init__(self, *args): """Takes coordinates either as a tuple or separate""" self.set(args) def set(self, *args): """Takes coordinates either as a tuple or separate""" if le...
2e81de05795a1ef96ef92598646419e6e9237239
Rich43/rog
/albums/3/challenge60_easy/code.py
701
3.9375
4
''' A polite number n is an integer that is the sum of two or more consecutive non-negative integers in at least one way. Here is an article helping in understanding Polite numbers Your challenge is to write a function to determine the ways if a number is polite or not. ''' def polite(n): # 1 is an impolite numbe...
bca1282e3df27cd5f281130bdf80cfc61e0d01fc
StaNC2000/hangman
/hangman_python3.py
4,204
3.78125
4
import random import time import datetime import os from operator import itemgetter os.system('clear') play = True while play: print(chr(27) + "[2J") #clear terminal os.system('clear') # initial variables lifes = 7 user_name = input('Enter your name, to play the game: ').capitalize() print('\...
91538436e6c538a9145efad664b26fe9307ce682
yzl232/code_training
/mianJing111111/epic/Let the user enter a decimal number_Greatest_Common_Divisor.py
1,012
3.703125
4
# encoding=utf-8 ''' Let the user enter a decimal number. The range allowed is 0.0001 to 0.9999. Only four decimal places are allowed. The output should be an irreducible fraction. Eg: If the user enters 0.35, the irreducible fraction will be 7/20. X = input(); Y = 10000; X = X*Y; Z = Greatest_Common_Divisor_Of (X,...
1a84de296000421f725a38ef905ab5f590d085ac
SanghamitraDutta/dsp
/python/markov.py
2,440
4.5625
5
#!/usr/bin/env python # Write a Markov text generator, [markov.py](python/markov.py). Your program should be called from the command line with two arguments: the name of a file containing *text to read*, and the *number of words to generate*. For example, if `chains.txt` contains the short story by Frigyes Karinthy, w...
b8c3d251e41f70c843322fe346cd9b2a98e63d74
jberkow713/TurtleGamePython
/Adjacency.py
2,175
3.609375
4
# def neighbors(matrix, rowNumber, colNumber): # result = [] # for rowAdd in range(-1, 2): # newRow = rowNumber + rowAdd # if newRow >= 0 and newRow <= len(matrix)-1: # for colAdd in range(-1, 2): # newCol = colNumber + colAdd # if newCol >= 0 and newC...
600aa65f5c42a23dad9a91a0f63860fc4f3cf82b
anajera10/mis3640
/Session 5/hw_5.py
680
3.796875
4
from turtle import * RAD = 100 RAD2 = RAD / 2 RAD6 = RAD / 6 degrees() # Switch to degrees # Draw the circle, radius 100, half black fillcolor('black') begin_fill() circle(RAD, 180) end_fill() circle(RAD, 180) # Draw smaller black semi-circle left(180) penup() goto(0, RAD) pendown() begin_fill() circle(RAD2, 180) en...