blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
55f9b147c48411aae4b6b1609568e459fafdef7b
BrindaSahoo2020/Python-Programs
/Basic_Programs/Average.py
274
4.1875
4
#Calculate the average of numbers in a list lst = [] for i in range(1,20,5): lst.append(i) print(lst) l = len(lst) total = 0 for i in lst: total = total+i print(total) avg = float(total/l) print("Average of the list is ",avg) #Output (Average of the list is 8.5)
9542708331bf8413e0bebd9feca926c04493afb3
ziv1989/my-isc-work-1
/python_work/python_string3.py
327
4.09375
4
#!/bin/env python #3rd exercise from ncas-isc about python strings something="Completely Different" #Counts the number of appearences of 't' something.count('t') #Split the string by the given character split_string=something.split('e') #replace an entire section of the string thing2=something.replace('Different','...
f1b1770e67a5b71e501d89841df6a303dbdf97f1
rkeisling/gladiator_code
/glad_game.py
2,978
4.125
4
from gladiator import Gladiator import random import time names = ['Maximus', 'Brutus', 'Romulus', 'Remus', 'Aurelius', 'Vulpes'] weapons = ['Spear', 'Sword', 'Knife', 'Mace'] def main(): print(""" Welcome to the colloseum! Here you will command your champion to fight to the death against a gladiator ...
e98829fb451ad3669b2fbca35afee69dfc74065d
norbour/leetcode
/src/reverse-words-in-a-string.py
1,086
3.5625
4
class Solution: # @param s, a string # @return a string def reverse(self, s, st, ed): if s == None or st > ed: return None if st == ed: return s[st] return s[st:ed][::-1] def clear(self, s): st = 0 ed = len(s) - 1 while st < le...
b25490a77e00539954ca80240770688cdedf4060
RajaSekar1311/Data-Science-and-Visualization-KITS
/Data Frame & Load Excel File/LoadExcelDataIntoPandasDataFrame.py
791
3.6875
4
import pandas myFileName = 'Session2-KITS-Guntur-DataSet.xls' #with is a context manager here # group of instructions will be exexuted in a particular context #In pandas there is a method called as ExcelFile() #ExcelFile() method opens a excel file #With opening the file in read mode perform lines 11 to 15 w...
31debebcd11797b8f7f914f17fbf32dc2dcac577
kkaixiao/pythonalgo2
/leet_0219_contains_duplicate_II.py
1,037
3.796875
4
''' Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k. Example 1: Input: nums = [1,2,3,1], k = 3 Output: true Example 2: Input: nums = [1,0,1,1], k = 1 Output: true Exa...
3a53ac8b43bc18398e9902466ce2994b031dcf6f
FilipVidovic763/vjezba
/predavanje6.py/skrivanje.py
243
3.546875
4
class Brojac: __brojac = 0 def broji(self): self._tekst = 'dodajem +1' self.__brojac += 1 print(self.__brojac) brojac = Brojac() brojac.broji() brojac.broji() print(brojac._tekst) print(brojac.__brojac)
ae2ae6f309cc59191a36fd5450687a78cc70c36c
vkvasu25/leetcode
/linked_list/leetcode_ll_implementation.py
4,100
4.15625
4
class Node(object): def __init__(self, value, next_node=None): self.value = value self.next_node = next_node def getValue(self): return self.value def getNextNode(self): return self.next_node def setValue(self, value): self.value = value def setNextNode(se...
0896f2ddf92640c57d1bbd678444d12f448debc6
Vaibhavnath-Jha/Hangman-Game
/main.py
2,661
3.84375
4
import os import game import time from Winner import winner class Player: def __init__(self, name, score): self.name = name self.score = score def display(self): print("{:12}{:12d}\n".format(self.name,self.score)) def rules(): #11 print("\n\t\t\t\t-:GAME RULES:-") print("1. You will have 7 tries.\n...
afb127dab864edc82e04105dfbb49a58ee23d53b
tashbekova/neobis
/hackerrank/alphabet rangli.py
231
3.609375
4
N = map(int(input())) a = input("input character") b = input("input character") for i in range(1,N,2): print((a * (i)).center(N, "-")) print(a.center(N, "-")) for i in range(N-2,-1,-2): print(("b" * (i)).center(N, "-"))
5c659f1c45966745726caaff6361d2f659e659db
superyang713/pcookbook
/03_numbers_dates_and_times/12_convert_days_to_seconds_and_other_basic_time.py
792
4.125
4
""" Problem: You have code that needs to perform simple time conversions, liek days to seconds, hours to minutes, and so on. Solution: Use datatime module. """ from datetime import timedelta from datetime import datetime # Example 1: perform conversions and arithmetic involving different units of # time, use the da...
a8730900420fca55bceac74513aa53c5465028f0
arhandreu/OOP
/OOP.py
5,156
3.765625
4
def average_grade(grad, course="all"): all_grades = [] if course == "all": for grade in grad.values(): all_grades += grade return sum(all_grades) / len(all_grades) else: return sum(grad[course]) / len(grad[course]) def average_grad_all(course, *units): sum_aver_grad...
f44452d5bd4673542147e977c71a18b90b09c0b5
sethyeboah/RaspberryPi
/HelloWorld.py
122
3.765625
4
x = input("Print welcome? (y|n): ") if x == 'y': print("Hello World") elif x == 'n': print("Exiting..") exit()
dde1fe08ccd7c0a1d2f8346dd70b1d3b8902f7d3
gdoorenbos/twister-spinner
/twister.py
375
3.625
4
from itertools import product from random import randint colors = ["blue", "green", "yellow", "red"] sides = ["right", "left"] appendages = ["hand", "foot"] options = [sides, appendages, colors] options = [' '.join(i) for i in product(*options)] while True: opt_ind = randint(0, len(options)-1) print('{}: {}'....
b99bfd32461e006ca23ba132a25c17bab08f0275
destinyplan/ZenCloud2
/homework/d20180802_6.py
124
3.84375
4
str1 = "jintianquweinanle !!!" str2 = "tian"; print (str1.find(str2)) print (str1.find(str2, 3)) print (str1.find(str2, 19))
47b95e3dbbd2542e1485a52ae0917dcad9791f9d
Tyzeppelin/Project-Euler
/problem34/problem34.py
785
3.5625
4
def tailFacto(n, r): if n == 0: return r else : return tailFacto(n-1, r*n) def factorial (n): if n == -1: return 0 return tailFacto(n, 1) def cond (a): num = int(''.join(map(str,a))) res = 0 for e in a: res += factorial(e) return num == res def form...
e7c8c380169809aeddba540325bf49aeb4a55425
Mart1nDimtrov/DoingMathPython
/03. Describing Data with Statistics/read_search_correlation.py
1,356
3.59375
4
import csv import matplotlib.pyplot as plt def find_corr_x_y(x, y): n = len(x) # Find the sum of the products prod = [] for xi,yi in zip(x,y): prod.append(xi*yi) sum_prod_x_y = sum(prod) sum_x = sum(x) sum_y = sum(y) squared_sum_x = sum_x**2 squared_sum_y = sum_y**2 x_square = [] for xi in x: x_squ...
b4a6846edd71a5148c815413785ee0bb9e3fcad4
dav-ell/looptimer
/timing.py
2,313
4.09375
4
import time import types def timing(iterable, every_n=None, every_fraction=None): """Wraps your iterables to give you automatic timing! Want to time this loop? for i in arr: # do things Just write, instead: for i in timing(arr): # do things Et vo...
23fcb4b58a4f3b2580ca5e3015b6b5c72caccba0
luyisimiger/proyecto_sensores
/sensores/client/python_cli/visualize.py
1,300
3.640625
4
def matplotlib_demo(): # Import the necessary packages and modules import matplotlib.pyplot as plt import numpy as np # Prepare the data x = np.linspace(0, 10, 100) # Plot the data plt.plot(x, x, label='linear') # Add a legend plt.legend() # Show the plot plt.show() def...
cc462edda955fbc158aa5b6c6f8824ded31864bd
valies/AoC2020
/Day5/seat.py
1,092
3.578125
4
class FileReader(): @classmethod def read_file(cls, file): a = [] with open(file) as my_file: for line in my_file: a.append(line.rstrip()) return a class SeatFinder(): @classmethod def find_available_seat(cls, lines): occupied_seats = [] ...
c6b3f0883ba5c1ed8aff9e3d80a4ace179b110f4
lazyp/pycommon
/logger.py
1,689
3.546875
4
#-*- coding:utf-8 -*- import time class Logger: DEBUG = "DEBUG" INFO = "INFO" ERROR = "ERROR" Level = INFO def print_out(self ,level , msg): localtime = time.localtime() y = localtime.tm_year mon ...
6f75c85f3d163369daefbfcd231e63b1431b62fe
msaei/coding
/LeetCode/Top Interview Questions/Arrays and Strings/Group Anagrams.py
461
3.875
4
#Group Anagrams #https://leetcode.com/explore/interview/card/top-interview-questions-medium/103/array-and-strings/778/ class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: anagrams = {} for word in strs: key = ''.join(sorted(word)) if key in anagrams....
d01089406fd65e71a5202687600e157400d729b5
apoorvkk/LeetCodeSolutions
/problems/301_remove_invalid_brackets.py
1,330
3.8125
4
''' URL: https://leetcode.com/problems/remove-invalid-parentheses Time complexity: O(2^n) Space complexity: O(n!) ''' from collections import deque class Solution(object): def is_valid(self, s): open = 0 for char in s: if char == "(": open += 1 elif char == ...
1420aaf0ba7cbba11f56f5de9da2cd18240ebc54
syedasifuddin/CS61A
/assignment/bathtub.py
465
3.53125
4
def bathtub(n): def ducky_annihilator(rate): def ducky(): nonlocal n nonlocal rate n = n - rate return n return ducky return ducky_annihilator def weird_gen(x): if x % 2 == 0: yield x * 2 else: yield x ...
bbb3014f75b85cf2521a5862c5522476d6d15772
davis-mwangi/python-data-structures
/classess_and_objects.py
795
4.21875
4
class MyClass: x = 5 # object p1 = MyClass() print(p1.x) class Person: def __init__(self,name,age): """ This is executed when a class is initiated """ self.name = name self.age = age def myfunc(self): print("Hello my name is "+ self.name) p1 = P...
f5073f2b369cb6d4db041232019a2148ed965a8f
dev-arthur-g20r/how-to-code-together-using-python
/How to Code Together using Python/PYC/absolutevalue.py
337
3.984375
4
import os class AbsoluteValue: def __init__(self,n): self.n = n def absValue(self): if (self.n < 0): abs = self.n * -1 else: abs = self.n return "Absolute value: {}".format(abs) number = float(input("Number to check its absolute value: ")) x = AbsoluteValue(number) result = x.absValue() print(result) o...
953549d0476251f189e7d3596d6700167a91b261
salvadorraymund/Python
/Standard Library/efficient_array.py
221
3.703125
4
from array import array """i at the beginning means you are going to use integer data type""" arr1 = array('i', [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]) print(arr1) arr2 = array('i', [elem * 2 for elem in arr1]) print(arr2)
b1cbb8c5802b8bb2610a9e6a1b382b2affa6a074
daniel-reich/turbo-robot
/RvZfGXR3TQHjLy7mN_16.py
787
4.125
4
""" Write the **regular expression** that matches all street addresses. All street addresses begin with a number. Use the character class `\d` in your expression. ### Example txt = "123 Redding Dr. 1560 Knoxville Ave. 3030 Norwalk Dr. 5 South St." pattern = "yourregularexpressionhere" (re.findall(...
7199d9d5b3d361e52afeec4ba5c3a705b7802063
MerveillesKoina/Python2020
/GUI/TextBoxExample.py
366
3.65625
4
################################### #June2020 #LearnToCode #Author: Merveille Koina Guidingar from tkinter import * import os os.system('clear') root = Tk() root.title('TextBox Example') entry = Entry(root,width=25) entry.insert(0,'Enter your name') entry.grid(row=0,column=0,columnspan=5,padx=5,pady=8) b = Butt...
b19a73e943cc2fa5c2d1527668b50a9ca6f74e7f
ladosamushia/PHYS639F19
/NathanMarshall/ODE3/Orbital Motion - Stationary Center Mass.py
1,151
3.84375
4
# -*- coding: utf-8 -*- """ Created on Tue Oct 1 13:14:58 2019 Nathan Marshall This code simulates the orbit of an object around a stationary central mass. """ #%% import matplotlib.pyplot as plt x0 = 1 #initial x y0 = 0 #initial y vx0 = 0 #initial x velocity vy0 = 0 #initial y velocity t0 = 0 #start time tmax = 10 ...
4775dc3a38827a4615444b6f83158bb2e216c546
Arkzirk/Practice
/final_practice.py
691
3.921875
4
print('Общество в начале XXI века') x = int(input('Сколько Вам лет?')) def myfunc(x): if x >= 0 and x <= 7: t = 'Вам в детский сад' elif x > 7 and x <= 18: t = 'Вам в школу' elif x > 18 and x <= 25: t = 'Вам в профессиональное учебное заведение' elif x > 25 and x <= 60: t...
584f418d76b05c16360a40ff52e2fa983e3f3f3d
shahrukh357/MachineLearning
/Regression/Multiple Linear Regression/multiple_linear_regression.py
2,235
4.03125
4
# Multiple Linear Regression # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('50_Startups.csv') X = dataset.iloc[:, :-1].values y = dataset.iloc[:, 4].values # Encoding categorical data from sklearn.preprocessing import La...
606491180daf23150d0a65b4e1ce2af1d1e5069d
luciogutierrez/iron-hack
/1-module/9-map-reduce-filter/test.py
216
3.703125
4
from functools import reduce def solution(digits): num_ini = int(reduce(lambda a,b: a if a>b else b , str(digits))) num_fin = num_ini + 3 return digits[num_ini:num_fin] print(solution('19265'))
c2b370a8a66b19aba585e629d16d5e87a7e65534
J-A-S-0-N/1DAY-1COMMIT
/opencv face/when_started.py
307
3.703125
4
import tkinter as tk root= tk.Tk() canvas1 = tk.Canvas(root, width = 300, height = 300) canvas1.pack() def hello (): label1 = tk.Label(root, text= 'hello wellcome', fg='green', font=('helvetica', 12, 'bold')) canvas1.create_window(150, 200, window=label1) hello() root.mainloop()
d5cec864958d7396b842729ca13ad24201d72087
jonaschianu/2D-Graphics
/Graphics2d.py
6,692
3.921875
4
################################################################################ # Project: 2D Graphical Outputs using Matrices # # # # Name: Jonas Chianu #...
c268721c43fe1e3c225b40b7ef9fe5af2e79cdf8
topherCarpediem/python
/hello.py
475
3.578125
4
# def exc(): # num = input("number: ") # if float(num) < 0: # raise ValueError("Negative") # # # exc() # # the_file = open("sample.txt", "w") # the_file.writelines("Topher") # the_file.close() another = open("sample.txt", "r") content = another.readline() print(content) another.close() aanother = ope...
43488d6d80af05b1e4d8aec1f57a0fbca7198686
yoojunwoong/python_review01
/test2_02.py
207
3.765625
4
# if else 문을 활용하여, 값의 여부확인 a = int(input('insert Numeber...')); if a > 10: print('big nummber'); print('ok'); else: print('small number'); print('end python.....');
09332092e3c022c872d13e889521b9c11ceb1b0f
hengyangKing/python-skin
/Python基础/code_day_1/列表.py
477
3.5625
4
# coding=utf-8 # 列表类型变量 foo=["foo1","foo2","foo3","foo4"] print foo # 列表类似于c中的数组 但是区别在于可以存储不同类型的数据 更像是NSArray for i in xrange(0,len(foo)): print foo[i] print "..................." # for枚举用法 for j in foo: print "---foo %s"%j # 列表的遍历 names=["dlsandnas",dsakdasdsa,"nsdkjnsandksankdnsak","ndkanskdnka","nskda"] ...
b12a4a09c28db5f8390196bf96b00e7941adaa60
FarzanaEva/Data-Structure-and-Algorithm-Practice
/InterviewBit Problems/Two Pointers/merge_two_sorted_lists_II.py
1,181
3.921875
4
# -*- coding: utf-8 -*- """ Created on Mon Jul 12 02:09:52 2021 @author: Farzana Eva """ """ PROBLEM STATEMENT: Given two sorted integer arrays A and B, merge B into A as one sorted array. Note: You have to modify the array A to contain the merge of A and B. Do not output anything in your code. TIP: C users, please ma...
42768de6149e331e494ce878f39c67c44de56b47
kunamdeepthipriyanka/raspi
/power.py
173
3.875
4
a=10 b=20 c=30 if (a>b) and (b>c): print("a is greater",str(a)) print(a) elif: print("b is greater",str(b)) print(b) else: print("c is greater",str(c))
6539b0d220380616a643d96bbfbf99a86fba3080
dollarkid1/pythonProjectSemicolon
/chp3/ExamAnalyzer.py
402
3.6875
4
def analyzer(): passes = 0 failures = 0 print("enter results (pass = 1 and fail = 2)\n") for i in range(10): result = int(input()) if result == 1: passes += 1 else: failures += 1 print(f'Students Passed = {passes}') print(f'Students Failed = {fail...
3bb2eee3b219e51a5f98e7acd069260e0c14facd
ClowDragon/MSCProject
/algorithms/cg.py
802
3.5
4
import numpy as np def cg(A, b, x): """ A function to solve [A]{x} = {b} linear equation system with the conjugate gradient method. ========== Parameters ========== A : matrix A real symmetric positive definite matrix. b : vector The right hand side (RHS) vector of the system. ...
4bd6967bbeeb67e4d754ec2e1293c37123757d46
asishnayak1999/fispy
/py/numpy.py
336
3.515625
4
# -*- coding: utf-8 -*- """ Created on Thu Aug 19 10:13:53 2021 @author: User """ import numpy as np x = np.array([[12,43,65], [32,11,77], [12,90,65], [3,6,99]]) print(x[...,2]) #any row 2 column print(x[2,...]) #2nd row clo 1 onwarnd print(x[...,1:]) #any r...
7a35f2bf82d0e76ed6f7edbfc7d6388a47e192ab
adamhartleb/cracking_codes
/caesar.py
1,495
4.34375
4
from string import ascii_letters def encode(word, key, mode): key = key % 26 letters = list(word) encrypted_letters = [] for letter in letters: encrypted_letter = '' if letter == ' ': encrypted_letter = ' ' elif not(letter in ascii_letters): ...
9a6fc0f5588170554b278f44cb4e2c4cf2cc382a
robbertmijn/kudo_plotter
/auth.py
1,189
3.515625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Dec 11 11:47:07 2020 https://medium.com/swlh/using-python-to-connect-to-stravas-api-and-analyse-your-activities-dummies-guide-5f49727aac86 @author: robbertmijn This is the script that creates the json auth tokens. I needed to refresh my code when I ran ...
927998aee9859f8601dec3a632388ac89fb1171a
laddng/NeuralNetwork
/main.py
1,086
3.71875
4
from classes.NeuralNetwork import *; from copy import deepcopy, copy; def main(): """ Run neural network tests """ # 10 different hidden layers for i in range(10): # 10 different epochs epochs = []; RMSE = []; for k in range(10): hidden_layers = (i+1)*10; net = NeuralNetwork(2, 1, hidden_layers); n...
42cd21f405f0fe7c78e09e500de6e49099545e73
STEEL06/Calculadora_Dieta
/calculo_metabolismo.py
10,919
3.734375
4
print "" #----------------------------------------------------------------------------------------------------------------------------------------------------------- print "Calculo da Taxa do Metabolismo Basal (TMB)." lacoTMB = 0 while ( lacoTMB != 1 ): print"" genero = input ("Qual o seu genero? 1-Homem ; 2-...
422230d39c8a9518c1da1beb7c60040946c704f3
heitorchang/learn-code
/battles/number_theory/mirrorBase.py
625
3.90625
4
description = """ Given number (in the form of a string) represented in base1, we'd like to determine whether its digits form a palindrome when represented in base2. """ import string as g from collections import deque as q def z(n, b): # change base from decimal int "n" to base b p = g.digits + g.ascii_lower...
7d55656d582da78c03b72cef27936a3dbe12cc9b
sbalun/codecademy-homework
/more-list-challenges.py
3,157
4.59375
5
""" 1. Every Three Numbers Create a function called every_three_nums that has one parameter named start. The function should return a list of every third number between start and 100 (inclusive). For example, every_three_nums(91) should return the list [91, 94, 97, 100]. If start is greater than 100, the function s...
8bb30371ec3b59beab98bfead801f861e21ee61e
thuchimney292/thutran-fundamental-c4ep35
/lesson5/homework/5.py
202
3.890625
4
from turtle import * def draw_star(x,y,length): penup() setpos(x,y) pendown() left(72) for i in range(5): forward(length) right(144) draw_star(100,100,100) mainloop()
9d7575306cfd4eb3aead4bb9f862c93f53ec795b
koles289/Udacity_facial_detection
/models.py
1,827
3.65625
4
## TODO: define the convolutional neural network architecture import torch import torch.nn as nn import torch.nn.functional as F # can use the below import should you choose to initialize the weights of your Net import torch.nn.init as I class Net(nn.Module): def __init__(self): super(Net, self).__init_...
084369e4ad0ce5dd14a6679c6611f8d31b4c4acb
nsimsofmordor/PythonProjects
/Projects/Python_Tutorials_Corey_Schafer/PPBT2 Srings.py
625
4.1875
4
message = "Hello" print(message) print(len(message)) print(message[0:5:2]) # string slicing print(message.lower()) # string methods print(message.upper()) print(message.find('e')) message = message.replace('Hello', "GoodBye") print(message) greeting = "Hi" name = "nick" message = greeting + ' ' + name prin...
017341ee29dd0126edcce9c868a60ec3eabbfad9
vaipathak/LearnPython
/Python 2.7/ex18.py
2,875
4.6875
5
print "Exercise 18: Names, Variables, Code, Functions" print """Big title, right? I am about to introduce you to the function! Dum dum dah! Every programmer will go on and on about functions and all the different ideas about how they work and what they do, but I will give you the simplest explanation you can use right ...
1432dba7e8a6757b8e35032983d85af8a511fd06
Aanandi03/15Days-Python-Django-Summer-Internship
/Day_5/Task_Exercise/ex2.py
488
4.21875
4
# Create a class cal2 that will calculate area of a circle. Create setdata() # method that should take radius from the user. Create area() method # that will calculate area . Create display() method that will display area . class Cal2: radius=0 def setdata(self): r = int(input("Enter radius: "))...
b23f7f22824a191ff1c2229685b42edc27e956f4
roger6blog/LeetCode
/SourceCode/Python/Problem/00287.Find the Duplicate Number.py
2,029
3.96875
4
''' Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive. There is only one repeated number in nums, return this repeated number. You must solve the problem without modifying the array nums and uses only constant extra space. Example 1: Input: nums = [1,3,...
3823b577b1b3d44fb40201be3f6351ced17411f7
AviCodeBoy/MathTools
/primeNList.py
659
3.875
4
def prime_or_not(numberToTest): findFactorsOf = numberToTest divisor = 1 factorList = [] comparator = [1, findFactorsOf] while True: x = findFactorsOf / divisor wholeOrNot = x - int(x) == 0 if wholeOrNot: factorList.append(divisor) divisor = divisor + 1 ...
8e4e3ff1039c1dc4127867afacdc84f8797177ad
hochu-leto/generators
/main.py
1,726
3.5
4
import json import os R_FILE = "countries.json" # Первый вариант, без всяких там классов и итераторов // # R_FILE = "countries.json" # W_FILE = "countries.txt" # URL = 'http://en.wikipedia.org/wiki/' # # with open(R_FILE, "r") as read_file: # data = json.load(read_file) # # url_country = {} # for country in data...
edc6072a859611513ec506c71f532ab5cfb98177
samir28/Proyectos-
/funciones con listas.py
737
3.65625
4
def sumar_lista(lista): suma = 0 for x in range(len(lista)): suma = suma + lista[x] return suma def mayor_lista(lista): may = lista[0] for x in range(1,len(lista)): if lista[x] > may: may = lista[x] return may def menor_lista(lista): men = lista[0] for x in ...
95b098a2ba33cf02160677b5ceb3e871e8548a3d
simzam/solutions_digital_dice
/p15.py
2,470
4.0625
4
"""Problem 15: How Long is the Wait Simulation of a queue in a deli store using FCFS principle. The customers in the queue are served by a number of "workers". The arrival of customers are modeled as Poisson process with a fixed rate. The service time of the workers are also simulated as a Poisson process with a fix...
2f947514b3b1d5c6286ace3edf414cf4016f5d03
allenai/pubmedextract
/pubmedextract/corvid/table.py
9,530
3.8125
4
""" The Table class is a physical representation of tables extracted from documents This code was written by Kyle Lo. https://github.com/allenai/corvid/edit/master/corvid/table/ """ from typing import List, Dict, Tuple, Union, Iterable, Callable import numpy as np def format_grid(grid: List[List[str]]) -> str: ...
ba6c9018cdc16a044601c702e07da661a6aeb804
darkerego/solutions
/dashitize.py
872
4.375
4
""" Given a number, return a string with dash'-'marks before and after each odd integer, but do not begin or end the string with a dash mark. Ex: dashatize(274) -> '2-7-4' dashatize(6815) -> '68-1-5' """ def dashatize(num): """ Gross and hacky, i know, i know """ if num is None: return 'None' ...
e035f4cdb9450d143f49b99551e6d5ee91b907ac
toshhPOP/SoftUniCourses
/Python-Advanced/Exam_Practice/list_pureness.py
691
3.5625
4
from collections import deque def best_list_pureness(nums, k): data = {} nums = deque(nums) for rotation in range(k + 1): result = sum([index * number for index, number in enumerate(nums)]) data.update({rotation: result}) nums.rotate(1) max_pureness = max(data.values()) for...
7a1691afd8e457fa331edd203eb1af997f91f148
fank-cd/python_leetcode
/Problemset/palindrome-partitioning/palindrome-partitioning.py
470
3.796875
4
# @Title: 分割回文串 (Palindrome Partitioning) # @Author: 2464512446@qq.com # @Date: 2019-12-03 11:48:28 # @Runtime: 92 ms # @Memory: 11.8 MB class Solution: def partition(self, s): res = [] self.helper(s, [],res) return res def helper(self,s, tmp,res): if not s: ...
a59282ac9a57b82ec060b612d942f2e227acdea1
RustPython/RustPython
/extra_tests/snippets/syntax_nested_control_flow.py
683
3.71875
4
# break from a nested for loop def foo(): sum = 0 for i in range(10): sum += i for j in range(10): sum += j break return sum assert foo() == 45 # continue statement def primes(limit): """Finds all the primes from 2 up to a given number using the Sieve of Erat...
06e83803a3678f52b9440d3f4638f62ff150544a
lgauthereau/lgauthereau.github.io
/python/trialmethod.py
306
3.734375
4
def method_one(): print("look I'm a method") def method_two(name): #because it is executed in line 8, name is defined as "Brandon" print("about to call our first method for " + name) method_one() #above is where the method is inside the method method_two("Brandon")
f1acef2e2802c79c6ffd74b1b357fb84aeaf2d26
Kyrylo-Kotelevets/NIX_python
/Trainee/9.py
762
4.46875
4
""" создайте функцию-генератор, которая принимает на вход два числа, первое - старт, второе - end. генератор в каждом цикле должен возвращать число и увеличивать его на 1 при итерации генератор должен начать с числа start и закончить итерации на числе end т.е. при вызове for i in my_generator(1, 3): print(i...
68cc613981da30f88de98d70544c627a36320f3d
lpgarzonr/PythonKatas
/reverseOnlyLetters.py
407
3.734375
4
from queue import LifoQueue def reverseOnlyLetters(string): stack = LifoQueue() reversedStr = '' for char in string: if char.isalpha(): stack.put(char) for char in string: if char.isalpha(): lastLetter = stack.get(char) reversedStr += lastLetter else: reversedStr += char return reversedStr p...
3efc83e32ce761116a15a9108141520fb1ecc492
yuseungwoo/baekjoon
/10474.py
133
3.625
4
# coding: utf-8 while True: a, b = map(int, input().split()) if not a and not b: break print(a//b, a%b, "/", b)
70dd9be154cb948fa4638589e034ea5977f57994
MaryJane-Ifunanya/Cursoemvideo
/exercicio052.py
527
3.984375
4
print('''Faça um programa que leia um número inteiro e diga se ele é ou não um número primo''') cont = 0 num = int(input('Digite um numero:')) for c in range(1, num+1): if num % c == 0: print('\033[33m', end='') cont += 1 else: print('\033[31m', end='') print('{}'.format(c), end=' ')...
aaff2840112da2ff60a32ba852d181885249aa3c
CrissDefaz001/03_DesktopApps
/04_Python/01_Formas/Rombos.py
656
3.53125
4
print('Rombo normal:') num = 8 if(num%2 == 0): num2 = int(num/2) else: num2 = int((num+1)/2) for i in range(num2, 0, -1): for j in range(i, num2): print('* ', end="") print('') for i in range(0, num2): for j in range(i, num2): print ('* ',end="") print('') print('\nRombo con forma:\n') if(num%2...
7dbc3798cd8eacbf3383578e7ba6af486bf04b73
BubuYo/religious
/array/219. Contains Duplicate II.py
491
3.5
4
class Solution: def canJump(self, nums): """ :type nums: List[int] :rtype: bool """ l, remain = len(nums), 0 for idx, i in enumerate(nums): if idx + i + 1 >= l: return True remain = max(i, remain - 1) if not any([i, ...
3f3be192651ae5345fe41b48f121840d0e53522a
franklaercio/Python-PC-UFRN
/Lista 02/questao02.py
379
4.0625
4
contador = 0 numero = 0 maior = 0 menor = 0 while(contador < 4): numero = int(input("Informe um número: ")) if contador == 0: maior = numero menor = numero if numero < menor: menor = numero if numero > maior: maior = numero contador += 1 else: print("--------------------------") print("O maior número ...
82b94fffc093bf25c4bf8a174c877c6c249ca398
doubledherin/datastructs_algorithms_exercises
/Chapter03_BasicDataStructures/isPalindrome.py
390
3.671875
4
from deque import Deque def isPalindrome(s): d = Deque() for char in s: d.addFront(char) while d.size() > 1: item1 = d.removeFront() item2 = d.removeRear() if item1 != item2: return False return True if __name__ == '__main__': print isPalindrome("r...
e830a75ff3a5648e839e5fe92fada4ed0bd847b9
abalcorin/DevNet_vCC_assignments
/abalcorin_DevNet_vCC_Team0_Camp1_Day2_assign1_Assignment_02.py
638
3.921875
4
""" Programmability Black Belt Apprentice (Level1) https://github.com/Devanampriya/DevNet_vCC_Team0/blob/master/Camp1_Day2_assign2 Participant: ALBREN ALCORIN Assignment Write a program (in Python 3) to guess a randomly generated number between 1 and 10. For Example: Guess the number: 4 Wrong, try again! Guess the n...
a3548cba0549c0e475ab89cdb506c7baee03a25b
brunopontes90/Cursos
/Python/Mundo 1/desafios/desafio04.py
484
4.15625
4
print('===== desafio 04 ====='.upper()) ler = input('Digite algo: ') print('O tipo primitivo é? ', type(ler)) print('É alfabetico? ', ler.isalpha()) print('É alfa numerico? ', ler.isnumeric()) print('Pode ser impresso? ', ler.isprintable()) print('É apenas numeros? ', ler.isnumeric()) print('Esta em minusculo? ...
c91f5c4e9efe10d796cb52e0c2cf95541eacbc63
barbarahf/Python_DAW
/Practicas/Adivina.py
1,373
3.890625
4
# Ejercicio 5 import random __author__ = "Barbara Herrera Flores" continuar = True while continuar == True: # El usuario decide con que rango de valores jugar print("Introduce un rango de dos numeros para jugar, por ejemplo entre 5 y 18 ") num1 = input("Numero 1: ") num2 = input("Numero 2: ") # C...
d8737c0f1c80dfb403b01cf2e5750ea554df6f6b
xiaohuanlin/Algorithms
/Leetcode/257. Binary Tree Paths.py
979
4.03125
4
''' Given a binary tree, return all root-to-leaf paths. Note: A leaf is a node with no children. Example: Input: 1 / \ 2 3 \ 5 Output: ["1->2->5", "1->3"] Explanation: All root-to-leaf paths are: 1->2->5, 1->3 ''' # Definition for a binary tree node. class TreeNode: def __init__(self, x): ...
4d997f791daad95d180516ead2c396ec173d0b12
pgupta371/104
/median.py
695
3.6875
4
import csv with open("data104.csv", newline = "") as f: reader = csv.reader(f) fileData = list(reader) fileData.pop(0) #print(file_data) #sorting data to get the height of people newData = [] for i in range(len(fileData)): num = fileData[i][1] newData.append(float(num)) # get the ...
cf6125e1b39d2412551269caa1408dbf3938762d
jro867/project3
/ArrayQueue.py
637
3.578125
4
#!/usr/bin/python3 import pprint class ArrayQueue: def __init__(self): self.list = [] # # print("NODE:") # print(self.list) # for node in self.list.getNodes(): # print("NODE: ") # print(node) # def point_sorting(self, point): # print('X valu...
ff1985c0ecc2c15c78142e04b6337facf68f19e4
redherring2141/Python_Study
/Python_200/Intermediate/ex_076_1.py
125
3.859375
4
# Ex076 - Extracting a string from specific range of a string txt = 'python' for i in range(len(txt)): print(txt[:i+1])
957ed02ad10d1bce62e7215d2a6283e8b16a6996
siyan/starbucks
/src/com/sywood/starbucks/andi/Python/ucfcontest/plates.py
694
3.515625
4
def update(poles, i): temp = list(poles) for j in range(n): temp[j] -= 2.5 temp[i] = speed return tuple(temp) def possible(poles): if any([i <= 0 for i in poles]): return False if poles in memo: return True else: memo.add(poles) return any(possible(up...
2b5709c6045d2e2814b8d06694c355f34bc08547
guillechuma/bioinformatics
/rosalind/reverse_complement.py
526
4.4375
4
# This program calculates the reverse complement of a DNA sequence import sys complement = { 'A':'T', 'T':'A', 'G':'C', 'C':'G' } def reverse_complement(dna): ''' This function recives a DNA string and returns its reverse complement ''' reverse_dna = dna[::-1] reverse_complement = '' for i in reverse_dna: re...
9b18734c527b3a75ffcfea045e64bd573b931cc8
michaelChen07/studyPython
/cn/wensi/idle/QuickSort.py
2,373
3.640625
4
# coding=utf-8 """快速排序""" # 校验函数,对输入的列表或者元组进行校验 def list_check(pend_list): if not isinstance(pend_list, list) and not isinstance(pend_list, tuple): # 元组列表才能排序 print("输入必须输入列表或者元组") return if isinstance(pend_list, tuple): # 元组转成列表 pend_list = list(pend_list) return pend_list ...
8cf46ea28080cd13860b49f43b925b73227ff866
masterawr/Python-3-Scripts
/convert_xlsx_csv.py
385
3.578125
4
# Converts all xlsx files in a directory to csv import glob,os import pandas as pd inputdirectory = input('Enter the directory: ') for xls_file in glob.glob(os.path.join(inputdirectory,"*.xls*")): data_xls = pd.read_excel(xls_file, 'Sheet1', index_col=None) csv_file = os.path.splitext(xls_file)[0]+".c...
955d3d65ded72ddbc32281bfd1008bc0d5d4d0ff
victoriaBelokobylskaya/PythonBase
/lesson1_6.py
1,050
4
4
# Спортсмен занимается ежедневными пробежками. В первый день его результат составил a километров. # Каждый день спортсмен увеличивал результат на 10 % относительно предыдущего. # Требуется определить номер дня, на который результат спортсмена составит не менее b километров. # Программа должна принимать значения парамет...
3e38b19deb3f74b8cc72756583dccf2e95a5d3ee
Kabur/bc
/tests.py
273
3.90625
4
import numpy as np x1 = np.array([1, 2, 3, 4, 5]) x2 = np.array([5, 4, 3]) print("x1: ") print(x1) # x1_new = x1[:, np.newaxis] x1_new = x1[np.newaxis, :] # now the shape of s1_new is (5, 1) print("x1_new: ") print(x1_new) # print("x1_new + x2: ") # print(x1_new + x2)
4415d16bd657a447b6993ba8cea39c0405bc95f2
AsuwathamanRC/Python-Programs
/Turtle/PongGame/main.py
1,164
3.703125
4
from turtle import Turtle, Screen from paddle import Paddle from ball import Ball from scoreboard import Scoreboard import time screen = Screen() screen.setup(width=800,height=600) screen.bgcolor("black") screen.title("Pong") screen.tracer(0) rightPaddle = Paddle(350,0) leftPaddle = Paddle(-350,0) ball = Ball() scor...
c8afb1f86e5c73d5291cd7bca2cbf34a297da7ff
mahmudz/UriJudge
/URI/URI/2313.py
573
3.546875
4
# -*- coding: utf-8 -*- """ Created on Tue Feb 21 12:16:30 2017 @author: Matheus """ a,b,c = input().split() a,b,c = int(a),int(b),int(c) entrou = False if(a==b and b==c): print ("Valido-Equilatero") entrou = True elif(a==b or b==c or a==c): print ("Valido-Isoceles") entrou = True elif((a+b)>c and (a+...
724b821e5c842a7d13b0d78c011a6456711dec63
HoangTan351/hoangtan_btpython_buoi2
/Bai 2.py
572
3.71875
4
# bai 2 import math print("nhap x: ",end="") x=float(input()) print("nhap n: ",end="") n=int(input()) s1=s2=s3=0.0 print("S1 = 1 + x + x^2 + x^3 + ... + x^n=",end="") for i in range(n+1): s1+= pow(x,i) i+=1 print(s1) print("S2 = 1 - x + x^2 - x^3 +...+(-1)^n*x^n=",end="") for i in range(n+1):...
18609ece35c5896dfeeb82e00fa2908698615e13
99003607/Advanced-python
/11_exception_handle.py
1,046
3.734375
4
# exception handling ''' print("before"); i=10; j=0; #here divsion by zero is not possible so it will give exception k= i/j; print("k value:",k); print("after"); ''' ''' output=. Traceback (most recent call last): File "11_exception_handle.py", line 6, in <module> k= i/j; ZeroDivisionError: divis...
dacc30c673932f5e92a7b2ad14d03bc4f85949f2
demo112/1807
/regex/project/ID_check.py
489
3.546875
4
import re ID_card = input("请输入身份证号") if len(ID_card) == 18: pattern = r"(?P<province>\d{4})(?P<city>\d{2})(?P<date>\d{8})(?P<code>\d{4}|\d{3}X)" province = re.search(pattern, ID_card).group('province') city = re.search(pattern, ID_card).group('city') date = re.search(pattern, ID_card).group('date') ...
c1cc5acfbec4d262bfc002565428cd8a679a2773
aker4m/c_algorithm
/python3/ch02/intary.py
352
3.65625
4
NUMBER = 5 def int_input(string): return int(input(string)) if __name__ == '__main__': list_number = [] for i in range(0, NUMBER): list_number.append(int_input("list_number[{}] : ".format(i))) print("각 요소의 값") for i in range(0, len(list_number)): print("list_number[{}] = {}".format...
f0cffd02d79fc735a791dd338e2e39a8ed90a848
csYuryV/geekbrains_PyBasic
/04 Lesson/PracticalTask/01 Exercise.py
1,010
4.375
4
""" Python Basic Lesson 04, Exercise 01 Реализовать скрипт, в котором должна быть предусмотрена функция расчета заработной платы сотрудника. В расчете необходимо использовать формулу: (выработка в часах*ставка в час) + премия. Для выполнения расчета для конкретных значений необходимо запускать скрипт с параметрами. 2...
f4c314ed3d0efb1a4ce2a977327dc92c7337bcf3
lcqbit11/algorithms
/medium/binary-tree-preorder-traversal.py
1,485
4.03125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- from utils.treeNode import TreeNode def binary_tree_pre_order_traversal2(root): res = [] s = [] if root: s.append(root) while s: root = s.pop() res.append(root.val) if root.right: s.append(root.right) if...
b21db48d5f25c5f558d7db33150553179379628e
yhx0105/leetcode
/05_liangbiao/02_liangbiaozhongdaoshudikgejiedian.py
1,088
3.75
4
""" 输入一个链表,输出该链表中倒数第k个结点。 """ class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: #读出来放到,列表里面,完成操作,空间时间复杂度O(n) def FindKthToTail1(self, head, k): # write code here #判断是否为空 if not head: return None res=[] wh...
343c0f44c05302445634cc99c1147dfa0c3dd13c
ne1son172/GB2-algo-and-data-structures
/HW1/task8.py
498
4.0625
4
# Определить, является ли год, который ввел пользователем, високосным или не високосным while True: year = input('Enter q for quit or enter some year >>> ') if year == 'Q' or year == 'q': break else: year = int(year) temp = year % 4 if temp == 0: print('{} year i...
d829c9de800808d0f52455b4db878156880c74fa
tchimih/link_query
/engine/analyse.py
5,088
3.6875
4
# coding: utf-8 from __future__ import division import re def get_stat_eff(n ,m, t): """ This function will compute the : - Worst; - Best; - Random. Efficiencies according the input variables, as follow: ------------------------------------------------------ (1) n: # Nodes (2) m: #...
b7bfbbc130f2d70c826a76066ad57e5daa5ec562
WardMaes/aoc-2020
/day_01/01.py
968
4.09375
4
def get_tuple(arr, sum): # Returns a tuple. The sum of these 2 values equals sum arr_sorted = sorted(arr) l = 0 r = len(arr) - 1 while l < r: if (arr_sorted[l] + arr_sorted[r] == sum): return [arr_sorted[l], arr_sorted[r]] elif (arr_sorted[l] + arr_sorted[r] < sum): l += 1 else: ...
45b9882b581d7965febbc27263d07f084365a8ef
iidodson/MOA-Python
/python-cheatsheet.py
4,733
3.9375
4
from sys import argv from os.path import exists ############# Print Statements ############# print("hello World") ### Multi-line prints print(""" Alight, so you said you like food ad you just figuted out how to do multi-line prints Nice! """) ############# Operators ### Mdoulo remainder = 10%3 print(remainder) ###...
ea3696c88325d137e823551f72db27469729eb96
Kfirinb/Computational-Biology-Course
/Project 2 - Genetic Algorithms/gridRefactor.py
26,516
3.640625
4
""" Computational Biology: Second Assignment. Developed by CUCUMBER an OrSN Company and Kfir Inbal May 2021. UNAUTHORIZED REPLICATION OF THIS WORK IS STRICTLY PROHIBITED. """ from sys import argv # Basic grid design, courtesy of Auctux: https://www.youtube.com/watch?v=d73z8U0iUYE import pygame import pygame.font imp...