blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
cd52872bb60cc623d2fcff85f2bf10a0fd7315fc
ngocvuu/vuubaongoc-fundamental-c4e16
/session05/homework/bacteria.py
291
4
4
howmany = int(input("How many B bacterias are there? ")) howmuch = int(input("How much time in mins will we wait? ")) #check lại công thức final = howmany * 2 ** (howmuch - 1) sum = howmany * (1 - 2 ** howmuch) / (1 - 2) print("After",howmuch, "minutes, we would have",sum,"bacterias")
e61730efef371632a91a0ac2b33654c1bcb003f5
leoflorov/python1
/lesson_2_hw_easy.py
1,992
4.21875
4
# Задача-1: # Дан список фруктов. # Напишите программу, выводящую фрукты в виде нумерованного списка, # выровненного по правой стороне. # Пример: # Дано: ["яблоко", "банан", "киви", "арбуз"] # Вывод: # 1. яблоко # 2. банан # 3. киви # 4. арбуз # Подсказка: воспользоваться методом .format() newList = ["яблоко", "...
87bd984142adcc63f0d6705a0885a6dea6ee2320
Walrusbane524/Basic-python-projects
/Mathematical Scripts/SimpleWordCounter.py
1,194
4.25
4
## Recebe uma frase de um usuário, identifica a palavra mais frequente, imprime ela e as vezes que ela foi usada. # Receives a phrase from the user, identifies the most frequently used word, prints it and how many times it was used. c = 0 itemIndex = 0 rep = 0 lista = [] ## Recebe a frase do usuário e a divide nas ví...
6bbe2a6d5a548998c6c7d517300faab63bd137d9
Leon201/praticingpython
/algorithmForDummies/Ch09reconnectingTheDots/depthFirstTraverse.py
760
3.71875
4
graph = { 'A': ['B', 'C'] , 'B': ['A', 'C', 'D'] , 'C': ['A', 'B', 'D', 'E'] , 'D': ['B', 'C', 'E', 'F'] , 'E': ['C', 'D', 'F'] , 'F': ['D', 'E'] } def dfs(graph, start): stack = [start] parents = {start: start} path = list() while stack: print ('Stack is : %s' % stack) ...
934913ea4b0753b8df0e211270f113853fc5464a
Othmanbdg/Frigo
/test_knnnn.py
4,466
3.578125
4
import random from tkinter import * ingredient=['sauces','yaourts','fruits','legumes','viandes','eau','soda','glace','fromage','lait'] temoin=['sauces','yaourts','fruits'] prsn=[] path=r"C:/Users/Vil/Desktop/" def gens(num): var = 1 secu=[] prsn.clear() for i in range(num): a = ...
85303a958e191e19fa32c26b5e58b86a4de15f73
hsmith851/Python-Projects
/LatticePath.py
561
3.609375
4
import math def LatticePath(down, right): #Euler Problem Lattice Path if (down == 0 or right == 0): return 1 else: return LatticePath (down - 1, rigLatticePathht) + LatticePath (down, right - 1) #Recursive counting of Lattice Path of NxM Grid #LatticePath_v2 uses binomial coefficie...
b411ef4bf33cdc46da458f5e092aaa09e25cb3f5
latinos/HWWAnalysis
/CutBasedAnalyzer/scripts/dumpSelected.py
2,750
3.515625
4
#!/usr/bin/env python import optparse import sys import ROOT import array import os.path import HWWAnalysis.Misc.ROOTAndUtils as utils #--------------------------------------------------------- import locale locale.setlocale(locale.LC_NUMERIC, "") def format_num(num): """Format a number according to given places....
e2e2c2401953feeba59a95db21b8844edd14e988
namnamgit/pythonProjects
/bonus.py
159
3.734375
4
anos = int(input("Anos de servico: ")) valor_por_ano = float(input("Valor por ano: ")) bonus = anos * valor_por_ano print("Bônus de R$%5.2f" %bonus) input()
411a765cd54ceaff36b818e3f5afab7df79d55cd
iasminqmoura/algoritmos
/Lista - Repetição/Exercicio28.py
1,008
3.5625
4
a = 0 c = 0 maior = -9999 soma_salarios = 0 soma_filhos = 0 media = 0 salario_menor_q = 0 while a != 'a': c = c + 1 salario = float(input(f'{c} salario:')) numero_de_filhos = int(input(f'{c} filhos:')) if salario >= 0: soma_salarios = soma_salarios + salario ...
0fabb182524fd2f3a1af51e2d60f7f174ef8b88b
TryNeo/practica-python
/ejerccios/ejercicio-125.py
899
4.34375
4
#!/usr/bin/python3 """ You will be given a number and you will need to return it as a string in Expanded Form. For example: expanded_form(12) # Should return '10 + 2' expanded_form(42) # Should return '40 + 2' expanded_form(70304) # Should return '70000 + 300 + 4' NOTE: All numbers will be whole numbers greater than ...
f072d87cc8a2c892861471c9cd16a81e555415b5
Jaikelly/CursoPython
/Turtle/Turtle.py
483
3.5625
4
import turtle; #creamos un objeto(pantalla) s = turtle.Screen(); #la pluma t = turtle.Turtle(); ''' #hace una linea de xxx pixeles, se mueve a la izquierda t.backward(100); #se mueve hacia la derecha(se voltea la pluma) t.right(90); #hace una linea hacia abajo t.forward(100); #se mueve a la izquierda(la pluma) t.l...
eff27306cc2e0cc7b31c4510e97a6ec5090b823a
GuidoTorres/codigo8
/Seman4/Dia1/02-clasesconconstructor.py
1,497
4.125
4
# class Persona: # #Este es el constructor de la clase # #Se usa self para instaciar todos los atributos de la clase, se crean # #con el constructor y se pueden utilizar en todos los metodos # def __init__(self, nombre, edad): # self.nombre = nombre # self.edad = edad # def saludar(...
9c1abe3be9d10087be84725e6d42bdd20d5b4070
abhiprd-219/sand-clock-pattern-
/.py
433
3.71875
4
def printLine(nums): print(space, end='') for i in nums: print(i,end='', sep='') print() MAX = int(input()) space = "" num = [i for i in range(1,MAX)] + [i for i in range(MAX, 0, -1)] for i in range(2*MAX): if i < MAX: printLine(num[i:2*MAX-i-1]) space += " " elif ...
041e186966d84c714fd1af9e6047dd896fb8447f
codecampNick/bots
/utilities.py
656
3.578125
4
import csv class CsvFunctions: def createCsv(self,filePath, fileMode, job): with open('testFile.csv',mode='w') as testFile: writer = csv.DictWriter(testFile, fieldnames=list(job.__dict__)) writer.writeheader() print('Headers Created!!') def addCsvRows(self, fileMode...
2bd309408bb0aa2d406be49cc978a47194f1f462
hongyilinux/python
/basic/dic/2ex.py
404
3.84375
4
str = "hello python" l1 = list(str) print('将字符串转换成列表') print(l1) tu1 = tuple(str) print('将字符串转换成元组') print(tu1) set1 = set(str) print('将字符串转换成集合:集合是没有次序的,会删除重复元素') print(set1) list2 = [('a',1),('b',2),('c',3),('d',4)] dic1 = dict(list2) print('把带有键值对的元组列表转换成字典') print(dic1)
6eafa1625ea71b0734eb0b54222350b8e61ed590
bhatnitish1998/aps-2020
/check_prime.py
283
4.125
4
# check if a given number is prime or not def isPrime(n) : if (n <= 1) : return False if (n <= 3) : return True if (n % 2 == 0 or n % 3 == 0) : return False i = 5 while(i * i <= n) : if (n % i == 0 or n % (i + 2) == 0) : return False i = i + 6 return True
d292cd3f513e1def295cbd60e74cc997fa1ccc41
CrazyClown41/PythonProjects
/src/personal-projects/CheckPrime.py
508
4
4
def getNum(): num = int(input("Enter number to see if it is prime: ")) return num def check(num): listRange = list(range(1,num+1)) divisorList = [] for number in listRange: if num % number == 0: divisorList.append(number) if divisorList[0] == 1 and divisorList[1] =...
fc970e3e39a64a94b7c2c078c534563123885967
Wilson1211/LeetCode
/Manacher_Algorithm.py
1,505
3.5625
4
class Solution: def longestPalindrome(self, s: str) -> str: string_size = len(s) if string_size < 3: if s==s[::-1]: return s else: return s[0] manacher_str = "#" for index in range(len(s)): manacher_str +...
02a39c17d27e6895eee4acd35c9ea933723cd7fe
Chidalu567/computervision
/Open cv project/Opencv2/Drawing Function in opencv.py
1,237
4.125
4
'''We use the cv2.(line,rectangle,circle,ellipse,putText,polylines) functions to draw things in opencv2''' import cv2 import numpy img=numpy.zeros((512,512,3),numpy.uint8); #create a black background #===>Drawing line in opencv cv2.line(img,(0,0),(450,450),(255,255,0),3); #create a line in cv2 #===Drawing Rec...
b5e466b531f0afafee881658b96d1babaaa587b0
bgoonz/UsefulResourceRepo2.0
/GIT-USERS/TOM-Lambda/CSEU2-Algorithms-gp/src/challenge.py
1,960
3.84375
4
# Work out the time complexity of these solutions """ Formally: 1. Compute the Big-O for each line in isolation 2. if something is in a loop, multiply it's Big-O by the loop for the total. 3. If two things happen sequentially, add the Big-Os. 4. Drop leading multiplicative constants from each of the Big-Os. 5. From al...
3dc922ef17a09cd6c13f81f4a092f42c46b15e1e
Sushmi-pal/pythonassignment2
/Q18.py
469
3.59375
4
import json info={"about_me":[{"name":"Sushmita Palikhe", "age":22}]} # File representation of json data with open("info.json",'w') as f: json.dump(info,f,indent=2) # String representation of json data serialize_info=json.dumps(info,indent=2) print('Serializing') print(serialize_info) print('Deserializing'...
e7ce968ade37234d00d4f9e30537137742c740e9
shevonwang/Python-Logistic-Regression
/main.py
3,666
3.5625
4
#!usr/bin/env python # -*- coding: utf-8 -*- from sklearn.metrics import confusion_matrix # 导入混淆矩阵函数 from numpy import * import pandas as pd from sklearn.metrics import roc_curve #导入ROC曲线函数 import matplotlib.pyplot as plt # calculate the sigmoid function def sigmoid(z): return 1.0 / (1 + exp(-z)) # m denotes th...
df41dd31b7a3a37a714bb0cbd698a31996967551
caojcarlos/ProjetosPython
/adivinhacao.py
638
3.625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon May 25 07:12:03 2020 @author: Jose Carlos Nunes Objetivo: Programa Basico para jogo de Adivinhacao """ import random sorteado = random.randrange(1,100) jogador = int(input('Digite um numero entre [1, 100]: ')) erro = 0 while (jogador != sorteado): ...
df39801e5d068a99ffcf6bd85caf590864b9ee28
btRooke/smart-home
/controller/password_hashing.py
335
3.5625
4
import hashlib import random import string def generate_salt(length=16): """ random salt of 16 characters """ return "".join([random.choice(string.ascii_letters + string.digits) for i in range(length)]) def hash_string(string_to_hash): h = hashlib.sha256(string_to_hash.encode("utf-8")) return...
4894e18e1a23c3e899e0fdddfe1cad49709cdf8c
leeinae/algorithm-python
/Programmers/12899.py
299
3.53125
4
def solution(n): num = ['1', '2', '4'] answer = '' while n > 0: remainder = n % 3 if n % 3 != 0 else 3 answer = num[remainder - 1] + answer n = (n - 1) // 3 return answer solution(3) solution(18) solution(16) solution(8) solution(10) solution(500000000)
a18e167f77e38de3bf44bf278c41643cf662a33b
KatherineCG/TargetOffer
/8-旋转数组的最小数字.py
1,133
3.515625
4
class Solution(): def Min(self, list): length = len(list) index1 = 0 index2 = length - 1 indexMid = index1 while list[index1] >= list[index2]: if index2 - index1 == 1: indexMid = index2 break indexMid = (index2...
1d9bf325002b36143e4820464e7e4e99ec2d3e9e
CesarGlezR/EVA1
/python/EVA1_12_Pendiente.py
247
3.9375
4
print("Introduce y1") y1 = float(input()) print("Introduce y2") y2 = int(input()) print("Introduce x1") x1 = float(input()) print("introduce x2") x2 = float(input()) p = (y1 - y2) / (x1 - x2) print("La pendiente es ", end='', flush=True) print(p)
95441465172155a3a245d011f8866310cf559add
aco1731/snippets
/snippets/factorial_asyncio.py
783
3.59375
4
import asyncio import time async def factorial(name, number): f = 1 for i in range(2, number + 1): print(f"Task {name}: Compute factorial({i})...") await asyncio.sleep(0.01) f *= i print(f"Task {name}: factorial({number}) = {f}") async def print_time(x): for _ in range(x): ...
986d87f329ba154fe9a121d7972b4ac9c243894f
thalita89/ChallengePython
/challenge02
993
4.25
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Dec 9 14:34:51 2020 @author: thalitaramires """ #Challenge02 #---------------------------------------------------------------- #Digital root is the recursive sum of all the digits in a number. #Given n, take the sum of the digits of n. If that value ...
b9306df1eef5e353d89626ab1112eadb68db7207
t4d-classes/python_03012021
/app.py
574
4.3125
4
result = 0 command = input("Please enter a command: ") print(command) while command: if command == "clear": result = 0 else: num = int(input("Please enter an operand: ")) if command == "add": result = result + num elif command == "subtract": result = r...
51d17769fb6aabf35bf590e073c4364b3d564985
natalyazhiltsova/Zhiltsova-Natalya
/Lecture02/Lecture02.py
2,271
4.125
4
#1 Спросить пользователя и получить строку в ответ s = input("Please, enter the number: ") s = s.strip() #2 Проверить корректность ввода if not (1 <= len(s) <= 2): print("Invalid input") exit(1) # Завершает программу если ввод некорректный if not s.isdigits(): print("Invalid input") exit(1)...
c7c785e0fe2c104c360bc61c91b45285d0a18f1b
Sergey-Laznenko/Stepik
/Generation Python - A Beginner's Course/9_String_data_type/9.4.str_methods_v2/8.py
349
4.03125
4
""" На вход программе подается строка текста, состоящая из слов, разделенных ровно одним пробелом. Напишите программу, которая подсчитывает количество слов в ней. """ text = input() a = text.count(' ') print(a + 1)
6a3643776752f9d9cec9f3137f282cb538e9f1e6
JuniorDugue/002-tip-calculator
/fstrings.py
699
4.4375
4
print(8/3) # returns 2.6666666666666665 a floating point number print(int(8/3)) # returns 2 as an integer print(round(8/3)) # will return 3 rounding to a whole number print(round(8 / 3, 2)) # to specifify a decial placement e.g. 2 decimal places print( 8 // 3) # floored divisions that'll return 2 # if you wanted t...
c372b22474cfa7434ab7bc61edd54f24fa8105b0
HaidiChen/Coding
/python/recursion/hanoi.py
210
3.96875
4
def hanoi(n, p1, p2, p3): if n == 1: move(p1, p2) return hanoi(n - 1, p1, p3, p2) move(p1, p2) hanoi(n - 1, p3, p2, p1) def move(x, y): print('from {} to {}'.format(x, y))
7810134033b10fb730cafa531b546237c159ae4d
bennosski/elph
/imagaxis/convolution.py
7,548
3.9375
4
from numpy import * import fourier def basic_conv(a, b, indices_list, axes, circular_list, izeros, op='...,...'): ''' a and b must be the same size the length of each axis must be even indices_list specifies the way in which to convovle for the corresponding axes in 'axes' the repeated index ...
1e20bd47ebf020bad0e2f40a16ca38c969bf1eaf
liguoyu666/chuji_suanfa
/04.存在重复元素.py
1,396
3.84375
4
# -*- coding: utf-8 -*- # @Time : 2020/6/4 下午2:23 # @Author : liguoyu # @FileName: 04.存在重复元素.py # @Software: PyCharm # 给定一个整数数组,判断是否存在重复元素。 # 如果任意一值在数组中出现至少两次,函数返回 true 。如果数组中每个元素都不相同,则返回 false 。 # # 输入: [1,2,3,1] # 输出: true # # 输入: [1,2,3,4] # 输出: false # # 输入: [1,1,1,3,3,4,3,2,4,2] # 输出: true def containsDupli...
98afc5982cfef6ef0d70bdfbb79c8d51456b048d
DyuldinKS/stepik.algorithms
/4.2.huffman-codes/heap.py
1,870
3.6875
4
class Heap: def __init__(self, iterable=None): if not iterable: return for item in iterable: self.insert(item) def _swap(self, i, j): self.list[i], self.list[j] = self.list[j], self.list[i] def _get_parent_index(self, index): return (index - 1) >> 1...
6e21458cfb0bfb9d76e72293085cd3b8cf262126
Rustofaer/GeekUniversity-Python
/lesson-4/task1.py
865
3.859375
4
# 1. Реализовать скрипт, в котором должна быть предусмотрена функция расчета заработной платы сотрудника. В расчете # необходимо использовать формулу: (выработка в часах * ставка в час) + премия. Для выполнения расчета для конкретных # значений необходимо запускать скрипт с параметрами. from sys import argv try: ...
ed769537d5841025208f669c8cf814e6f39a34c2
Nurmatov-07/PythonTasks
/На GitHub/Tuples_in_python.py
489
3.953125
4
def max_min(): new_tuple = (23.4, 54.123, -5.4344, -99.1, 4.1, 0.999, 78.78, 98.123, 12.21, 1.11) i = 0 max = 0 min = 0 for j in range(0, len(new_tuple)): for i in range(0, len(new_tuple)): if new_tuple[i] > max: max = new_tuple[i] if ne...
7868ee5e7fe380d0760e9fefd7b1cfa36905dbbc
HOZH/leetCode
/leetCodePython2020/2373.largest-local-values-in-a-matrix.py
847
3.515625
4
# # @lc app=leetcode id=2373 lang=python3 # # [2373] Largest Local Values in a Matrix # # @lc code=start class Solution: def largestLocal(self, grid: List[List[int]]) -> List[List[int]]: n = len(grid) ans = [] for i in range(n - 2): res = [] for j in range(n - 2):...
7ed40abe4cc67b18dbed5fa0f6854df320486850
surya-lights/Python_Cracks
/Tuple.py
254
4.09375
4
# Tuple items - data types tuple1 = ("apple", "banana", "cherry") tuple2 = (1, 5, 7, 9, 3) tuple3 = (True, False, False) print(tuple1) print(tuple2) print(tuple3) # A Tuple with multiple data types tuple1 = ("abc", 34, True, 40, "male") print(tuple1)
f01db7fea13aa2b5b796bb214eb634cd673fd7df
habpygo/DeltaPlotting
/3-Dplot.py
564
3.6875
4
from numpy import * import pylab as p import mpl_toolkits.mplot3d.axes3d as p3 # u and va are parametric variables. # u is an array from 0 to 2*pi, with 100 elements u=r_[0:2*pi:100j] # v is an array from 0 to 2*pi, with 100 elements v=r_[0:pi:100j] # x, y, and z are the coordinates of the points for plotting # each ...
a5bb95bde84a8fa2f865bad5d4a30e09188d6647
nathanlct/cp
/project_euler/27.py
830
3.65625
4
""" P(n) = n^2 + an + b |a|, |b| < 1000 Find a, b st N is maximal: for n < N, P(n) is prime Return ab """ """ P(0) = b has to be prime P(1) = a+b+1 has to be prime """ def _is_prime(n): if n < 2: return False if n % 2 == 0: return (n == 2) for k in range(3, n, 2): if n % k == 0: return False ...
20c73e8dc19eb3224516519d285414b36b442005
khoabangnguyen/JSON-Handlers
/json_to_csv/JsonConverter.py
2,905
3.859375
4
import json import csv import os # Program to convert nested JSON files into flat CSV files # Helper function to help flatten nested JSON values def flatten_json(nested_json): out = {} def flatten(x, name=''): if type(x) is dict: for a in x: flatten(x[a], ...
2995d9d0ba2a04c3695bf2da89596e0e73538597
alecmori/project_euler_answers
/answers/problem_33/run_problem.py
1,848
3.890625
4
# -*- coding: utf-8 -*- import fractions def run_problem(n=2): max_num = 10**n min_num = 10**(n-1) total_frac = fractions.Fraction(1, 1) for denom in range(min_num + 1 , max_num): for numer in range(min_num, denom): first_digit_numer = int(numer / 10) second_digit_numer ...
d713d69c7ca2a058981722f24b74ae10934364c9
petercollingridge/code-for-blog
/language/analyse_frequency.py
2,667
3.671875
4
from utils import get_word_counts, show_in_order, convert_counts_to_percentages from collections import defaultdict def get_most_common_words(word_counts, num=10): common_word_counts = [] for i, (word, count) in enumerate(sorted(word_counts.items(), key=lambda word: -word[1])): common_word_counts.app...
7b96af8aef0e4760c93fd819d286691f9ffc0b17
HitenSidapara/Python3-Bootcamp
/DebuggingAndErrorHandling/Handle.py
325
3.734375
4
# Handle the error # name # Gives us the name error # now handle this error # # try: # name # except NameError as err: # print(err); # Another Example : def get(d,key): try: return d[key] except KeyError: return None d = {"name":"Hiten"} print(get(d,"name")); print(get(d,"city...
db96cda3d915c74fd3dc0a3290d95b221aae2b0f
lishulongVI/leetcode
/python3/106.Construct Binary Tree from Inorder and Postorder Traversal(从中序与后序遍历序列构造二叉树).py
1,447
4.03125
4
""" <p>Given inorder and postorder traversal of a tree, construct the binary tree.</p> <p><strong>Note:</strong><br /> You may assume that duplicates do not exist in the tree.</p> <p>For example, given</p> <pre> inorder =&nbsp;[9,3,15,20,7] postorder = [9,15,7,20,3]</pre> <p>Return the following binary tree:</p> <...
4a6513ef15c9d949f432ccadf3fabc08af4fa8ec
xbaysal11/Python
/Encryption/decryptStory.py
1,284
3.875
4
#daniyarovbaysal def decryptStory(): """ Using the methods you created in this problem set, decrypt the story given by the function getStoryString(). Once you decrypt the message, be sure to include as a comment your decryption of the story. returns: string - story in plain text """ ...
98db346a5f98ad75d3333dbe3aff0153aef4052c
socio-culturalBrainLab/social_network
/mc/load.py
3,305
3.53125
4
import pandas as pd import numpy as np import os def list_files(path): """ MC 14/06/21 Inputs: path : path of the folder were the focals are stored Outputs: list of all the paths to all the files """ fichiers = [] for (_,_,files) in os.walk(path): #look at all the files in ...
93656adccf3266a1b7b5e1b39637108f7a2124ae
Crissky/python_IA
/Perceptron.py
2,153
3.59375
4
class Perceptron: def __init__(self, dataset, labels, threshold=0.2, learning_rate=0.01, epoches=100): self.dataset = dataset self.labels = labels self.threshold = threshold self.learning_rate = learning_rate self.epoches = epoches self.weights = [0]*len(datase...
50fb9ca05833e71c30328517097bb0267fe66fb3
zpoint/Reading-Exercises-Notes
/core_python_programming/8/8-7.py
338
3.75
4
def getfactors(num): alist = [] for i in range(1,num): if num % i == 0: alist.append(i) return alist def isperfect(num): if sum(getfactors(num)) == num: print 1 else: print 0 isperfect(int(raw_input('Please enter a number to determine whether it\'s ...
97342f0b6bc30b3eed4b5f636e445ba8c5d6a9c2
chithien0909/Competitive-Programming
/Leetcode/Leetcode - Bitwise AND of Numbers Range.py
773
3.625
4
""" Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive. Example 1: Input: [5,7] Output: 4 Example 2: Input: [0,1] Output: 0 """ import math class Solution: def rangeBitwiseAnd(self, m: int, n: int) -> int: if m* n == 0: return 0 st...
66cb276a6a31a1298a474f8fa582023276f9526d
kckoh/python_tutorial
/python_101/part1/function.py
335
4
4
def factorial (num): if num is 1: return 1 else: return num * factorial(num -1 ) # print factorial(3) def rgb(r,g,b): if isinstance(r, int) and isinstance(g, int) and isinstance(b, int) : print "#%x%x%x" % (r,g,b) else: print "r,g,b has to be integer" rg...
d72b032aac0f2d0a245dc4b9d086c81565df937b
dq-code/leetcode
/101-SymmetricTree.py
729
3.828125
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 isSameTree(self, n1, n2): if n1 == None and n2 == None: return True if n1 and n2 and n1.val == n2.val...
59a20f8dce60d54b83fc5a8d4a6aa46e27ec76e4
priyanshi-mittal/Python-Lab
/Prime.py
158
3.96875
4
x=int(input("Enter a number")) c=0 for i in range(1,x+1): if x%i==0: c+=1 if c==2: print("prime no.") else: print("not prime")
0f54d9796fe1f78bff2a44fea034b9f86d31d11e
ssj234/PythonStudy
/sklearn/tu_c2_9.pca.train.py
1,100
3.53125
4
#!/usr/bin/python # -*- coding: UTF-8 -*- matplot = True # Python机器学习及实践的第二章中的例子, # 使用手写数字,先对其将维,再训练 import pandas as pd import matplotlib.pyplot as plt import numpy as np # 导入数据,每条数据65个, 最后一个是结果 digits_train=pd.read_csv('data/optdigits.tra',header=None) digits_test=pd.read_csv('data/optdigits.tes',header=None) x_digi...
a6c2402662c9c30682f8b87932d9df545286c46e
danilo-montes-code/Playlist-Updator
/UpdatePlaylist.py
5,670
3.8125
4
# Updates a playlist in reference to other playlists # Pulls data from other playlists and removes songs that are no longer in said playlists # Basically a playlist merger # https://spotipy.readthedocs.io/en/latest # developer.spotify.com import spotipy from spotipy.oauth2 import SpotifyClientCredentials import spotip...
837826234e845fcb720051e740ef4484fe4d0852
Sreelekshmi-60/Programming-lab
/1.3-7colordiff.py
210
3.796875
4
list1=set(['red','blue','green','white','black']) list2=set(['green','orange','violet','black','yellow']) colorlist=list1.difference(list2) print("Set of colors from list1 not contained in list2 = ",colorlist)
79dad1a5e25b039a5182f844d94ed2c06d065c12
shettysahab/Networks
/Computer-Networks-1/examples/sample.py
2,876
3.65625
4
from socket import * import ssl msg = "\r\n I love computer networks!" endmsg = "\r\n.\r\n" # Choose a mail server (e.g. Google mail server) and call it mailserver mailserver = "smtp.gmail.com" port = 587 # Create socket called clientSocket and establish a TCP connection with mailserver clientSocket = socket(AF_INET...
c939f22c85e1665432bce018b093d50c7e45a205
4dv3ntur3r/Python
/100-Days-of-Code/day-18/main.py
1,600
3.796875
4
import random import turtle from random import choice timmy = turtle.Turtle() screen = turtle.Screen() turtle_colors = ["lime green", "cyan", "crimson", "magenta", "deep pink", "dark violet", "dark blue",] turtle.colormode(255) #timmy.shape("turtle") # for _ in range(4): # timmy.forward(100) # timmy.right(90...
a340adc9136e662cc23b0cb72d6760d346750482
mrblack10/tamrin
/jadi/azmon4_3.py
390
3.9375
4
def find_longest_word(input_string): input_string = input_string.split() #print(input_string) maxs = None maxlen = 0 for s in input_string : #print ('s:',s) if len(s)>= maxlen : maxlen = len(s) maxs = s #print (maxlen,maxs,'\n************') return ...
2be6f72d84d3b86afdf839a5520aa7dce99102df
thecodearrow/LeetCode-Python-Solutions
/Merge Sorted Array.py
850
3.6875
4
#https://leetcode.com/problems/merge-sorted-array/submissions/ class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: n=len(nums1) l2=len(nums2) if(n==0): return if(l2==0): return p1=n-l2-1 p2=l2-1 ...
3dbbbb4a0fcd3c7010dfb705a876afd4baf77940
simyy/leetcode
/combination-sum.py
1,947
3.71875
4
# -*- coding: utf-8 -*- """ https://leetcode.com/problems/combination-sum/ Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target. The same repeated number may be chosen from candidates un...
a704862041b009effedab157ec42cacd5695957d
DmitryVlaznev/leetcode
/1551-minimum-operations-to-make-array-equal.py
1,434
3.875
4
# 1551. Minimum Operations to Make Array Equal # Medium # You have an array arr of length n where arr[i] = (2 * i) + 1 for all # valid values of i (i.e. 0 <= i < n). # In one operation, you can select two indices x and y where 0 <= x, y < # n and subtract 1 from arr[x] and add 1 to arr[y] (i.e. perform arr[x] # -=1 ...
9ba276d2521de23841146af5a03138d6671167c0
imarkofu/PythonDemo
/Demo/day07.py
3,199
4.09375
4
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- from collections import Iterable from collections import Iterator # import builtins from functools import reduce print(isinstance([], Iterable)) print(isinstance({}, Iterable)) print(isinstance('abc', Iterable)) print(isinstance((x for x in range(10)), Iterable)) print(...
d2de1248daa9522382bfa206d89cf4caf1de88e5
naman-32/Python_Snippets
/BASIC/v3.py
1,088
3.8125
4
courses = ['History' , 'Math', 'Physics', 'CompSci'] print(len(courses)) print(courses[1:3]) print(courses[0]) print(courses[1]) print(courses[:3]) print(courses[1:3]) courses_a = ['art','maths'] #courses.extend(courses_a) #courses.append(courses_a) courses.insert(1,courses_a) print(courses) courses.r...
db2749b26991284a3f3995e986dafd0f97159286
ambrocio-gv/PythonConsoleApps
/2c.py
457
3.984375
4
#In #The program accepts any number of integers, one on one on each line, ranging -100 to 100 #inclusive. Input is terminated by any value that is outside the acceptable range. #Out #On a single line, print the sum of all the numbers from the input x = int(input("x:")) total = 0 while True: if (x >= -...
a132a794d5a97777d88f9eeb571bfd84b4be3483
lucashsouza/Desafios-Python
/CursoEmVideo/Aula07/ex009.py
588
3.890625
4
num = int(input('Digite um numero e veja sua tabuada: ')) t1 = num * 1 t2 = num * 2 t3 = num * 3 t4 = num * 4 t5 = num * 5 t6 = num * 6 t7 = num * 7 t8 = num * 8 t9 = num * 9 t10 = num * 10 print('A tabuada é: ') print('{}x1 = {}'.format(num, t1)) print('{}x2 = {}'.format(num, t2)) print('{}x3 = {}'.forma...
2de82a7035e6686e412a118504025d50f6ac2844
JARVVVIS/ds_algo_practice
/hackerrank/6FibTillN.py
243
3.953125
4
## Print all fibonacci numbers <=n def main(): n = int(input()) vals = [0,1] while vals[-1]<=n: num = sum(vals[-2:]) vals.append(num) [print(x,end=' ') for x in vals[:-1]] if __name__ == '__main__': main()
d03755090035d43d2109e04fe0f75d7b4a9fc013
kercheval/Fun_ProjectEuler
/Problem 4/problem4.py
1,560
3.875
4
def is_palindromic(candidate: int): check_string = str(candidate) first_index = 0 last_index = -1 while first_index < check_string.__len__(): if check_string[first_index] != check_string[last_index]: return False first_index += 1 last_index -= 1 return True def ...
6a2db4c3b82c6a06385ce51b9670f4bd377a5a33
mzahn571/PYTHON
/archive/cisco-web-gui-02.py
977
3.53125
4
import requests import json import xlsxwriter # Define variable for RESTful Call hostname = 'localhost' url = "http://%s:5000/json/cisco/routes"% hostname username = 'student' password = 'student' # Making RESTful call via python to attain JSON data data = requests.get(url, auth=(username, password)) format_data = da...
3c3f6e1d026d692765bb85325471adfb1704d4f7
moinsoft/Programming-Essential-Python-3
/exercise_6_2a.py
110
3.890625
4
moin = [3,5,9,6,7,4,1,2] min = moin[0] for x in moin[1:]: if x < min: min = x print("Minimum = ",min)
69039b212084ce581fbf238d60aeb8f56c57c8e8
n4tm/stem-games
/mypong/natanael.lucena/mypong.py
4,913
4.34375
4
# Jucimar Jr 2019 # Adaptado por Natanael Lucena de Medeiros # pong em turtle python https://docs.python.org/3.3/library/turtle.html # baseado em http://christianthompson.com/node/51 # fonte Press Start 2P https://www.fontspace.com/codeman38/press-start-2p # som pontuação https://freesound.org/people/Kodack/sounds/2580...
4d527669d921bc0be49b8d75a003551ff76f6f8e
bil-bal/cs50-submissions
/Python/Readability/readability.py
376
3.671875
4
from cs50 import get_string import re s = get_string("Text: ") regex = re.compile('[^a-zA-Z]') L = len(regex.sub("", s)) W = len(re.split(" ", s)) S = len(re.split("! |\. |\? ", s)) index = round(0.0588 * ((L / W) * 100) - 0.296 * ((S / W) * 100) - 15.8) if index < 1: print("Before Grade 1") elif index > 16: ...
ecd40f515408178c70a5426f4607e75bd3188852
sreenivr/Sudoku
/sudoku.py
2,700
4.125
4
board = [ [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 4, 0, 0, 2, 0, 7, 0], [0, 0, 0, 0, 1, 3, 2, 8, 0], [8, 0, 0, 9, 0, 6, 0, 4, 0], [7, 0, 1, 0, 0, 0, 0, 2, 9], [0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 8, 0, 0, 0, 0, 5, 3, 7], [0, 0, 0, 5, 6, 0, 0, 0, 4], [0, 0, 7, 0, 0, 0, 0, 0, 0], ...
be601f01069a264ea285dcb5453804432cb693cf
Srini-py/Python
/Sci-Kit/ip_transforms.py
2,965
4
4
''' In machine learning (especially in graph neural networks), we need to convert the IP addresses into integers starting from 0. So we need a transformation that converts ips into integers and vice versa. Please note that an ip address should be mapped to the same integer, whether it is a source ip (src_ip) or a ...
f851ba5a7c9a463f7d0c3cedab7ed992ef207607
brpadilha/PythonPractice
/aManOrABoy.py
154
3.78125
4
def check (a): if a > 18: print ('You are a man') else: print ('You are a boy') age = int(input('How old are you? ')) check(age)
bbade80c726055ae90d98ca67092cd834587b9ca
manhcuongpbc/tranmanhcuong-lab-c4e18
/Lab03/homework/ex9.py
192
3.953125
4
def get_even_list(l): even_list = [] for i in l: if i % 2 == 0: even_list.append(i) return(even_list) even_list = get_even_list([-1,2,1,3,4,6]) print(even_list)
3d45724ec562cd03e98bdc875407005e1c642e78
aaruel/advent-of-code-2017
/Day 11/day11.py
901
3.734375
4
# Help from here # https://www.redblobgames.com/grids/hexagons/#coordinates import functools path = input().split(",") distance = lambda x, y: (abs(x) + abs(y) + abs(x+y))/2 move = { "n": lambda p: {"x": p["x"], "y": p["y"]+1}, "ne": lambda p: {"x": p["x"]+1, "y": p["y"]}, "se": lambda p: {"x": p["x"]+1, "y": p["...
394565498fe9fb77bb9f8354cd8b7edcb1db343d
egor909/algrtm
/деревья/23.py
1,593
4.0625
4
class Node: def __init__(self, data): self.left = None self.right = None self.data = data def insert(self, data): if self.data: if data < self.data: if self.left is None: self.left = Node(data) else: ...
a874f0cc33df74bb95d0ace9027c31302754628b
EvangelineRebello/Programs
/ass6.py
2,184
3.828125
4
import math def accept_array(A): n=int(input("Enter the total number of students")) print("Input percentage of the students") for i in range(n): per=float(input("Enter percentage %d : "%(i+1))) A.append(per) print("Student percentage accepted successfully\n\n") return n de...
a397c10c0bc6bde27de8eba3eb89c234d58c0f3e
nphucnguyen/python_cc1
/Algorithm/lab13.py
3,645
3.796875
4
from collections import defaultdict class Graph: def __init__(self): self.graph = defaultdict(set) def __str__(self): return str(dict(self.graph)) def addEdge(self,u,v = None): if v is None: self.graph[u] return self.graph[u].add(v) self.graph[...
9818a6c2a541296f85e9fe4db4c1c49516287452
ManuelsPonce/ACC_ProgrammingClasses
/COSC1336-IntroToProgramming/Test/Test 2/John_Fonseca_Test2_LoopFile.py
3,075
3.75
4
import os #Defining Main def main(): #Accumulator total = 0 finalTotal = 0 #Create File to write data to numFile = open("numbers.txt", 'w') #Loop 10 times and write each iteration to the file for count in range(1, 11): numFile.write(str(count) + '\n') #Close File ...
5b5f80595a53c01050d4da241f7bfb61c6682b6b
Lnan95/project-Euler
/project Euler 1.py
685
4.34375
4
''' 1.If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. ''' def f(number): s = 0 for i in range(number): if (i // 3) * 3 == i or (i // 5) * 5 == i: s += ...
b47565c024fbfa162a0f12dce7e9ce7423c17bb3
viniciuslopes13/sistemas_inteligentes
/busca em profundidade limitada.py
710
3.5
4
class State: def __init__(self,n, depth): self.n = n self.depth = depth def initialState(): return State(1,0) def stackIsEmpty(): return len(stack) == 0 def showState(s): print(s.n) def expand(s): if s.n >= 4: return [] ret = [] ret.append(State(2*s.n + 1,s.d...
f8cd684a457ca4850903e5fabef63dab68f12fe1
nurl8n/PP2
/pygame/drafts4/main.py
2,812
3.53125
4
import pygame import random # initialization pygame.init() # screen size screen = pygame.display.set_mode((800, 600)) # downloading an image backImage = pygame.image.load("bg.png") # ("./images/bg.png") we can do, ./ means that the same folder, but another path # name of game pygame.display.set_caption("GALAXY GAME")...
c847f11c77a52271e194b71ab29dba3136da2c49
yastil01/two_pointers
/LC_259_three_sum_smallest.py
556
3.65625
4
class Solution: def threeSumSmaller(self, nums: List[int], target: int) -> int: if len(nums) < 3: return 0 nums.sort() count = 0 n = len(nums) for first in range(n): second = first + 1 third = n - 1 while second < third...
17db071fa3bcb3809f736aa12ee9f3957ef4c35e
ratedRA/python
/Algo/DP/stairs.py
137
3.703125
4
def ways(n): if n==1: return 1 if n==2: return 2 return ways(n-1)+ways(n-2) n = int(input()) countWays = ways(n) print(countWays)
151bbbd0b691acd494d84f4f5c5968a4699b3ed1
mahimrocky/NumerialMathMetics
/runge_kutta_fourth_order.py
515
3.734375
4
import math import parser formula = str(input("Enter the equation:\n")) code = parser.expr(formula).compile() def f(x,y): return eval(code) print("Enter the value of x0:\n") x0=float(input()) print("Enter the value of yo:\n") y0=float(input()) print("Enter the value of h:\n") h=float(input()) k1=round(float(h*...
5c4f2b4dcaa9e94dec00889706cd9d6b6525ed3b
jpspm/PLC
/python/caracteristicas.py
629
3.640625
4
countFLV = 0 person = 0 maxAge = 0 while(1): age = int(input()) if age != -1: caracteristicas = list(input().split()) if caracteristicas[0] == 'f' and caracteristicas[1]=='l' and caracteristicas[2] == 'v' and age >= 18 and age <=35: countFLV+=1 if age > maxAge: ma...
a7468e942d30f58de3e6206dfb6e8d402a3e91e4
peipei1109/P_05_Books
/python_core_programing/18threads/mtsleep5.py
981
3.53125
4
# -*- encoding: utf-8 -*- ''' Created on 2016年5月14日 @author: LuoPei ''' import threading from time import ctime,sleep loops = [ 4, 2 ] class MyThread(threading.Thread): def __init__(self,func,args,name=''): threading.Thread.__init__(self) self.name=name self.func=func ...
b450667f8653100dd4ff1acf170f9e343170eb0a
Devoid33/CSC310Project1JacobW
/CSC310Project1JacobWilliams.py
6,497
4.21875
4
"""Basic example of an adapter class to provide a stack interface to Python's list.""" # from ..exceptions import Empty class ArrayStack: """LIFO Stack implementation using a Python list as underlying storage.""" def __init__(self): """Create an empty stack.""" self._data = [] # n...
18a60ca4fa6b42b3e20d7db58866940bacc078da
bgnori/online-judge
/project-euler/0019/run.py
1,797
3.828125
4
""" 1900 Jan 1 is 1st day. 0th day is 1899 Dec 31. define "day1900" as follows: 1900 Jan 1 is 1 1900 Jan 31 is 31 1900 Feb 1 is 32 1900 Feb 28 is 59 1901 Jan 1 is 366 mod 7 == 1 <=> Monday """ def month2days(month, isleap): # - 1 2 3 4 5 6 7 8 9 10 11 12 us...
65455e7dc5f6df7bcbff9ccfbd27220908ad6dfb
ptoche/GDLC
/GDLC/future/skip_split.py
2,274
3.9375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Not thoroughly tested: edge cases probably fail def skip_split(string, separator=' ', start=None, end=None): """ Split a string between two occurrences of the same separator. Returns: (head, body, tail) Modules: string (separator) """ ...
ac464afdde83cc84892e56e463e049f659f98771
pharick/python-coursera
/week7/8-guess-number-2.py
335
3.671875
4
n = int(input()) numbers = set(range(1, n + 1)) line = input() while line != "HELP": question = set(map(int, line.split())) if len(numbers & question) > len(numbers) / 2: print("YES") numbers &= question else: print("NO") numbers -= question line = input() print(*so...
e4abd0e0cb8020d72062ac83580bd60bb1bf441a
xxrom/5_part_grokaem
/0_simple_multi-input_gradient_decant.py
1,679
3.78125
4
# Neural network weights = [.1, .2, -.1] # learn Info toes = [8.5, 9.5, 9.9, 9.0] wlrec = [0.65, 0.8, 0.8, 0.9] nfans = [1.2, 1.3, 0.5, 1] # ans info win_or_lose_binary = [1, 1, 0, 1] # Sum two vectors def w_sum(a, b): assert (len(a) == len(b)) output = 0 for i in range(len(a)): output += a[i] * b[i] ...
adfe67028140b151fe3105555d9f5225fbe24c51
medapalli/Python_UNH
/Homework8/HW8_Prog1.py
3,569
4
4
class Animal(): def __init__(self, name): self.name=name def guess_who_am_i(self): print("I will give you 3 hints, guess what animal I am\n") while True: if (self.name=="Elephant"): print("I have exceptional mem...
3f9a742dbfe45ddd6157bc4097f1d78f0de0e2e8
sankeerthankam/Code
/Coderbat/2. Warmup - 2/6. Array Count9.py
113
3.5
4
# Given an array of ints, return the number of 9's in the array. def array_count9(nums): return nums.count(9)
4a94ad08ce821e198b51c9d10b0075927dcb5f0f
eckelsjd-rose-old/csse120
/Final Exam/src/problem4.py
5,219
4.03125
4
""" Final exam, problem 4. Authors: David Mutchler, Dave Fisher, Matt Boutell, their colleagues, and Joshua Eckels. """ # DONE: 1. PUT YOUR NAME IN THE ABOVE LINE. import time def main(): """ Calls the TEST functions in this module. """ run_test_problem4() def is_prime(n): """ What c...