blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
d1e091b33b61af9fda6b7a3d0110b7af7926e666
TinyIke/Python_Object-oriented-practice
/Client/AddEmployee.py
798
3.671875
4
class AddEmployee(): def __init__(self,Data_Object): self.Data = Data_Object self.database = Data_Object.database def execute(self): id = input('Please enter the employee ID:') if(self.Data.Check_if_exist(id)): print('ID already exist!') else: ...
126b36f53c75440e0c66a97af718ccc9e2ae4768
Nishanky/SnakeWaterGun
/main.py
1,588
3.96875
4
# Snake Water Gun import random lst = ["Snake", "Water", "Gun"] my_count = 0 comp_count = 0 def win(me, comp): global my_count global comp_count if me == "s" and comp == "Water": my_count += 1 print(f"You Win!!({my_count})") elif me == "s" and comp == "Gun": comp_count += 1 ...
ea5a870e32911f81fd60bddf7e7d5c252ddedb8f
AnushkaTiwari/FSDP_2019
/Day01/format2.py
254
3.953125
4
# -*- coding: utf-8 -*- """ Created on Mon Jun 3 12:50:16 2019 @author: ANISHKA """ # Code Challenge : Formatting string newstr = input("Enter the string>") # replacing space with * newstr2=str.replace(newstr , ' ', '*') print(newstr2)
bf379c60cc2d18e40d13d02b6ded7d4edc7f4fb6
JaeCoding/keepPying
/foo/lc/leetcode/editor/cn/[143]重排链表.py
2,083
3.890625
4
# Given a singly linked list L: L0→L1→…→Ln-1→Ln, # reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→… # # You may not modify the values in the list's nodes, only nodes itself may be c # hanged. # # Example 1: # # # Given 1->2->3->4, reorder it to 1->4->2->3. # # Example 2: # # # Given 1->2->3->4->5, reorder it to...
75d07a7e726f8fd065e1ca22330709fbf5ae6174
bpull/fall16
/graphics/pp/02/triangle.py
979
3.9375
4
import math def dimensions(s1, s2, a2): '''Given two parallel lines of two triangles and the internal angle of triangle 2, all dimensions will be returned''' tri2angle1 = float(a2) tri2angle2 = 90 - tri2angle1 tri2opp = float(s2) tri2hyp = tri2opp / math.sin(tri2angle1 * math.pi/180) tri2adj =...
ffba5114e51affc51c22f8371379925999275005
artbohr/codewars-algorithms-in-python
/7-kyu/element-parity.py
583
4.25
4
def solve(arr): for x in arr: if x*-1 not in arr: return x ''' In this Kata, you will be given an array of integers whose elements have both a negative and a positive value, except for one integer that is either only negative or only positive. Your task will be to find that integer. For exam...
e4ad81264a08a42608aa8940a105273289a939b6
RuzimovJavlonbek/qudrat-abduraximovning-kitobidagi-masalalarni-pythonda-ishlanishi
/for_40/for_2.py
540
3.828125
4
# Assalomu aleykum. Python dasturlash tilini o'rganishni davom etamiz. # Bu dastur Qudrat Abduraximovning C++ dasturlash tili uchun ishlab chiqgan masalalar kitobidagi FOR bo'limidagi masala.Uzr masalani shartini yozib o'tirishga vaqt bo'lmadi. To'g'ri tushunasiz degan umiddaman. Shu kitobni topib for bo'limini ko'r...
4b1e19c0ac6faa4442b57b4cbfac82c80a6df5d7
jonush/leetcode
/old/easy/min_distance.py
1,149
3.984375
4
""" -------EASY------- On a plane there are n points with integer coordinates points[i] = [xi, yi]. Your task is to find the minimum time in seconds to visit all points. You can move according to the next rules: In one second always you can either move vertically, horizontally by one unit or diagonally (it means to ...
da53d280bb6854fa398f81446f68aff0e6e47973
daniel-reich/turbo-robot
/q4bBcq5NET4CH5Rcb_1.py
520
3.9375
4
""" Jay and Silent Bob have been given a fraction of an ounce but they only understand grams. Convert a fraction passed as a string to grams with up to two decimal places. An ounce weighs 28 grams. ### Examples jay_and_bob("half") ➞ "14 grams" jay_and_bob("quarter") ➞ "7 grams" jay_and_bob("e...
36d7961ddb37f5cefe2b1db065a94461baac8635
MAdisurya/data-structures-algorithms
/questions/highest_product_of_three.py
2,042
4.1875
4
""" Given a list of integers, find the highest product you can get from three of the integers. The input list_of_ints will always have at least three integers. """ import unittest def highest_product_of_3(list_of_ints): if len(list_of_ints) < 3: raise Exception() high = max(list_of_ints[0], list_of_in...
0fc27d48445ac6c3af2a380818fe952648efe20b
Zhaoput1/Python
/Leetcode/highfre/57_16threeSumClosest.py
985
3.78125
4
# -*- coding: utf-8 -*- """ # @Time : 5/18/21 # @Author : Zhaopu Teng """ from typing import List def threeSumClosest(nums: List[int], target: int) -> int: nums.sort() best = float('inf') n = len(nums) def updatebest(cur): nonlocal best if abs(cur - target) < abs(best - target):...
98726dec71adf556c81cef3016315c1db5460021
parksebastien/broca
/broca/tokenize/keyword/apriori.py
3,571
3.8125
4
""" Apriori Algorithm for text documents. The original apriori algorithm was mainly for looking at "baskets" (i.e. shopping), so some terminology may seem weird here. In particular, "transaction" refers to the set of tokens for a document. See <https://en.wikipedia.org/wiki/Apriori_algorithm> """ from itertools impo...
46a125869e8eed1acc177ba6d919a2c07d757c92
natmote/section
/algorithms/mergesort.py
1,028
4.09375
4
# Provides the merge sort algorithm with the following set of performance # characteristics # best -- O(n log n) # average -- O(n log n) # worst -- O(n log n) # This implementation sorts in place (). # # We might also want to consider using the .sort function in Python which # to the best of my u...
b699e587fbeb61f8c13c4208fd67c7bd8898d4ed
Asymi/python-CLI-drag-or-peng
/name_generator.py
958
3.8125
4
def dragon_name(name, month): months = { 'January': 'Scaly', 'February':'Hot', 'March':'Ice', 'April':'SupaHotFire', 'May':'ISpitThat', 'June':'Arithmetic', 'July':'Golden', 'August':'san', 'September':'chan', 'October':'nim', ...
cb4f9cd17da5bfd3a17b5ab70f564f51235aff07
victor-murta/EmailSender
/Pessoas.py
1,356
3.78125
4
import os from time import sleep arquivo = 'PessoasEmail.txt' def creating_file(name): try: arquivo = open(name, 'wt+') arquivo.close() except : print(f'ERRO ao criar o arquivo {name}') else: print(f'Arquivo {name} criado com SUCESSO!!!') print(f'A rota do arquivo é ...
b95379fe8a8a0706e559f9d630f61b3e09db8d2c
SpawnQQ/Mis_proyectos
/Factorial/factorial.py
1,236
3.765625
4
def factorial_recursivo(n): if n==0: return 1 if n==1: return 1 return n*factorial_recursivo(n-1) def entero_ncientifica(n_entero): contador=0; lista=range(2) nm=float(n_entero) if nm/10 > 1: while nm/10 > 1: nm=nm/10 contador=contador+1 lista[0]=nm lista[1]=contador else: lista[0]=nm lista...
9b72cffd717d0cea5dd6ab9e3ab83d51b5eece60
sanjitk7/abbreviation_generator
/abbreviation_generator.py
1,429
3.875
4
#!/usr/bin/env python3 import re #check camel case 2 words def isCamelCase(word): #check for whitespaces res = bool(re.search(r"\s", word)) if (not res): x = re.search(r"^[a-z](.+?)([A-Z])",word) if (x): return True return False def camelCaseSplit(word): if (isCamelC...
6c9868f51fa12d838e264f6b896f34e70922726a
annabelle-wright/youtube
/Home.py
4,457
3.828125
4
import random print("Welcome to my YouTube :)") current_video = None is_paused = False playlist_name = None another_command = True while another_command is True: command = input("What would you like to do- \nSHOW ALL VIDEOS \nPLAY \nSTOP \nPLAY RANDOM \nPAUSE " "\nCONTINUE \nSHOW P...
3f5badaae714ea6b802569bd72a283927f6e9935
Pollyvitamin/pytasks-Basic-functions-and-generators
/Subtask3.py
1,644
4.46875
4
""" Create function planify and generator planify2 to expand a nested sequence. For example, you have nested sequences such as list, tuple, MyList: class MyList(list): def __str__(self): return "<MyList>" seq = ('abc', 3, [8, ('x', 'y'), MyList(xrange(5)), [100, [99, [98, [97]]]]]) print(planify(seq)) # ...
06f7d93fb5417aed2079ce0e9c8a7a20ca9645b7
LezhankinaAI/TestCase
/task1.1.Lezhankina.py
362
3.765625
4
def parser(lst: list): size = len(lst) left = lst[:size // 2] right = lst[size // 2 + size % 2:] print('The first part:', left) print('The second part:', right) if sum(left) > sum(right): return True return False lst = [26, 13, 6, 16, 17, 2, 0, 1] print('Sum of the firs...
73a56b51f5d5c80ddc643d215583ed70e29ec79b
jdraiv/Algos
/Sorting/quicksort.py
606
3.984375
4
from test_sort import Tests # Elements on the left of the pivot should be lower and the elements on # the right side of the pivot should be greater def quicksort(l): left = [] right = [] equal = [] if len(l) > 1: pivot = l[0] for elem in l: if elem < pivot: ...
53e4a8503866e93d0895a1d012f2bedc6855803e
munikarmanish/cse5311
/algorithms/min_spanning_tree/prim.py
768
4.1875
4
""" Implementation of the Prim's algorithm to find the minimum spanning tree (MST) of a graph. """ from data_structures.heap import Heap def prim(G, root=None): """ Find the minimim spanning tree of a graph using Prim's algorithm. If root is given, use it as the starting node. """ nodes = Heap([(...
9c2810afc429a42783b9988821e60e0575511864
OptionSistemas/DioDesafiosPython
/rodizio_cavalos_carruagens/rodizio.py
445
3.75
4
import re n = int(input()) for i in range(1, n + 1): dias = ["SEGUNDA", "TERCA", "QUARTA", "QUINTA", "SEXTA"] final = [(1, 2), (3, 4), (5, 6), (7, 8), (9, 0)] regex = r"^[A-Z]{3}-[0-9]{4}$" placa = input() if not re.match(regex, placa): print('FALHA') else: finalplaca = int(plac...
2eddd267aee6d60c008b28c0378eb8c2812dd0f2
coachgately/Basic-Python-Projects
/dict_count_example.py
1,096
3.921875
4
import string counts = dict() file = input("Enter file name") if len(file) < 1: file = 'clown.txt' fh = open(file) for line in fh: wrds = line.rstrip().translate(line.maketrans('','',string.punctuation)).lower().split() for word in wrds: #print(word) #if key is not there, the count is 0...
99f4e1219a359e721b4f4dbdce761c2f60acd701
AleksRomario/Python
/w3resource/01_basic/94_task.py
241
4.28125
4
#!/usr/bin/env python3 """ Write a Python program to convert a byte string to a list of integers. """ print("--- my solution ---") x = b'123' print(list(x)) print("--- w3resource solution ---") x = b'Abc' print() print(list(x)) print()
c29a267b48878246e6bb5030a89a275c7592d3c1
falvey20/100-Days-Python
/027 - Miles to Km GUI/main.py
1,029
3.890625
4
import tkinter from tkinter import END def calculate_km(): converted = round(float(mile_input.get()) * 1.609) conversion_result["text"] = converted # Set Window window = tkinter.Tk() window.title("Mile to Km Converter") window.minsize(width=250, height=150) window.config(padx=50, pady=50) # User input mile...
05f8cd71ff46e8bfa277da3972c2d1193f45a3bb
MomePP/CleverAlgorithms-Python
/python/stochastic/iterated_local_search.py
3,977
3.546875
4
#! usr/bin/env python3 from .common import path_cost, random_permutation from ..switch import decide import math import random """ 2.5 Iterated Local Search improves upon Multi-Restart Search by sampling in the broader neighborhood of candidate solutions and using a Local Search technique to refine solutions to the...
3553cf99cb7500b87f505059465faeb3a5a5ed06
bibhuty-did-this/MySolutions
/Warmup/710A.py
614
3.515625
4
# 710A : KING MOVES # Prerequisite : Implementation # Algorithm: # Check for the corner cases # Check for the extreme row cases excluding corner # Check for the usual rows and columns move=raw_input() if (move[0]=='a' and (move[1]=='1' or move[1]=='8')) or (move[0]=='h' and (move[1]=='1' or move[1]=='8')):...
e00e5ee83e8274d390a83d74bd2f4f81cd8d67a4
sglavoie/code-snippets
/python/mathematics/modular_arithmetic/exponentiation_mod_k.py
4,110
4.15625
4
"""Compute the result of a^b (mod k) by using the exponentiation technique. The goal here is not efficiency, even though the program is actually pretty fast: the algorithm is applied manually for demonstration purposes. Testing on a modest Intel Core i5, having `a` and `b` each set to a random number containing 2,000...
73675e7ff29b792943a1c79421b940e1aa7d291d
leah-braswell/Election_Analysis
/Python_practice.py
2,560
4.4375
4
print("Hello World") counties = list() counties.append("Arapahoe") counties.append("Jefferson") counties.append("Denver") print(counties[1]) if counties[2] =='Denver': print(counties[2]) if "El Paso" in counties: print('El Paso is in the list of counties.') else: print('El Paso is not in the list of counti...
4607b816b9afb2415dd2332b79bc188e31664d4f
vaswin0/Numerical-Methods
/birge-vieta.py
895
3.6875
4
''' Birge Vieta Aswin October 15 2020''' import numpy as np #numerical python library def is_approx(x,y): '''Function to check convergence ARGS: x,y RETURN: bool''' return (abs(x-y) < 0.000000000001) def gradient(f, x): h = 0.0001 return ((f(x + h) - f(x - h))/(2*h)) def birg...
a34ae263276c9c50267f9d99265365d2beb9f64a
ag300g/leecode
/permutations.py
1,019
4
4
# Given a collection of numbers, return all possible permutations. # For example, # [1,2,3] have the following permutations: # [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1]. class Solution: # @param num, a list of integer # @return a list of lists of integers # per(1) = 1 # per(n) = per...
f2591b4e50943ade0f19aefdeb4e80e7592e53b1
BMariscal/coding-challenges
/HackerRank-master/Python/Strings/Alphabet_Rangoli.py
546
3.515625
4
length = int(input('Enter a number between 1 and 26: ')) s = "-" Alphabet = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z') Alpha = Alphabet[0:length] largest = (s.join(Alpha[::-1]+ Alpha[1:])) maxlen = (len(largest)) #print(largest) l...
b7797e8e3d1ed7e802433923829c5624aebaa6c2
kodicpu/codekata
/set119.py
92
3.734375
4
number=int(input()) result=1 for i in range(1,number+1): result=result*i print (result)
897e5563a78a5c863c5036774fd5408b3c1ddd32
IsseW/Python-Problem-Losning
/Uppgifter/1/1.19.py
387
3.84375
4
""" Övning 1.19 - Maximum Definiera en funktion max2(num1, num2) som returnerar det största av de två talen num1 och num2 givna som parametrar. När funktionen körs från Python-terminalen ska det se ut så här: >>> max2(8, 2) 8 """ def max2(num1, num2): if num1 > num2: return num1 return num2 print(...
12dadf1bd0c6474d634f9ccae3f8025f1b4b4fea
priyankamaladi77/msitp
/CSPP_1/day 15/Inheritance-Exercise on genPrimes/gen_primes.py
547
3.9375
4
#define the gen_primes function here def prime(number): for _ in range(2,number): if number % _ == 0: return False return True def genPrimes(): number = 2 while True: if prime(number): yield number number += 1 def main(): data = input() l = d...
26be111bca117762fe792e22a1bd983e26a3390a
huioo/Mega-Project-List
/Python3.6.5/Numbers/coin_change.py
2,206
3.65625
4
# 找零问题 """ https://github.com/taizilongxu/interview_python#12-%E6%89%BE%E9%9B%B6%E9%97%AE%E9%A2%98 https://www.cnblogs.com/xsyfl/p/6938642.html """ def coinChange(values, valuesCounts, money, coinsUsed): """ 贪心算法:局限,取决于values的值,可能有的就不能求出解。 如果我们有面值为1元、3元和5元的硬币若干枚,如何用最少的硬币凑够11元? 表面上这道题可以用贪心算法,...
20e87b6575f45e777274c3fd412b40fe60c11ad1
a1008u/PythonTraining
/src/Algorithm/FizzBuzz.py
1,907
3.65625
4
# coding: utf-8 from typing import List class Solution: def fizzbuzz(self, nums: List[int]) -> List[str]: results: List[str] = [] for index, num in enumerate(nums): if num % 3 == 0 and num % 5 == 0: results.append("FizzBuzz") continue if num ...
afa1081bbf21f5929b089bccd9017adeb14aaaa2
eroicaleo/LearningPython
/interview/leet/85_Maximal_Rectangle.py
1,411
3.546875
4
#!/usr/bin/env python3 class Solution(object): def maximalRectangle(self, matrix): """ :type matrix: List[List[str]] :rtype: int """ if len(matrix) == 0 or len(matrix[0]) == 0: return 0 nrow, ncol = len(matrix), len(matrix[0]) height = [0] * (ncol...
575deaefe554bc0ce3b2e9e839e11486f74f7da1
febimudiyanto/TimeSeriesDataGenerator
/generate_evc_time_data.py
5,697
4
4
import datetime import numpy as np import math import csv from random import randrange class TimeValueGenerator: def __init__(self, morning_values, afternoon_values, evening_values, csv_filename): self.the_morning_values = morning_values self.the_afternoon_values = afternoon_values self.t...
58dc324c7723b5515b09d36b055bd30a280ac8fa
KonstantinAlxVlasenko/algorithms
/data structures/graph.py
6,296
4.125
4
""" Module Graphs. A graph data structure consists of a finite (and possibly mutable) set of vertices or nodes or points, together with a set of unordered pairs of these vertices for an undirected graph or a set of ordered pairs of directed graph """ import networkx as nx import numpy as np import matplotlib.pyplot ...
b578e53670a92c1133e396a15a60de07a1222889
SinanKhanGitHub/SummerSchool-Game
/Speed_Snake_Final.py
15,441
3.65625
4
# Import needed modules import math import random import pygame pygame.init() # Initial variables rows = 30 one_row = rows // rows ratio_header_to_screen = 0.1 width = 900 white = (255,255,255) purple = (150,111,214) red = (255,0,0) green = (0,255,0) yellow = (253, 208, 35) emerald = (31,78,48) dark_green = (58,95,1...
13252b8f6d49228fa3392bac6a7087fa1a680bcb
MrGoatMan/Simulations
/cards.py
784
3.703125
4
import sys deck = [] suits = ["♠", "♥", "♦", "♣"] for i in range(4): for j in range(1, 14): value = str(j) if(j == 1): value = "A" elif(j == 11): value = "J" elif(j == 12): value = "Q" elif(j == 13): value = "K" deck....
f67676652f155cc75f523902022ef38175e1afa3
Aasthaengg/IBMdataset
/Python_codes/p00001/s506106815.py
98
3.65625
4
s=[int(input()) for x in range(10)] print(sorted(s)[-1]) print(sorted(s)[-2]) print(sorted(s)[-3])
13d7768691d10f9a3abca316502dcc39b8a24836
Ayaz-75/Miles_to_Km-Using-GUI
/Mile_to_kilo.py
878
3.875
4
from tkinter import * windows = Tk() windows.minsize(300, 200) windows.title("Mile to Kilometers Converter") windows.config(padx=50, pady=50) entry_input = Entry(width=10) entry_input.grid(column=1, row=0) miles_label = Label(text="Miles", font=("Arial", 10, "normal")) miles_label.grid(column=2, row=0) miles_label...
2a6a944ee1d8ae7e781cc70176fc21704beba804
alynmhfl/mygit
/201104_example_1.py
491
4.09375
4
#get an initial guess guess str = input("Guess a number: ") guess = (guess_str) # while guess is range, keep asking while 0 <= guess <= 100: if guess > number: print ("Guessed Too High.") elif guess < number: print("Guessed Too Low.") else: # correct guess, exit with break was: ",number) print("You guessed...
e96a637fbdb30416ba05baec0b42b004cd45c909
ytf513/python_code
/file/fileopen_readbuffer.py
245
3.609375
4
#list.txtļݵlist2.txt #ļ֮ǰȴ򿪣дļ֮ǰҲȴ with open("list.txt",'rb') as file1: temp=file1.read(10) while(temp): print temp temp=file1.read(10)
f4960ab7dde0989b60c8b2acc7c486dd8e981ff3
gapgag55/awesome-algorithms
/artificial-intelligence/longest-common-subsequence.py
302
3.734375
4
def lcs(word, term, i, j): if i == 0 or j == 0: return 0 elif word[i-1] == term[j-1]: return 1 + lcs(word, term, i-1, j-1) else: return max(lcs(word, term, i, j-1), lcs(word, term, i-1, j)) word = "FISH" term = "FOSH" print("Length of LCS is", lcs(word, term, len(word), len(term)))
e91ecd9d73d7f26cb22ffc4e71d7a7360444017b
nhannt201/100AlgorithmsChallenge_Python
/6.NextChar.py
277
3.640625
4
alphabetChar = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']; def input(str): rs = []; for x in str: rs.append(alphabetChar[(alphabetChar.index(x) + 1)]) print(''.join(rs)) input("abc")
b254e44778c31c16f620ec27b7dc96214a3b5599
amyghotra/IntroToCS
/computingFare.py
1,294
3.921875
4
#program 43 def computeFare(zone , ticketType): computeFare = "" if zone == 1 and ticketType == "peak": computeFare = "6.75" print("The fare is " , computeFare) elif zone == 1 and ticketType == "off-peak": computeFare = "5.00" print("The fare is " , computeFare) elif zon...
fd0a324b785b12cbdf17ad9283e185ed0d24fa57
gprakkash/big-mat-big-num-multplication
/src/large_multi_brute_force.py
2,714
3.890625
4
# -*- coding: utf-8 -*- """ Created on Wed Apr 27 01:52:30 2016 @author: mythcard """ import time def mult(a,b): num = a * b digit = num % 10 carry = int(num / 10) return digit,carry def add(a,b): num = a + b digit = num % 10 carry = int(num / 10) return digit,...
75b0b2cf211c834973d380486dd13d7075ae371a
matheustxaguiar/Programming-Period-1
/moduloapnp23.py
347
3.859375
4
# modulo22 - arquivo 1 # Função de cálculo da raiz quadrada de N>0 def mdc(num1,num2): r = num1 % num2 while (r != 0): num1 = num2 num2 = r r = num1 % num2 return num2 def mdc2(mdc1,num3): r = mdc1 % num3 while (r != 0): mdc1 = num3 num3 = r r = mdc1...
c27e20a3aa108aea316dcbb0595064781d267855
danielchen26/fast_density_clustering
/fdc/density_estimation.py
6,418
3.59375
4
import numpy as np from sklearn.model_selection import train_test_split from sklearn.neighbors import KernelDensity, NearestNeighbors class KDE(): """Kernel density estimation (KDE) for accurate local density estimation. This is achieved by using maximum-likelihood estimation of the generative kernel density m...
a51c0935e78091e02bc0da5850f60a5e53868327
babiswas2020/Blind-paractise
/test28.py
358
3.65625
4
class A: def __init__(self,filename): self.name=filename def __enter__(self): self.file=open(self.name,'w') return self.file def __exit__(self,x,y,z): if self.file: self.file.close() if __name__=="__main__": with A("hello100.txt") as f: f.write("Hello") ...
dd6e182fa82b4c7d2ad315e2643989bd141a73b3
Al3dekev/Calco
/calculation.py
524
3.828125
4
# Class de prise en charge des calculs def calcul(): def __init__(self, elem1, elem2): self.el1 = elem1 self.el2 = elem2 def addition(self): return self.el1 + self.el2 def soustraction(self): return self.el1 - self.el2 def multiplication(self): ...
28809b0fc0746826daa717b6486f402d5f7c3b45
MichaelPay/michael_learns_python
/Python Projects/Python Basics 2/yob exercise.py
1,028
4.03125
4
# -*- coding: utf-8 -*- """ Created on Mon Jul 24 20:49:04 2017 @author: Monic """ # ask the user for their name and year they're born # calculate the print the year they'll turn 25, 50, 75, and 100 # if they already past any of these ages, skip them name = input('Hello! Welcome to the age calculator! Wha...
adf93192af396e4fbaf067b44b2102364d74598b
MON7Y/Simple-Python-Programs-
/countdigitsinNo.py
615
4.3125
4
''' Python Program to Count the Number of Digits in a Number This is a Python Program to count the number of digits in a number. Problem Description The program takes the number and prints the number of digits in the number. Problem Solution 1. Take the value of the integer and store in a variable. 2. Usin...
f278ec770b4d3e940ba3b3181490d96d8b486a99
kaini/aoc2019
/day1.py
402
3.8125
4
#!/usr/bin/env python3 def recfuel(n): result = 0 n = n // 3 - 2 while n > 0: result += n n = n // 3 - 2 return result def main(): with open("day1.txt", "r") as fp: numbers = [int(s) for s in fp.read().split()] print(sum(n // 3 - 2 for n in numbers)) p...
5aae22ecc57ea7a2762bc110ed3a55a913519a92
Aasthaengg/IBMdataset
/Python_codes/p03206/s703219007.py
77
3.78125
4
d=int(input()) s="Christmas" for i in range(25,d,-1): s=s+" Eve" print(s)
6e7205ad4463678ba1ee87390cae19c5c3c9c3c1
Valtory/Exercises
/If_Elif.py
703
3.984375
4
def introduction (name, age, sex): if age > 18 and sex == 'hombre': print(f'Hola {name} tienes {age}, tremendo grandulon') elif age > 18 and sex == 'mujer': print(f'Hola {name} tienes {age}, señora digna de belleza y gracia') elif age <= 18 and sex == 'hombre': print(f'Hola {name} ti...
8701c648162c4d129b78a783772ff42b288b6793
SobrancelhaDoDragao/Exercicio-De-Programacao
/Exercicios-Python/Basico/Pacotes/Modulos/uteis.py
433
4
4
""" Bibliotecas criada para aprender módulos """ def fatorial(n): """ Função que recebe um valor como parâmetro, e retorna o fatorial desse valor """ f = 1 for c in range(1,n+1): f*=c return f def dobro(n): """ Retorna o dobro do valor passado por parâmetro """ return n...
2eeae4af57c59971ab734701ce4028d44b05a46e
tdthuan97/myday04
/right_triangle_errors/right_triangle_errors.py
353
3.5625
4
def right_triangle_errors(a, b, c): arr = [a, b, c] right = [] try: right = [s for s in arr if int(s) > 0] right.sort() if len(right) == 3: return right[0] ** 2 + right[1] ** 2 == right[2] ** 2 raise ValueError('Incorrect value') except ValueError: rai...
8bb6646fb25e32476e6c15508e5bda063234395e
Ved005/project-euler-solutions
/code/uphill_paths/sol_411.py
1,018
3.625
4
# -*- coding: utf-8 -*- ''' File name: code\uphill_paths\sol_411.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #411 :: Uphill paths # # For more information see: # https://projecteuler.net/problem=411 # Problem Statement ''' Let n be ...
a6aa178a56e42dddab7d4560c2a94b6c4f7e35e0
chjdev/euler
/python/problem19.py
1,695
4.0625
4
# Counting Sundays # Problem 19 # You are given the following information, but you may prefer to do some research for yourself. # # 1 Jan 1900 was a Monday. # Thirty days has September, # April, June and November. # All the rest have thirty-one, # Saving February alone, # Which has twenty-eight, rain or shine. # And on...
d2495aa403cfaf28872f2f9eddcf47a6beb2845b
deggs7/py-practice
/sweet/merge_sort.py
118
3.578125
4
a = [8, 2, 7, 9, 1, 3 ] b = [73, 23, 34, 34, 7, 8, 3, 5, 4] a.extend(b) print a print sorted(set(a), key=a.index)
8fdce5a659129e7922493ce24751bfd282b4fbc8
Okroshiashvili/Data-Science-Lab
/Data Visualization/Plotly/bubble_chart.py
1,158
3.5
4
import plotly.offline as pyo import plotly.graph_objs as go import pandas as pd # Read the data df = pd.read_csv('data/mpg.csv') # Add columns to the DataFrame to convert model year into string and # then combine it with name so that hover text shows both df['text1'] = pd.Series(df['model_year'], dtype=str) df['...
21c11c6adc719fd4cfe1d7b5432be17c5ec314bb
HOZH/leetCode
/leetCodePython2023/1379.find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree.py
755
3.609375
4
# # @lc app=leetcode id=1379 lang=python3 # # [1379] Find a Corresponding Node of a Binary Tree in a Clone of That Tree # # @lc code=start # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: ...
5ddb66df57fabd98555facbdbb16ce7ea9e7368f
18684092/AdvProg
/ProjectEuler/General-first-80-problems/problem66b.py
942
3.828125
4
# continued fractions from # https://en.wikipedia.org/wiki/Methods_of_computing_square_roots import math def checkPell(x, d, y): if (x * x) - d * (y * y) == 1: return(True) return(False) def isSquare(integer): root = math.sqrt(integer) if int(root + 0.5) ** 2 == integer: ...
7924c3376f378b492c5bdd906d4c8695ca8e7e2f
bhatiakomal/pythonpractice
/Pythontutes/NestedFunction.py
275
3.515625
4
#Nested function '''def disp(): def show(): print("Show function") print("disp function") show() disp()''' def disp(k): def show(): return "Show Function " result=show() + k + " Disp Function " return result a=disp("komal") print(a)
1b8eacd714d48f6b8fb556748eab4fb95f92131a
jrodriq3/budget_manager
/Budget.py
1,571
3.84375
4
class BudgetManager: def __init__(self, amount): self.available = amount self.budgets = {} self.expenditure = {} def add_budget(self, name, amount): if name in self.budgets: raise ValueError('Budget exists') if amount > self.available: raise Valu...
7d7478288dc70c87cec8103ee434b800aeac4549
maxigarrett/cursoPYTHON
/2-clase2/2.6-ejercicio.py
388
4.125
4
"""Escribir un programa que le pregunte al usuario cuantas palabras desea ingresar, luego le permita ingresarlas todas y finalmente mostrarlas por pantalla""" array_palabras=[] cantidad_palabras=int(input("cuantas palabras desea ingresar\n")) for item in range(0,cantidad_palabras): palabra=input("ingrese una p...
b474abe4f14b1aceef04f13d5ef8e36a6acd3c19
adriangorski05/Python
/slownik.py
321
4.03125
4
dict = {} keys = input ("Podaj slowa-klucze slownika: ") values = input ("Podaj opisy slow-kluczy: ") keys_list = keys.split() values_list = values.split() print(keys_list) print(values_list) for key in keys_list: for value in values_list: dict[key] = value values_list.remove(value) print(dict)...
f9059cbb49d189197501f1a871e819a73bdaf515
hhc97/online_coding
/Kattis/faktor.py
560
3.71875
4
# https://open.kattis.com/problems/faktor # accepted answer, CPU time: 0.05s """ Sample input: 10 10 Sample output: 91 """ def _get_numbers(): """ Gets a line of input from stdin and return the numbers in a list. If there is only 1 number, return the number itself. """ numbers = [int(v) for v ...
b055e38dd0423fb52e96776f35497162bb177d09
DaltonLarrington/Dalton-Larrington-Data-Structures
/Dalton Larrington DS Lab 00 - A Crash Course in GIT/PrimeNumbers.py
237
3.9375
4
# Prime numbers # Programmer: Dalton Larrington # DatE: 1-13-18 for i in range(2, 50): isPrime = True for j in range (2, i): if i % j == 0: isPrime = False break if isPrime: print(i)
b9c53decd2cb0f038407b48c0c675c3c0c5c7a83
Dark6767/pythone
/ex32.py
1,701
3.734375
4
class Employee: full_names = [['Ivan','Ivanov'],['Vitya','Loshkin'],['Lev','Tolstoj']] departments = ['hr','base','space'] def __init__(self,name,surname,department,year): try: self.check_name = False self.check_year = False self.check_department = False ...
3f1c2d169ada8c160dd3ebf521892c90f125c912
iswangyj/Python001-class01
/week07/homework.py
1,355
3.90625
4
from abc import ABCMeta, abstractmethod class Zoo(object): def __init__(self, name): self.animals = [] self.name = name def add_animal(self, instance): if type(instance).__name__ in self.animals: print(f'{type(instance).__name__} existed') else: self.ani...
6700f28887a353f0eef5b63d49c31fd6a9d8dd76
kdpujie/epython
/python-e/modue/lambda.py
204
3.609375
4
from functools import reduce #lambda表达式 f=lambda x,y,z:x+y+z print(f(1,2,3)) n=5 f1=reduce(lambda x,y:x*y,range(1,n+1)) print(f1) def action(x): return lambda y:x+y ff=action(2) print(ff(22))
94ce15239e305930efe29e4f01008bc97498b8b3
matthew99carroll/lunar-satellite-propagator
/celestial_body.py
2,819
3.515625
4
# -*- coding: utf-8 -*- """ File name: celestial_body.py Author: Matthew Carroll Date created: 18/05/2021 Date last modified: 18/05/2021 Python Version: 3.9.5 File Description: Creates and handles all of the parameters required for a celestial body includng calculations of its position """ from mas...
596a6d381360bf3c63b334dbd169462e7ff21bb9
harshil1903/leetcode
/Linked List/0206_reversed_linked.list.py
1,042
4.03125
4
# 206. Reverse Linked List # # Source : https://leetcode.com/problems/reverse-linked-list/ # # Given the head of a singly linked list, reverse the list, and return the reversed list. # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.ne...
489c0f64f9d747d1673af36aafe2bfce17622986
huangyuzhen/algorithm_python
/3.1_a.py
924
3.8125
4
''' 全排列问题 给定一组互不相同的字符,求这组字符的全排列 用递归实现 复杂度 n的阶乘 O(n!) ''' result = [] # def permutations(aString, head = ''): # l = len(aString) # if l <= 1: # s = head + aString # result.append(s) # return # for i in range(l): # h = head + aString[i] # if i == 0: # a =...
84bdebcc33a4f917e0bc55325beae1a7b6897ba2
salonikarnik/web-development-with-django
/lessons/variables.py
112
3.609375
4
name = "Tim" age = 23 print(name+" is a boy") print(name," is ", age) print(name+" is from turkey") print(name)
95eec10358d867ac84c3c282c39ce5c3299444bd
stjsmith8/stjsmith
/Coding Problem 2.4.10.py
2,990
4.4375
4
start_hour = 3 start_minute = 48 length = 172 #You may modify the lines of code above, but don't move them! #When you Submit your code, we'll change these lines to #assign different values to the variables. #Let's try something trickier! The variables above represent #the start time for a run as well as the length of...
2d2366ba5ba99558ea7ccae520d3fe3bdf593eaf
zdyxry/LeetCode
/tree/1382_balance_a_binary_search_tree/1382_balance_a_binary_search_tree.py
718
3.65625
4
class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def balanceBST(self, root): def dfs(node): if not node: return dfs(node.left) values.append(node.val) ...
33151cd113ee059b0efbcee031267b704063e1c6
RoKu1/PCB_RCNN
/Codes/utils/renamer.py
561
3.5625
4
import os # Function to rename multiple files def main(): i = '0001'; dirc = "missing\\annots" ; print(dirc) for filename in os.listdir(dirc): dirc = "missing\\annots\\" dst ="mh" + i + ".xml" src = dirc + filename dst = dirc + dst print(filename[2:-4...
f9cb1daa8cef91ab4c89b1ed134e27f756b5215e
numjax/pytestproject
/old2/vari14.py
867
3.546875
4
# - *- coding: utf- 8 - *- def max_profit(price_list, count): # 코드를 작성하세요. # 타뷸레이션 방식 profit_table = [0] maxi = 0 if count ==0: return 0 for i in range(1, count+1): # count개를 팔 수 있는 조합들을 비교해서, 가능한 최대 수익을 찾는다 if i < len(price_list): maxi = price_list[i]...
93ace119f08089269a597f584361036c5a7cf971
Lv296TAQC/python_tasks
/tasks/task_554.py
699
4.03125
4
#!/usr/bin/python """Oleksandr's module for solving task 554""" def task554(from_input): """Take input natural number and search for all it's Pythagorean triples, that like 'a < b < c < input natural number' Args: from_input (int): Incoming value Returns: result (dict): Return dict w...
28feb88acb5199bae8612c21b8ac3dfc91052dbd
pedrosiracusa/caryocar
/caryocar/cleaning/namesatomizer.py
5,337
3.625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Names Atomizer module """ import json from collections import Counter class NamesAtomizer: """ The NamesAtomizer is built with an atomizing operation to be defined as the instance's default and an optional list with names to be replaced. Names to be replaced ...
f5a7cfe9e9b8d57b5d7e76a866b32ae3b9f3de36
Zarwlad/coursera_python_hse
/week1/test.py
388
4.15625
4
print(11 + 6) print(11 - 6) print(11 * 6) print(11 ** 6) # возведение в степень print(11 // 6) # целочисленное деление (возвращается число до запятой) print(11 % 6) # остаток от деления print(11 / 6) # полноценное деление speed = 108 time = 12 distance = time * speed print(distance)
028fd641dc00a82e9032bf75dcad2c196242ee36
jssemeone/lesson2
/exception1.py
830
3.90625
4
# """ # Домашнее задание №1 # Исключения: KeyboardInterrupt # * Перепишите функцию ask_user() из задания while2, чтобы она # перехватывала KeyboardInterrupt, писала пользователю "Пока!" # и завершала работу при помощи оператора break # """ user_dict = {'Как дела?': 'Хорошо', 'Что делаешь?': 'Программирую'} ...
852eb2811cf089b6060260eb1d3e830baa02aaa3
ElisaPiperni/first-homework
/Collections/08.py
278
3.53125
4
#Most Common #!/bin/python import sys from collections import Counter if __name__ == "__main__": s = raw_input().strip() c = Counter(s) sort = sorted(c.items(), key=lambda x: (-x[1], x[0])) for i in range(0,3): print sort[i][0], sort[i][1]
fd1dd434d4cad64ddc99e64631fba82eb40e7524
Ing-Josef-Klotzner/python
/_the_market1.py
2,199
3.59375
4
from sys import stdin, stdout from collections import Counter, defaultdict from functools import reduce from operator import mul from itertools import accumulate def sieveOfEratosthenes(n): """sieveOfEratosthenes(n): return the list of the primes < n.""" if n <= 2: return [] sieve = list (range (3,...
aaa67c74699f0b478f12959ce013ecec1b16e1df
NDM2021/hello-world
/NorrisMayesCSS225M6P2.py
176
3.859375
4
import random integers = random.randrange(0, 100) print(integers) if integers > 2 == 0: print(odd) # Norris # 2/18/20 # This code prints random from 0 to 100
3bf4af6c0b4001a1432866886085b233ce536af5
christopher-nguyen-huy/Python
/snippets/generators.py
407
3.875
4
# Generator example def genrange(max): k = 0 while k < max: yield k k += 1 # Shove into object funcvar = genrange(32) # 1st way to call out for j in funcvar: pass for i in genrange(42): pass # 2nd way funcvar = genrange(32) print(funcvar.next()) print(next(funcvar)) # Generator comprehensi...
78460320023f840be43ed7e134ef3490aea163f9
Dharani-18/CODEKATA
/pgm/numbers.py
127
3.765625
4
a=int(input()) dict={1:"One",2:"Two",3:"Three",4:"Four",5:"Five",6:"Six",7:"Seven",8:"Eight",9:"Nine",10:"Ten"} print(dict[a])
3ec8de178e0ac0e3353f63cc54cbbfde8784caef
Kalpesh14m/Python-Basics-Code
/Basic Python/File_Handling/12 Write to file.py
374
3.703125
4
text = 'Sample Text to Save\nNew line!' # notifies Python that you are opening this file, with the intention to write saveFile = open('Output/exampleFile.txt','w') # actually writes the information saveFile.write(text) # It is important to remember to actually close the file, otherwise it will # hang for a while and...
ef11d760341cd2b21fdafe609ff094f0e359a89a
blaketeres/csc521
/python-quirk/parser.py
15,601
3.71875
4
import sys import re import json import pprint pp = pprint.PrettyPrinter(indent=1, depth=100) parseTreeInput = [] currentIndex = 0 # append subtree to immediate parent tree upon function returning True # this will keep the order of the tree in tact, and eliminate incorrect leafs """ How My Parser Works: Each functi...
0ee81ef1a7a2b419441b6bfada2b73c4ef5bb1f9
atahar123/eng-54-python-basics-new
/exercise_102.py
661
4.40625
4
# # Create a little program that ask the user for the following details: # - Name # - height # - favourite color # - a secrete number # Capture these inputs # Print a tailored welcome message to the user # print other details gathered, except the secret of course # hint, think about casting your data type. name ...
ddae0bee5370871daac63c50da2af485be830164
Khrystynka/LeetCodeProblems
/504_base-7.py
452
3.59375
4
# Problem Title: Base 7 class Solution(object): def convertToBase7(self, num): """ :type num: int :rtype: str """ if num == 0: return '0' s = '' neg = False if num < 0: neg = True num = abs(num) print num...
eed5817202b915188ebbfe69aeec89ddd5fd48df
ericbfriday/Learn-Python3-The-Hard-Way
/ex14.py
464
3.78125
4
from sys import argv script, user_name = argv prompt = '> ' print(f'Hi {user_name}, I\'m the {script} script') print('I am here to ask you a few questions.') print(f'Do you like me, {user_name}?') likes = input(prompt) print(f'Where do you live, {user_name}?') location = input(prompt) print(f'What kind of computer d...
5b519bbdb036214ef73b769fddb6f94678164cc2
gopuu/PasswdManager
/passwdMngr.py
6,627
3.75
4
import sqlite3 import random import string import datetime conn = sqlite3.connect('PasswdMngr.db') c = conn.cursor() def generatePasswd(): N = 3 str1 = random.choices(string.ascii_uppercase, k = N) str2 = random.choices(string.ascii_lowercase, k = N) str3 = random.choices(string.digits, k ...