blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
077531c87b4f6a43dc48b68957d8e84e554d1bb4
EgorSevriugov/pythonscripts
/lists6.py
103
3.546875
4
A = [1,2,3,2,3,3] for i in range(1,len(A)): if A.count(A[i]) == 1: print(A[i], end = ' ')
c5a43fb983b6fc90d0302ca4bd87eaceb0d8559c
SoulSlain/123
/lesson4/char_freq.py
239
3.5625
4
from collections import Counter message = input("Введите текст:") res = {i : message.count(i) for i in set(message)} print ("Частота использования символов такова:\n " + str(res))
689b18a0e34241ba7ab71aadd711e23876f72132
SoulSlain/123
/lesson4/bubble_sort.py
393
3.890625
4
from random import randint def bubble(array): for i in range(N-1): for j in range(N-i-1): if array[j] > array[j+1]: buff = array[j] array[j] = array[j+1] array[j+1] = buff N = int(input("количество цифр в цикле: ")) a = [] for i in range(N): ...
9c34f452bd06967dddd0f93dc06286733c19a1e5
CoolyXIE/git_repo
/python/firstPython/class1.py
413
3.765625
4
# -*- coding: utf-8 -*- import datetime class MyClass(object): def __init__(self): self.create_at = datetime.datetime.now() def __str__(self): return "my create at {0}".format(self.create_at) import new obj = MyClass() obj.hello = "Hello" #动态添加成员对象 say = lambda self:self.create_at obj.say = ...
076b8c531e7c37f14a80bc4b40a7eaa5d502cc17
Fellepp/ITGK
/Eksamen2017Kont/Oppgave 3.py
2,332
3.96875
4
import time # a) def enter_line(prompt, length): sentence = input(prompt) while (len(sentence) != 30): print("The text must be", length, "characters long") sentence = input(prompt) return sentence # text = enter_line("Enter line 1: ", 30) # print(text) # b) def adjust_string(text, length...
44397bcc817e9f246f031190a15d9b9004f258e0
Fellepp/ITGK
/Øving 6/Mynter.py
1,056
3.765625
4
import math def count_coins(coins): return sum(coins) coins = [20, 10, 1, 1,5, 10] print(count_coins(coins)) def num_coins(numbers): coins = [] for i in range(0, len(numbers)): value = numbers[i] twentys = math.floor(value/20) value = value - twentys*20 tens = math.floor(v...
33fade1942cacff694e925cf06f0fa1648436113
Fellepp/ITGK
/Eksamen2016/Oppgave 4.py
2,418
3.515625
4
D = {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten', 11: 'eleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen', 15: 'fifteen', 16: 'sixteen', 17: 'seventeen', 18: 'eighteen', 19: 'nineteen', 20: 'twenty', 30: 'thirty', 40: 'forty', ...
4c2bf0f58e707debfdea875abbc13d91de06c646
Fellepp/ITGK
/Øving 5/Kollektiv-app.py
769
3.609375
4
#a) def billettPris(alder, sykkel): sum = 0 if sykkel == "j": sum = 50 if alder > 60 or alder < 5: return sum elif 5<=alder<=20: sum += 20 return sum elif 21<=alder<=25: sum += 50 return sum elif 26<=alder<=60: sum += 80 return sum ...
2b0930d93325742aab5d09148740dcc97f02d601
Fellepp/ITGK
/Øving 5/ForenklingAvBrøker.py
339
3.765625
4
def gcd(a, b): while b!=0: gammel_b=b b = a%b a=gammel_b return a def reduce_fraction(a, b): d = gcd(a, b) var1 = a/d var2 = b/d return var1, var2 x, y = reduce_fraction(5, 10) print(x, "/", y) x, y = reduce_fraction(4, 2) print(x, "/", y) x, y = reduce_fraction(42, 1...
0757ff156980867d05df2751f6b230cc391f426c
Fellepp/ITGK
/Øving 2/Øving 2/epletigging.py
1,435
3.96875
4
sann = True while(sann): print("Dette er et program for å teste din sjenerøsitet.") try: har_epler = int(input("Hvor mange epler har du? ")) if har_epler<0: print("Skriv inn et positivt heltall") continue except ValueError: print("Skriv inn et heltall") ...
49b09c36f6ba3b4865615c06ed4e9c180aaee458
hero007feng/show-me-the-code
/No.0004/main.py
217
3.671875
4
def count_total(filename): file = open(filename) word = file.read().split() count_word = len(word) return count_word if __name__ == "__main__": total = count_total("input.txt") print(total)
7ce9286b30bc12ec129cc3bbe76d177d6b3d823a
KAHerbst/KAHerbst_project
/plot.py
3,142
3.578125
4
from PIL import Image, ImageDraw from PIL.ImageColor import getrgb class Plot: """ Provides the ability to map, draw and color regions in a long/lat bounding box onto a proportionally scaled image. """ @staticmethod def interpolate(x_1, x_2, x_3, newlength): """ linearly inter...
cfcd0baa03e8b3534f59607103dfec97f760ea28
zoeang/pythoncourse2018
/day03/exercise03.py
699
4.40625
4
## Write a function that counts how many vowels are in a word ## Raise a TypeError with an informative message if 'word' is passed as an integer ## When done, run the test file in the terminal and see your results. def count_vowels(word): if (type(word)==str)==False: raise TypeError, "Enter a string." else: vowel...
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-...
7714f5becbbe89e6d32638054424178136e0c56d
Quantum-Anomaly/codecademy
/intensive-python3/unit2w3codechallenge.py
3,882
3.984375
4
#--- #2/11 In Range def in_range(num,lower,upper): if (num >= lower) and (num <= upper): return True else: return False print(in_range(10, 10, 10)) print(in_range(5, 10, 20)) #--- #3/11 - Movie review def movie_review(rating): if rating >= 9: return "Outstanding!" elif rating > 5 and rating < 9: ...
aece9b8d89ba1db933790e23bc5296bb32ef13cd
Quantum-Anomaly/codecademy
/intensive-python3/unit5w7d1.py
4,136
4.46875
4
#Lesson #---1/9 - Dicitonaries sensors = {"living room": 21, "kitchen": 23, "bedroom": 20, "pantry": 22} num_cameras = {"backyard": 6 "garage": 2 "driveway": 1} print(sensors) #You’ve just added a sensor to your "pantry", and it reads 22 degrees. Add this pair to the dictionary on line 1 #Remove the # in front of t...
bb7941ec61dab5e4798f20fb78222c933efdcfe4
Quantum-Anomaly/codecademy
/intensive-python3/unit3w4d6project.py
757
4.5
4
#!/usr/bin/env python3 toppings = ['pepperoni', 'pineapple', 'cheese', 'sausage', 'olives', 'anchovies', 'mushrooms'] prices = [2,6,1,3,2,7,2] num_pizzas = len(toppings) #figure out how many pizzas you sell print("we sell " + str(num_pizzas) + " different kinds of pizza!") #combine into one list with the prices attache...
033bf85a2f2dc74f59883833aae0c665c917e147
Dawson-Jones/test_test
/pypy/iterator_generator_coroutine/fluent_python/16-17_coroaverager3.py
2,393
3.859375
4
"""开始使用yield from""" from collections import namedtuple from coroutil import coroutine Result = namedtuple('Result', 'count average') # 子生成器 def averager(): total = 0.0 count = 0 average = None while True: term = yield if term is None: break total...
7d2150fe9c2637473023bd4bd581544b54e68c4d
Dawson-Jones/test_test
/pypy/with_systax/with_principle.py
1,128
3.84375
4
import time class Sample1: A = 'Foo' def __enter__(self): print("in __enter__") # return "Foo" # 返回值作为as后面的东西 return self def __exit__(self, exc_type, exc_val, exc_tb): print("in __exit__") def show(self): return self.A def get_sample(): ...
8ad608b134e6244dc51b15a8b94e33fd316a063d
Huynh-Soup/huynh_story
/second.py
391
4.1875
4
""" Write a program that will ask the user what thier age is and then determine if they are old enough to vote or not and respond appropriatlely """ age = int(input("Hello, how old are you?: ")) if age < 17 : print("You can't vote") if age > 18 : print("Great, who would you vote for in 2020? (a,b,c) ")...
f6c78cca2d4dca716bec1bcf61d25852e6b8ad73
gauripatil20/tpkinter
/tiknter.py
3,039
3.640625
4
from tkinter import Button, Tk, Frame, Label, Button from time import sleep from tkinter import font from tkinter.constants import LEFT, TOP from tkinter.font import BOLD class Question: def __init__(self, question, answers, correctLetter): self.question = question self.answers = answers se...
544c379a54a69a59d25a1241727d02f9414d6d1b
Murrkeys/pattern-search
/calculate_similarity.py
1,633
4.25
4
""" Purpose : Define a function that calculates the similarity between one data segment and a given pattern. Created on 15/4/2020 @author: Murray Keogh Program description: Write a function that calculates the similarity between a data segment and a given pattern. If the segment is shorter than the pat...
dcdf02cb773fdd2eafb9ae51431047c0d9335edd
YerimMG/cursopython
/temperatura.py
264
3.828125
4
#/usr/bin/python for celcius in range (0,11): print " De " +str(celcius) + " grados celcius a Fahrenheit son " +str((celcius*1.8)+32) for Fahrenheit in range (0,11): print " De " +str(Fahrenheit) + " grados Fahrenheit a celcius son " +str((Fahrenheit-32)/1.8)
d6cebb830687fbf862b7eb5ac58a2064f77ff6ff
YerimMG/cursopython
/lista.py
512
4.03125
4
listas=['cadena de texto', 15,2.8,'otro dato, 25'] #listaABCD=['a','b','c','d'] #cadena de datos en la que si se pueden cambiar print listas[1:4] print listas[1] print listas[1:2] print listas[-2] listas[2]=10 #la lista de arriba cambia un codigo print listas[1:4] listas.append('cuaderno') #la linea de arriba agrega d...
26d06b59f81478b713d441397ca18a230e02d3b3
ac1093/python-challenge
/PyPoll/new_poll.py
1,571
3.609375
4
import os import csv poll_csv = os.path.join('..', '..', 'election_data.csv') election_output = os.path.join('election_output.txt') total_vote_count = 0 candidate_option = [] candidate_votes = {} winning_candidate = '' winning_count = 0 with open(poll_csv) as csvfile: csvreader = csv.reader(csvfile, delimiter=',') ...
f7dc5fc81e5522660c916fad9400518208e030f7
kudoxi/KXalgorithm
/searchInsert.py
636
4
4
import re class Solution: """ @param A: an integer sorted array @param target: an integer to be inserted @return: An integer """ def searchInsert(self, A, target): # write your code here if not A: return 0 if target not in A: A.append(target) ...
07534363ad731e3223be1c5a7f6be4958bbe40c5
kudoxi/KXalgorithm
/canAttendMeetings.py
1,191
3.765625
4
""" Definition of Interval. """ class Interval(object): def __init__(self, start, end): self.start = start self.end = end class Solution: """ @param intervals: an array of meeting time intervals @return: if a person could attend all meetings """ def canAttendMeetings(self, i...
558cadbcc130d08bf65ba8d408378bfdfab46774
kudoxi/KXalgorithm
/isUnique.py
356
3.6875
4
class Solution: """ @param: str: A string @return: a boolean """ def isUnique(self, strs): # write your code here a = len(list(strs)) b = len(set(list(strs))) if b < a: return False else: return True if __name__ == "__main__": pr...
13593ebd81e6210edd3981895623975c820a72bc
MurrayLisa/pands-problem-set
/Solution-2.py
367
4.4375
4
# Solution-2 - Lisa Murray #Import Library import datetime #Assigning todays date and time from datetime to variable day day = datetime.datetime.today().weekday() # Tuesday is day 1 and thursday is day 3 in the weekday method in the datetime library if day == 1 or day == 3: print ("Yes - today begins with a T") ...
9e6640cd8f4d2d03f34b66f25036d3bea5c83466
JellOnRails/Geek
/hackerrank/contact_search.py
765
3.5625
4
import collections class Contact_list(object): def __init__(self): self.contacts = collections.defaultdict(int) def _add(self, name): self.contacts[name] += 1 max = len(name) for i in range(1, max): self.contacts[name[:-1*i]] += 1 ...
9cd0767870e7e3bce5e65ceb19a4271f2512027c
micahshute/ece_code
/networks/graph/binary_tree.py
773
3.578125
4
class BinaryTree: def __init__(self, nodes = []): self.nodes = nodes def root(self): self.nodes[0] def iparent(self, i): return (i - 1) // 2 def ileft(self, i): return 2*i + 1 def iright(self, i): return 2*i + 2 def left(self, i): ret...
64fd06ca6d91bab50e514f4277a6f369991e5bcb
Qingtian-Zou/LeetCode-Python3Answers
/643. Maximum Average Subarray I.py
777
3.96875
4
''' Given an array consisting of n integers, find the contiguous subarray of given length k that has the maximum average value. And you need to output the maximum average value. Example 1: Input: [1,12,-5,-6,50,3], k = 4 Output: 12.75 Explanation: Maximum average is (12-5-6+50)/4 = 51/4 = 12.75 Note: 1 <= k ...
0f15f34d5bf4bd3ea64995f3252d8a0c43926232
zhcHoward/Advent_of_Code
/Day13/part1.py
3,079
3.96875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from collections import deque from operator import attrgetter from typing import Deque from utils import read_input class Direction: UP = "^" DOWN = "v" LEFT = "<" RIGHT = ">" def turn_left(direction): if direction == Direction.DOWN: retur...
11757dbdf633c88a990cfcbc00ef25e66e6f8858
OlenchenkoM/python-laboratory
/task1.py
1,336
3.625
4
import math const = math.pi print("Оленченко Максим Андрійович \n Лабораторна робота №1 \n Варіант 15" " Завдання №1 Обчислити, скільки потрібно банок фарби") a = (input("Введіть діаметр бака ")) while(a.isdigit() == False) : a = (input("Ви ввели не правильну форму заповнення." ...
40cf91decb3ffb4ffe920a1fe04bb151b67fe284
twseel/InformationScience
/extra/databases.py
1,785
3.90625
4
""" Exercise for database handling in Python """ database = b''' <database> <teachers> <teacher nr="1"> <name type="last">Deneire</name> <name type="first">Tom</name> </teacher> <teacher nr="2"> ...
0f7a0e5d41d8e79f56f1e30176af7f3951281531
catherineverdiergo/XebExercice
/mowerstestplayer.py
6,743
3.6875
4
# -*- coding:utf-8 -*- import re from mower import Mower UP_RIGHT_CORNER_PATTERN = re.compile('([-+]?\\d+) ([-+]?\\d+)') MOWER_STATUS_PATTERN = re.compile('([-+]?\\d+) ([-+]?\\d+) ([NESW])') def read_integer(matcher, grp_number, line_number): """ Parse an integer from a regex matcher able to parse strings...
39cfcffe9ef324a4de6bef8e5ccf1229ee8279f7
harshita0902/programming-exercises
/array_left_rotation.py
377
3.640625
4
def rotLeft(a, d): for i in range(d): # print(i) f = a[0] a.remove(f) a.append(f) return a if __name__ == '__main__': nd = input().split() n = int(nd[0]) d = int(nd[1]) a = list(map(int, input().rstrip().split())) # print(a) resu...
1ce00c88692041d91e398c76a53a610454f61ed7
sinth80/katas
/python/disemvowelTrolls.py
417
3.765625
4
def disemvowel(string): vowels = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"] strArr = list(string) count = 1 while count <= 10: testChar = vowels[count - 1] print(testChar) if testChar in strArr: strArr = ['' if wd == testChar else wd for wd in strArr] ...
638753d5cb295f5bb8af22c3bf67971ddcbb6720
Thanhthanhbinh/C4TA05_DTTB
/1_Dec/Session2.py
2,395
4.0625
4
''' |LIST| ---------------|THEORY|---------------- |||||||ROOM FOR IMPROVEMENTS||||||| NOTE: index: starts from 0 to n [-1]==[n] NOTE: loop: for i in list --print(value) loop: for i in range (len(list)) --print(index) loop: for i,j in en...
97a6bfa28fd7bf3e32a3483895d91c5a3f63bac7
Thanhthanhbinh/C4TA05_DTTB
/22_Dec/session5.py
2,089
3.953125
4
''' _________________________________________________|MERGE_SORT|_________________________________________- NOTE: ''' def merge_sort(nums): if len(nums)<=1: return nums mid=len(nums)//2 left_list=merge_sort(nums[:mid]) right_list=merge_sort(nums[mid:]) return merge(left_list,right_list) def ...
00c63f2572974a410eb7dfeaad043c1e067dfdf4
room29/python
/FOR.py
1,820
4.21875
4
# lista en python mi_lista = ['pocho', 'sander', 'caca'] for nombre in mi_lista: print (nombre) # Realizar un programa que imprima en pantalla los números del 20 al 30. for x in range(20,31): print(x) '''La función range puede tener dos parámetros, el primero indica el valor inicial que tomará la variable ...
9d2359ced2be3ae302168eb925cc6dc8d00f91bb
tsadev/Python-Scripts
/millionare.py
5,941
3.75
4
# millionare.py (By: Tomás A.) # This game has a total of 8 questions, with multiple answers (more to come) import time import random from random import randint playerBank = 0 print("Who wants to be a super millionare?") myName = input("What's your name little man? ") print("Welcome to the show, ", myName, "!") p...
088b3644fa1da2118badaf09a8e035d71e3395e1
KokuraSona/course-exercise-in-mechanical-design
/Code/rolling_bearing.py
1,888
3.609375
4
from math import ceil class rolling(): num=0 def __init__(self,P,n,d): rolling.num+=1 print("\n-----------------") print("Now, begin the design of rolling bearing on shaft {}.\n".format(rolling.num)) self.P=P self.n=n self.d_min=d self.T=9550*P/n...
a3ce324291a4b4d948b80fd873243cee0380d373
basfl/python-panda-example
/app.py
1,686
3.625
4
import pandas as pd import re df = pd.read_csv('data.csv') #df_xlsx = pd.read_excel('data.xlsx') # df_txt=pd.read_csv('data.txt',delimiter="\t") # print(df_txt) # print(df_xlsx) # print(df.head(3)) # print top 3 rows # print(df.tail(3)) # print bottom 3 rows # read headers : df.columns # read each/specific column e.g ...
1e4f3f87ac57841da31132f0ddbc2c9b30ff1edb
Saisurya03/Python_Numpy_Pandas
/python_square.py
151
3.71875
4
l = [1,2,3,4,5,6,7] print("Input list: {}".format(l)) x = 0 for i in l: i = i ** 2 l[ x ] = i x = x + 1 print("Output list: {}".format(l))
4049260e78af062fad0154de0dfdf4279da82f6d
Saisurya03/Python_Numpy_Pandas
/dict-4.py
113
3.78125
4
dictionary1 = {'a': 100, 'b': 200, 'c': 300} for i in dictionary1.values(): if i == 200: print("200 exists")
c0babd8461d2df8c5c3fe535b4fcc9ae15464adf
dcassells/Project-Euler
/project_euler001.py
565
4.46875
4
""" If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ def three_multiple(x): if x%3 == 0: return 1 else: return 0 def five_multiple(x): if x%5 == 0: return 1 else...
8b4dc7b2e54fd0f60a08fc54870f03efc2a36999
azlar911/azlar911.github.io
/python_practice/dataProcesser/mod2.py
595
3.828125
4
def md2(num1): num = num1 print("{0}'s Prime factories: ".format(num)) for i in range(2, num+1): count = 0 while True: if num % i == 0: count += 1 num /= i else: if count != 0: print("{0}^{1} ".f...
ed2f0f25bcca9c6220189d9de17563c91a2f3245
azlar911/azlar911.github.io
/python_practice/p47_3.py
235
3.5625
4
a = input("Input a date: (mm-dd)") mon = int(a[0])*10 + int(a[1]) day = int(a[3])*10 + int(a[4]) d = 0 md = [31,28,31,30,31,30,31,31,30,31,30,31] cmd = [0] for i in range(1, 12): cmd.append(cmd[i-1] + md[i-1]) print(cmd[mon-1]+ day)
6973208b6ddee93608ffaaedc35f07951e9dae32
azlar911/azlar911.github.io
/python_practice/p93_1.py
1,024
3.6875
4
with open("grades.txt", "r") as f: cont = f.read().split("\n") count = len(cont) while True: a = input("---------\noptions:\n1 to insert grades\n2 to print all records\n3 to print current grades average\n4 to quit\n---------\n") a = int(a) if a == 1: inp = int(input("Grades: ")) wit...
a5630bb8f963b397c84dd53c9bbf8574c837944e
azlar911/azlar911.github.io
/python_practice/dataProcesser/mod1.py
830
3.65625
4
def md1(ilist): for i in ilist: if not isinstance(i, int): print("There is a instance not an integer") return print("Sum: {0}".format(sum(ilist))) ilist.sort() if len(ilist)%2 != 0: a = ilist[int((len(ilist)+1)/2)] else: a = ilist[int(len(ilist)...
4814a899f2986e2f2af0029bf0658a2bb3f84716
exxmanster/introduction_python_hw
/task_14.py
322
3.984375
4
#task_14 ''' Написать функцию, которая будет проверять четность некоторого числа. def is_even(number): # returns boolean value pass ''' def is_even(number): if number %2==0: return True if number%2!=0: return False print(is_even(6))
034e5b7fe7945fb025d0cfe61fd2c86db02f9ff8
exxmanster/introduction_python_hw
/task_4.py
390
3.890625
4
#Task_4 ###Найти результат выражения для произвольных значений a,b,c: (a - b * c ) / ( a + b ) % c a = 25 b = -25 c = 18 if a + b != 0: result = (a - b *c) / (a + b) % c print('The result of (a - b * c ) / ( a + b ) %',' c a = %d for b = %d c = %d is equal to = %f' %(a, b, c, result)) else: print('Erro...
40465db59b8709f96c87e401dbe50512514809e8
exxmanster/introduction_python_hw
/test_5.py
294
3.890625
4
#test_5 def nearest_number(number_1, number_2): numbers = [number_1, number_2] numbers.sort(key=lambda elem: abs(10 - elem)) return numbers[0] number_1 = int(input('Enter first number:')) number_2 = int(input('Enter second number:')) print(nearest_number(number_1, number_2))
5af9348c7a72d67d0985911be231eb92519c8610
elagina/Codility
/lessons/lesson_1.py
580
4.15625
4
""" Codility Lesson 1 - Iterations BinaryGap - Find longest sequence of zeros in binary representation of an integer. """ def solution(N): bin_N = str("{0:b}".format(N)) max_counter = 0 counter = 0 for ch in bin_N: if ch == '1': if max_counter < counter: max_coun...
9e9b978d6b246752a05d8df18237a9665a2a3105
oooto/nlp100
/第1章_準備運動/ans08.py
231
3.6875
4
def cipher(org_str): org_str = [chr(219 - ord(s)) if 97 <= ord(s) <= 122 else s for s in org_str] return "".join(org_str) org_str = 'ParaParaParadise' ans = cipher(org_str) print(ans) ans = cipher(ans) print(ans)
4b1c6406fc8f915545d4c4d5fadf9c4f3fe7dd30
faniislahul/poxpro
/_djikstra_networkX.py
31,583
4.71875
5
def dijkstra_path(G, source, target, weight='weight'): """Returns the shortest weighted path from source to target in G. Uses Dijkstra's Method to compute the shortest weighted path between two nodes in a graph. Parameters ---------- G : NetworkX graph source : node Starting node ...
a2a5f8cb14271d88f72aec40ed0fda7e0116eed8
josemigueldev/algoritmos
/01_calcular_edad.py
1,029
3.5625
4
# Calcular la edad de una persona pasando como parametro la fecha de nacimiento from datetime import date def calcular_edad(fecha_nacimiento): # obtenemos la fecha de hoy hoy = date.today() # 2021-08-22 (ejemplo) try: # sustituimos el año de nacimiento por el actual para comparar solo # l...
b3bd54dd4116a00744311a671f01040d70799f98
josemigueldev/algoritmos
/07_factorial.py
442
4.21875
4
# Factorial de un número def factorial(num): result = 1 if num < 0: return "Sorry, factorial does not exist for negative numbers" elif num == 0: return "The factorial of 0 is 1" else: for i in range(1, num + 1): result = result * i return f"The factorial of ...
4edab4f21df3b90f460ed1075405737271336f36
qwertyAAA/common_data_structure
/bidirectional_tree.py
6,692
3.734375
4
from collections import deque from typing import Any, Optional, List, Dict, Generator class Node(object): """ the Node object of BidirectionalTree """ def __init__(self, parent: Optional[Any] = None, data: Optional[Any] = None, children: Optional[List[Any]] = None) -> None: s...
c5cdfbda5e8cb293bb7773ef345ddb5c8157313e
udhay1415/Python
/oop.py
861
4.46875
4
# Example 1 class Dog(): # Class object attribute species = "mammal" def __init__(self, breed): self.breed = breed # Instantation myDog = Dog('pug'); print(myDog.species); # Example 2 class Circle(): pi = 2.14 def __init__(self, radius): self.radius = radius ...
7e3e0e8a6f5fcce127d6687b993574a78371d76e
tomatolike/raspi-car
/carside/test.py
802
3.75
4
from control import CONTROL controller = CONTROL() while True: order = raw_input("Input order:\n") if(order == "G" or order == "g"): controller.forward() if(order == "B" or order == "b"): controller.back() if(order == "L" or order == "l"): controller.left() if(order == "R" ...
ef0df63e33ee12558c61e2307e13f513cac81abe
pntehan/The-higher-study-about-python
/attr_mro.py
504
3.9375
4
# 类和实例属性的查找顺寻 class A: name = 'A' def __init__(self): self.name = 'obj' a = A() print(a.name) print(A.name) # 实例属性的查找是自下而上的, 现在实例属性中查找, 再在类属性之中查找 # C3算法, 确定类的查找顺序 class D: pass class C(D): pass class B(D): pass class A(B, C): pass print(A.__mro__) class five: pass class four: pass class three(five): ...
3989fb0f68ca8365a0c197138efce6025c2c45a2
pntehan/The-higher-study-about-python
/ThreadPool.py
1,207
3.71875
4
# # python线程池操作 # from concurrent.futures import ThreadPoolExecutor, as_completed, wait, FIRST_COMPLETED # import time # # def get_html(page): # time.sleep(1) # # print('Get {} success.'.format(page)) # return 'Get {} success.'.format(page) # # executor = ThreadPoolExecutor(max_workers=3) # # 此处创建了一个线程池,最多开启三个线程 # #...
96f8b4a09b7927fe2beede6f99806df726373241
pntehan/The-higher-study-about-python
/progress_test.py
3,710
3.5
4
# # 多进程编程 # # 进程切换代价高于线程切换,多进程是多cpu操作,所以在耗cpu操作时用多进程,耗IO操作用多线程 # from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor, as_completed # import time # # # def fib(num): # if num <= 2: # return 1 # else: # return fib(num-1) + fib(num-2) # # # if __name__ == '__main__': # with ThreadPoolExecutor(max...
c66482b12fc0601302e7d087b5322a8d34a95a71
bhargavsaidasari/Algorithms
/Median Maintanence/heap.py
2,177
4
4
def swap(array,index_1,index_2): array[index_1],array[index_2] = array[index_2],array[index_1] class Heap: def __init__(self,array): self.array = array #Indices to keeptrack of the original location of each element in the heap self.__heapify() def __str__(self): return...
42fef0971ae40aca1c4a9f483d128703b1a989f3
KyleMMoore/Snabe
/body.py
7,795
3.515625
4
import pygame from global_toolbox import GlobalSettings class Body: def __init__(self, screen, head, global_vars, segment_number): # Useful game elements self.screen = screen self.screen_rect = self.screen.get_rect() self.snabings = GlobalSettings() self.gv = global_vars ...
da07996a003eac9a5499efef17ee95ac828dc82b
Pancinator/hacker_rank_practise
/largest_connected_region_DFS.py
1,110
3.828125
4
def get_biggest_region(matrix): max_cell_counter = 0 for row in range(len(matrix)): for col in range(len(matrix[row])): if matrix[row][col] == 1: size = _get_biggest_region(matrix, row, col) #pass the currnet location to recursive function max_cell_cou...
d4816cb2b3542c5f1f66c443557afa9a27e88c4d
Pancinator/hacker_rank_practise
/binary_search_example_facebook.py
988
3.828125
4
def find_element(arr, element): min = 0 max = len(arr) mid = (max + min) // 2 left_index = 0 right_index = 0 while True: if arr[mid] == element: index = mid break elif element > arr[mid]: min = mid + 1 mid = (max + min...
f71123356170785cf7fd7a70c56015d4b4a737b6
pleung1987/DojoAssignment
/Python/Python_Fundementals/CoinToss.py
634
3.796875
4
import random def coinToss(): number = 5000 heads = 0 tails = 0 for amount in range(5000): flip = random.randint(0, 1) coin = "Heads" if flip == 1 else "Tails" if (flip == 0): print "Throwing a coin... It's a tails! ... Got", heads,"head(s) so far and", tails,"t...
b933eb9e17fadffc3dbc89e083c3fa13b9fd329b
pleung1987/DojoAssignment
/Python/Python_Fundementals/pythontest.py
236
3.984375
4
print 4 + 5 print 18 - 5 print 4*7 print 31/2 # If you divide an integer by an integer, the result will always be an integer rounded down. print 9.0/4 print 9.0/4.0 # If either number is a float, the result of the division is a float!
6d881d4c9a442ea9525046e24a9dd97b2f2293f2
StellaStoyneva/python-refresher
/find_first_phone_number/find_first_phone_number.py
908
3.625
4
import re phonebook_data = [ {'name': 'John Doe', 'phones': '0888463789 / /032/ 26 74 27'}, {'name': 'Corey Lee', 'phones': '052 62-47-72 | 003590988371591'}, {'name': 'Reece Russell', 'phones': 'every working day +359 32 267453; supervisor +359889-463789'}, {'name': 'James Thomas', 'phones': ' (032...
0816f69a8f61da6f2910f6f1369ba351a9810e6a
yallyyally/algo-moreugo
/Section3. 탐색&시뮬레이션/봉우리.py
575
3.65625
4
import sys def countTop(board,N): #봉우리 수 리턴 cnt=0 for i in range(1,N+1): j=1 while j<N+1: around = list((board[i-1][j],board[i+1][j],board[i][j-1],board[i][j+1])) if all (x<board[i][j] for x in around ): cnt+=1 j+=2 else: ...
a63723748543a840b2f7652190658305424e2fd5
yallyyally/algo-moreugo
/Syntax of Python/02.자료형/02-2.문자열.py
5,411
4.0625
4
#02. 파이썬 프로그래밍의 기초, 자료형 #########################02-2문자열 자료형######################### #큰 따옴표, 작은 따옴표, 큰따옴표3개, 작은 따옴표 3개 sent1 = "Hello" sent2='World' sent3="""!!!""" sent4='''hi~''' #문자열 더하기 print(sent1+sent2+sent3+sent4) #HelloWorld!!!hi~ #문자열 길이 print(len(sent1))#5 #문자열 인덱싱 a = "Hello world!" print(a[-1]) #! prin...
afc63420558ab8f3981a04f3575eda664e9c0ba0
yallyyally/algo-moreugo
/Syntax of Python/03.제어문/03-1.if문.py
358
3.796875
4
#03. 프로그램의 구조를 쌓는다!제어문 ######################### 03-1. if문 ######################### money=2000 card=True if money>=1500 or card: #|| 말고 or! print('택시타긔') else: print('걸어가긔') #다중 if문 x=93 if x>=90: print('A') elif x>=80: print('B') elif x>=70: print('C') else: print('F')
b6d319d3c1675663a9bb8988e67d0e2460d0f1f4
yallyyally/algo-moreugo
/Syntax of Python/03.제어문/03-2.반복문.py
1,467
3.78125
4
#03. 프로그램의 구조를 쌓는다!제어문 ######################### 03-2. 반복문 ######################### a = range(1,10) #1~9까지 정수 리스트 만듦 b = range(10) #0~9까지 리스트 만듦 print(list(a)) #a를 list 화 #[1, 2, 3, 4, 5, 6, 7, 8, 9] #1. for문 for i in range(10): # print("hi "+str(i)) print("hi",end=str(i)) #나의 예상: hi0\nhi1\n.. #출력 결과:...
bb4e784993467ea1317a32818d070a00e0530287
monroy8888/SIATA
/reto3.py
2,081
3.609375
4
""" --- Analisis de datos: Problematica: -Crear un sistema de informacion que permita concer la ubicacion de sus rcuersos: (paquetes , vehiculos y personal operativo) en tiempo real. RF01: 1-Listar las ubicaciones con su numero de casos asociados para un dia especifico. 2-Listar las ubicaciones con su numero de ...
5a4f3fd9706e338a2dd3731efe3fc022f35f476e
Mariia-Kosorotykova/python-education
/Python_OOP_hw1/transport_oop.py
6,898
4.71875
5
"""This module provides general description of Transport. Exercise: - Practice in creating classes from zero and inheritance from another classes - Create class Transport, think about attributes and methods, supplement the class with them - Think and implement the class - inherited class Transport (min 4), redefine me...
5b292d78832c91ac6f53e07a96bc5b078a621463
Mariia-Kosorotykova/python-education
/algorithms_practice/tests/test_binary_search.py
701
3.5
4
"""Implements unit tests binary_search method for algorithms.py""" import pytest import random from algorithms_practice.basic_algorithms.algoritms import binary_search def random_list_for_b_search(): r_list = [-3, 0, 1, 3, 5, 7, 9, 10, 67, 257, 435] item = random.choice(r_list) list_items = [random.choic...
31820429a481764c15f599938e238c1534e1040f
Mariia-Kosorotykova/python-education
/data_structures/tests/test_stack.py
1,101
3.625
4
"""This module describes unit testing for module stack.py""" import pytest from data_structures.basic_data_structure.stack import Stack def test_pushed_stack(): pushed_stack = Stack() pushed_stack.push(1) pushed_stack.push(2) pushed_stack.push(3) assert pushed_stack.display() == print(1, 2, 3, se...
ae3487f0bd596714227cde7eef294389b1b9ef61
Mariia-Kosorotykova/python-education
/python_HW_2/ex12_sets.py
371
4.0625
4
"""This module describes the solutions from the learnpython.org. Exercise: In the exercise below, use the given lists to print out a set containing all the participants from event A which did not attend event B. """ a = ["Jake", "John", "Eric"] b = ["John", "Jill"] if __name__ == "__main__": a_set = set(a) ...
30d9a57f023dacb9ade449c4c844b404e5fb2fd0
Dragoncall/Project_Euler
/6.py
239
3.890625
4
def sum_of_squares(max): return sum([i * i for i in range(1, max + 1)]) def square_of_sum(max): x = sum([i for i in range(1, max + 1)]) return x*x if __name__ == '__main__': print(square_of_sum(100) - sum_of_squares(100))
77b87cca77d0d3daa1c7213425f393f54487793e
Dragoncall/Project_Euler
/20.py
198
3.5625
4
from functools import reduce def factorials(n): return reduce(lambda x, y: x * y, [i for i in range(1, n)]) if __name__ == '__main__': print(sum([int(i) for i in str(factorials(100))]))
827d9fcbbf9c329e0d5e55901c012439c2050ccd
JamesWClark/Game-of-Circles---Python
/GameOfCircles/Enemy.py
288
3.5
4
from Sprite import Sprite class Enemy(Sprite): velocity = PVector(8, 0) c = color(0,0,255) def move(self): super(Enemy, self).move() self.pos.add(self.velocity) if self.pos.x < 0 or self.pos.x > width: self.velocity.x *= -1
e59ad19d126050d7eac15d5fcf8f816d11cef1ee
serinamarie/CS-Hash-Tables-Sprint
/applications/crack_caesar/crack_caesar.py
2,324
3.765625
4
# Use frequency analysis to find the key to ciphertext.txt, and then # decode it. # Unable to solve this one at the moment :/ def crack(filename): # open file with open(filename, 'r') as f: # set string text to variable string = f.read() # create an empty dict letter_dict = {} ...
4647f2fad080340252f2bd7f2b66fd05698bbcd0
datcua9x/HackerRank
/Easy/TimeConversion.py
754
4.0625
4
""" Given a time in 12-hour AM/PM format, convert it to military (24-hour) time. """ def timeConversion(s): """ :param s: string of time(must be in format hh:mm:ssAM or hh:mm:ssPM) :return:string of time in military time hh:mm:ss """ # Checking if last two elements of time is AM and first two elem...
68049296af4614c822bb3b95e00cdf1bef0d3350
MoravianCollege/ImageProcessingF2020
/zerocross.py
352
3.65625
4
def zerocross(im): """Finds the zero-crossing in the given image, returning a binary image.""" from numpy import pad p = im[1:-1,1:-1] u,d = im[:-2,1:-1], im[2:,1:-1] l,r = im[1:-1,:-2], im[1:-1,2:] out = (((p<0)&((u>0)|(r>0)|(d>0)|(l>0))) | ((p==0)&(((u<0)^(d<0))|((r<0)^(l<0))))) ...
0dd2e58546521da6931ed25d5bb71fcb719f4ee9
ethanhart/rosalind
/subs/subs.py
712
3.515625
4
#!/usr/bin/env python # encoding: utf-8 """ Given: Two DNA strings s and t (each of length at most 1 kbp). Return: All locations of t as a substring of s. """ from sys import argv __author__ = "Ethan Hart" def find_substring(orig_string, substring): instances = [] for i in range(len(orig_string)): ...
ef745d73f62e5a6045017b452d2adccca204f8cd
Rohit-Verma8240/Python-100-Days-Challenge
/Day-2/Project/Tip_Calculator.py
338
3.96875
4
total_bill = float(input("What was the total bill? $")) tip = int(input("What percentage tip would you like to give? 10,12 or 15? ")) split_bill = int(input("How many people to split the bill? ")) billwithtip = (total_bill * (1 + tip /100)) finale_bill = round((billwithtip / split_bill),2) print(f"Bill for each perso...
d5fa275d39808648247efb3e8128fb43f9a2c22a
juliiette/bigdata_labs
/lab7/length_reducer.py
872
3.640625
4
"""Подсчитывает количество слов каждой длины.""" import sys from itertools import groupby from operator import itemgetter def tokenize_input(): """Разбивает каждую строку стандартного ввода на ключ и значение. """ for line in sys.stdin: yield line.strip().split('\t') # Построить пары "ключ-значен...
2364321fc5b36d9ae7c78c612e3ac354a49f6417
dasaripragna/if_else
/sum.py
127
3.5
4
def fun(a): sum=1 i=0 while i<len(a): sum=sum+a[i] i=i+1 return sum a=[8,2,3,0,7] print(fun(a))
35dc0a434e3368fca11a72552409648ff109a37b
Sterling3Rapp/Week-1-
/Guess.py
245
4.03125
4
import random secret = random.randint(1,10) for i in range(0,3): guess = int(input("Guess a number: ")) if guess == secret: print("You Win!!") break else: print("You Lose! The number was actually ", secret)
87db53e2cbde1cbcb4781f7a3a4a777b7f90934b
GiHyeonAn/programming-practice
/python practice/day08.py
3,605
3.625
4
# if ~ elif 문 # elif는 if문을 사용할 때 여러개의 조건식을 사용하고 싶을 때 쓰는 문법입니다 # if문의 조건식이 거짓일 경우 elif의 조건식을 비교합니다 # elif의 조건식에서 결과가 참이면 더이상 그 아래에 있는 문장은 실행하지 않습니다 # (elif의 조건식에서 결과가 참이면 그 아래에 있는 같은조건식 문장은 실행됩니다) # elif는 독립적으로 사용할 수 없습니다 반드시 if와 같이 사용합니다 # elif조건식 뒤에 else사용 가능합니다 # 순서, 조건식의 범위설정 중요 # num = int(input("정수를 입력하세...
f7ba7fbb5be395558e1d8451e6904279db95952d
Nour833/MultiCalculator
/equation.py
2,637
4.125
4
from termcolor import colored import string def equation(): print(colored("----------------------------------------------------------------", "magenta")) print(colored("1 ", "green"), colored(".", "red"), colored("1 dgree", "yellow")) print(colored("2 ", "green"), colored(".", "red"), colored("2 degree...
d7447cb60c0e48e90a58569cd4b6eda1847252d4
sjain02/python-learning
/car_inheritnace.py
1,341
3.96875
4
class Car(): def __init__(self, make, model, year): self.make=make self.model=model self.year=year self.odometer_reading=0 def get_descriptive_name(self): long_name=str(self.year)+ ' '+self.make+' '+self.model return long_name.title() def read_odomet...
0512efcb54b9e64b56b70ca860d5a11a1f867082
eduardoritter/hr_python
/statistics/standard_deviation.py
402
3.8125
4
#number = int(input()) #elements = list(map(int, input().split())) elements, number = [10, 40, 30, 50,20] , 5 mean = sum(elements) / number squared_distance = [(e - mean) ** 2 for e in elements] #the power of 0.5 is the same as square root print("%.1f" %(sum(squared_distance) / number ) ** 0.5) """ Solution us...
88f8018380404a76f38e852176d7a00ca3da835b
shaozhenyu/pythontool
/leetcode/solution.py
304
3.515625
4
#!/bin/python def moveZeroes(nums): # length = len(nums) # i = 0 # num = 0 # while i < length: # if nums[i] == 0 and i < length - num: # del nums[i] # nums.append(0) # num += 1 # else: # i += 1 nums.sort(key=lambda x:x==0) nums = [0, 1, 0, 2, 0, 0, 4, 4, 4, 0] moveZeroes(nums) print nums
b83be17f80a7ca243f7e1a47c4de9da804ef4b28
marcello-telles/Python-URI-Challenges
/1012.py
358
3.578125
4
pi = 3.14159 inp = input().split() a, b, c = float(inp[0]), float(inp[1]), float(inp[2]) triang = a * c / 2 circ = pi * c**2 trap = (a + b) * c / 2 quad = b**2 retang = a * b print('TRIANGULO: %.3f' % (triang)) print('CIRCULO: %.3f' % (circ)) print('TRAPEZIO: %.3f' % (trap)) print('QUADRADO: %.3f' % (quad)) ...
983ee19464c2fb2b8698f9e4a8413aaba47689bb
ScarlettBian/DataCamp_Python-Intro
/DataCamp_PythonIntro.py
14,473
4.5625
5
########################### Section1 Python Basics ########################## # Example, do not modify! print(5 / 8) # Put code below here print (7+10) 7+10 # Division print(5 / 8) # Addition print(7 + 10) # Addition, subtraction print(5 + 5) print(5 - 5) # Multiplication, division, modulo, and exponentiation ...
5a8c9067842ce46ce5ba79bcc97c0c52f2e72438
riceb53/data-analysis
/prac.py
781
3.734375
4
# with open("/Users/Apprentice/documents/new-york-city-current-job-postings/nyc-jobs.csv") as f: # # print(f.size()) # index = 0 # for line in f: # print() # print(line) # index += 1 # print(index) import csv with open('/Users/Apprentice/documents/new-york-city-current-job-postings/...