blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
b8be9c27288af8d730136c39e3e0d32605380610
RealConjugate/Code-Golf
/Swap the Parity.py
180
4.03125
4
# Attempt at the shortest possible program to do the following: # Given positive integer n, output n+1 if n is odd and n-1 if n is even. def f(n): return n+(-1)**(n%2+1)
5d426f5a00d348f45b5cbcf44e9104a544a2d640
mikemeko/6.01_Tools
/src/system_simulator/simulation/util.py
706
3.5625
4
""" Utility methods. """ __author__ = 'mikemeko@mit.edu (Mike Mekonnen)' from constants import DEFAULT_ROUND_DIGITS def complex_str(c, ndigits=DEFAULT_ROUND_DIGITS): """ Returns a string representing the complex number |c| with the real and imaginary parts rounded to |ndigits| digits after the decimal poin...
204f87fb68c07a173d99b48f3302af952a1179c2
huipengly/PythonLearn
/a Byte of Python/helloWorld/io_input_homework.py
536
4.28125
4
def reverse(text): return text[::-1] def is_palindrome(text): return text == reverse(text) forbidden = ('.', '?', '!', ':', ';', '-', '_', '(', ')', '[', ']', '...', '\'', '"', '/', ',') something = input('Enter text: ') # something = "Rise to vote, sir." something = something.lower() something ...
6c777f42eae03dc0ef6294ffbdd10e8643e013b0
CatrunaMarius/python
/Day/day18.py
3,035
3.875
4
#Utilizând comprehension listei, vă rugăm să scrieți un program pentru a imprima lista după ce eliminați numerele 0, 4, 5 din [12,24,35,70,88,120,155]. #sugestii #Utilizați comprehension listei pentru a șterge o mulțime de elemente dintr-o listă. Utilizați enumerarea () pentru a obține (index, valoare). l =[12,24,3...
440c791f790c4c6c17d5bed12f01b3112a84d470
MrPicklePinosaur/learn-ML
/classification-models/OptimizeTrees.py
1,142
3.65625
4
#Find out what the optimal tree amount is for random forest import matplotlib as mpl import matplotlib.pyplot as plt from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score import numpy as np import sys from RForest import * data = [] ...
a72b6a1f5a9c75d4669096f9c006636596375e04
sondongmin0419/study
/python/b_1110.py
241
3.65625
4
num = input() cnt = 0 num2 = int(num) num3 = num2 while(True): a = num2 // 10 b = num2 % 10 s_num = a + b n_num = b*10 + s_num%10 cnt += 1 if num3 == n_num: break else: num2 = n_num print(cnt)
54bcae0d1d83c03b9def6ff166f902114be315b0
rakmeister/pythonlab
/6b.py
344
3.90625
4
word1 = input("Enter the text") print(len(word1)) x = len(word1) i=0 a=0 d=0 s=0 r=0 for i in range(0,x): if word1[i].isalpha(): a+=1 elif word1[i].isdigit(): d+=1 elif word1[i].isspace(): s+=1 else: r+=1 print("No of alphabets ",a) print("No of digits",d) print("No of...
24f8bf5881dfaff50c3be06d7f5829b61b99dc69
twtrubiks/leetcode-python
/test_Reverse_Bits_190.py
1,743
3.78125
4
import unittest from Reverse_Bits_190 import Solution, SolutionBitOperations """ Reverse bits of a given 32 bits unsigned integer. For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000). Follow up: If...
aa549adc9209c974b26f4ea588927b0883641c62
Aasthaj01/DSA-questions
/Recursion/Paths_in_nxm_matrix.py
267
3.90625
4
def path_finder(r, c): if r == 1 or c ==1: return 1 return(path_finder(r-1, c) + path_finder(r, c-1)) n = int(input("Enter the number of rows: ")) m = int(input("Enter the number of columns: ")) answer = path_finder(n, m) print(answer)
af9c842901b2ef7f169a89c495475a31266fe1c1
zwwpaul/CISC481-681_Programming2
/Maze.py
5,371
3.828125
4
import Square as sq import numpy as np import Agent as ag class Maze: def __init__(self): self.agent = ag.Agent() self.index = 9 self.width = 4 self.height = 3 # To create a map with 4*3 size self.matrix = np.array([[sq.Square()] * self.width] * self.height) self.squares = { 1: self.matrix[2][0], ...
0ed1edf76ab7e81f5a2e8066e204e6b03cf975cb
InfoTech-Academy/Python_Week_4
/Homework Ersin Öztürk/mis_calculator.py
1,994
4.03125
4
import addition import subtraction import multiplication import division import sys from math import ceil while True: try: operand = input("Please make your selection!\n" "insert 'a' for addition: \n" "insert 's' for subtraction: \n" ...
b4f1ba78e426b1f154234ddcb97abf4ed1d3c39a
jagruthnath/MSIT_CT
/CT/L1P6.py
160
3.625
4
n=int(input("Enter n : ")) i=2 j=1 f=[] f.append(1) print("Factors of ",n," are") while i<=n/2: if n%i==0: f.append(i) i+=1 f.append(n) print (f)
f19f1cce95fc1af31a3b622b9457adeaa7ac68a3
pscx142857/python
/作业/Python基础第三天/12转变得到新列表.py
531
3.765625
4
#假设有一个列表 names = [[“张飞”,”刘备”,”关羽”],[“曹操”,”典韦”,”司马懿”]],如何将names这个列表通过代码 # 转变得到如下列表 li=[“张飞”,”刘备”,”关羽”,“曹操”,”典韦”,”司马懿”] names = [["张飞","刘备","关羽"],["曹操","典韦","司马懿"]] # 定义一个空列表 li = list() # 遍历得到两个列表 for i in names: # 遍历获取里面的元素 for j in i: # 追加到空列表 li.append(j) print(li)
9a7d696c6ba894d755c097adf0ceb138c348bb32
AstridWH/H20_Project-0
/calculator.py
449
3.734375
4
def add(x, y): return x + y def Factorial(n): s = 1 for i in range(1, n+1, 1): s = s*i return s def Sin(x, N): s = 0 for n in range(0, N): s += (((-1)**n)*(x**(2*n + 1)))/(Factorial(2*n+1)) return s def divide(x, y): return x/y def Cos(x, N): s = 0 for n in ra...
fcfc073108f4efa70724aa7dcccbd86082b69be8
AffDk/dd-genomics
/parser/md_cleanup.py
1,214
3.546875
4
#! /usr/bin/env python import fileinput import sys def getDigits(text): c = '' for i in text: if i.isdigit(): c += i if len(c) > 0: return int(c) return -1 if __name__ == "__main__": for line in fileinput.input(): comps = line.strip().split('\t') if len(comps) == 0: continue ...
ea96c3f6705650bd6357658a054799490f8019bb
rafaelperazzo/programacao-web
/moodledata/vpl_data/405/usersdata/288/75674/submittedfiles/exe11.py
121
3.5625
4
n=int(input("Digite um numero inteiro: ")) if n>=10000000 and n<99999999: print n else: print ("Nao sei")
f4427085f11c90fe321a5c6b2261deff967ea442
damirbar/learning_pandas
/lesson3.py
3,978
3.78125
4
import pandas as pd import matplotlib.pyplot as plt from helpers import hdr ''' Description of the data: Year: Year of data State: State/Territory of data Table_Data: The scraped, unclean data from the US Department of Labor. Footnote: The footnote associated with Table_Data, provided by the US Department of Labor...
9951c449156026e339b99c889d659cfee937f0ac
cjxnew/Programming-Training
/剑指offer(Sword for offer)/从上往下打印二叉树.py
714
3.953125
4
# -*- coding:utf-8 -*- # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # 用python的列表实现了队列。思路同cpp的。 class Solution: # 返回从上到下每个节点值列表,例:[1,2,3] def PrintFromTopToBottom(self, root): # write code here if root is None: ...
a2c11474f42964f96294537f4076dcbba4f7cba2
EastTown2000/ITGK
/Øvinger/Øving 5/Euklid.py
162
3.75
4
def gcd(a, b): while b != 0: gb = b b = a % b a = gb return a def reduce_fraction(a, b): d = gcd(a, b) return (a/d, b/d)
23614e685200dbd2221ec301a066fe9d8eb82a72
mbaseman1918/testrep
/madlibs.py
679
3.953125
4
answer = "yes" import random while answer.lower() == "yes" or answer == "y": word1 = input("Give me a name: ") word2a = input("Give me an adjective: ") word2b = input("Give me an adjective: ") word2c = input("Give me an adjective: ") word3 = input("Give me a noun: ") word_list = [word2a, word2b,...
d503251d64687fa9ee397deb13e5452eb198fbc6
yeshsurya/MyPythonScripts
/youtubeGetTransScript/get_transcript.py
819
3.609375
4
import requests from bs4 import BeautifulSoup def get_youtube_transcript(video_url): # Fetch the YouTube video page response = requests.get(video_url) if response.status_code == 200: html_content = response.text soup = BeautifulSoup(html_content, 'html.parser') # Find the transcrip...
193fa4d9aa7746568286cfb881ececc9a6bf1dc5
pex24/Enigma-Machine
/rotor.py
4,146
4
4
""" M3 rotor Rotor # ABCDEFGHIJKLMNOPQRSTUVWXYZ Date I EKMFLGDQVZNTOWYHXUSPAIBRCJ 1930 II AJDKSIRUXBLHWTMCQGZNPYFVOE 1930 III BDFHJLCPRTXVZNYEIWGAKMUSQO 1930 IV ESOVPZJAYQUIRHXLNFTGKDCMWB 1938 V VZBRGITYUPSDNHLXAWMJQOFECK 1938 VI JPGVOUMFYQBENHZRDKASXLICTW 1939 VII NZJHGRCXMYSWBOU...
a4c74dd7b039487293500424d2dc33c4e053d6ec
argetamorina/CodingDojo-Bootcamp
/Python-Django/Python/EvenOdds/sample.py
327
3.859375
4
# a = [1, 2, 5, 10, 255, 3] # print sum(a)/len(a) number = 1 def function(): for number in range(1,2000): if number % 2 == 0: print "Number is %(first)d. This is an even number." % {"first": number} else: print "Number is %(second)d. This is an odd number." % {"second":number} number + 1 funct...
ad8fa38d15a91e342f16f248c0563573f0d60b39
carlosfajardor/Python-cardio
/Reto 1/triangulo.py
1,453
4.03125
4
import math def run(): lado_1 = int(input("Ingresa la medida del primer lado en cm: ")) lado_2 = int(input("Ingresa la medida del segundo lado en cm: ")) lado_3 = int(input("Ingresa la medida del tercer lado en cm: ")) if lado_1 == lado_2 == lado_3: print("Tienes un triángulo equilat...
a27f17769950d52091f0aa55237ddd43076663b0
ljt270864457/leetcode
/12.设计模式/1.单例模式.py
862
3.578125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2021/4/7 4:27 下午 # @Author : liujiatian # @File : 1.单例模式.py ''' 单例模式将类的实例化限制为一个对象。 它是一种创建模式,只涉及创建方法和指定对象的一个类。 它提供了创建实例的全局访问点。 ''' class Singleton(object): def __new__(cls, name, age): if not hasattr(Singleton, '_instance'): # 调用父类...
a6a39dd4b997b2f2d9d111cda13a7a0f51a0053d
TIU11/pi-workshop
/turtles_and_drones/t_logic.py
271
4.09375
4
import turtle t = turtle.Turtle() t.shape("turtle") problem = int(input("What is 3 X 4?")) if problem == 3*4: t.write(str(problem) + 'is correct!') t.penup() t.backwards(30) else: t.write('You said ' + str(problem) + '. I got ' + str(3*4)) t.penup() t.backwards(30)
9710ba93aa21889bd84ad6395f14c5a6c9e82500
NikitaFir/Leetcode
/Distribute Candies to People.py
581
3.53125
4
class Solution(object): def distributeCandies(self, candies, num_people): people = [0] * num_people i = 0 c = 1 while candies != 0: people[i] += c candies -= c if candies - c > 0: c += 1 else: ...
4ba58c8dd99f62961e43f8ef5e611839e81a8b74
Jean-pierre14/Python_Data
/list.py
769
4.21875
4
list = ["item 1", "item 2", "item 3", "item 4", "item 5", "item 6"] # list[6] = "item 7" print(list[-1]) print(list[1:5]) print(len(list)) for x in list: print(x) if 'item 1' in list: print('Yes it is in') else: print('No does not') list.append("Added") list.insert(1, "Pikipiki") print(list) # To remov...
3a51e4f82dec2bcd40ec790c2125edcc35916957
bmvmarc/dominoes
/dominoes.py
6,343
3.5625
4
from random import shuffle class Domino: domino_set = [] @classmethod def generate_domino_set(cls): Domino.domino_set = [[i, j] for i in range(7) for j in range(i, 7)] def __init__(self): self.stock = [] self.computer = [] self.player = [] self.snake = [] ...
588fa92a046696525fa86c36cb05cf7236df1d87
frapa/dino
/lib/vector.py
4,042
4.03125
4
from math import sqrt class Vector(object): def __init__(self, *args, **kwargs): # check if a list or a tuple was passed if isinstance(args[0], tuple) or isinstance(args[0], list): self.coordinates = args[0] else: self.coordinates = args # Tribute to Pytagor...
bd1a036920cfcd3c3f311133de0e51c72cefb96c
stud-labs/pt-2271-2018
/euler_2261.py
1,218
3.5625
4
# -*- coding: utf-8 -*- # Снизу вверх. # Сверху вниз. # Diffur1 import matplotlib.pyplot as plt import numpy as np # y'=f(x,y). def expeuler(f, F0, h, eps, n, x0=0): x=x0 F=F0 # F(x0)=F(x)=F0=F Fp=None l=[] c=0 while True: if c % n == 0: l.append(...
b31fa0be67674125cbd6e889d1580cef4f8ca92c
chengyh23/drunksearch
/scripts/python/final_model/tools/matrixOperations.py
1,144
3.53125
4
#!/usr/bin/env python3 """ Collection of tools for "less standard" math operations @author: Mario Coppola, 2020 """ import numpy as np def round_to_multiple(a, mult, floor=True): '''Rounds a number to its multiple''' if floor: a = np.floor(a / mult) else: a = np.round(a / mult) return a * mult def normalize_r...
a4ce45add728ebcab7d09b6c85fc63c020e05f08
24apanda/python_useful
/function.py
384
3.84375
4
# -*- coding: utf-8 -*- """ Created on Thu Dec 15 21:48:45 2016 @author: apanda88 """ ###########prime Number########## max = 10 count=0 for i in range(2,max+1): for j in range(2,i+1): if (i%j==0 and i !=j): count=1 break if(count==1): print( i,"Opposite...
9698b07142d0770f1008e96135e36d59d1f638f6
MurphyMarkW/random
/python/examples/amazon.py
185
3.78125
4
#!/usr/bin/env python def Paired(a,x): values = set(a) for i in values: if x-i in values: return i,x-i return None if __name__ == '__main__': print Paired([5,2,3,4,5],10)
c98046655c20fcdeb574744fa17fed631214ed03
soniya-mi/python
/dict_programs/degree_of_array.py
1,309
4.03125
4
nums = [1,2,2,3,1,4,2] dict = {} l = {} r = {} count = 1 for index in range(0,len(nums)): if nums[index] in dict: count = dict[nums[index]] + 1 dict[nums[index]] = count r[nums[index]] = index else: dict[nums[index]] = 1 l[nums[index]] = index r[nums[index]] = in...
f52a303c45e60cbc6057e60ce1faa8784f851d02
balpa/Python-Guess-Number
/guessnumber.py
629
3.96875
4
import random randNum = random.randint(0,100) def guess(): num = int(input("Guess: ")) if num == randNum: print("*-*-*-*-*-*-*-*-*-*-*-*") print("That was right!") print(f"No:{num}") print("*-*-*-*-*-*-*-*-*-*-*-*") elif num < randNum: print("Wrong, nu...
1d6b963d9476ea37c31bf9d21cdbe2c65850043a
anthony-silva/Data-Structures-And-Algorithms
/quicksort3.py
1,860
4.125
4
''' python3 Author: Anthony Silva Objective: To force the given implementation of the quick sort algorithm to efficiently process sequences with few unique elements, the goal is replace a 2-way partition with a 3-way partition. That is, the new partition procedure should partition the array into three parts: ...
0d8e7b3fe2109652c0c77eea7124e48d0e8a4287
hosalli2704/pythonexamples
/set_ex.py
549
4.09375
4
# set -> class # collections of unordered elements # NO INDEX # NO KEY # MUTABLE # It can hold only immutable objects (Number, String and Tuples only) # Its always store the unique values s1 = {10, 10, 'python', 'py'} print('Set', s1) s1.add(20) s1.add(20) print('Updated Set',s1) r1 = s1.remove(20) print('Updated New...
8e7e36b4fba4a952b64f9e2e5300252d5adff745
Rahulsudheerkumar/file-based-key-value-data-store
/datastore.py
2,514
3.96875
4
import threading from threading import* import time db={} #'db' is the Database in which user stores the data # we use create methode to create new key in database # user have to use "create(key_name,value,ttl_value)" as syntax to create new key. as ttl is optional we can also continue by passing two argument...
9f7946769080e9bb152801dbf72b21b87aae1408
jhodgson/Kraken
/core/maths/vec.py
27,771
3.703125
4
"""Kraken - maths.vec module. Classes: Vec2 -- Vector 2 object. Vec3 -- Vector 3 object. Vec4 -- Vector 4 object. """ import math from math_object import MathObject class Vec2(MathObject): """Vector 2 object.""" def __init__(self, x=0.0, y=0.0): """Initializes x, y values for Vec2 object.""" ...
bf912d6c70d55a5559d2ee0ba7eec2a1d50fa028
dumb-anchovy/Byckov_Georgiy_Moi_krivye_laby
/Turtle_2/Ex_5.py
1,694
3.546875
4
from random import randint import turtle turtle.tracer(10, 1) turtle.speed(0) n = 50 # колво черепах t = 1000000 xb = 300 # границы yb = 300 vmax = 50 # во сколько уменьшается скорости r = 10 # расстояние , когда отталкиваются sp = list() turtle.penup() turtle.goto(xb, yb) turtle.pendown() tu...
b4d53873c054a92c1cfe9f7eda6619f6e0412b21
louisuss/Algorithms-Code-Upload
/Python/DongbinBook/binary_search/stick_point.py
417
3.625
4
n = int(input()) arr = list(map(int, input().split())) def binary_search(arr, start, end): if start > end: return None mid = (start+end) // 2 if mid == arr[mid]: return mid elif mid < arr[mid]: return binary_search(arr, start, mid-1) else: return binary_search(arr, ...
3d96c971cb169e8affb175c528d9bbc1cfd0630c
rabiatuylek/Python
/functions.py
551
4.03125
4
# create function # FUNCTIONS #def Metot(): # definition = metot u tanımlamak icin. # print("metot denemesi Vol1") #Metot() # 1 ile 100 arasındaki sayıları ekrana yazdıran metot yazınız. #def metot(): # for a in range(1,100): # print(a,"yazdırıldı") #metot() # 1000 ile 1 arasındaki sayıları ...
a120c0185a33330b30fd85c1c776fe23a5eafc9c
mi6eto/SoftUni
/Programming Fundamentals/data_types_and_ariables_exercise/chars_to_string.py
111
3.828125
4
char_1 = str(input()) char_2 = str(input()) char_3 = str(input()) word = char_1 + char_2 + char_3 print(word)
2c97e056e7be0ba7333080627c7440f02ae4b58b
strikingraghu/Python_Exercises
/Ex - 11 - Functions.py
3,772
4.21875
4
""" In Python, function is a group of related statements that perform a specific task. Functions help break our program into smaller and modular chunks. As our program grows larger and larger, functions make it more organized and manageable. Furthermore, it avoids repetition and makes code reusable....
86f550345bc949769aa30311ece2053dff7510b7
JuanDavidEspitia/python-course-master
/code/estructuras_secuencia/Conjuntos.py
1,651
4.125
4
# Conjuntos # Colecciones desordenadas # Comprobacion de pertenencia a un conjunto # No permite registros duplicados # Creando un conjunto en python A = {1,2,3} print(A) # Creamos un conjunto conjunto = {1,2,3,4,5,6} # Agregamos un nuevo valor al conjunto conjunto.add(7) print(conjunto) # al agregar un valor numerico ...
72049b2c208fd6d03b69719b53428b295b5bba3e
CafeVisthuset/VisthusetAPI
/database/helperfunctions.py
450
4.03125
4
''' Created on 1 jan. 2017 @author: Adrian ''' from datetime import datetime, date # For summing up e.g., the price in a booking def listSum(NumberList): ''' Adds numbers in a list. ''' total = 0 for number in NumberList: total += number return total def named_month(month_nu...
6f2f91113a3715d94b2b2b4657d069b2d0c11df7
Medic5700/NExTor
/Bootstrap.py
4,021
3.5625
4
'''a bootstrap server, returns a short list of nodes that are alive''' import socket import time import random def BootstrapServer(): """ """ nodes = {} host = "127.0.0.1" #loopback adress port = 5555 publicKey = hex(random.randint(0, 256**64 - 1))[2:] socket1 = socket.socket() so...
17853d9eaad3efaa2bf091960ccf8cc66027ce47
pnouris/Distributed_Library-Map_Reduce-with-Python
/part1/person.py
2,128
3.59375
4
from __future__ import print_function import sys import csv import uuid #references #uuid -> http://www.geeksforgeeks.org/generating-random-ids-using-uuid-python/ # class Person(object): def __init__(self, name): self.name = name def visit(self, warehouse): print("This is {0}.".format(self.na...
0a4dbddff03eba4ff89f1e29836e88a40c55bbd8
jabedude/Python-zerg-miner
/drone/location.py
787
3.828125
4
#!/usr/bin/env python3 '''This module implements the Location class''' class Location: ''' The Location class is used by Drone units to store their current and adjacent locations ''' def __init__(self, x=0, y=0): self.x = x self.y = y def __str__(self): return "({}, {...
2fcdf801c7c73ca2678a7bfe6bc29c2049415822
551100kk/PPHW
/Ch9/9.10/seq.py
343
3.859375
4
def is_prime(val): for i in range(2, val): if i * i > val: break if val % i == 0: return False return True if __name__ == '__main__': base = 2 for i in range(1, 60): base *= 2 left = base - 1 if is_prime(left): pr...
c9c65d5f3aa915dae13ab0a81c0b177f1de13322
tnakaicode/jburkardt-python
/combo/part_sf_check.py
3,198
3.71875
4
#! /usr/bin/env python # def part_sf_check ( n, npart, a ): #*****************************************************************************80 # ## PART_SF_CHECK checks a standard form partition of an integer. # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 31 December 2...
c018ec84ec367137452b961575b6cb904df5cd67
nmomaya/Python_Assignment
/Assignment13_String.py
660
3.890625
4
""" Write a program to accept string from user print how many vovels and consonnts are present in that string. hint: count no. """ def vowels(str1): count=0 for i in str1: if(i=='a' or i=='e' or i=='i' or i=='o' or i=='u' or i=='A' or i=='E' or i=='I' or i=='O' or i=='U'): count=count+1 retur...
6db2e0c3294fec3770f3876e74466b7199f393cf
GuanYangCLU/AlgoTestForPython
/LintCode/ladder/chapter_2/0464_Sort_Integers_II.py
881
3.734375
4
class Solution: """ @param A: an integer array @return: nothing """ def sortIntegers2(self, A): # write your code here if not A: return [] left, right = 0, len(A) - 1 self.quickSort(0, len(A) - 1, A) def quickSort(self, left, right, n...
705b4adf4499ce93f90d37996a86080c30198562
JavierCabezas/hackerrank
/10-days-of-statistics/day04-s10-binomial-distribution-1.py
800
3.890625
4
from math import factorial p_girl = 1/(1.09+1) p_boy = 1-p_girl n_children = 6 def binomial(x, n, p): ''' This function calculates a binomial, that being, with events a and b p(a) + p(b) = 1 Ex: Having exactly 2 4's with 3 4 sided dices. :param x: Number of successful events ( 2 ) :param n: Number...
5d368f1b6c0805677ca43bb1a2b9b855359e9ed8
rongzhao/Code-for-fun
/simpleCode/calculate_median.py
461
4.03125
4
"""This program is used to calculate the median value in a list""" import sys def main(): print "type in a list:" ls = [] for line in sys.stdin: ls.append(float(line)) #type <CTRL-d> to send EOF print ls print ls.sort() if len(ls)%2 == 1: median = ls[(len(ls) - 1)/2] ...
0eba43bea1ddf3d6e30b34dd2c1148506e0b5de0
xhan91/advent-of-code
/2017/day1/second.py
355
3.59375
4
#!/usr/bin/python import sys input = sys.argv[1] arr1 = list(input) arr2 = list(input) input_arr = arr1 + arr2 sum_num = 0 length = len(arr1) steps = length / 2 for index, num in enumerate(input_arr): num = int(num) if index == length: break else: sum_num += num if num == int(input_arr[in...
6510214ec6cacedd114e1f15670a567745704cf8
Muhammadsaquib/bikeprojoops
/test_projbike.py
4,101
3.734375
4
#@author: Saqib Shaikh # Bike Rental System import random total_av_bike = 20 class B_rental_s: cs_info = {} cs_record ={} cs_cod = {} global total_av_bike total_av_bike = 20 def __init__(self): self.a = 0 self.b = 0 def show_d(se...
8f49db1d3defd81ffba41cf2132ac7a02d5b4644
DanielSOhara27/DataBootcamp-PythonVanilla-Module
/PythonClass2/HousePies.py
742
4
4
pieList = ["Pecan", "Apple Crisp", "Bean", "Banoffee", "Black Bun", "Blueberry", "Buko", "Burek", "Tamale", "Steak"] pieOrder = list() flag = "y" while flag != "n": print(f"Welcome to the House of Pies! Here are oure Pies:\n\n{' _ '*30}\n(1) Pecan, (2) Apple Crisp, (3) Bean, (4) Banoffee, (5) Black Bun, (6) B...
5edafd47ef538cbfbde9143db9cb9257bc770fa5
bera5186/Travis-CI-Test-
/password_test.py
616
3.671875
4
import unittest from src.utility import generate_password class PasswordTest(unittest.TestCase): def test_for_checking_length_of_returned_password_list(self): length_list = [4, 6, 8] list_of_passwords = generate_password(length_list) self.assertEqual(len(list_of_passwords), 3) def tes...
9c836958a67c6b251d4ba31a00cdb46ad9b41527
vinay5656/Python
/CommanDictionary/gradingProgram.py
754
3.75
4
student_scores = { "Harry": 81, "Ron": 78, "Hermione": 99, "Draco": 74, "Neville": 62, } student_grades = {} # Scores 91 - 100: Grade = "Outstanding" # Scores 81 - 90: Grade = "Exceeds Expectations" # Scores 71 - 80: Grade = "Acceptable" # Scores 70 or lower: Grade = "Fail" for name in stud...
888e5de7cf3ead2c9bd39d0303b6c2510f847292
lucasviinic/URI
/Ad-Hoc/numbers_frequence.py
492
3.6875
4
n = int(input()) frequencia = {} def conta_frequencia(valor): if valor in frequencia: frequencia[valor] += 1 else: frequencia[valor] = 1 def ordena_invertido(dicionario): dic_key = [] for i in dicionario: dic_key.append(i) dic_key = sorted(dic_key) for j in dic_ke...
3b536be66027d6a1ba13445f425cc0c2775ecacf
Richardwillianx/Exercicios-em-Python
/Desafio40.py
676
3.953125
4
""" Crie um programa que leia duas notas de um aluno e calcule sua média, monstrando no final, de acordo com a média atingida. - Média abaixo de 5.0: 'Reprovado' - Média entre 5.0 e 6.9: 'Recuperação' - Média 7.0 ou superior: 'Aprovado'. """ nota1 = float(input('Informe a sua primeira nota: ')) nota2 = float(input('I...
d3834f38fa147fcbb14c18f6a54aeb133b01ab50
vishnusak/DojoAssignments
/20-JUNE-2016_Assignment/python/factorial.py
181
3.578125
4
def rFact(num): num = int(num) if num > 1: return num * rFact(num - 1) else: return 1 myNum = 6.5 print("rFact({}) is {}").format(myNum, rFact(myNum))
7267ed742a7deae50fcebe2f25901e88de4ccb95
vagmithra123/python
/Tuples.py
353
4.15625
4
# Tuples r immutable # we use parentheses #create tuple t = (1, 2,3) print(f'Type of t is {type(t)}') #check length print(f'Length of t is {len(t)}') #Accessing tuple with index print(f'Item at index 2 of t is {t[2]}') #using count method print(f"Number of 1's in t are {t.count(1)}") #using index method print(f'Ind...
abf5d86fde3d484858611e782c4f30900569007b
akhandsingh17/assignments
/boilerplates/Microsoft/find_substring.py
438
4.21875
4
def find_substring(substr, str_exp): """ Find the number of substrings in a given string expression. Time complexity (M*N) :param str_exp: :return: """ k = len(substr) # length of the substring cnt = 0 for i in range(len(str_exp)): if str_exp[i:i+k] == substr: cnt +=...
ce08cbed29c01313d5b7b024dfe840110d0d05ac
densaiko/coding-challenge
/Top K Frequent Elements.py
881
3.703125
4
# Top K Frequent Element is a medium coding challenge in Leetcode. This challenge can be solved using the Heap, once you get the # minimum number with the most frequency based on the number of K. # For instance, if the number of K is 2 and the numbers in list are [1,1,1,2,2,3], which means that you have to give the ...
b4f09ee4212f4d0b58b13319e241a091040464df
821363701/pepperpicky
/stock/daily_monitor_simple.py
1,759
3.5
4
from __future__ import print_function __author__ = 'yu' import os import time clear = lambda: os.system('clear') from util import get_stock_price, rate from datetime import datetime class Stock: def __init__(self, stock, name): self.stock = stock self.name = name self.five_price = [] ...
21c55a3e89e00e5afffdacd1c408a8f025f441b0
iloverugs/pcc_2e_student
/chapter_05/5-1_Conditional_Tests.py
983
4.1875
4
dogs = ['Brittany', 'Poodle', 'German Shepard', 'Huskie'] my_dog = 'Brittany' print("Is dog == 'Brittany'? I predict True.") print(my_dog == 'Brittany') print("\nIs dog == 'brittany'? I predict True.") print(my_dog.lower() == 'brittany') print("\nIf dogs == 'Brittany', print 'Rugger!'") for dog in dogs: if dog ==...
603be5a1be72997c7b5329b54b12756f9d0d699a
pkc-3/Python_Q100
/Q1~Q50/Q45.py
476
3.921875
4
# python의 모듈 중 하나인 time 모듈은 1970년 1월 1일 0시 0분 0초 이후로부터 지금까지 흐른 시간을 초단위로 반환합니다 # 이를 이용하여 현재 연도(2021)를 출력해보세요 import time secs = time.time() # 초로 계산 tm = time.gmtime(secs) print(tm.tm_year) print("year:", tm.tm_year) print("month:", tm.tm_mon) print("day:", tm.tm_mday) print("hour:", tm.tm_hour) print("minute:", tm....
96386d5ffde0501af4e8cacff8fdcc6874a44e95
navyasree-583/NAVYA
/anagram.py
686
4.46875
4
# str1=input("enter the first string : ") # str2=input("enter the second string : ") # if(sorted(str1)==sorted(str2)): # print(f"{str1} and {str2} are anagrams") # else: # print(f"{str1} and {str2} are not anagrams") # Python3 program for the above approach from collections import Counter # funct...
5117af620e663d26d31f62fe742718e6ba486706
JiaoZexin/PyDemo
/kaike/three/1/Demo2.py
1,488
3.78125
4
from pandas import Series,DataFrame import pandas as pd # 使用字典创建 dic={ '姓名': ['小罗伯特·唐尼', '克里斯·埃文斯', '斯嘉丽·约翰逊', '克里斯·海姆斯沃斯'], '饰演': ['钢铁侠', '美国队长', '黑寡妇', '雷神'], '武器': ['钢铁战衣', '盾牌', '寡妇蜇', '雷神之锤'], '语录': ['和平,我热爱和平','最好的选择就是重新开始 ','嘿,大兄弟,太阳下山了','要用知识来打败无知']} df=DataFrame(dic) print(df) from pandas impo...
63912072e354602933a16bbfdba1cb3d937d9aba
masakiaota/kyoupuro
/practice/D_ABC/abc016_d.py
2,982
4.03125
4
# https://atcoder.jp/contests/abc016/tasks/abc016_4 # 交差している線分の数//2 -1が答え from math import sqrt class Vector: def __init__(self, ls): ''' ls ... list ''' self.vec = ls def __len__(self): return len(self.vec) def __getitem__(self, idx): return self.vec[idx]...
2c8bc0cf16d8b620b47c73c47a5a6de9e2628962
ericdegan/Curso-em-Video
/ex051.py
361
3.875
4
print('-=-'*5,'Vamos Fazer uma PA','-=-'*5) a = int(input('Escrava o primeiro termo: ')) b = int(input('Escreva agora a RAZAO: ')) d = a + (10 - 1) * b #essa formula é usada para descobrir o decimo termo da PA se eu quisesse o vigezimo termo seria: # a + (20-1) * b for c in range(a,d+ 1,b): print('{}'.for...
e5983000f28c0498a0675576a318683ebea4c4f6
kratium/Project
/new.py
119
3.828125
4
a = list() while True: number = int(input()) a.append(number) a = [number * 2 for number in a] print(a)
11c82a9adc186590ce0818d140c6a6d2069358cc
skoli0/project-9424
/sorting/selection_sort.py
348
3.578125
4
# Time: # Best: O(n^2) # Average: O(n^2) # Worst-O(n^2) # # Space: O(1) def selection_sort(a): n = len(a) for i in range(n): min = i for j in range(i+1, n): if a[j] < a[min]: min = j a[i], a[min] = a[min], a[i] a = [55, 22, 33, 66, 11, 77, 0]...
1fbe91e6b32c1dcbf8d662fafde1de7c5cb11cd4
saradhix/newsreco
/pos.py
471
3.5625
4
import nltk def get_nouns_and_verbs(sentence): pos_result = nltk.pos_tag(nltk.word_tokenize(sentence)) result = [] print pos_result for t in pos_result: if str(t[1]).startswith('NN'): result.append(t[0]) if str(t[1]).startswith('VB'): result.append(t[0]) return result sentence = "Narend...
1789806360b368e79c54e97b9462b8677342d30b
radadiyamohit81/Code-for-FAANG
/DFS/DFS-3/valid Sudoku .py
1,798
3.859375
4
class Solution: # row check + col check + block check => 3 PASS SOLUTION def isValidSudoku(self, board): return self.row_check(board) and self.col_check(board) and self.block_check(board) def row_check(self, board): # row check for every row for row in range(9): flag = [...
b99057dd65a91a3efef32fe182bd44bfac175cb2
DavidWallacedot/pythonScripts
/Python/debug.py
227
3.890625
4
print('Enter te first nubmer to add:') first = input() print('Enter the second number to add') second = input() print('enter the third number to add') third = input() print('the sum of the three numbers is'+first+second+third)
42b0a1b30d62bee908da9271837a70952a3a867c
diachkina/h3_homework
/home_work/calculator.py
4,153
4.1875
4
from tkinter import * root = Tk() root.title("Basic calculator") e = Entry(root, width=30, borderwidth=5) e.grid(row=0, column=0, columnspan=5, padx=5, pady=10) def button_click(number): current = e.get() e.delete(0, END) e.insert(0, f'{str(current)}{str(number)}') def button_clear(): e.delete(0, ...
c4ae7b834a9a26aef816af4a3b888cb37a1cebea
AgustinLema/algorithms
/src/sorting_algorithms.py
7,549
4.1875
4
from searching_algorithms import find_pos_in_list from data_structures.max_heap import MaxHeap from common_algorithms import partition def bubble_sort(numbers): numbers_len = len(numbers) for starting_pos in range(numbers_len - 1): for left_compared_pos in range(numbers_len - 1 - starting_pos): ...
bfbcdc61a0c1bcaeec171257b0cc425eb9579bb5
eobrie16/courses
/coursera_algorithmic toolbox/greedy/covering_segments.py
1,974
3.875
4
# Uses python3 # Given a set of 𝑛 segments {[𝑎0,𝑏0],[𝑎1,𝑏1],...,[𝑎𝑛−1,𝑏𝑛−1]} # with integer coordinates on a line, # nd the minimum number 𝑚 of points # such that each segment contains at least one point. # Output the minimum number 𝑚 of points on the rst line and # the integer coordinates of 𝑚 points ...
90adada8d0d3fed14f98e2a234cf0bfd7daef51b
naveensambandan11/PythonTutorials
/tutorial 71_Selection Sort.py
476
3.953125
4
# Selection Sort # sort by fiding minimum value in the lsit and placing it to integer 0 def sort(nums): for i in range(len(nums)-1): minpos = i for j in range(i, len(nums)): if nums[j] < nums[minpos]: minpos = j temp = nums[i] nums[i] = nu...
2045a7ccb31bdf3ab656fbabe3e1d2b5da57f545
ananyajana/practice_problems
/binary_tree_bst_ckeck.py
3,121
3.8125
4
INT_MIN = -4294967296 INT_MAX = 4294967296 class Node: # fn to initialize the node object def __init__(self, data): self.data = data self.left = None self.right = None #linked list contains a node object class binary_tree: def __init__(self): self.root = None def pr...
05cf3a235d54e98e2dbf3fbb32f26ef3771c8b65
ionut23carp/Training
/PythonAdvance/python-mar2020/examples/comprehensions.py
821
3.9375
4
multiples_of_3 = [] for nr in range(10): if nr % 2 == 0: multiples_of_3.append(nr * 3) print(multiples_of_3) multiples_of_3_comprehension = [nr * 3 for nr in range(10) if nr % 2 == 0] print(multiples_of_3_comprehension) words = ['bye', 'hello', 'hi', 'world'] word_lengths = [(word, len(word)) for word in...
2b5e77b5c1248bc6e49019e90ffa7d77153fb856
jideedu/Parsing_Alexa_Skllls
/processing the Json file.py
456
3.5625
4
import json from pprint import pprint ############load the file print('NOW WE LOAD AND PRINT THE FILE') alll = [] with open('file.json', "r") as f: for line in f: jsonobj = json.loads(line) print(jsonobj['name']) #loading all the file into an array alll.append...
bcd9787cd9a8a74c7dbf582c40fd50ef8c2384c9
lhansford/project-euler
/python/problem_32.py
696
3.625
4
def get_pandigital_products(): products = [] for x in xrange(1,100000000): print x y = 1 while is_correct_length(x,y): if is_pandigital(x,y) and x*y not in products: products.append(x*y) y+=1 return sum(products) def is_correct_length(x,y): if (len(str(x)) + len(str(y)) + len(str(x*y))) < 10: ret...
c8dc7e9a65ce69d2681bd3ff4f5403bab9372aba
deepanshi1208/Python
/smallest_in_array.py
174
4.3125
4
list1=[] num=int(input("Enter number of elements:")) for i in range(1,num+1): n=int(input("Enter elements:")) list1.append(n) print("smallest element is:",min(list1))
0f32e9b161f63c27c060b2eba052bbe1aa24f1f9
MarianoCol/um-programacion-i-2020
/58164-von-Kesselstatt-Philipp/TP1/Objetos/ejercicio9.py
1,047
3.953125
4
class Persona(): def __init__(self, nombre, edad, direccion, telefono): self.nombre = nombre self.edad = edad self.direccion = direccion self.telefono = telefono self.diccionario = { "nombre": nombre, "edad": edad, ...
0ec7cff2012124e2130a42050da0646d7718a4a9
GrinchCodeFactory/sirmodel
/simulator/Commuter.py
786
3.6875
4
class Commuter: N = 0 S = 0 I = 0 R = 0 idFrom = "" idTo = "" def __init__(self, N, S, I, R, idFrom, idTo): # print("init Commuter from:" + str(idFrom) + " to: " + str(idTo)+ " with N: " + str(N) + ", S: " + str( # S) + ", I: " + str(I) + ", R: " + str(R)) self.id...
d529c027c5ccbbb40d0b908960620e9ff4dfa763
ElChurco/Introprogramacion
/Flujo_Condicional/Ejercicio2.py
222
3.96875
4
v1 = int(input("Ingrese un numero: ")) v2 = int(input("Ingrese un segundo numero: ")) if v1 < v2: print(f"{v1} es menor que: ") elif v1 == v2: print(f"{v1} es igual {v2}") else: print(f"{v1} es mayor que {v2}")
ceb9713c32808500925ee1f8f07a9e43395e70b7
KJlaccHoeUM9l/unn-numerical-optimization-methods-conditional-optimization
/src/ShowTargetFunction.py
639
3.515625
4
from sympy import * from sympy.plotting import plot3d # Инициализация заданных функций x1, x2 = symbols('x1 x2') f = 3 * (x1**2 + x2)**2 + (x1**2 - 1)**2 g1 = 0.5 * x1 + x2 + 0.5 g2 = -10 * (x1 + 1)**2 - (x2 - 2)**2 + 12 g3 = x2 + 0.8 # Отрисовка графика функции leftBoundary = -3.5 rightBoundary = 3.5 plot3d(f, (x1, ...
9dbab2c04a3f55bc633b267c615b3eb800e26167
rajshares/Python_basics
/function.py
1,500
4.125
4
## 1) Write a function named same that takes a string as input, and simply returns that string. def same (string): return string ## 2) Write a function called same_thing that returns the parameter, unchanged. def same_thing(a): return a ## 3) Write a function called subtract_three that takes an integer ...
2cad8579e3cf53c14c10f774d96a6b7d54d53a75
MrYangShenZhen/pythonstudy
/多线程/同步锁.py
687
3.578125
4
import threading,time lock=threading.Lock() def sum(): global num # num-=1 lock.acquire()#加上锁,使以下代码线程串联执行 NUM=num time.sleep(0.001) '''加上等待时间,CPU会在未处理完该线程情况下切换去处理其它线程, 当遍历执行其它线程,达到0.001S导致第一个线程有机会执行下一步-1操作。会使部分能正常-1. 大部分只赋予了值未-1,遍历最后那个线程结束操作''' num=NUM-1 lock.release()#释放锁,使后面代码...
670ffb3507fa0797d9fc853b81ebba48cc94ba2b
fduda/Intro_prog
/Prova Final/Moed Alef/tirgul8.py
1,058
3.5
4
def func1(n): if n ==0: return 0 return (n%10 + func1(n//10)) def func2(lst): if len(lst) == 0: return 0 return lst[-1] + func2(lst[:-1]) # print(func2([1,2,3])) def func3(string): if len(string) == 0: return "" return string[-1] + func3(string[:-1]) ...
d14348bafe3439de9e5bfb534d6af098600b2cf2
Mostofa-Najmus-Sakib/Applied-Algorithm
/Leetcode/Python Solutions/Trie/designSearchAutocompleteSystem.py
2,498
3.671875
4
""" LeetCode Problem: 642. Design Search Autocomplete System Link: https://leetcode.com/problems/design-search-autocomplete-system/ Language: Python Written by: Mostofa Adib Shakib L = Length of the sentence array k = Average length of each word in the sentence array. Time Complexity: O(K * L) Space Complexity: O(N) ...
118105d517ad8f3f2668930b6bf646878b4e0ba0
sshantel/leetcode
/867_transpose_matrix.py
557
4.25
4
""" Given a 2D integer array matrix, return the transpose of matrix. The transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices. """ def transpose(matrix): #0,0 => 0, 0 #0,1 => 1, 0 #0,2 => 2, 0 # #flip y, x # matrix_grid = [[0]...
b5c453b32461e11eb27c42b38ca495a94a33124a
ArnoldCody/Python-100-exercise
/exercise4.py
1,134
4.1875
4
# coding:utf-8 # 题目:输入某年某月某日,判断这一天是这一年的第几天? birthday = raw_input("please input birthday, like yyyymmdd: ") # 检验是否为闰年 def leap_year(year): if year%4 == 0: return True else: return False # 定义每月的天数 def month_has_days(month): for i in [1, 3, 5, 7, 9, 10, 12]: if month == i: ...
cd6e8aff988c1519c25399ae477a4426dd41c0dc
shai2707/learning
/programs/abstraction.py
287
3.59375
4
from abc import abstractmethod, ABCMeta class Parent(object): @abstractmethod def show_properties(self): raise NotImplementedError class Child(Parent): def __init_subclass__(self): pass def __init__(self): pass c = Child() c.show_properties()
e5df88287297eef5a72ac00d4cc2224608b2a65f
Gyol/Multicampus_Cloud
/common_ground/python_programming_stu/mycode/4_list/Cities.py
234
3.5625
4
cities = ['Auckland', 'Seoul', 'Busan', 'Jeju', 'Taipei', 'Melbourne', 'Hongkong', 'Napier'] print(cities[0:6]) print(cities[0:6:2]) print(cities[::-1]) print(cities[:]) print(cities[-50:50]) print(cities[::2], " and ", cities[::-1])