blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
399d5d0aafde77a01cb98e4d0e5b4284eabb2db2
simbaTmotsi/eye-vision
/ziso/save/save.py
634
3.515625
4
def save(filename, file): """ ------------------------ module for saving images ------------------------ """ def save(filename, file): try: saved_file = cv2.imwrite(str(filename),file) except: print ("Please check the file path/name, there seems to be an error") """ error checking "...
912d357085500978b63cc66e5cae14d650f1a726
dharm6619/CodeLibraries
/Python Foundations/variables.py
236
4.03125
4
# Declaration of a variable f=0 print(f) f="abc" print(f) # print("abc " * 2) # print("abc " + str(123)) def someFunction(): global f f = "def" print(f) someFunction() print(f) del f print(f)
30233e24109e96da7db0217b6f9d48f10c49fb58
redforks/spork-compiler
/clientlib/sftest/string.py
7,871
3.734375
4
# -*- coding: utf-8 -*- from unittest import TestCase class StringTests(TestCase): def test_concat(self): self.assertEqual('a', 'a' + '') self.assertEqual('汉bc', '汉' + 'bc') self.assertEqual(u'汉bc', u'汉' + u'bc') def test_str_constructor(self): self.assertEqual('', str('')) ...
728c57a99d958e46071a42d3739aeb13a246fd8f
Boellis/PatRpi3
/IndividualStock.py
1,460
3.703125
4
from urllib.request import urlopen from bs4 import BeautifulSoup from googlesearch import search def findStock(StockName): #Ask what stock #StockName = input('Enter the name of the stock you want information for: ') #Specify this input is a stock that exists on the nasdaq and format the input StockPag...
5781e66e5bbfb2ca9f7902c0e03346fa2df61b2b
cassiossousa/dabbling-in-ai
/tictactoe/player.py
1,124
3.546875
4
# Defines a generic player of tic-tac-toe. from abc import ABCMeta, abstractmethod from random import choice class Player(): __metaclass__ = ABCMeta symbol = None board = None def __init__(self, player_id, board, symbol): self.id = player_id self.board = board self.symbol = s...
3ac3bf4c40a478f27b78b30a2abc34f93073fe72
jcemelanda/HackerRankResolution
/warmup/sherlock_beast.py
512
3.984375
4
__author__ = 'julio' test_case = input() for _ in xrange(test_case): digit_num = input() if not digit_num % 3: print '5' * digit_num continue fives = digit_num - 5 while fives >= 3: if not fives % 3: print '5' * fives + '3' * (digit_num - fives) brea...
c450c4f017804b93595bc90865dfd220dd07bd73
shellshock1953/python
/games/snake.py
4,175
3.515625
4
import time import copy import sys, select import os import random class Board(): def __init__(self, size=10): self.size = size self.board = self.generate() def generate(self): board = [[ '.' for _ in range(self.size)] for _ in range(self.size)] return board def show(s...
fb992c8c25e5283b82a87f67972ee0445e4e0c85
Sindhu983/function
/function.py
260
3.703125
4
def func1(): print( " I am learning Python function") print (" still in func1") func1() def square(x): return x*x print( square(4)) def multiply(x,y=0): print("value of x=",x) print("value of y=",y) return x*y print (multiply(y=2,x=4))
bc75a37e05ce01e03e436a6e793e696b65bd3154
hunter-darling/hackerrank-junk
/hackerrank-challenges/repeatedString.py
547
4
4
#!/bin/python3 #solved 2020-01-19 #Hunter Darling import math import os import random import re import sys # Complete the repeatedString function below. def repeatedString(s, n): l = len(s) #print(l) c_temp = s.count('a') #print(c_temp) q = int(math.floor(n/l)) #print(q) r = n%l #pri...
a61ca2a777e6452653fe7fbf6cbcf84232362311
rafaelperazzo/programacao-web
/moodledata/vpl_data/77/usersdata/224/40216/submittedfiles/exercicio24.py
217
3.671875
4
# -*- coding: utf-8 -*- import math a=int(input('Digite o primeiro valor: ')) b=int(input('Digite o segundo valor: ')) cont=0 i=1 for i in range(1,n+1,1): if (a%i==0) and (b%i==0): cont=cont+i print(cont)
49fdf3e106d81fcb1ea21b97c11999d3dfc5608b
JeeZeh/kattis.py
/Solutions/oddities.py
155
4.03125
4
m = int(input()) for i in range(0, m): n = int(input()) if abs(n)%2 != 0: print("%d is odd" % n) else: print("%d is even" % n)
1a1befe7ec2557c875fb529fc11348e9df7ad814
ananiastnj/PythonLearnings
/LearningPrograms/RegExp.py
5,459
3.734375
4
''' ***** REGULAR EXPRESSIONS ***** -> A regular expression is a special sequence of characters that help you to match or find other strings or sets of strings using specialized syntex held in pattern -> The module re provides full support for RE. if any error occurs module raises the exception re.error Single line ma...
ff57ecdea59911bf3b39dc12a0328cdc660ea639
qudcks0703/python
/python0303/for02.py
155
3.765625
4
result=[] for i in range(1,5): result.append(i*3) print(result) result=[i*3 for i in range(1,4)] #표현식 for 항목 in 반복가능개체 if 조건
621a0ff1cb09f8f3aa8bb1d4ccfc2e9706d1bbbf
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_136/2031.py
640
3.6875
4
def worthIt(cost, curRate, boost, goal): # calculate whether we will finish earlier if buy timeToFinish = goal / curRate timeToBoost = cost / curRate timeFromBoost = goal / (curRate + boost) if timeToFinish < timeToBoost + timeFromBoost: return False else: return True T = in...
fce0eb31b46a3838baca3c5bf1ae6082ce3323b2
lsjhome/algorithms_for_all_py
/Chapter_05/E01_Fibo.py
181
3.609375
4
def fibo(n): if n <= 1: return n return fibo(n-1) + fibo(n-2) if __name__ =="__main__": print (fibo(1)) print (fibo(3)) print (fibo(10))
eb59e72e9173cd3712e9cdd79e18f8d1182cfc15
ianaquino47/Daily-Coding-Problems
/Problem_34.py
1,151
4.21875
4
# This problem was asked by Quora. # Given a string, find the palindrome that can be made by inserting the fewest number of characters as possible anywhere in the word. If there is more than one palindrome of minimum length that can be made, return the lexicographically earliest one (the first one alphabetically). # ...
2c70a04e773f8a74b0f624244beb2da19c3cdf90
eduardorasgado/divide-and-conquer-algorithms
/selectionsort.py
982
4.15625
4
#SelectionSort """ Ordenamiento por seleccion Es un algoritmo que consiste en ordenar de manera ascendente o descendente Funcionamiento: -Buscar el dato mas pequeño de la lista -Intercambiarlo por el actual -Seguir buscando el dato mas pequeño de la lista -Intercambiarlo por el actual -Repeticion sucesiva ...
ab9a445d8e4180bff2255046363ef6988ed96cdc
minhajar/hajar-lamtaai-42AI-bootcamp
/module00/recipe.py
1,963
4.1875
4
cookbook={ "cake":{"Ingredients":["flour","eggs","sugar"], "mealType":"dessert", "cookingTime":60}, "sandwich":{"Ingredients":["bread","greens","chicken"], "mealType":"lunch", "cookingTime":10}, "salad":{"Ingredients":["greens","veggies","sauce"], ...
4f4df4e509d2016939ccd61b348272a77d8fca09
liangsongyou/python-crash-course-code
/chapter2/new.py
133
3.59375
4
mess = "new mess" print("{}".format(mess)) mess = "Yet another new mess" print("The previous mess was changed to: {}".format(mess))
1099c6a0cd94af611a55a81067d49540ce6739c6
juanall/Informatica
/TP2.py/2.3.py
432
4.0625
4
#Ejercicio 3 #Escribí un programa que dado un número del 1 al 6, ingresado por teclado, muestre cuál es el número que está en la cara opuesta de un dado. Si el número es menor a 1 y mayor a 6 se debe mostrar un mensaje indicando que es incorrecto el número ingresado. numero = int(input("ingrese un numero del 1 al 6:"))...
69d7097a364b14a4a72eb9c5f70b5a2579c12d4f
arnoldvc/Leccion1
/Leccion05/Set.py
565
4.03125
4
# set planetas = {'Marte', 'Júpiter', 'Venus'} print(planetas) #largo print(len(planetas)) # revisar si un elemento está presente print('Marte' in planetas) # agregar un elemento planetas.add('Tierra') print( planetas) #no se pueden duplicar elementos planetas.add('Tierra') print(planetas) # eliminar elemento posibleme...
81f584cd1b42d1954bd3acc0d98bb9850eadcb83
nda11/CS0008-f2016
/ch3/ch3-ex9.py
645
4.21875
4
#get the input for user number=input('give me the number:') # assighn number number=int(number) # I test if it is out of range if not(number>=0 and number<=36): print (' you enter number that outside the range') if number==0: color='green' print ('your color is', color) elif (number>=1 and number<=10) o...
1f14a35d989ba8754660426c04c83271a699565a
DevmallyaK/Neural-Network-Basics-with-Tensorflow-Keras
/Neural_Network_Basics_Using_Tensorflow_&_Keras.py
3,131
3.671875
4
# Import the Libraries import tensorflow as tf from tensorflow import keras tf.keras.Model() from tensorflow.keras.models import Sequential from tensorflow.keras import Model import numpy as np import matplotlib.pyplot as plt # Import the dataset mnist = keras.datasets.mnist (x_train, y_train), (x_tes...
670d548d3c8a923aa1bdc49fffba2976a8f39c9c
C14427818/Advanced_Security
/Lab4.py
1,204
4.03125
4
#!/usr/bin/python from Crypto.PublicKey import RSA from Crypto import Random print "Lab 4 RSA Algorithm" ''' STEPS IN CODE BUT ALL DONE IN RSA LIBRARY OF PYTHON #1 TWO PRIME NUMBERS P AND Q def generate_keypair(p, q): if not (is_prime(p) and is_prime(q)): raise ValueError('Both numbers must be prime.') ...
38f8d2c7d2512e40e85007b8824fcc506f45c48a
PushkarIshware/pythoncodes
/bridgelabz_pythonproj/functional/cardextend.py
3,820
4.03125
4
''' /********************************************************************************** * Purpose: Deck of cards extend * @author : Janhavi Mhatre * @python version 3.7 * @platform : PyCharm * @since 10-1-2019 * ***********************************************************************************/ ''' import random imp...
57f489912e9906f1fb5e2bd0a03b8263fe277b36
stdiorion/competitive-programming
/contests_atcoder/agc018/agc018_a.py
232
3.5
4
import math from functools import reduce def gcd(*n): return reduce(math.gcd, n) n, k = map(int, input().split()) a = list(map(int, input().split())) if max(a) < k or k % gcd(*a): print("IMPOSSIBLE") else: print("POSSIBLE")
9af941661b450ba18f8d1c1cc6afc4d320964737
y-usuf/hackerrank-practice
/plus_minus.py
894
4.125
4
''' Given an array of integers, calculate the fractions of its elements that are positive, negative, and are zeros. Print the decimal value of each fraction on a new line. ''' n = int(input()) arr = list(map(int, input().split())) [:n] #initializing count. pos_sum = 0 neg_sum = 0 zero_sum = 0 #Using lambda...
4b312dac988e5c61d7399aaa80d9bdd2419feeda
Alexrg/Python_challenges
/math/basic_math/area_calculator.py
2,348
4.5625
5
import math """ Write a Python function rectangle_area that takes two parameters width and height corresponding to the lengths of the sides of a rectangle and returns the area of the rectangle in square inches """ def rectangle_area(width, height): """ Calculate the area of a rectangle Args: width (number): Width ...
231eb8189fc494cd1829a301b785e7fb35186397
rrdrake/vvtools
/vvt/config/script_util/simple_aprepro.py
14,592
4
4
#!/usr/bin/env python3 from __future__ import division # Make python2 and python3 handle divisions the same. import sys import os import math import random import re class SimpleAprepro: """ This class is a scaled-down version of Aprepro, a text preprocessor for mathematical expressions. It only supports ...
b163aacca460dbcc7fa69343b6ee68ef54e9f04b
kgaurav7/tournament_planner
/tournament.py
3,812
3.5
4
#!/usr/bin/env python # # tournament.py -- implementation of a Swiss-system tournament # import psycopg2 import bleach def connect(): """Connect to the PostgreSQL database. Returns a database connection.""" return psycopg2.connect("dbname=tournament") def deleteMatches(): """Remove all...
bba5e7727c6abedaf3ad8fc1fef28615bbd38c81
EladAssia/InterviewBit
/Two Pointers Problems/Intersection_Of_Sorted_Arrays.py
1,129
4.0625
4
# Find the intersection of two sorted arrays. # OR in other words, # Given 2 sorted arrays, find all the elements which occur in both the arrays. # Example : # Input : # A : [1 2 3 3 4 5 6] # B : [3 3 5] # Output : [3 3 5] # Input : # A : [1 2 3 3 4 5 6] # B : [3 5] # Output : [3 5] # NOTE : For...
525c1d6b1fe4f591439f6074b766ad275bdd622a
Htoon/Python-Tkinter
/tk_textbox_with_scrollbar.py
410
3.640625
4
import tkinter as tk import tkinter.scrolledtext as scrolledtext root = tk.Tk() root.resizable(0,0) # windowwin frame canvas = tk.Canvas(root, width = 520, height = 400) canvas.pack() # scrolledtext input_textbox = scrolledtext.ScrolledText(root, undo=True, font=('courier new', 10)) canvas.create_window(...
1824863c5831b3cc9aea20701a6eb2c9676f3cdc
chase001/chase_learning
/Python接口自动化/GWE_test/common/scripts/parama.py
2,985
4.0625
4
# def bubbleSort(arr): # n = len(arr) # # # 遍历所有数组元素 # for i in range(n): # # # Last i elements are already in place # for j in range(0, n - i - 1): # # if arr[j] > arr[j + 1]: # arr[j], arr[j + 1] = arr[j + 1], arr[j] # # # arr = [64, 34, -20,25, 12, 22, 90,11] ...
d4d2b28086c5415fc59e57abd208dc67292901bd
Satily/leetcode_python_solution
/solutions/solution112.py
805
3.796875
4
from data_structure import TreeNode, build_binary_tree class Solution: def hasPathSum(self, root, sum): """ :type root: TreeNode :type sum: int :rtype: bool """ if root is None: return False if root.left is None and root.right is None: ...
c032faff325da53f1224e35205e20d270150351f
Occhima/stanford-cs221-code
/sentiment/submission.py
5,979
3.515625
4
#!/usr/bin/python import random import collections import math import sys from util import * ############################################################ # Problem 3: binary classification ############################################################ ############################################################ # Prob...
06e7b82cdddf294ba03e8d2d4bdc5997b66b2e2d
woorud/Algorithm
/practice/1992 쿼드트리.py
767
3.609375
4
def quadtree(x, y, n): global matrix, answer flag = False check = matrix[x][y] for i in range(x, x+n): if flag: break for j in range(y, y+n): if matrix[j][i] != check: answer += '(' quadtree(x, y, n//2) ...
c37b0fe040aab49f012bb5b2e348a9f37f17a2b0
he1016180540/Python-data-analysis
/Experiment-2/Untitled-1.py
168
3.859375
4
import math def f(x): return math.pow(x//100, 3) + \ math.pow(x//10 % 10, 3)+math.pow(x % 10, 3) for x in range(100, 1000): if(f(x) == x): print(x)
e23f4a285ef54f1e48a73ad13b20c624475c7642
therikb31/Hospital_Database_Management_Python
/20.py
900
3.5625
4
import mysql.connector mydb=mysql.connector.connect(host="localhost",user="root",passwd="12345",database="Rik") mycursor=mydb.cursor() ch=int(input("Search according to the following Criteria\n1.Code\n2.Name\n3.Price(Range)\n4.Author Name\nEnter Choice:")) if ch==1: code=raw_input("Enter Book Code:") sql=...
72d6bd0e6c38d90b4230e978dba27f392f094f0b
mhesshomeier/big-data-spring2018
/week-03/submission/pset2_test2.py
3,375
3.609375
4
```python import pandas as pd import numpy as np import matplotlib.pylab as plt # This line lets us plot on our ipython notebook %matplotlib inline # Read in the data df = pd.read_csv('data/skyhook_2017-07.csv', sep=',') # check it output df.head ## check out the data types df.dtypes ## check out the shape df.shape...
b5b74e510cf8e1595e66ed8241a69bb2a427fd89
varshinireddyt/Python
/CCI/RemoveDups.py
1,171
3.96875
4
""" Solutions 2.1: Remove Duplicate: Write code to remove duplicates from an unsorted linked list. Time Complexity: O(n*2) """ #Using Two Pointers class ListNode: def __init__(self,data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def...
95911d695fc5c654f3cba2cfd3b6e7b08a257929
NoorAbdallh/pythonTestBasic
/lec1/try.py
675
3.875
4
def inputNumber(sen): try: print(sen) num = int(input()) except: num = 0 return num #num1 = inputNumber('input number 1 : ') #num2 = inputNumber('input number 2 : ') #print('sum is ' + str(num1 + num2)) #try: print('div is :' + str(num1/num2)) #except: #print('num2 must not...
da2a799dcab556ee793941b2bfec874aae4342ea
sunminky/algorythmStudy
/알고리즘 스터디/개인공부/Loop/MillionairePJT.py
593
3.59375
4
# https://swexpertacademy.com/main/code/problem/problemDetail.do?problemLevel=2&problemLevel=3&contestProbId=AV5LrsUaDxcDFAXc&categoryId=AV5LrsUaDxcDFAXc&categoryType=CODE&problemTitle=&orderBy=RECOMMEND_COUNT&selectCodeLang=CCPP&select-1=3&pageSize=10&pageIndex=1 if __name__ == '__main__': for tc in range(int(inpu...
868dd1cbab9cd61a4086712a9ad54a5f50a8d464
jameskulu/Data-Types-and-Function-Assingment-Insight-Workshop
/Data Types/15.py
431
4.28125
4
# 15. Write a Python function to insert a string in the middle of a string. # Sample function and result : # insert_sting_middle('[[]]<<>>', 'Python') -> [[Python]] # insert_sting_middle('{{}}', 'PHP') -> {{PHP}} def insert_string(outer_string, inner_string): outer_first = outer_string[:2] outer_last = outer_...
70db2053031ccec97e69b032380b342740079e2e
Sabotaz/cracking-the-coding-interview
/src/exo_1_1.py
368
3.78125
4
def uniq(s): return len(set(s)) == len(s) def uniq2(s): all = set() for i in s: if i in all: return False all.add(i) return True def uniq3(s): # without additionnal datastructure for i in range(len(s)): for j in range(i+1, len(s)): if s[i] == s[j...
b14550a51266da2c5eea8296dbdb7d9efd781f29
crizzy9/Algos
/leetcode/sorted_subseq.py
1,102
3.984375
4
# Find a sorted subsequence of size 3 in linear time # 3.3 # Given an array of n integers, find the 3 elements such that a[i] < a[j] < a[k] and i < j < k in 0(n) time. If there are multiple such triplets, then print any one of them. # # Examples: # # Input: arr[] = {12, 11, 10, 5, 6, 2, 30} # Output: 5, 6, 30 # # Input...
b9323faae9adc1afc4c9ca4c16e069a35169af15
xdc7/PythonForInformatics
/misc/ListFromFile.py
211
3.6875
4
data = open('romeo.txt') finalList = [] for line in data: l = line.rstrip() words = l.split() for word in words: if word not in finalList: finalList.append(word) print(finalList)
9ec1560ecb65a7099b6e4760a5b98c3b95e0bad5
824zzy/Leetcode
/Q_Greedy/BasicGreedy/L2_2498_Frog_Jump_II.py
436
3.796875
4
""" https://leetcode.com/problems/frog-jump-ii/description/ The best strategy for the frog is to jump skipping one stone. Therefore, our answer is the longest jump between st[i] and st[i-2]. """ from header import * class Solution: def maxJump(self, A: List[int]) -> int: # when there are only two stones ...
a9614936c86234fe1256adb4a7bdafd4df01ab68
Chloemartin99/PythonSem1
/Sessions/Sess9_10/url_file.py
476
3.875
4
#count amount of times the word 'the' appears in an url from urllib.request import urlopen fd = urlopen("https://en.wikipedia.org/wiki/Main_Page") counter = 0 punctuation = '.,<>-=!\/"?!:;[]{}()|_+$#@^%&*' text = "" for line in fd: text = text+ line.decode().rstrip() for p in punctuation: text = text...
c9dfae92c7adc9d19571ba816836208ce7f10fd1
medvedodesa/Lesson_Python_Hillel
/Lesson_14/oop.py
413
3.703125
4
''' class ClassName(parent_list): body_of_class ''' class Point: xx = 23 yy = 0 def __init__(self, X=0, Y=0): self.x = X self.y = Y pt1 = Point(3, 6) # print(id(pt1)) # print(pt1.x) # print(pt1.xx) pt2 = Point() # print(id(pt2)) # # print(pt1.x) # print(pt1.y) # pt1.x = 9 # print(p...
9d57491fe1b6c1b677050891badbac9ba359c2ba
FarzanRashid/Codewars-solutions
/Product Of Maximums Of Array (Array Series #2).py
268
4.03125
4
def max_product(lst, n_largest_elements): output = 1 lst.sort() lst.reverse() nums = [] for i in range(0, n_largest_elements): nums.append(lst[i]) for i in nums: output *= i return output print(max_product([4, 3, 5], 2))
8e613fb0d4111b3b7402ff58d570f4933d57ae62
AdamZhouSE/pythonHomework
/Code/CodeRecords/2804/60764/234125.py
159
3.59375
4
str=input() nums=str.split('+'); nums.sort(); for i in range(len(nums)): if i!=len(nums)-1: print(nums[i],end="+") else: print(nums[i])
022f118231ba617738b48f8d45141df339c1cfca
bikramjitnarwal/CodingBat-Python-Solutions
/String-2.py
1,978
4
4
# double_char: # Given a string, return a string where for every char in the original, there are two chars. def double_char(str): string = "" for i in range(len(str)): string += str[i]*2 return string # count_hi: # Return the number of times that the string "hi" appears anywhere in the given string. def co...
b168a7b9a7a788c28b8ec5abc22fd2f542c4ae29
alexjercan/algorithms
/old/leetcode/problems/merge-two-sorted-lists.py
1,109
3.84375
4
class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: result = None list_iter = result while l1 and l2: if not result: if l1.val...
cc86a876aff1efefa6d7816d195ec2083828f17e
wyattm14/Robot-Navigation
/RobotNavigation.py
29,388
3.671875
4
# https://www.geeksforgeeks.org/reading-writing-text-files-python/ # https://pythonprogramming.net/euclidean-distance-machine-learning-tutorial/ from math import sqrt import sys import time # import time #opening a file with an arg command file1 = open(sys.argv[1],"r") #initializing variables grid = [] mangrid = [] ...
9e24b20386c310454e8ce60ad16a33ed5a8d67dd
HemantSrivastava01/Python-Practice-Program
/duplicate_list.py
570
3.890625
4
import math # To get Entry from User--> NumArr = [] n = int(input("Enter the list size : ")) print("\n") for i in range(0, n): print("Enter number at location", i, " : ") item = int(input()) NumArr.append(item) print("User Entered List is : ", NumArr) def Repeat(x): _size = len(x) repeated = [] ...
715a9496a5164e134430f67f4bc349e1fcb17ba6
aroraakshit/coding_prep
/path_sum_III.py
2,836
3.8125
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: #almost works def pathSum3(self, root, s, arr, os): if not root: return 0 if root.val == s: ...
a57929450cd171611beb3166318d383dd05b2951
kubaunold/evolutionaryAlgorithm
/helperFolder/dynamicEquation.py
400
3.609375
4
from sympy import symbols # Symbolic Math # Working with mathematical symbols in a programmatic way, # instead of working with numerical values in a programmatic way. # n <= 5 x1, x2, x3, x4, x5 = symbols('x1 x2 x3 x4 x5') expr = 2*x1 + x2 #Booth Funtion with global minimum in f(1,3)=0 exprBF = (x1+2*x2-7)**2 + (...
326a4339386953103576132ade3665601b18ac9b
whoiskhairul/python
/encription hackerrank.py
506
3.71875
4
import math # Complete the encryption function below. def encryption(s): s = s.replace(" ", "") length = len(s) m = math.isqrt(length) n = math.sqrt(length) if m != n: p = m + 1 list = [p] r = [] i = 0 j = 0 while i <= length: list[j] = s[i: i + p:] i = ...
2d49f2ae3842b3ec30677dd7d6fed90a2da3bae2
blutarche/someone-in-the-maze
/elements.py
2,724
3.703125
4
import pygame from pygame.locals import * from maze_algo import make_maze class Map(object): WALK_LIMIT = 5 def __init__(self, row, column, piece_size): self.row = row self.column = column self.map = make_maze(walk_limit=Map.WALK_LIMIT, w=(column-1)/2, ...
8c5ba7707866e42df8c4513f800e335ba9bf97af
GennadiiStavytsky/PythonMarathon
/00/t11_bot/bot.py
827
4.0625
4
mainstring = input("Enter your first string: ") substring = input("Enter your second string: ") if mainstring == "" or substring == "": print("One of the strings is empty.") else: com = input("Enter your command: ") if com != "concat" and com != "find" and com != "beatbox": print("usage: command f...
e1792b5137ce77e4b6b9bd70665952dc5c6adde9
jinurajan/Datastructures
/LeetCode/monthly_challenges/2021/january/02_find_corresponding_node_of_binary_tree_in_a_clone.py
2,612
3.96875
4
""" Find a Corresponding Node of a Binary Tree in a Clone of That Tree Given two binary trees original and cloned and given a reference to a node target in the original tree. The cloned tree is a copy of the original tree. Return a reference to the same node in the cloned tree. Note that you are not allowed to cha...
babe1266cc6f21a9e65512c69c9c8deba26b15fe
drkiettran/testing_python
/test/calculate_test.py
503
3.5625
4
import unittest from app.calculate import Calculate, main class TestCalculate(unittest.TestCase): def setUp(self): self.calc = Calculate() def test_add_method_returns_correct_result(self): self.assertEqual(5, self.calc.add(2, 3)) def test_add_method_raises_typeerror_if_not_ints(self): ...
bc0a00fbcc706ccae50259a4c0c744a8c4076ccd
oltionzefi/daily-coding-problem
/problem_22/problem_22.py
733
3.59375
4
def original_sentence(dictionary, string): return generate_list(dictionary, string, len(string), []) def generate_list(dictionary, string, length, results): for i in range(length + 1): prefix = string[0:i] if dictionary_contains(dictionary, prefix): if i == length: ...
9f4e3c001190ba5339ebb92f4b173c00944fd825
goo314/2019-LearningFair-MoneyDiary-py
/nose.py
579
3.640625
4
import turtle as t def move(a, b, t): t.penup() t.goto(a, b) t.pendown() return #코_원 def circle(nose_color): t.color('black', nose_color) move(0, -60, t) t.begin_fill() t.circle(20) t.end_fill() return #코_세모 def triangle(nose_color): t.color('black', nose_...
1184142bc6cf5ab8f62201645d418ab215dcf453
sdytlm/sdytlm.github.io
/downloads/code/LeetCode/Python/Binary-Tree-Preorder-Traversal.py
664
3.875
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 preorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ ...
63c95a6d09e0e8f19563eaada26898ce941a6b26
aratik711/100-python3-programs
/12.py
436
4.0625
4
""" Write a program, which will find all such numbers between 1000 and 3000 (both included) such that each digit of the number is an even number. The numbers obtained should be printed in a comma-separated sequence on a single line. """ answer = [] for i in range(1000, 3000): i = str(i) if ((int(i[0])%2==0) a...
3f29f98cad0a0f2cba01bf7c44a100ca24f91d72
UjjwalDhakal7/basicpython
/stringtypes.py
2,086
4.84375
5
#String datatypes #Any sequence of characters within single or double quotes is a string. a = 'Hello World' A = "Hello World" print(type(A)) print(type(a)) #Using triple quotes to represent a string. #1. To define a doc string. #2. To enclose string values having single or double quotes. a = 'I lov...
2af99668bed9ba892ceb15663ca2b30abd999800
huyngopt1994/python-Algorithm
/leet-code/linked_list/linked_list_cycle.py
917
3.8125
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def hasCycle(self, head: ListNode) -> bool: # just go slow and go fast, if one of the node is reach to None => return false # If the node from go slow == g...
68653a631583306cc53e8e9e7a8d3a9c18d05400
ss2576/Interview
/Lesson_2/task_5.py
2,297
3.671875
4
""" 5. Реализовать расчет цены товара со скидкой. Величина скидки должна передаваться в качестве аргумента в дочерний класс. Выполнить перегрузку методов конструктора дочернего класса (метод init, в который должна передаваться переменная — скидка), и перегрузку метода str дочернего класса. В этом методе должна перес...
02cc29dc1e9b5ce6d4b8823d4d874ba2e2eadb6c
gerardomdn95/Batch15-Front
/week1/Figuras/Figures.py
332
3.6875
4
class Figures def __init__(self,name,area,perimeter): self.name = name self.perimeter = perimeter self.area = area def area(self) print("The perimeter of the %s is %s" % (self.name, self.area)) def perimetro(self) print("The area of the %s is %s" (+self.name, self...
4930b57a15de87942cda14f783d3f6158b5bc4a1
ashutosh77198/python-tutorials-2
/Assign2.py
6,668
3.953125
4
#QUES1 """ x="Python is a great language!", said Fred. "I don't ever remember having this much fun before." print(x) """ #QUES 2 """ year=int(input("Enter year to be checked:")) if(year%4==0 and year%100!=0 or year%400==0): print("The year is a leap year!") else: print("The year isn't a leap year!") """ #QUES3...
15415458f1e3945e2cc2a2ab02bfdd2a4d3ea3da
ericmintun/rl-tools
/rl/postprocessors.py
3,824
3.96875
4
''' Postprocessors are in charge of taking the output of a network and producing definite actions, expected rewards, or other requested results derived from the network output. Postprocessors operate in torch variables since they need to connect forward to the network trainer. ''' import torch from torch.autograd imp...
901bb203bf344cf6ab4aa05292dea52426714416
ian-dqn/perceptron
/first_neuron.py
742
3.5625
4
import numpy as np def sigmoid(x): return 1 / (1 + np.exp(-x)) def sigmoid_derivative(x): return x * (1 - x) train_inputs = np.array([[0,0,1], [1,1,1], [1,0,1], [0,1,1]]) train_outputs = np.array([[0,1,1,0]]).T np.random.seed(1) synaptic_weights = 2 * np.random.random((3, 1)) - 1 print('Random st...
43f67becf734831185f45b8eadee7c417aab3b9c
qua-platform/qua-libs
/examples-old/basics/intro-to-macros/intro-to-macros.py
2,471
3.921875
4
""" intro-to-macros.py: An intro to usage of macros in QUA Author: Gal Winer - Quantum Machines Created: 26/12/2020 Created on QUA version: 0.6.393 """ from qm.QuantumMachinesManager import QuantumMachinesManager from qm.qua import * from qm import SimulationConfig from configuration import config QMm = QuantumMachi...
bac3751657727eba6d350ce85425c2d91066064e
matthewatabet/algorithms
/sort/heapsort.py
1,278
3.96875
4
class PriorityQueue(object): ''' Zero indexed heap. ''' def __init__(self): self.data = [] def _exchange(self, i, j): t = self.data[i] self.data[i] = self.data[j] self.data[j] = t def _less(self, i, j): return self.data[i] < self.data[j] def _promo...
97ef5942db351e6fdbe08256cf075e5df402bb2f
kwr0113/BOJ_Python
/step10/2447-3.py
272
3.65625
4
# 2447-3.py def star(x): if x == 1: return ['*'] x = x // 3 a = star(x) topbottom = [i * 3 for i in a] middle = [i + ' ' * x + i for i in a] return topbottom + middle + topbottom n = int(input()) mystar = '\n'.join(star(n)) print(mystar)
1a5c57eabd3d487cdfe5df7ca5375fc35c9070f2
vaavaav/LEI
/3ano/2semestre/pl/aula7/listas/listas2_yacc.py
1,514
3.75
4
''' listas_yacc.py aula7: 2021-04-13 Listas heterogéneas: inteiros e alfanuméricos [78] [1,2,3] [121,asa,c45] T = {number, '[', ']', alfanum, ','} N = {Lista, Elementos, Elemento} p1: Lista -> '[' Elementos ']' p1.5: Lista -> '[' ']' p2: Elementos -> Elemento p3: E...
ae846be11a095f14c090941f9e60b81bd9908e23
SteffanySympson/BLUE-MOD-1
/Desafios/Desafio Sena.py
1,819
4.09375
4
# Faça um programa que ajude um jogador da MEGA SENA a criar # palpites.O programa vai perguntar quantos jogos serão gerados e vai sortear 6 # números entre 1 e 60 para cada jogo, cadastrando tudo em uma lista composta. #um número deve ser randomizado # lista principal #contador #enquanto for verdade repete import ra...
7c4aba9ab641b9488ec1eaf778a42548f342e092
Riley-Milligan/pythonweekone
/day3/sixreverse.py
83
4.15625
4
to_reverse = input("What word would you like to reverse?") print(to_reverse[::-1])
00c392f6d795efec60950ff303bbcc489aff5738
leonhostetler/undergrad-projects
/computational-physics/07_derivatives/derivative.py
799
4.21875
4
#! /usr/bin/env python """ Numerically compute the derivative of f(x) = x(x-1) using different values for the small number delta. Leon Hostetler, Feb. 21, 2017 USAGE: python derivative.py """ from __future__ import division, print_function # Main body of program def f(x): """ This function returns the val...
d80fb86b726b06fa58924cfbe2861eb51f78599e
mrahul16/Green-Index---Hadoop
/mapper.py
582
3.6875
4
#!/usr/bin/env python import sys total = 0 green = 0 # input comes from STDIN (standard input) for line in sys.stdin: line = line.strip() rgb = line.split(',') # print '%s\t%d' % ("green", 100) if len(rgb) > 0: r, g, b = rgb total += 1 if int(g) > int(r) and int(g) > int(b...
b78580ba071016af237dcd90668bb1fb3412f6aa
aaronbae/competitive
/kickstart/contention.py
1,588
3.578125
4
class Interval: def __init__(self, l, r): self.left = l self.right = r def length(self): return r-l class Organizer: def __init__(self, num, book): self.data = {} self.N = num self.Q = book def add(self, interval): if interval.length() not i...
cb2f3a53e0040a7dd242532601d1b6398f1b907e
Infero93/advent-of-code-2019
/6/script_1.py
1,116
3.84375
4
def read_input(): values = [] with open('6/input.txt', 'r') as f: values = f.readlines() return [value.strip() for value in values] def count_steps(dest_planet, start_planet, orbits, count = 0): if dest_planet == start_planet: return count planets = orbits[start_planet] if len(...
d897c1579a483432d6d82e1a0186d59b77748e71
gitchaussette/test-git
/1910/script1910.py
116
3.515625
4
given_list = [1,5,4,7,8,7,4,1,2,6,4,7,] comprehension_list = [x for x in given_list] print(comprehension_list)
dd7269499f3a5059d5d1d96f50d456d981c850b8
rodrigohuila/python_scripts
/MyScripts/sendEmail2.py
3,950
3.546875
4
#! /usr/bin/python3 import os, email, smtplib, ssl from email import encoders from email.mime.base import MIMEBase from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText # Capturing some info from user subjectEmail = "An email with attachment from Python" fromAddr = "rodrigo.huila@gmail....
4ccb1bda8088b4fababcebfb6dfef90fb3a02de2
gowitz/canalisations
/cana.py
7,983
3.53125
4
# -*- coding: utf-8 -*- # from math import * import math class Point: def __init__(self, pid, x, y, z): self.pid = pid self.x = x self.y = y self.z = z def getX(self): return self.x def getY(self): return self.y def getZ(self): return self.z def getID(self): return self.pid def info(self): ...
5c74963c69fa6f36415c858bddb1f6790c105f3a
Nampq281/phamquynam-fundamentals-c4e21
/session03/homework03/serious2.1_4.py
477
3.8125
4
flock_sheep = [5, 7, 300, 90, 24, 50, 75] print ("Hello, my name is Nam, and here are my ship sizes ", flock_sheep) biggest = max(flock_sheep) print ("Now my biggest sheep has size ", biggest, "let's sheer it") sheep_no = flock_sheep.index(biggest) flock_sheep[sheep_no] = 8 print ("After sheering, here is my flock "...
50aa6de0884b1432515833a7c6b8560a37afbdc5
gitter-badger/survival-python
/07 Data Types Details/integers_and_floats_2.py
254
3.546875
4
a = int(2.8) b = int('2') # Not supported int('2.8') would return an error c = float('2') d = float('2.1') e = float(2) f = int(float('2.8')) print(a, type(a)) print(b, type(b)) print(c, type(c)) print(d, type(d)) print(e, type(e)) print(f, type(f))
6e820ab8a69f7003e387c0b12af40c35178f2ca1
buidler/LeetCode
/二分查找/1111. 有效括号的嵌套深度.py
1,358
3.65625
4
""" 示例 1: 输入:seq = "(()())" 输出:[0,1,1,1,1,0] 示例 2: 输入:seq = "()(())()" 输出:[0,0,0,1,1,0,1,1] 解释:本示例答案不唯一。 按此输出 A = "()()", B = "()()", max(depth(A), depth(B)) = 1,它们的深度最小。 像 [1,1,1,0,0,1,1,1],也是正确结果,其中 A = "()()()", B = "()", max(depth(A), depth(B)) = 1 。 """ class Solution(object): def maxDepthAfterSplit(self, s...
6f1d38474e51fd597359e78ee2ca46b6c17927bc
jszandula/JetBrains-Academy-Projects
/coffee_loop.py
3,435
4
4
class CoffeMachine(): def __init__(self): self.water = 400 self.milk = 540 self.beans = 120 self.cups = 9 self.money = 550 def user_interaction(self, action = str(input("Write action (buy, fill, take, remaining, exit) : ")) ): while action != 'exit': ...
edd815175fb97fdec8e4139b235be01be6810415
m2rik/MLprojects
/SVM/SVMsklearn.py
1,793
3.671875
4
#classification algorithm import pandas as pd import numpy as np import matplotlib.pyplot as plt #dataset problem- classify whether the person will purchase a product or not #age/salary independent,purchase is the dependent variable D=pd.read_csv("Social_Network_Ads.csv") X=D.iloc[:,[2,3]].values y=D.iloc[:,4].value...
bf15138e810cbffc17fdcbbacba14bb1a8b5ff61
muralweirdo/PF-codes
/a03.py
804
3.921875
4
## IMPORTS GO HERE ## END OF IMPORTS #### YOUR CODE FOR good_enough() FUNCTION GOES HERE #### def good_enough (n,g): if abs(g*g-n) < 0.1: return True else: return False #### End OF MARKER #### YOUR CODE FOR sqrt() FUNCTION GOES HERE #### def sqrt (n,g=0): count=1 if good_enough(n,...
55bfaead7a57bff5c4cd582146d995353696e53f
panu2306/Python-Articles
/programs_in_python/programming_excercise/4.py
523
4.3125
4
''' Write a program which accepts a sequence of comma-separated numbers from console and generate a list and a tuple which contains every number. Suppose the following input is supplied to the program: 34,67,55,33,12,98 Then, the output should be: ['34', '67', '55', '33', '12', '98'] ('34', '67', '55', '33', '12', '98'...
ad9b8de4db681f2b8395420446c21f8d5a3c0936
RashiSinghvi/CIPHERSCHOOLS_ASSIGNMENTS
/web app/Adult project/adult_data.py
5,780
3.75
4
import streamlit as st import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns def load_sidebar(): st.sidebar.header("Income Prediction of a person using given dataset") st.sidebar.info(''' 1) Original owners of database - US Census Bureau\n 2) Do...
5e6c18ff67bdeaf57d24e8b1b2a83461dd486d0c
jesusble/project
/bb.py
170
3.546875
4
s=input() b=0 a=0 for w in s: if(w.isalpha()==True): a=a+1 elif(w.isdigit()==True): b=b+1 if(a>0 and b>0): print("Yes") else: print("No")
7746a64ff6372e44a08d656c8bd8796a481b4ecd
werellel/Algorithm
/hackerrank/warm_up_challenges/counting_valleys.py
2,380
3.734375
4
#!/bin/python3 import math import os import random import re import sys # Complete the countingValleys function below. def countingValleys(n, s): if s[0] == 'U': result_list = [(0, '_')] compare_pos = -1 else: result_list = [(1, '_')] compare_pos = 0 position...
393012f0ea721e755bb07b750c7a51c497ddd601
snufkinpl/public_glowing_star
/Countdown app/Countdown app_in_1_file/Countdown app.py
1,097
3.953125
4
#Wytyczne projektu #Użytkownik wprowadza nazwę celu oraz czas na jego osiągnięcie poprzez podanie daty w postaci:yyyy-mm-dd #Na ekranie pojawia się informacja, ile czasu pozostało na osiągnięcie celu (w dniach) import datetime def information_from_user(): user_input = input("Wprowadź nazwę celu oraz jego k...
f51dd563efe2f74b53bf6bbf09dff3db13be00f1
Amiao-miao/all-codes
/month01/day11/homework01.py
1,636
4.34375
4
""" 以面向对象的思想,描述下列情景. 划分原则: 数据不同使用对象区分——小王 行为不同使用类区分——手机/卫星电话 """ # (1)需求:小明使用手机打电话 # 识别对象:人类 手机 # 分配职责:打电话 通话 # 建立交互:人类 调用 手机 """ class People: def __init__(self, name=""): self.name=name def use(self,phone): print(self.name,"使用") phone.call() class Phone: ...
adeac0244ac4850d573159353f9efb0e2ea6a928
jinhongtan/calculator3
/src/StatisticsCalc.py
1,945
3.78125
4
from Calculator import * import collections import sys import math class StatisticCalculator(Calculator): #check the list is valid # 1. not string # 2. not empty @staticmethod def check(data): if not all(isinstance(item,int) for item in data) or len(data)==0: print("Your data ...
9cfef1268648f1a5fdbabec4776d900793dd8a77
dexterchan/DailyChallenge
/Jan2020/LongestConsecutiveSequence.py
3,183
3.921875
4
#You are given an array of integers. Return the length of the longest consecutive elements sequence in the array. #For example, the input array [100, 4, 200, 1, 3, 2] has the longest consecutive sequence 1, 2, 3, 4, and thus, you should return its length, 4. #Can you do this in linear time? #Anaysis #Sorting costs O(...