blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
9e57a0f694622cd1b0b67e17f4adcd790535b2f2
himal8848/Python-Beginner-Projects
/comprehensions.py
496
4.28125
4
#List comprehensions lst = [i for i in range(100) if i % 3 ==0] print(lst) #dictionry comprehension dict = {i:f"item{i}" for i in range(5)} print(dict) dict1 = {value:key for key,value in dict.items() } print(dict1) #Set comprehensions #It does not print repeatable value st = {i for i in [2,4,5,3,3,4,5,3] if i % 2 =...
a9ac520b1a01cdacea55462697ad5cbd64db577e
typemegan/Python
/CorePythonProgramming_2nd/ch08_loops/countWords.py
244
3.984375
4
#!/usr/bin/python ''' script for counting words of a given file key point: list comprehensions ''' fname = raw_input('enter a file path> ') count = sum(len(words) for line in open(fname,'r') for words in line.split()) print 'words:',count
4d0167519427aeaee1ac31fa5a65ad455cbfd8dd
Mgtcaleb/Health-Management-System-1.0
/HMS.py
3,324
3.921875
4
#This is the code to execute simple data whiuch is based on food and exercise of individual person #Author:Caleb Gore; Date of Code Creation: 11:50 A.M, 20.08.2020. """ Notes: 1.Time stamp contains both number and : so predefine the data type as string 2. It is important to import built-in function (dateti...
94b82e69a4a57360362b4c729f1236d07933a00a
sagarrjadhav/Problem-Solving-in-Data-Structures-Algorithms-using-Python
/Heap/MedianHeap.py
1,939
3.59375
4
#!/usr/bin/env python import heapq class MedianHeap(object): def __init__(self): self.minHeap = [] self.maxHeap = [] def MinHeapInsert(self, value): heapq.heappush(self.minHeap, value) def MaxHeapInsert(self, value): heapq.heappush(self.maxHeap, -1 * va...
26c9f7e383cce71cde211cd35562d951f7c64c54
RAJARANJITH1999/Python-Programs
/even.py
214
4.1875
4
value=int(input("enter the value to check whether even or odd")) if(value%2==0): print(value,"is a even number") else: print(value,"is odd number") print("vaule have been checked successfully")
d067d0f200cf65ab05128444894a24191db2ac93
RoseMagura/AlgorithmNotes
/Python_Exercises/heap_sort.py
5,363
4
4
from collections import deque class Node(object): def __init__(self,value = None): self.value = value self.left = None self.right = None def set_value(self,value): self.value = value def get_value(self): return self.value def s...
c7fabd810b612e7d86760814041a1a4acc5f8201
jan-2018-py1/Python_Anton
/Python/Fun with Functions.py
650
4.21875
4
#Odd/Even: def odd_even(): for i in range(1,2001): if i%2 == 0: print "Number is ", i, "This is an even number" else: print "Number is ", i, "This is an odd number" #odd_even() def multiply(incoming_list, value): result=[] for key in incoming_list: result.a...
48a554771654d67bce5b298070d58ccfc790da50
Naveduran/holbertonschool-higher_level_programming
/0x0F-python-object_relational_mapping/5-filter_cities.py
977
3.515625
4
#!/usr/bin/python3 '''my module 1''' import MySQLdb from sys import argv def Filter_Cities(username, password, db_name, state_name): '''receive a city name as argument and list it's cities''' # Open database connection db = MySQLdb.connect(host="localhost", port=3306, user=username, ...
60e268d79364768ec389988f9268edba0145eddb
mkoundo/Automate_the_Boring_Stuff
/chapter_19_Images/custom_seating.py
2,771
4.40625
4
#! python3 # custom_seating.py # Author: Michael Koundouros """ Chapter 15 included a practice project to create custom invitations from a list of guests in a plaintext file. As an additional project, use the pillow module to create images for custom seating cards for your guests. For each of the guests listed in the g...
91d54b639a5399c5f5067a7e51675d14b7853c79
Kalliojumala/School-Work
/Week 3/Week3_hard/hard3.3.py
746
4.03125
4
#even or odd number def even_or_odd(num: int): return num % 2 == 0 def even_and_compare(): #takes 2 numbers as input num = int(input("Syötä kokonaisluku: ")) compare = int(input("\nSyötä vertailuluku: ")) #comparison block, self explanatory imo! if even_or_odd(num): print("\nSyött...
2029516113189f6ff938ed936c698dbf5ed754db
damonchen/pytimer
/timer.py
3,882
3.515625
4
#!/usr/bin/env python # coding=utf-8 # author: damonchen # date: 2018-02-07 # 给公司内部做培训,编写一个Hierarchical Timing Wheels的timer的实现 class Slot(list): pass class Wheel(object): def __init__(self, size): self.size = size # 0~59, or 0~23 self.pointer = 0 # wheel指针,达到wheel_buffer尾部后会重...
d122e317db05f4bc6646a27fe9e6cf975f4e25df
Punit-Choudhary/Python-PatternHouse
/Series Patterns/CodeFiles/Pattern8.py
442
4.21875
4
""" In this program, we print the series of prime numbers up to 'n'. * First we check each number (1 to n) for prime number. * If the number is prime we print it. """ n = 10 # size num = 1 count = 0 while (num <= n): for x in range(1, num + 1): if (num % x == 0): count += 1 if (count == 2...
dbfb52350d52c7834c25eae0d49ef1fd604f919e
allenfrostline/Tetris-AI
/genetic_algorithms.py
6,357
3.5
4
# chromosome = heuristics dictionary # populations = [chromosome] # fitness function = score/lines # selection = top X (elitism)/tournament/roulette/others # crossover = pick attributes from parents randomly/average attributes/others # mutation = assign random value/random variance from tetris import TetrisApp from ai...
4780d5db192141091b881ba6071f7a51c9e15eb4
evanpelfrey00/python-assignments
/HW06_EvanPelfrey.py
2,507
3.6875
4
#Exercise 1 def twoWords(length, firstLetter): returnList = [] word = input('A ' + str(length) + '-letter word, please: ') if len(word) != length: while len(word) != length: word = input('A ' + str(length) + '-letter word, please: ') if len(word) == length: ...
4725a9282852fdbeef337745a9090a42fe1bd5e9
Cunningham-Wayne-Jeremy/lpthw
/022/ex22.py
2,806
4.59375
5
# List all of the key words and symbols that I now know and write its # name and what it does next to the code. MAKE A COMPLETE LIST print("This is my list of code that I now know for Python: ") print("# is the comment character") print("print will echo to the terminal") print("""f can be used in every single functio...
cf03db1459a35800854dc3ee76a455d96a0f99f6
dvanderk/twitter_analysis
/top_ten.py
1,136
3.65625
4
# Computes ten most frquently occuring hashtags from a json file of twitter data # Runs from the comnand line: python top_ten.py <tweetfile> import os import json import sys import types def main(): tweets = open(sys.argv[1]) #read in command line argument -- file from twitter stream hashtag_freq = {} #hasht...
15c028fa81a3add76da690197035ce42e4f8bb4d
UMKCRobotics/2016-2017-TunnelGeneral
/Competition Game/src/Grid_Util.py
1,444
3.59375
4
# Utility classes for using a grid GRID_WIDTH = 7 GRID_HEIGHT = 7 DISPLAY_WIDTH = 8 DISPLAY_HEIGHT = 8 # this is an enumeration, but we can't use enumerations because someone doesn't update their python class Knowledge: # class Knowledge(IntEnum): def __init__(self): pass unknown = -1 yes = 1 ...
2d5d4da584dd1e87a2b205dec8d1e1df69f97744
brenopolanski/labs
/python/basic/lambda.py
235
3.75
4
lamb = lambda x: x ** 3 print(lamb(3)) def writer(): title = 'Sir' name = (lambda x: title + ' ' + x) return name w = writer() print(w('Breno Polanski')) L = [lambda x: x ** 2, lambda x: x ** 3, lambda x: x**4] for f in L: print(f(3))
82d7a60738be069d790b8131899f043cb1977b2f
BParesh89/The_Modern_Python3_Bootcamp
/decorators/delay.py
289
3.5625
4
from functools import wraps from time import sleep def delay(time): def inner(fn): @wraps(fn) def wrapper(): print(f"Waiting {time}s before running {fn.__name__}") sleep(time) return fn() return wrapper return inner @delay(3) def say_hi(): return "hi" print(say_hi())
453c942eda820ad7715f141d743167c4cb6fa638
athena15/leetcode
/longest_substring.py
574
3.53125
4
from collections import defaultdict class Solution: def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ d = defaultdict(int) start = 0 stop = 1 length = 0 longest = 0 while s[start] == s[stop]: stop += 1 length += 1 if length > longest: longest = length if s...
ceaf3208a60663be216e95ea415b97a7b6797409
garciaac/Hackerrank-Challenges
/Implementation/Easy/caesar-cipher/caesar_cipher.py
433
3.765625
4
if __name__ == "__main__": n = int(input()) s = input() k = int(input()) encrypted = "" for ii in range(n): if s[ii].isalpha(): if s[ii].isupper(): encrypted += chr(ord("A") + (ord(s[ii])-ord("A")+k)%26) else: encrypted += chr(ord(...
014f962cbc866c84008399d910b9d78ffbbe0601
sonamk15/codesignal_questions
/adjacentElementsProduct.py
237
3.609375
4
def adjacentElementsProduct(array): num=-100 i=0 while i<len(array)-1: if array[i]*array[i+1]>=num: num=array[i]*array[i+1] i+=1 return num print (adjacentElementsProduct([5, 1, 2, 3, 1, 4]))
0b8b553a9dd25de1fd2bd9e009eba3e2b791b0d9
TMcMac/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/2-uniq_add.py
148
3.84375
4
#!/usr/bin/python3 def uniq_add(my_list=[]): uniq_list = set(my_list) sum = 0 for num in uniq_list: sum += num return sum
197c54999a1958ac595a386f1d0f4f86ba612150
davelasquez12/PythonPractice
/algos/sliding_window.py
3,327
3.53125
4
def longestSubStrWithAtLeastKRepeatedChars(s, k): if k > len(s): return 0 max_unique = len(set(s)) result = 0 for num_unique_expected in range(1, max_unique + 1): count_map = [0] * 26 window_start, window_end, alphabet_index, num_curr_unique_in_window, numCharsInWindowWithAtLea...
54cbed599b642c36c3c54ec50bd073b54bb428b5
abdulkaderm11/BlackMagician
/PythonBasic/Find_Angle_MBC.py
663
4.1875
4
''' ABC = 90° Point M is the midpoint of hypotenuse AC. You are given the lengths AB and BC. Your task is to find MBC in degrees. Input Format The first line contains the length of side AB. The second line contains the length of side BC. Output Format Output MBC in degrees. Sample Input 10 10 Sample Output 45°...
b1ff068536ee0e488edd932a82ea1692e36b1176
fernandodmaqueda/practicasprofexo
/C - Trabajo práctico 1/TP34.py
2,732
3.625
4
#TP34 #Problema: TP34 - Escribí funciones que dada una cadena y un carácter: # a) Inserte el caracter entre cada letra de la cadena. Ej: 'separar' y debería devolver ’s,e,p,a,r,a,r' # b) Reemplace todos los espacios por el caracter. Ej: 'mi archivo de texto.txt' y '_' debería devolver ‘mi_archivo_de_texto.txt' # c)...
f7eb89931f071c0c79f70cfdf46f7df50a885cb0
Ralph-Wang/MyPythonCookBook
/modules/use_pipe.py
354
3.734375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # pipe 库需要额外安装 from pipe import * def fib(): a, b = 0, 1 while True: yield a a, b = b, a + b # 小于 1000 的斐波那契数的奇数和 answer = fib() |\ take_while(lambda x : x < 1000) |\ where(lambda x : x%2 == 1) |\ add print answer
ea2d7f4c42d0d61382afeb3efbfc21bade41f8df
robotlightsyou/pfb-resources
/sessions/002-session-strings/exercises/string_methods_video.py
665
4.0625
4
#! /usr/bin/env python3 ''' Ask the user for input, modify the return ''' #print("helloworld") import sys global_var = "howdy" def main(data): print_some_word(data) data = 'test' print_some_word(data) def print_some_word(word): print(word) if __name__ == "__main__": someword = 'blue' m...
923ae602bfb9982100192b7eb0fb0d5ce178c2ef
garuan2/Algorythms
/nearest_zero.py
817
3.625
4
# passed tests ID: 52304665 def nearest_zero(length, numbers): left_array, right_array = [], [] counter = length - 1 for item in numbers: if item == 0: counter = 0 else: counter += 1 left_array.append(counter) counter = length - 1 for it...
7c89a8fd3525d0577e9fc3534a3025375479ff44
1286211699/mmc_code
/1_10_面向对象的三大特征/03_game_test.py
1,072
3.640625
4
#!/usr/bin/python # -*- coding: utf-8 -*- # @Time : 2019/4/15 21:08 # @Author : Xuegod Teacher For # @File : 03_game_test.py # @Software: PyCharm # 简单的游戏,利用一个类创建Game类? # 要求: # 1、 玩家可以自己输入自己的名字和姓名 # 2、 登录后开始游戏就会打印“帮助信息” # 3、 帮助信息的下方会出现最高分 # 4、 启动游戏会打印欢迎字句 # 5、 利用类方法,静态方法完成 class Game: def __init...
62711d5d30533221556db171bbde2684d91b7ad9
tututuana/MazeGenerator
/main.py
6,418
3.65625
4
import random from colorama import Fore, init def printMaze(maze): for i in range(0, height): for j in range(0, width): if (maze[i][j] == 'u'): print(Fore.WHITE + str(maze[i][j]), end="") elif (maze[i][j] == 'c'): print(Fore.GREEN + str(maze[i][j]), end="") else: print(Fore.RED + str(maze[i][j]...
02e044728fe04d2754221f08ca5af2ce248d5f29
ReneNyffenegger/about-python
/types/set/set-operators.py
243
3.796875
4
even = { 2, 4, 6, 8, 10, 12 } odd = { 1, 3, 5, 7, 9, 11 } prime = { 2, 3, 5, 7, 11 } print(prime - odd) # # {2} print(prime & even) # # {2} print(even | prime) # # {2, 3, 4, 5, 6, 7, 8, 10, 11, 12} print(odd ^ prime) # # {1, 2, 9}
6f6b6b8c3226b1f98af94c66635376fdfcda1c4e
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/Python_Hand-on_Solve_200_Problems/Section 15 Sort/merge_sort_implement_solution.py
1,560
3.859375
4
# # To add a new cell, type '# %%' # # To add a new markdown cell, type '# %% [markdown]' # # %% # # Write a Python program to sort a list of elements using the merge sort algorithm. # # Note: According to Wikipedia "Merge sort (also commonly spelled mergesort) is an O (n log n) # # comparison-based sorting algorithm. ...
b74c5ad63523c58a2189bb4477362b007672eb24
yrmt/python
/b-设计模式/b_16_迭代子模式.py
771
3.9375
4
# 迭代器 class Iterator(object): def __init__(self, collection): self.names = collection self.index = 0 def __iter__(self): self.index = 0 return self def __next__(self): if len(self.names) > self.index: name = self.names[self.index] self.index ...
39b146d0acbca2a9576b85e38f978c6e93c7a49a
JCVANKER/anthonyLearnPython
/learning_Python/basis/异常/ZeroDivisionError/ZeroDivisionError.py
991
4.125
4
""" 异常的特殊对象管理程序执行期间发生的错误 每当发生让Python不知所措的错误时,都会创建一个异常对象 try-except代码块: 如果try代码块中的代码出现错误,执行except,若except指定的错误与引发的错误 相同,则运行其中的代码; try-except-else代码块: ...;如果try代码块中的代码执行成功,则运行else代码块内代码 可能引发异常的代码才需要放入try语句中,在try代码块成功执行时才需要运行else代码块 中的代码。 """ print("Give me two number, and I'll divide them.") print("Enter 'q' ...
4df318e97ad8c36e103a5ba30fa36b0b1393dcfb
joeyhachem/Treasure-Maze-Search
/Bfs-A-Star-Search.py
5,847
3.59375
4
import sys import helper from functools import cmp_to_key start = 13, 2 treasure = 5, 23 bfs_path = [] nodes_explored = 0 path_hash_map = {} # Returns the cost from node passed to start node def get_cost_from_node_to_start(j: int, i: int): # Print path from start to end current = (i, j) counter = 0 ...
ad31f0e98a97adb13b83302761675232f4606545
sonalinegi/Training-With-Acadview
/regular.py
1,449
3.8125
4
#Extract user id,domain name and suffix from the given email addresses. emails="zuck@facebook.com page33@google.com jeff42@amazon.com" import re pattern=r'(\w+)@([A-Z0-9]+)\.([A-Z]{2,4})' print("Output:") print(re.findall(pattern,emails,re.IGNORECASE)) #Retrieve all words starting with 'b' or 'B' from the given text. ...
ed6fcb9c2ae8e9521c9b4592e78337f145392b48
himanshu2922t/FSDP_2019
/DAY-02/translate.py
457
4.125
4
# -*- coding: utf-8 -*- """ Created on Tue Jun 4 15:05:28 2019 @author: Himanshu Rathore """ def translate(string): translated_string = "" for char in string: if char in ('bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ'): translated_string += char+'o'+char else: transl...
b82805c0e4b17bfd1df4244f44f9782bef1014c7
in3xes/projecteuler
/problem97.py
326
3.6875
4
#!/usr/bin/env python #Problem ## 97 # #To find lat 10 digits we should only care about last 11 digits #To be safe consider 13 digits def l(num): return int(str(a)[-13:]) a = 2 ** 100 for x in range(101, 7830458): a = l(a) a = a * 2 if x%10000 == 0: print a, x a = a * 28433 a = a +1 print...
07f0f22caa9aac78355c13b4a67861875a4fbbbf
guhaigg/python
/month01/day04/exercise08.py
375
3.75
4
""" 练习: 循环录入编码值打印文字,直到输入空字符串停止。 效果: 请输入数字:113 q 请输入数字:116 t 请输入数字: Process finished with exit code 0 """ while True: str_code = input("请输入编码值:") if str_code == "": break code = int(str_code) print(chr(code))
2bc18fa38097abcdbc7b159d14b9d23cad1de919
Krdshvsk/python_less
/7.functions.py
2,877
4.21875
4
# *** Функции *** # встроенная функция ввода данных # data = input('введите данные: ') # print(f"Вы ввеели вот это - {data}") # 1 вариант. Функция, принимающие данные (обладдающаяя аргументами) def func_1(arg_1): s = arg_1 ** 2 w = s + 10 print(f"результат: {w}") # вызов функции # func_1(1000) def fun...
1555c62758ea8daed9b4c26d9e4af73452cfccb3
arianjewel/python_begin
/Python/function.py
233
3.984375
4
'''def add(n1,n2): return n1+n2 n=int(input('enter a number: ')) m=int(input("enter another number: ")) #result=add(n,m) print('your result is ',add(n,m))''' def strchar(num): num-=1 print(a[num]) a='ahfdghdm' strchar(5)
88bcbc62847eadd799c8a760d65f5fbf6b9f7a56
davidf1000/dataanalyticsiot
/dtdavid/statistical-gis-boundaries-london/convert.py
1,033
4.15625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Jan 25 21:40:22 2020 @author: davidfauzi """ #example : January 11, 2020 at 07:33PM timeinput=input() print(timeinput) _,_,_,_,time=timeinput.split() print(time) time=time[:-2]+":00 "+time[-2:] print(time) # Python program to convert time # from 12 ho...
1f3d008861cda3cdeede7c1c072baefb0874762b
deepaksharma9dev/DSA
/Step7/change_case.py
814
3.890625
4
#method 1 # string = "AbC" # for i in range(len(string)): # string = list(string) # if ord(string[i])<=90 and ord(string[i])>=65: # string[i] = chr(ord(string[i])+32) # elif ord(string[i])<=122 and ord(string[i])>=97: # string[i] = chr(ord(string[i])-32) # print(string) # print(''.join(s...
fffa3475e5a157303efe44d8bd76d6994d13ab23
Darlan-Freire/Python-Language
/exe69 - Análise de dados do grupo.py
952
3.859375
4
#Crie um prog que leia a IDADE e o SEXO de VÁRIAS PESSOAS. #A cada pessoa cadastrada, o prog deverá perguntar se o USUÁRIO quer ou não continuar. #No final, mostre: # (a) Quantas pessoas tem mais de 18 ANOS. # (b) Quantos HOMENS foram cadastrados. # (c) Quantas MULHERES tem menos de 20 ANOS. M18anos = totalhome...
edadb46ce028a894d4f0f84331fe2482388007f4
GustavoHMFonseca/Desenvolimento-Web-full-Stack-com-Python-e-Django---Python-Moudulos-e-Pacotes
/modulos-padroes.py
966
4.40625
4
""" Um módulo é im arquivo contendo definições e instruções Python que podem ser importados para utilização de seus recursos Permitem expandir as funcionalidades da linguagem além dos recursos padrões 1) É possível utilizar módulos padrões do Python 2) É possível instalar módulos https://docs.python.org/pt-br/3/py-modi...
c19a8d49d35221d00bc1f27a33f2744d61d58bb6
sycLin/LeetCode-Solutions
/412.py
717
3.5625
4
class Solution(object): def fizzBuzz(self, n): """ :type n: int :rtype: List[str] """ ret = [] three_counter = 0 five_counter = 0 for i in range(n): three_counter += 1 five_counter += 1 three_counter -= 3 if three_co...
25efd1d33a79639bf9d8f629e7ad8c91c9de982d
ozzutest/miw2021
/src/kNN.py
6,892
3.921875
4
import math import copy from operator import itemgetter from collections import Counter, defaultdict class kNearestNeighbors: """ The k - Nearest Neighbor machine learning classificator. The supervised algorithm for classification. Available metrics are with provided example...
adc3ed7c037b3eaaa103a0c9841860b9181121d3
gsimoes91/Python-para-Zumbi
/Lista de Exercícios 1/Exercício_4.py
439
3.59375
4
'Exercício 4 - Faça um programa que calcule o aumento de um salário. Ele deve solicitar o valor do salário e a porcentagem do aumento. Exiba o valor do aumento e do novo salário' salario = float(input('Digite o salário em R$: ')) aumento = float(input('Digite o percentual do aumento: ')) aumento = salario * (aumento /...
e23b5e474cc3ccfd16004b2738dda665c725133c
Zerl1990/python_algorithms
/problem_solving/cracking_the_code_interview/linked_lists/partition.py
1,034
4.34375
4
# Partition: Write code to partition a linked list around a value x. # such that all nodes less than x come before all nodes greater # than or equal to x. import os import sys from Node import head # 1->2->3->4->5->2->3->4->5 def partition(head, partition): left_side = None right_side = None it = head ...
4a8428404b8913d0fa96cdf9119c34a39f48811d
406project/FastCampus-Python-Django
/Week-2/02_if.py
882
3.875
4
if True: print("True") if False: print("False") a = 13 b = 12 if a < b: print("a({a})가 b({b})보다 작다.".format( a=a, b=b)) else: print"a({a})가 b({b})보다 크다.".format( a=a, b=b)) # in, not in animals = ["강아지", "고양이", "이구아나"] if "이구아나" in animals: print("이구아나를 키우고 있습니다.") else: print("이구아나를 키우고...
f8ef3c39e8a9fdbfe23f0316bab1378faa4a00b9
DoNotBiBi/Basic
/Error.py
924
4.25
4
# try/except # try/except...else # try-finally # try:执行代码 # except 发生异常时执行的代码 # else 没有异常时执行的代码 # finally 不管有没异常都会执行的代码 # 抛出异常 def test(): x = 3 if x > 5: raise Exception(f'x 不能大于 5。x 的值为: {x}') def error_test(): try: test() except AssertionError as error: print(error) els...
0caafec24b3fab413906682a05630a8eadaa2b20
BolajiOlajide/python-automation
/automateCSV.py
802
3.953125
4
import os import csv import json # ADAH Adah adah AdaH ADAH => Adah csv_name = input('Please provide the name for your CSV: ') file_path = 'csv/' + csv_name + '.csv' # csv/bolaji.csv if not os.path.exists(file_path): print('The CSV doesnt exist. Ensure the CSV exists in the csv folder of the project') else: ...
c8cc20970a0166d5929c202da102a113fee9d3b2
DustinFlynn297/Intro-to-python
/IntroToPythonWorksheet1.py
1,850
4.5
4
import random # 1. create a function that takes user input for "favorite programming language" and compares it to a list, if the users input matches the list, return and print result to console. #create function #create list of programming languages #create prompt that takes user input #compare user input to list of p...
b96096c122cf1f88b194efc99741e21fe5833356
Sen2k9/Algorithm-and-Problem-Solving
/leetcode_problems/401_Binary_Watch.py
2,099
4.125
4
""" A binary watch has 4 LEDs on the top which represent the hours (0-11), and the 6 LEDs on the bottom represent the minutes (0-59). Each LED represents a zero or one, with the least significant bit on the right. For example, the above binary watch reads "3:25". Given a non-negative integer n which represents the n...
22beeb891e772e888c40b89761211f05b04b0a6e
Fiskmasen/prog1-kap3
/program.py
486
3.671875
4
print("Välj mellan:\n\tolles\n\tcoop\n\tmax") eat = input("Var vill du äta? ").lower() if eat == "olles": print("Du äter, grattis") elif eat == "max": print("Du sparar inte på studiebidraget") elif eat == "coop": print("Dagens motion!") coop = input("2 vitlöksbröd för 20kr? [ja/nej]").lower() if c...
27d07551453748063ed49e34a5dd7d3a8a50914c
ryanbrown358/PythonStuff
/Python Tutorial/test.py
240
3.8125
4
print("Hello world") """ This is a multiline comment """ #this is a single line comment #print substrings print("Hello World"[0:4]) #print numbers print(2) print(1,2,3,"Hello world") #print on a new line print("Line1\nLine2\nLine3")
804edd2835f7f4cf2e626f429cc1a2332abb2e7c
Eben2020-hp/Bangalore-Air-Quality-Index
/Data_Collection.py
1,340
3.5625
4
# -*- coding: utf-8 -*- """ Created on Mon July 12 8:30:45 2021 @author: Eben Emmanuel """ import os import time import requests ## Helps us to download the required page in the form of html. import sys ## To retrieve Data def retrive_html(): for year in range(2013, 2019): for month in range (1,13)...
76be895a758f86b84f7bae5bd6a5883d4691de61
julianapereira99/AAB
/Automata.py
2,487
3.859375
4
class Automata: #Construir tabela onde vamos ter um dicionário da sequencia em que os matches são construídos def __init__(self, alphabet, pattern): self.numstates = len(pattern) + 1 self.alphabet = alphabet self.transitionTable = {} self.buildTransitionTable(pat...
31a751edad8f06f532c6a2ae4fbdaef3dd4ab84b
geometrian/QualityCpp
/rules/leading_space.py
578
3.65625
4
#Any line beginning with at least one leading space is marked. class RuleLeadingSpace(object): NAME = "Leading Space" @staticmethod def get_description(line_numbers): result = "Beginning with space(s) on line" if len(line_numbers)>1: result+="s" return result @stati...
f2fe53479e36fb6b08d5e5d4b9135166d689449d
stevestar888/leetcode-problems
/771-jewels_and_stones.py
1,403
3.71875
4
""" https://leetcode.com/problems/jewels-and-stones/ """ class Solution(object): """ Strat: Make a set to store occurances for each jewel. Then, iterate through each stone to see if it is a jewel. Stats: O(J + S) time, O(J) space -- iterate thru J and S + set of size J to store Jewel...
cc3f5719f92d6c7af2105778b2d70e4a4f0ebc60
AAM77/100-days-of-code
/round 1 code/r1d18_files/one.py
986
3.9375
4
#one.py # There is no main() function in Python # Instead, everything gets run implicitly # from the very first line of a file # In Python, there is a built in variable # called __name__ # This variable (__name__) gets assigned # a string, depending on how you are # running the actual script # For example, # if you ...
8054c69afddd4b6c960d517dbae92cb557da8a4d
vinay10949/DataStructuresAndAlgorithms
/Problems/Stacks/DesignStackWithGetMinimumO1.py
2,752
4.03125
4
''' Problem Statement: Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. push(x) -- Push element x onto stack. pop() -- Removes the element on top of the stack. top() -- Get the top element. getMin() -- Retrieve the minimum element in the stack. Example 1: ...
742fb5f77df16aadc2cea98336743c770ea32fe3
farhad-dalirani/AUT_Machine_Learning
/machineLearning3/logistic regression regularization.py
18,781
3.65625
4
def ten_fold_cross_validation(learningFunction, _lambda, xtrain, ytrain, threshold, iteration, learningRate): """ This function use 10-fold-cv to evaluate learningFunction which can be logistic regression, and any other learning function. :param learningFunction: Is a function that learns f...
c72275f0282e16123532d125a71abf24a0855291
gengwg/Python
/list2dict.py
808
4
4
# Convert List to Dictionary: Even items as keys, odd items as values # Example: # inv = ['apples', 2, 'oranges', 3, 'limes', 10, 'bananas', 7, 'grapes', 4] # I want to create a dictionary from this list, # where the items in the even positions (apples, oranges, limes, bananas, grapes) are the keys, # and the items in...
2c31f91ec35087fab4d98444d52430c50a5d34f4
bstelly/PythonPractice
/main.py
790
3.765625
4
#pylint: disable = E1101 #pylint: disable = W0312 import os def add(lhs, rhs): return lhs + rhs def subtract(lhs, rhs): return lhs - rhs def multiply(lhs, rhs): return lhs * rhs def divide(lhs, rhs): return lhs/rhs user_input = 0 while user_input != 5: print "What would you like to do? Input number.\n" print "1....
b15d68c4c8eecbb27b6c94b075983dcfdb583aac
ianpaulleong/collatz
/collatz.py
340
4.125
4
# -*- coding: utf-8 -*- """ Created on Sat Nov 23 16:27:31 2019 @author: GAMEZ """ def collatz(theNum): curNum = theNum numList = list([curNum]) while curNum > 1: if curNum%2 == 1: curNum = int(curNum*3 + 1) else: curNum = int(curNum/2) numList.append(curNum...
6ca1fb87730b30078a8647d7744d9d21061009f9
kanekyo1234/AtCoder_solve
/ABC/110/C-1.py
296
3.53125
4
import collections s=input() t=input() s= collections.Counter(s) t= collections.Counter(t) #print(s) sans=[] tans=[] for v in s.values(): sans.append(v) for v in t.values(): tans.append(v) sans.sort() tans.sort() #print(sans,tans) if sans==tans: print('Yes') else: print('No')
3381a36c4153ff56061800530ae8b6d92b66f225
jvtamm/online-judges
/hackerrank/warmup/repeatedstring.py
995
3.921875
4
#!/bin/python3 import os # Complete the repeatedString function below. def repeatedString(s, n): current_index = 0 #Stores the number of a's seen until index i lpa = [] for digit in s: if(digit == 'a'): if(not lpa): lpa.append(1) else: lpa.append(lpa[current_index...
96c8440ab12b5bf6d78e7b52be2f086db5758714
mseidenberg13/python_challenge
/PyBank/main.py
2,044
3.578125
4
import os import csv PyBank_csv = os.path.join("Resources","budget_data.csv") profit = [] monthly_changes = [] date = [] count = 0 total = 0 total_change = 0 initial_profit = 0 with open(PyBank_csv, newline="") as csvfile: csvreader = csv.reader(csvfile, delimiter=",") csv_header = next(csv...
8c35008e3eafc6f0877dd65325ee051cea3afaf3
ggrecco/python
/basico/zumbis/jogo_2.py
291
3.734375
4
from random import randint secreta = randint(1, 100) while True: chute = int(input("Chute:")) if chute == secreta: print("parabéns, vc acertou o número {}".format(secreta)) break else: print("Alto" if chute > secreta else "Baixo") print("Fim do jogo")
d8a230f48b0d4ba259d17e6045c24c97f5e9f41f
pmontesd/katando_python
/20180915/02_enclavedeJa/03/enclavedeja.py
949
3.609375
4
def add_to_discount_list(season, discount_lists): for discount_list in discount_lists: if season not in discount_list: discount_list.append(season) return discount_lists.append([season]) return def get_series_price(seasons): prices = { "0": 2.5, "1": ...
be9f0456747d5663ff42173a9c675a9414464937
berman82312/google-foobar
/level4_1 - Running with Bunnies/solution.py
2,063
3.59375
4
def carry_in_remain(distance, remains, start, end, time_left): if len(remains) == 0: time_spent = distance[start][end] if time_spent <= time_left: return [start] else: return False else: time_spent = distance[start][end] max_carried = [] can_reach = False if time_spent <= tim...
79e165e32cb1872266410ce6b7f66e48d05886fc
dnootana/Python
/Interview/MatrixFindNoOfIslands.py
382
4.28125
4
#!/usr/bin/env python3.8 """ Given a boolean 2D matrix, find the number of islands. A group of connected 1s forms an island. For example, the below matrix contains 5 islands Example: Input : mat[][] = {{1, 1, 0, 0, 0}, {0, 1, 0, 0, 1}, {1, 0, 0, 1, 1}, {0, 0...
93f4e1a023a0c213a5c8d551c185c20864b8215f
anantkaushik/Competitive_Programming
/Python/GeeksforGeeks/repetitive-addition-of-digits.py
879
4
4
""" Problem Link: https://practice.geeksforgeeks.org/problems/repetitive-addition-of-digits/0 Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. Input: The first line contains 'T' denoting the number of testcases. Then follows description of testcases. The next T line...
838831687906f18fc97f546f57cc44a636c51724
smallfishxz/Practice_Algorithm
/List/String_Compression.py
1,371
3.828125
4
# Iterate through the string char by char, and count its repeats. When next char is not the same as the current one, append the char and its repeats to the result string. # In the end return the result string only when it is shorter. def str_compression1(s): # In order to improve, check ahead of time before genera...
dffbe05d5c54b9d24558ee6f4ba91d05007238e9
FarazHossein/RallyGame
/main.py
9,292
3.515625
4
""" This is the main program to be run to run the game. Contributors: Siddharth - car, checkpoints Faraz - sounds, music, liaison classes implementation Rick - different screens, scores, times Shraddha - testing """ import pygame from images import * from carControl import Car import button import score_board import ...
13f6f0c8d8832c23d76921855f216d8972a08a54
rustytwilight/sandypi
/server/utils/buffered_timeout.py
1,310
3.5625
4
from threading import Thread, Lock import time # this thread calls a function after a timeout but only if the "update" method is not called before that timeout expires class BufferTimeout(Thread): def __init__(self, timeout_delta, function, group=None, target=None, name=None, args=(), kwargs=None): super(...
0702d5c22eee8ae1c180f93e2699d6a2490cd3cf
hc388/calculator_Team
/Calculator/Calculator.py
1,169
3.5625
4
import math from MathOperations.Addition import Addition from MathOperations.Subtraction import Subtraction from MathOperations.Division import Division from MathOperations.Multiplication import Multiplication from MathOperations.Logarithm import Logarithm from MathOperations.Exponentiation import Exponentiation from ...
8700650e4841478f35f30e35459fa1c2ee74a82d
thelsandroantunes/EST-UEA
/LPI/Listas/L2_LPI - repetição e condicionais/exe55l2.py
612
3.953125
4
# Autor: Thelsandro Antunes # Data: 13/05/2017 # EST-UEA # Disciplina: LP1 # Professora: Elloa B. Guedes # 2 Lista de Exercicios (06/04/2015) # Questao 55: Escrever um programa para ler um numero inteiro do usuario e exibir # o maior numero primo que seja menor do que o numero digitado. from __future__ imp...
de09cf1c729e3ad2a9fdc5075eef63a5fd2e8ec5
TheAlgorithms/Python
/strings/wildcard_pattern_matching.py
3,348
4.4375
4
""" Implementation of regular expression matching with support for '.' and '*'. '.' Matches any single character. '*' Matches zero or more of the preceding element. The matching should cover the entire input string (not partial). """ def match_pattern(input_string: str, pattern: str) -> bool: """ uses bottom...
323357a32f8b508e9f3582576b6fa40fd44a0e07
JakobKallestad/Python-Kattis
/src/Veci.py
332
3.5
4
import sys raw_n = input() n = int(raw_n) digit_list = [c for c in raw_n] if raw_n == ''.join(sorted(raw_n))[::-1]: print(0) sys.exit(0) current = n+1 while True: i = str(current) if len(i) != len(raw_n): continue if sorted(i) == sorted(raw_n): print(current) break c...
91e269b36fe61885766ebd5de049f2bbc80a87b2
joobond/ExerPython
/URI/1008.py
113
3.5
4
n = int(input()) h = int(input()) v = float(input()) sal = h*v print(("NUMBER = %d\nSALARY = U$ %.2f")%(n,sal))
46a5b705cc56953719e939eb7845bebccfb4991c
Sviatoslav-Lobanov/Python_learning
/X and O.py
2,103
3.96875
4
def print_step (table): # Печать игрового поля print (' | 1 | 2 | 3 |') print ('---------------') for i in range(len(table)): print(f'{i+1} | {table[i][0]} | {table[i][1]} | {table[i][2]} |') print('---------------') def check (a): # Проверка введенных координат point = input(f'Введит...
14181605223993953f0d338b549ab218af9d1238
myf-algorithm/Leetcode
/Huawei/106.求解立方根.py
152
3.90625
4
import math while True: try: num = float(input()) num2 = math.pow(num, 1.0/3) print('%.1f' % num2) except: break
ecec82f7d6a458418140579021abfe8fd06af04d
waithope/codewars
/CodeWars.py
12,745
3.796875
4
# 0123456789 # 0########## # 1## ## # 2# # # # # 3# # # # # 4# ## # # 5# ## # # 6# # # # # 7# # # # # 8## ## # 9########## # rowCount = 10 # columnCount = 10 # for i in range(rowCount): # for j in range(columnCount): # if i == 0 or i == rowCount - 1 or j == 0 or \ # j == c...
d3c25e265a105788d6b8ee85324e5a6745243ff4
Elton86/ExerciciosPython
/ExerciciosComStrings/Exe07.py
541
3.90625
4
"""Conta espaços e vogais. Dado uma string com uma frase informada pelo usuário (incluindo espaços em branco), conte: quantos espaços em branco existem na frase. quantas vezes aparecem as vogais a, e, i, o, u.""" frase = input("Digite a frase: ") cont_esp = cont_vog = 0 for f in frase: if f == " ": cont_e...
42fde8fea9d4073226f40af828e6477c4cf5baa1
stuycs-softdev/classcode
/7/regex/regtest.py
652
4.1875
4
import re def find_phone(s): """Return a list of valid phone numbers given a string of text Arguments: s: A string of text Returns: An empty list or a list of strings each one being a phone number >>> find_phone("") [] >>> find_phone("111-111-1111") ['111-111-1111'] ...
a704c66997229d74c036bd07ba671f733374bda0
anassinator/markov-sentence-correction
/sentence.py
1,928
3.890625
4
# -*- coding: utf-8 -*- class Sentence(object): """Sentence.""" START = "<s>" STOP = "</s>" LEFT_SIDED_SYMBOLS = set('"\',.-/:;<>?!)]}$%') RIGHT_SIDED_SYMBOLS = set('"\'-/<>([{') SYMBOLS = LEFT_SIDED_SYMBOLS.union(RIGHT_SIDED_SYMBOLS) def __init__(self): "Constructs a Sentence."...
c479a71f2860c1214693a38716e8460efd806f4c
josueocampol/introprogramacion
/practico_flujo_condicional_y_ciclico/ejercicio_11.py
301
3.625
4
print("Ingrese su fecha de nacimiento.") dia = int(input("Día: ")) mes = int(input("Mes: ")) año = int(input("Año: ")) from time import localtime t = localtime() t.tm_mday 11 t.tm_mon 10 t.tm_year 2020 if año<2020: print(f"Usted tiene {-año+2020} años y su cumpleaños es el {dia} de {mes}")
b293468e54ded3646abbfc2a5fe94fd6901b4704
Paul9inee/Elementary_Algorithm
/sanghwa_week4/[4주차] 가장 큰 수.py
262
3.5
4
def solution(numbers): numbers = [str(x) for x in numbers] numbers.sort(key=lambda x:(x*4)[:4], reverse = True) answer = ''.join(numbers) if answer == '0' * len(numbers): return '0' return answer print(solution([0,0,0,0,0,0,0,0,0]))
9eb6e28495760fe20df5d5175b308de048e096ed
jabhax/python-data-structures-and-algorithms
/OOP/Flyweight.py
1,229
3.84375
4
# Design Patterns ''' The Flyweight Pattern provides a way to decrease object count. It includes features that help in improving application structure. The most important feature of the Flyweight objects is immutabilty; they cannot be modified once constructed. The pattern uses a HashMap to store reference objects. ''...
6f44998992bdbb419e527cc6bd16135ba6c8b3c6
bcollins5/mis3640
/play_around.py
299
3.859375
4
# team = 'New England Patriots' # win_pct = 65 # print('%s %d' % (team, win_pct)) def check_team(team): if team == ('Patriots' and 'New England Patriots'): return 'Good' else: return 'Bad' team = input('Enter your favorite team: ').lower() print(check_team(team))
76a488f4952fb679fa3a30b86c309da1e9781185
atrox3d/python-corey-schafer-tutorials
/01-python-basics/11-slicing.py
2,721
4.25
4
# # https://www.youtube.com/watch?v=ajrtAuDg3yw # # Python Tutorial: Slicing Lists and Strings # ################################################################################# my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 # POSITIVE INDEXES # -10,-9,-8,-7,-6,-5,-4,-3,-2...
68af8dee7647e86450c2da7d97ab385bd4fceb6f
JimmyRomero/AT06_API_Testing
/JimmyRomero/Python/Session3/Practice8.py
281
4.09375
4
def replace(text, letter, letter_to_change): text_splitted = text.split(letter) print(letter_to_change.join(text_splitted)) replace("Mississippi", "i", "I") song = "I love spom! Spom is my favorite food.Spom, spom, yum!" replace(song, "om", "am") replace(song, "o", "a")
8b516c1a3ea5c32f9d1a9bc22a833f9545523e7c
JIMBLYB/Tinkering_Graphics_Teams
/Contract #4/SpriteReskinning.py
1,602
3.671875
4
# This script has been made by Joseph Broughton. import pygame from pygame.tests.test_utils import png pygame.init() # This will create the display that is the same size as my sprite i'm editing. main = pygame.display.set_mode((400, 200)) # This surface is the one that actually loads th image. my_sprite = pygame.ima...
7e1b28a8ab33e2cb3bbeaf11efce32f5bee953e3
stosik/coding-challenges
/leet-code/first-unique-char.py
493
3.828125
4
# Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1. # Examples: # s = "leetcode" # return 0. # s = "loveleetcode", # return 2. def solution(s): hash_table = {} for i in s: if i not in hash_table: print(i) hash_table[i] +=...
f233fc81cebee7c25d58e03e1cbdd0b89b741a01
Barracudayao/pythonbasic
/python3_list/python_list_notebook.py
2,371
4.34375
4
# Lists list1 = ["Cisco", "Juniper", "Avaya", 10, 10.5, -11] # creating a list len(list) # returns the number of elements in the list list1[0] # returns "Cisco" which is the first element in the list (index 0) list1[0] = "HP" # replacing the first element in the list with another value # Lists - methods list2 =...
a91340f921ad5da19817162cb88c35c21fcbe890
gongzhiyao/FirstTest
/venv/test/practice5.py
6,707
3.984375
4
#!/usr/bin/env python # coding=utf-8 # 函数式编程 print "函数式编程" # 高阶函数 # 变量可以指向函数 print abs(-120) print abs # 可见,abs(-10)是函数调用,而abs是函数本身。 # 要获得函数调用结果,我们可以把结果赋值给变量: x = abs(-100) print x # 如果把函数自身赋值给变量 a = abs print a # 结论:函数本身也可以赋值给变量,即:变量可以指向函数。 # 如果一个变量指向了一个函数,那么,可否通过该变量来调用这个函数?用代码验证一下: print a(-10000) # 成功!说明变量f现在已经指向了a...
631959c8d29fd1630bff5881d09fc1dce4b34057
lzs1314/pythonWeb
/week3/生成器/index.py
532
3.703125
4
# coding:utf-8 #@FileName: index.py #@Author :辰晨 #@Time :2019/4/17 11:02 s = (s*2 for s in range(10)) print(next(s)) for i in s: print(i) def foo(): print('ok') yield 1 g=foo() print(g) #<generator object foo at 0x000001DD5860A390> next(g) for i in foo(): print(i) #什么是可迭代对象(对象拥有__iter__方...