blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
908777f7f79e1776e6292c053edf99ba5f061388
kzhereb/kpi-acts-asd2020-2021
/code-examples/lecture_3_recursion/factorial.py
111
3.859375
4
def factorial(n): assert n>=0 if (n<=1): return 1 return n * factorial(n-1) print(factorial(3))
f68626f351e177244fd924aaac8abe57dbd921ea
hghimanshu/CodeForces-problems
/bose/python/misc/englishRuler.py
658
4.03125
4
def draw_line(tickLength,tick_label=""): line = "-"*tickLength if tick_label: line+= " "+tick_label print(line) def draw_interval(center_length): if center_length > 0: draw_interval(center_length-1) draw_line(center_length) draw_interval(center_length -1) def draw_ruler...
4f0339c26c058cde44ad36e34e2fc94fab92d1a9
AKXAT/pandas
/panda.py
1,843
4.03125
4
import pandas as pd dataframe = pd.read_csv('Salaries.csv') #print(dataframe) -> to check if the read was successful #print(dataframe.head(1)) print(dataframe.info()) #now find the average basepay print(dataframe.columns) basepay = dataframe['BasePay'] print(f'The Mean is {basepay.mean()}') #find the highest amount ...
e4113965d0502f240ad728c1013e55e89259beda
ahmedbing/udacity120-ML
/ahmed_feature_scaling.py
372
3.5
4
def featureScaling(arr): min = arr[0] max = 0 for num in arr: if(num < min): min = num if(num > max): max = num for idx , num in enumerate(arr): arr[idx] = (num-min)*1.0 / (max-min) return arr # tests of your feature scaler--line below is input data ...
d5e6a98cfe6389e9233ef776c0499de050e1d1fe
GhostDovahkiin/Introducao-a-Programacao
/Monitoria/Lista-Listas/10.py
334
3.59375
4
lista = list(range(20)) A = [] B = [] C = [] print('Lista A') for i in range(len(lista)): num = int(input('Digite um inteiro: ')) A.extend([num]) print('Lista B') for i in range(len(lista)): num2 = int(input('Digite um inteiro: ')) B.append(num2) v=[] for i in range(20): C = str(A[i]) + " " + str(B[i]) v.appen...
1f39ffa263df7bb2887bd19c0bebc3e4226b07c2
PedroVitor1995/Algoritmo-ADS-2016.1
/aula_15junho2016/questao14.py
765
3.671875
4
# -*- coding: utf-8 -*- """14. Leia 3 notas de um aluno e o peso de cada nota, calcule e escreva a média ponderada.""" nota_um = input("Escreva a nota um: ") nota_dois = input("Escreva a nota dois: ") nota_tres = input("Escreva a nota três: ") peso_um = input("Escreva o peso da nota um: ") peso_dois = input("Escreva o ...
40a1723199258c66d38b86581d0cd731891ced8e
vasanthakumarj/design_patterns
/creational_patterns/abstract_factory/frog_world.py
704
3.9375
4
class Frog: def __init__(self, name): self.name = name def __str__(self): return self.name def interact_with(self, obstacle): act = obstacle.action() msg = f"{self} encounters {obstacle} and action is {act}" print(msg) class Bug: def __str__(self): pri...
ba59c32b4dc38bdc5b2e49cae9be0b6c970f4bbf
Vatsal-Nagda/IIIT-H
/Sem1/Scripting/Lab7/20162008_lab7/tp.py
425
3.5
4
import sys f_read = open('corpus.txt','r') line_list = f_read.readlines() list_remove = ['the', 'an', 'a', 'has', 'to', 'of', 'as', 'is', 'in', 'if'] list_final=[] for i in range(len(line_list)): list_final.extend(line_list[i].split(' ')) print print "checking for the peices now" for piece in list_remove: v = l...
67e3f8cb818a7c1fbf40b08697de18b05c0dabf7
xiaosean/leetcode_python
/Q986_Interval-List-Intersections.py
1,151
3.5625
4
class Solution: def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]: # 2 pointer # while a or b finish -> bfs solution res = [] a, b = None, None while firstList and secondList: if a is None: a...
63373494ee52c81fad60f3438a47f80d51aa876c
dengl11/Leetcode
/problems/vowel_spellchecker/solution.py
1,178
3.53125
4
from collections import defaultdict class Solution: def spellchecker(self, wordlist: List[str], queries: List[str]) -> List[str]: EM = set() lowercases = defaultdict(list) # {w: [...]} nonVowels = defaultdict(list) # {(w, n): [...]} vowels = {'a', 'e', 'i', 'o', 'u'} def tri...
a885b7d6cf68e6ea6f161efd4b491b009873ecd7
pbragancacabral/Work-Log
/work_log.py
3,311
3.59375
4
#!/usr/bin/env python3 import csv import datetime import os import re from task import Task FILE = "log.csv" tasks = [] def clear_screen(): os.system('cls' if os.name == 'nt' else 'clear') def show_main_menu(): clear_screen() print("Work Log") print() print("What would you like to do?") ...
864abf31943eb2586cb8e29026b130c6acdbe4c4
dietherdayondon/CSC124
/iterative_multiplication.py
109
3.609375
4
def mult(a,b): prod = 0 for i in range(b): prod += a return prod print("Product: "+ str(mult(10,10)))
2ff1eff7318d9e4e9e1532c06e8885811f6c514f
p1pk4/GB_Video_course_number_0
/stepikMultiSep.py
674
4.34375
4
''' Напишите программу, которая считывает целое положительное число xx и выводит на экран последовательность чисел x, \, 2x, \, 3x,\,4xx,2x,3x,4x и 5x5x, разделённых тремя черточками. Формат входных данных На вход программе подаётся целое положительное число. Формат выходных данных Программа должна вывести текст согл...
89369e8d8f91d5f6711c8ce352c8587e7485271d
binsh/test
/words.py
1,000
3.859375
4
#!pathtopython\python # -*- coding: cp1251 -*- # 2. ? : , , . . import copy baseword= list("") try: n=0 f = open('dict_win.txt') for line in f: newword= list(line.rstrip()) x=len(newword) if x>1: tempword=copy.copy(baseword) # . i=0 www="" for letter in newword: if lette...
325cc9e6ef1e818a7039b45b44b26c008a73c9e6
wkwiatkowski/kurs-py
/exercises/w3resource/1.py
445
3.53125
4
#!/usr/bin/env python a = """ Twinkle, twinkle, little star, How I wonder what you are! Up above the world so high, Like a diamond in the sky. Twinkle, twinkle, little star, How I wonder what you are """ # print a print ("Twinkle, twinkle, little star,\n\t How I wonder what you are!\n\t\t ...
2a9daa792491c6700a679d0d94109bdb6a2e9e49
nirnicole/Artificial-Intelligence-Python-Repositories
/Constraint Satisfaction Problem/EightQueensConstrains.py
1,640
3.515625
4
from csp import Constraint """ Summery: The eight queens problem problem, This class contains relevant queens constrains. Author: Nir Nicole """ """The eight queens constrains""" # implementing framework constrain. class EightQueensConstraint(Constraint): def __init__(self, colu...
b79cc598d2b49e60e2524fc04f098a3bac6b9f5c
paulojuanifpb/IFTERACT
/ifteractWEB/ifteractApi/Model/Grupo.py
2,050
3.5
4
import sqlite3 def criarTabelaGrupo(conn): cursor = conn.cursor() cursor.execute(""" CREATE TABLE tb_Grupo( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, nome VARCHAR(70) not null, data date, administrador int not null, foreign key (administrador) references...
67f45c1a105a12ee61400f6d9e7b590682bab606
Quintuplin/CSCI_320
/hrank_problems/repeatedstring.py
520
3.625
4
#!/bin/python3 import math import os import random import re import sys # Complete the repeatedString function below. def repeatedString(s, n): count = 0 subcount = 0 c = len(s) nrem = n%c for letter in s: if letter=='a': subcount += 1 for i in range(nrem): if (s[i%c]=='a'): c...
5a3f3eaa444465bb344915ec77f83043cc78a72e
Rick-Houser/holbertonschool-higher_level_programming
/basic_oop_with_python/square.py
777
4.09375
4
from math import pi ''' This class describes a square ''' class Square(): ''' Constructor ''' def __init__(self, radius): ''' Private attributes ''' self.__radius = (radius) self.__center = (0, 0) self.__color = ("Yellow") ''' Public attributes ''' self.name = ("Square") ''' Getters ''' def get_center...
de323a40fe08612e502c0a42e4593372a2fd91c9
erjan/coding_exercises
/binarysearch/run_length_encoding.py
795
3.625
4
''' Given a string s, return its run-length encoding. You can assume the string to be encoded have no digits and consists solely of alphabetic characters. ''' from itertools import groupby class Solution: def solve(self, s): res = list() for c, g in groupby(s): res.append([len(list...
2d2dd2719a918c95d94e89f23390bfd6b4fd1ecc
tonton06/python
/exercicios/ex015.py
235
3.703125
4
d = int(input('Dias alugado: ')) km = float(input('Quilômetros rodados: ')) pd = d * 60 pkm = km * 0.15 print('Seu carro foi alugado por {} dias e percorreu {:.1f}km!'.format(d, km)) print('Isso equivale a R${:.2f}'.format(pd + pkm))
919178c4ff4ea61f07cfe2c17fb73f263e4b164a
ineed-coffee/PS_source_code
/BOJ/2579_동적계획_계단오르기.py
369
3.59375
4
from sys import * stair_num = int(input()) stair,point=[],[[0,0]] for _ in range(stair_num): stair.append(int(stdin.readline())) point.append([0,0]) for i in range(1,stair_num+1): if i==1: point[i]=[stair[i-1],stair[i-1]] else: point[i][0]=point[i-1][1]+stair[i-1] point[i][1]=s...
82dc9e094ae8a1aa1db1be357fbd4f32f5a44fe5
priyap97/advent-of-code
/day1/day1.py
1,173
3.703125
4
# Initial setup input = open('input.txt') result = 0 frequencies = {0} part2 = True # Part 1 for line in input.readlines(): # Parse input op = line[0] num = int(line[1:]) # Appropriately add or subtract from total if op == '-': result = result - num else: result = result + nu...
5fb607c07d59334131590fb042ad91bfe6583c44
nitendragautam/python_apps
/python_core/pythontutorials/python_variables_string.py
2,495
4.5625
5
msg = 'Hello World!' print(msg) # Concatenate String first_name = 'Nitendra' second_name = 'Gautam' full_name = first_name +second_name print(full_name) # A String print("My Name is Nitendra Gautam") print('This is my Blog') """ >>> print("My Name is Nitendra Gautam") My Name is Nitendra Gautam >>> print('This is ...
4aaa9c89a1b600202fed0709f064d33853810290
arogers0/SolarTracking
/DatesAndTimes.py
3,413
4.03125
4
import datetime from math import sin, cos, radians from Util import get_coordinates class DatesAndTimes: """ Performs various date and time calculations. Attributes: _date : datetime a timezone aware date _day_of_year : int the integer day of the year for today ...
8946d728f60b349f4b3b6ffedc6e3efac55f533f
310A/Eric
/Eric/ZHOUDIU/python_study/week2-project/mini_project.py
2,029
4.25
4
# template for "Guess the number" mini-project # input will come from buttons and an input field # all output for the game will be printed in the console import simplegui import random # helper function to start and restart the game def new_game(): global input_number global remain_guesses global ran...
fe8cb00db115eb78cdb80dd469730a57799e40b8
shantanu609/Two-Pointers-2
/Problem3.py
964
3.828125
4
# Time Complexity : O(m + n) where m will be all elements in col and n will be all elements in last row in worst case # Space Complexity :O(1) # Did this code successfully run on Leetcode : Yes # Any problem you faced while coding this : No # Your code here along with comments explaining your approach class Solution: ...
5d7d1cd3330f980cec018e30c05ff8a8f7e9d3e8
facunava92/Trabajos_Practicos
/TP2/TP2v1.py
12,596
3.5
4
import random def validacion(intentos): for i in range(intentos): email = input('* Ingrese su e-mail: ') cont_arroba = 0 access = True if email[0] == '@' or email[-1] == '@' or email[0] == '.' or email[-1] == '.': access = False if ".." in email: a...
3c49cd8556b168585313028e00b338b2d32a98ad
rbassett3/ProverbGenerator
/Generator1.py
1,292
4.09375
4
import random class Proverb: """A proverb generator, which takes a text corpus W at initialization. W is an array of words with '!' as a starting token and '.' as an end token. Generate a proverb with Proverb.Generate(). This method is a Markov chain model. The state is the current word. To proceed to the next...
ae9c47cbad8ea97eded1a2947f4a8a01472b1951
lucasilvabc/CS241
/O Big.py
178
3.859375
4
def contains(haystack, needle): # Does the haystack contain the needle? for item in haystack: if item == needle: return True return False
52970d763e7116b32502c5204bde3600bccb6245
mhtehrani/Algorithm_LeetCode_Easy
/majorityElement.py
560
3.859375
4
""" Majority Element (Greater Than n/2) =================================== @author: mhtehrani November 08, 2021 https://github.com/mhtehrani """ def majorityElement(nums): dic = {} for n in nums: if n in dic: dic[n] += 1 else: dic[n] = 1 #end ...
da7348ffd16d7919d1b6206bc1e67cc6df676e2b
siddiqua-aye/python_diceGame
/diceGame.py
10,485
4.09375
4
import random from graphics import * import time ''' Ayesha Siddiqua 3/5/2020 ''' # Getting dice number def rollDice(): return random.randint(1, 6) #Creating dice illustration based on dice number def dice_picture(dice): zero = "" one = " \n \n o \n \n...
7951f7e1c5a63071ce6d9065853d3a94530b3dd6
ZX1209/gl-algorithm-practise
/leetcode-gl-python/leetcode-599-两个列表的最小索引总和.py
2,288
4.125
4
# leetcode-599-两个列表的最小索引总和.py # 假设Andy和Doris想在晚餐时选择一家餐厅,并且他们都有一个表示最喜爱餐厅的列表,每个餐厅的名字用字符串表示。 # 你需要帮助他们用最少的索引和找出他们共同喜爱的餐厅。 如果答案不止一个,则输出所有答案并且不考虑顺序。 你可以假设总是存在一个答案。 # 示例 1: # 输入: # ["Shogun", "Tapioca Express", "Burger King", "KFC"] # ["Piatti", "The Grill at Torrey Pines", "Hungry Hunter Steakhouse", "Shogun"] # 输出: ["Sh...
8ed72de86a54fa8e783df3e8090b16f8e8d0a169
jessola/AI_CW
/questions/ask_travelling_alone.py
334
4.125
4
from random import choice def ask_travelling_alone(): """Prompts the user to specify whether or not they are travelling alone. """ options = [ 'Is it just you?', 'Are you travelling alone?', 'Are you going by yourself?', 'Just the one ticket, right?' ] # Select a random question. return c...
5b7ddd980eef5d63cc7cda3da0a9504a4a969a76
MateusdeOliveira15/IFCE-PYTHON
/Lista/q9.py
421
3.96875
4
#Faça um programa que receba do usuário uma string e imprima a string sem suas vogais. string = input('Digite uma string: ') lista = list(string) string_nova = [] for i in range(len(lista)): if lista[i] != 'a' and lista[i] != 'e' and lista[i] != 'i' and lista[i] != 'o' and lista[i] != 'u': string_nova.append(lis...
7b6ccf8c0b01c313273e4da18c39999983fb672d
Kunal352000/python_adv
/17_userDefinedFunction24.py
309
3.625
4
def f1(x,*y,**z): print(x,type(x)) print(y,type(y)) print(z,type(z)) f1(199) """ output: 199 <class 'int'> () <class 'tuple'> {} <class 'dict'> it is mandatary to pass value to the normal argument,but its not mandotory to pass value to the args and kwargs"""
fd635a292ff38298b0903dcbedf07ff844f6be13
jennyChing/onlineJudge
/10608.py
3,247
4.53125
5
''' Cardinality of a Set: 一個團體總共幾個人? 10608 - Friends There is a town with N citizens. It is known that some pairs of people are friends. According to the famous saying that “The friends of my friends are my friends, too” it follows that if A and B are friends and B and C are friends then A and C are friends, too. You...
6845ca058276d19ced1e19e1622b2fae0b9f803d
gutiere/HackerRank
/BetweenTwoSets/BetweenTwoSets.py
1,412
3.640625
4
# Problem: https://www.hackerrank.com/challenges/between-two-sets # Solved by: Edgardo (Elijah) Gutierrez # Date: 2/24/17 # Algorithm # 1) Find smallest element of 16, this is the upper bound to possible x. # 2) For all possible values of x, find the valid conditions. # 3) Increment counter when valid value of x is fo...
5e7cbc1d857a6a4fee6577d829975878f8eb23a8
leticiadedeus/learningPython
/MenuMath.py
714
4.03125
4
n1 = int(input('first number: ')) n2 = int(input('second number: ')) c = 0 while c != 5: print('What do you want to do?\n' '1 - sum\n' '2 - multiply\n' '3 - know the higher\n' '4 - change the numbers\n' '5 - exit') c = int(input('- ')) if c == 1: pr...
bb3c979c714c0f3ab1c6d2f1b7a3d1d4ef1c7fe9
anas-abulehia/Deep-Learning-Paper
/Deep Learning Fundamentals (Application Demo).py
3,439
4.0625
4
#!/usr/bin/env python # coding: utf-8 # # Deep Learning Fundamentals (Application) # Recongition of Handwritten numbers is an application on Deep Learning and AI technologies. This notebook shows the implementation of a Deep Learning algorithm to Solve MINST data set for 0~9 number (single digit). This example is...
49b982936721df09f5ef1bcef074a8aee78b6fcf
tmoertel/practice
/google-code-jam/2013/round-2-B-many-prizes/manyprizes.py
13,749
3.5
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Tom Moertel <tom@moertel.com> # 2013-09-15 """Solution to "Many Prizes" Code Jam problem https://code.google.com/codejam/contest/2442487/dashboard#s=p1 Discussion ========== It is evident that the outcomes of earlier rounds dominate later rounds in the final ranking...
63dcace5c23abd84c8b30137bec1a38ace3190e3
pablofrias/PPR2K11
/Temperatura_Listas/programa.py
2,507
3.515625
4
#Registro medición import random import menu import Registro import Alerta sectores = ['norte', 'sur', 'este', 'oeste'] # Listado de alertas por sector alertas_norte = [] alertas_sur = [] alertas_este = [] alertas_oeste = [] # Límites de temperatura lim_sup = 40 lim_inf = 5 # Listado de mediciones mediciones = [] ...
033441c07df8fdd11217e2a2329ebe65e0f444cf
susarahmet/python-ile-makine-ogrenmesi-alistirmalari
/b01_patika_python_temel_proje_1.py
312
3.765625
4
""" Bir listeyi düzleştiren (flatten) fonksiyon: """ def flatten(liste): if len(liste) == 0: return liste if isinstance(liste[0], list): return flatten(liste[0]) + flatten(liste[1:]) return liste[:1] + flatten(liste[1:]) print(flatten([[1,'a',['cat'],2],[[[[3]]],'dog'],4,5]))
a93e5f2bf9451287e87d7ac09369c052cee99d68
resahhdev/Python
/AlapProgramok/FormazottKimenet/format01.py
1,097
3.640625
4
""" Írjon programot, amely a következő hőmérséklet adatokat, valós számok alakjában tárolja: 15,82 18,27 22,40 23,19 24,57 22,02 20,28 Az adatok hétfőtől vasárnapig egy hét adatait tartalmazzák. A program írja ki egymás alá az adatokat. A sorok a hőmérséklet adat értéket mutassák először, 1 tizedesjegy pontossággal, ...
0d8dc757bb8de5a69bee6c467f152f0a3221ab42
KuroSeongbae/Project_Kakegurui
/CardDeck.py
416
3.515625
4
import random class CardDeck(): def GetDeck(self): cardsList = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3] cardsDeck = [] for i in range(len(cardsList)-1): r = random.randint(0, len(cardsList)-1) ...
a9a72197cb9e95c6cbda7e913cd4c269e2643b1c
onionmccabbage/further_adv_py_Oct_2021
/performance/07_semaphores.py
2,295
3.734375
4
# we have ticket sellers, each trying to sell tickets for a SINGLE show import threading import time import random class TicketSeller(threading.Thread): # we inherit from Thread ticketsSold = 0 def __init__(self, sem): threading.Thread.__init__(self) self.__sem = sem print('...
16333f49da4f08ef021169e4a37fc800166c516e
davidhuangdw/leetcode
/python/457_CircularArrayLoop.py
1,920
4
4
from unittest import TestCase # https://leetcode.com/problems/circular-array-loop class CircularArrayLoop(TestCase): # by union_find: proof: only the root of each set has not been visited yet, so loop if x -> y and y in x's set def circularArrayLoop(self, nums: 'List[int]') -> 'bool': n = len(nums) ...
4af23f9355c134e811774196d76406176e40fb07
Taoge123/OptimizedLeetcode
/LeetcodeNew/python2/LC_1923.py
1,305
3.546875
4
class Solution: def longestCommonSubpath(self, n: int, paths) -> int: # binary search the size of subpath --> check if it's common path minn = float('inf') for path in paths: minn = min(minn, len(path)) left, right = 1, minn while left <= right: mi...
b49830f81c848a6b89b355536e1f69c04d4a8b4f
eubr-bigsea/compss-hdfs
/Python/API/src/hdfspycompss/Utils.py
339
3.859375
4
def get_suffixes(length): """Create a list of suffixes to be able to merge all files after.""" import itertools import math alpha = 'abcdefghijklmnopqrstuvwxyz' r = int(math.ceil(float(length)/len(alpha))) product = list(itertools.product(alpha, repeat=r))[:length] return sorted(["".join(x) ...
f4582e2cf2ff465bf223edd0e0a4d9fe9b613883
StaroverovAleksey/GeekBrains
/lesson_2/lesson_2_task_3.py
665
4
4
user_input = input('Введите номер месяца: ') month_list = ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'] month_dict = {'1': 'Январь', '2': 'Февраль', '3': 'Март', '4': 'Апрель', '5': 'Май', '6': 'Июнь', '7': 'Июль', '8': '...
9ac4816671566fed6e854fd075eb2b9434e34384
zeyee/57-
/code_1(2).py
632
3.8125
4
#coding=utf-8 #!/usr/bin/env python print '输入:' a = input(' 账户金额:') if (isinstance(a, int) or isinstance(a, float)) and a>=0: b = input(' 小费比例:') if isinstance(b, int) or isinstance(b, float): c = a*b/100. if c%0.01 >= 0.001: c = c-c%0.001 print '预期结果:' print ' ...
6817aa186dbb48cb1e1448e7561181f11523bfb1
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_203/717.py
2,006
3.671875
4
# raw_input() reads a string with a line of input, stripping the '\n' (newline) at the end. # This is all you need for most Google Code Jam problems. def expand(row,col,cake,dir,forward): if row<0 or col<0 or row>len(cake)-1 or col>len(cake[0])-1: return if dir == 0: if forward == 1: ...
430fc6559decbd861b071182c13f453490554242
wei-xu/Leetcode
/Python/ImplementSwithQ.py
1,830
4.09375
4
from collections import deque class Stack(object): def __init__(self): """ initialize your data structure here. """ self.top_loc = 1 # 1 means top is at queue1, 2 at queue 2 self.queue1 = deque() self.queue2 = deque() def push(self, x): """ :type...
3fb95b8abeaef2f68ba89386edeadc7631118ed6
Mikailuo/PY.learn
/11.1.py
3,827
4.1875
4
# #构建实例变量 # class Animal(object): # """定义动物类""" # def __init__(self,age,sex,weight): # self.age=age # self.sex=sex # self.weight=weight # # animal = Animal(2, 1, 10.0) # # print('age:{0}'.format(animal.age)) # print('sex:{0}'.format('male' if animal.sex==0 else'female')) # prin...
573d87f4706dd41c029cf68023e99514289fe494
memachado/rasp_miscellaneous
/Shutdown/5 - 1PB1LED - T&H - TempControl/SafeShutdown.py
766
3.609375
4
import RPi.GPIO as GPIO import time import os GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(18, GPIO.IN, pull_up_down = GPIO.PUD_UP) print("----------------------------") print("Rodando SafeShutDown...") print("----------------------------") # Our function on what to do when the button is pressed...
20790eca47232cd1779d12b4c78164f530c1d71f
bwyt/spider
/requests 百度贴吧/百度贴吧 面向对象.py
1,463
3.5
4
""" 实例化 run发放 获取url列表 获取数据 保存数据 """ import requests class Me: # 实例化 def __init__(self, t_name, start, end): self.t_name = t_name self.start = start self.end = end self.h = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77...
70465eff62f7d7dea614e8b9be1c013cf448f88f
EsaikaniL/python-2
/countchar.py
242
4.1875
4
while True: print("Enter 'x' for exit.") string = input("Enter a sentence: ") if string == 'x': break else: char = input("Enter a character to count: ") val = string.count(char) print(val,"\n")
7dc7a83ef282bed98cda5a550759f4b8e5a462a7
AnmolTomer/lynda_programming_foundations
/02_Beyond_Fundamentals/01_06.py
442
3.609375
4
nearest_to_earth = ['Sol', 'Alpha Centauri', 'Barnard', 'Wolf 359', ] print(nearest_to_earth[3]) highest_peak = { 'African': 'Kilimanjaro', 'Antarctic': 'Vinson', 'Australian': 'Puncak Jaya', 'Eurasian': 'Everest', 'No...
e2abe38488041db67824c15b603f21d0ff27f347
uhhcomonn/coding
/dice game.py
1,518
4.125
4
import math import inquirer import random # def dice_guessing(): # dice_num = random.randint(1,6) # for tries in range(3): # try: # user_num = int(input("Guess the number: ")) # if user_num in range(1,7): # break # else: # pr...
c0c22e4556471cf78527b64b2e8c2c6a46682925
KonradJankowski/python-poczatek
/elif.py
1,118
4
4
# Mamy 4 rodzaje wsparcia - od najlepszych do najgorszych śa to: # - Główne wsparcie -> przychód poniżej 5000 # - Wsparcie z funduszu pracowników -> od 5 do 10 pracowników # - Wsparcie dla nowych firm -> krócej niz 3 lata na rynku # - Wsparcie na pocieszenie -> dla każdego kto nie dostał żadnego innego income = 42000 ...
6bc67c8c211607eeb80bab2ba21438cbe8cc22eb
ApoorvaJu08/CodeChef
/Attendance.py
580
3.53125
4
def repeat(x): _size = len(x) repeated = [] for i in range(_size): for j in range(i+1, _size): if x[i] == x[j] and x[i] not in repeated: repeated.append(x[i]) return repeated for _ in range(int(input())): fn, ln = [], [] l, r = 0, [] for i in range(int(in...
f6054605f6b7a32fd5c1a875460864f54ff8bad5
mizanurriyadh/GeeksForGeeks-Practice-Problems
/Searching_a_number.py
542
3.578125
4
# Problem Source - https://practice.geeksforgeeks.org/problems/searching-a-number/0 def search(arr, n, x): for i in range(0, n): if(arr[i] == x): return i return -1 def Main(): t = int(input()) while(t): t -= 1 n, x = list(map(int, input().split())) ...
66df990f5b961d81890f92e919b1098bc9fb5262
itsss/SASA_OOP
/ch08_exception_file_function/file1.py
257
3.578125
4
f = open('test.txt', 'w') f.write('Python') f.close() f = open('test.txt', 'r') string = f.read() print(string) # 출력 값: Python f.close() f = open('test.txt', 'a') return_value = f.write(' is simple') print(return_value) # 출력 값: 10 f.close()
c0a7635c3775a0409f9770ea03c5f413b1ec1eee
TetianaSob/Python-Projects
/Ex-66_Build_in methods.py
766
4.53125
5
# Ex-66_Build_in methods.py '''Greatest Magnitude Exercise Write a function 'max_magnitude' that accepts a single list dull of number. It should return the magnitude of the largest magnitude ( the number that is furthest way from zero).''' '''max_magnitude([300, 20, -900])''' '''max_magnitude([10, 11, 12)''' ...
6034c172c656e14a2f617fd4967812560701f74d
radoslawik/SimpleFeedForwardNN
/ffnn.py
3,015
4.03125
4
# -*- coding: utf-8 -*- """ Simple implementation of Feedforward Neural Network (FFNN) """ import numpy as np import matplotlib.pyplot as plt N = 2 #number of variables K = 10 #number of neurons in the layer x1, x2, y = np.loadtxt("input.data", delimiter =' ', usecols =(0, 1, 2), unpack = True) I = len(x1) # amoun...
2b738a6697f459e0c0a5c8108da17f7c03b8294f
DEVANSH-DVJ/CS154-Spring-2021
/Lab 10/Practice/python-preliminaries/15logical-operators.py
142
3.828125
4
x = 0 y = 20 if x < 10 and y > 10: print('satisfied') if x > 10 or y > 10: print('satisfied') if not x > 10: print('satisfied')
5d94d85fa697e419d3151b53749c723e00d7e1fb
stevalang/Coding-Lessons
/SoftUni/Python Developmen/Python-Fundamentals/05_Functions/orders.py
603
4.21875
4
""" Write a function that calculates the total price of an order and prints it on the console. The function should receive one of the following products: coffee, coke, water, snacks; and a quantity of the product. The prices for a single piece of each product are: """ def find_price_per_unit(product, quantity): i...
c6d7d54c435d1f19a5ac225104f7ccd8b4e2b9b9
buptwxd2/leetcode
/Round_1/23. Merge k Sorted Lists/solution_1.py
891
3.9375
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None import heapq class Solution: def mergeKLists(self, lists: List[ListNode]) -> ListNode: min_heap = [] for list_node in lists: while list_node: ...
5411fbf70271e9172b7e0c5efd71a44884be1c01
tm-roamer/python-learn
/src/basic_study/for.py
632
3.75
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # names = ['a', 'b', 'c'] # for name in names: # print(name) # sum = 0 # for x in [1,2,3,4,5,6,7,8,9,10]: # sum += x # print(sum) # sum = 0 # for x in range(101): # sum = sum + x # print(sum) # sum = 0 # n = 99 # while n > 0: # sum = sum + n # n = n - 2 # pri...
77868d22f9a6b8654efcd77604c990e2f8528cc2
rafaelperazzo/programacao-web
/moodledata/vpl_data/59/usersdata/161/29290/submittedfiles/testes.py
569
4.03125
4
# -*- coding: utf-8 -*- #COMECE AQUI ABAIXO a=int(input('Digite a:')) b=int(input('Digite b:')) c=int(input('Digite c:')) if a>b and a>c: print('%d'%a) if b>c: print('%d'%b) print('%d'%c) if c<b: print('%d'%c) print('%d'%b) if b>a and b>c: print('%d'%b) if a>c: ...
c89cfef340f6d9179424859cd0337148dd67be2a
szagot/python-curso
/1-Iniciante/exercicios/6-Condicionais/6-Menor-Maior.py
477
4.09375
4
# De 3 números qual é o menor e qual o maior? num1 = int(input('Digite um número: ')) num2 = int(input('Digite outro número: ')) num3 = int(input('Digite mais um número: ')) menor = num1 if num2 < num1 and num2 < num3: menor = num2 if num3 < num1 and num3 < num2: menor = num3 maior = num1 if num2 > num1 and ...
0aefa1aa1ccc77fa8d6e78ed1c195e86cb07cdb5
RJStuver/old-man-learning
/hello.py
312
4
4
# This program says hello and asks for my name. print('Hello, world!') myName=input('What is your name? ') print('It is good to meet you '+myName) myAge=input('What is your age? ') print('you will be '+str(int(myAge)+1)+' in a year')
610161ddc2e5e36d5711a040ba466f24d71d4b6c
domantasjurkus/python
/hacker.org/xor/didactic_xor.py
1,096
3.796875
4
from xor import * chal1 = "3d2e212b20226f3c2a2a2b" chal2 = "948881859781c4979186898d90c4c68c85878f85808b8b808881c6c4828b96c4908c8d97c4878c858888818a8381" chal3 = "31cf55aa0c91fb6fcb33f34793fe00c72ebc4c88fd57dc6ba71e71b759d83588" # Challenge 2 for i in range(1, 256): print i, xor_hex(chal2, i, 8) # Challenge 3 ...
70d065eae644d59cf34b694befb03ec2d6b5efd3
AmeanAsad/Projects
/Vigenere_Cipher.py
5,268
4.09375
4
# -*- coding: utf-8 -*- """ Created on Sat Jun 10 00:15:52 2017 @author: ameanasad """ import string import itertools as it class Cipher(object): def __init__(self, text, keyword): self.text = text def get_text(self): return self.text def build_shift_dict(self, shift):...
214c8d6b3f086319a9a24e5e1f5e55d4a2453646
AlisonMcGuinness/UCDExercises
/mod3_sqldb.py
2,392
3.65625
4
import pandas as pd from sqlalchemy import create_engine print('how to query SQLITE db!') print(' 1. create database engine ') print('(Note this does not work if you put chinook.db in the project workspace??') print('But is fine if you open it from c:\sqlite folder') print(' I THINK this was because I need to run pyc...
1b09ef9564ffb03c8f8e524977191ec77b92a8ca
selinerguncu/Yelp-Spatial-Analysis
/analysis/stats.py
7,382
3.703125
4
# Let's import data from the Yelp Database as a Data Frame: import pandas as pd import sqlite3 as sqlite import os import locale try: locale.setlocale(locale.LC_ALL, 'en_US') except: locale.setlocale(locale.LC_ALL, 'en_US.utf8') def findCategoryPairs(): categoryCityPairs = {} conn = sqlite.connect('/Users/s...
7a6283d438379ba375fd6db204e2bfc5b0067c7c
JiangYuzhu/LearnPython
/python-qiyue/eleven-enumeration&closure/c11-14-1.py
369
3.921875
4
#问题:旅行者从原点出发,每走一段路程,计算与原点的距离。 #比如,先走2步,再走3步,再走6步,每次走完之后与原点的距离。 #用非闭包编写(正确代码) origin = 0 def travel(step): global origin pos = origin + step origin = pos return pos print(travel(2)) print(travel(3)) print(travel(6))
7653ec8d0433feb353c66e383d36cfff3e637484
amirafzali/coding-questions
/Word Break/sol.py
835
3.515625
4
def wordBreak(s, wordDict): states = set() words = set(word for word in wordDict) return self.search(s, words, 0, states) def search(s, words, pos, states): if pos >= len(s): return True for i in range(pos, len(s)): if s[pos:i+1] in words and i+1 not in states and se...
19291001fb2b1a0667a899c0559f0d947f406390
Manmeet13121996/jan2019
/stringrepeat.py
224
3.875
4
str = input('enter the str') substr = input('enter the substr') count =0 flag=True start=0 while flag: a = str.find(substr,start) if a==-1: flag=False else: count+=1 start=a+1 print(count)
5f2eddae76618ea77a7adaa6aa68b8f0c42c42a6
Shihab-Shahriar/Library
/python/SkipList.py
2,191
3.6875
4
from random import randint class Node: def __init__(self,v): self.v = v self.prev = None self.next = None self.down = None def add(self,v): """Add Node(v) next to self""" n = Node(v) n.next = self.next n.prev = self self.next = n ...
7468577ed69362d9ee0e4bf382d929caebd46fc7
cambrackmann/Python
/dictionary_example.py
1,363
4.5
4
#!/usr/local/bin/python3 # Set contains only keys: people_in_class = set() people_in_class.add("Cameron") people_in_class.add("Antoshka") for person in people_in_class:     print(f"class contains: {person}") # Dictionary contains key-value pairs people_ages = {} people_ages["Cameron"] = 24 people_ages["Antoshka"] =...
2394f6d382f042c28033c6a784ca1ae5e78b35ab
Vaaleanpunainen/Python_Workbook
/ex13_a.py
779
4.25
4
# program reads a number of cents from the user, # then computes and displays the denominations of the coins # that should be used to give that amount of change to the shopper cents =int(input("Enter the number of cents: ")) cents_per_toonie = 200 cents_per_loonie = 100 cents_per_quarter = 25 cents_per_dime = 10 cent...
1174025ba4a8408dcbb8c6c0c5772c4826ea26e2
siraquino/python
/ejercicios_python_cumanes/ejercicios_115_al_120.py
4,100
4.125
4
# Ejercicios resueltos del 115 al 120 # Trabajaremos con Funciones creadas por nosotros # Parámetros - Argumentos #................................................. # Ejercicio resuelto N115 # Problema: crear una función que muestre un saludo personalizado print() print("-"*40) print("Programa N115: crear una función ...
08ea5584d2cf03e3dfe5e123a4c7d78407f6fd5f
Dod-Annie/Python-Learning
/lesson1/dict_order.py
415
3.890625
4
#根据字典中值的大小,对字典的项排序 ##内置函数sorted sorted([9,1,2,8,5]) from random import randint d = {x: randint(60,100) for x in 'xyzabc'} print(sorted(d)) #对字典使用sorted会直接对键排序 # 将dict转化成tuple ## 使用zip函数 s = zip(d.values(),d.keys()) print(sorted(s)) ## 使用sorted函数中的Key参数 s2 = sorted(d.items(), key=lambda x: x[1]) print(s2)
c91081827cac709c44e5b1499cadf3d954633b6b
CrazyYong/pythonProject
/列表元组字典/dictionaryExample.py
6,600
3.71875
4
#!/usr/bin/python3 #coding=utf-8 #字典 ''' 字典是另一种可变容器模型,且可存储任意类型对象。 字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中 ,格式如下所示: ''' #d = {key1 : value1, key2 : value2 } ''' 键必须是唯一的,但值则不必。 值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。 一个简单的字典实例: ''' dict1 = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'} #(1)此创建字典: dict1...
1eb4c33b0c87d1006509b4d4efa23ec1410e0756
jasuil/python
/day002/class/ex002.py
381
3.703125
4
#class class Calculator: result = 0 #define and set def __init__(self, x, y): self.x = x self.y = y self.result = 0 def plus(self, num): self.result = self.x + self.y return self.result call = Calculator(1, 2) call2 = Calculator(-2, 4.7) print(call.plus(10)) pri...
8d2b33392a40a8ce2bfce5a11860f82949490f2e
agnaka/CEV-Python-Exercicios
/Pacote-download/Exercicios/ex052.py
405
3.875
4
num = int(input('Digite un número: ')) tot = 0 # p = 0 for i in range(1, num + 1): if num % i == 0: print('\033[33m', end='') tot += 1 else: print('\033[31m', end='') print('{} '.format(i), end='') print('\n\033[mO número {} foi divisível {} vezes'.format(num, tot)) if tot == 2: ...
1e285a9222442fc693c901f94a859c5619041b6c
BangDaeGeon/2020_cphys2-1
/Hyeonho Choi/hw2.py
404
3.5
4
def multi(dan): print(dan,'단 :', [dan*i for i in range(1,10)]) def OorE(number): if(number%2 == 1): return 'Odd' if(number%2 == 0): return 'Even' else: return 'Input number must to be integer' def average(A): sum = 0 for i in range(len(A)): sum = sum...
9cec730461963ff9d06d29195489b85ec85a303e
BBtocchi/casino
/casino.py
1,885
3.796875
4
import os import sys from random import randrange from math import ceil cagnotte = 100 cagnotte = int(cagnotte)#on commence avec 100$ print (" début de la partie ..." , "vous avez 100$") continuer_partie = True while continuer_partie == True: #on crée une boucle pari= input("pariez sur un nombre e...
aa5a928a8cf3ddc0e338eae096cf06b8e531b566
tmu-nlp/100knock2017
/vincentzlt/chapter02/knock16.py
992
3.671875
4
# coding: utf-8 # In[5]: #!/usr/bin/python import sys,getopt # In[6]: def split_n(f_name,n): with open(f_name,"r",encoding="UTF-8") as input_f: lines=input_f.readlines() digits=len(str(len(lines))) for i in range(0,len(lines),n): output_f_name=f_name+"."+'{num:0>{digits}}'.format...
8fd72ca35eaac48ee2fb30788da66512031f9e1f
fahmedtech/Python-Courses
/CSC241. Intro Python/CSC241. HWs (5)/Py-HW 4 CSC241.py
12,568
4.3125
4
''' Python CSC241 HW 4 - 6/27/2016 ''' #HW 6 #Program 1: ''' A polynomial of degree n with coefficients a0, a1, a2, a3, ..., an is the function: p(x) = a0 + a1x + a2x**2 + a3x**3 + ... + anx**n. This function can be evaluated at different values of x. For examples, if p(x) = 1 + 2x + x**2, then p(2) = 1 + 2 * 2 + 2**...
a13a3723b5c5277071a88376c8a21ce8a716dbd5
lkjx031021/ML
/code/Linklist.py
2,608
3.640625
4
class LinkedListUnderflow(ValueError): pass class Node: def __init__(self, elem, next_=None): self.elem = elem self.next_ = next_ class DNode(Node): def __init__(self, elem, prev=None, next_=None): Node.__init__(self, elem, next_) self.prev = prev class LList: def __in...
c5625d7be6879ce6a8bec508a743b84fa0b917c5
tatumgb/rps
/choice_choice.py
146
4
4
def choice(): """calls for string input and returns that string in lowercase""" str = raw_input ("Enter a choice") return str.lower()
6b2e44b09af67fb02457b3299f10181aac7cbfab
anilgursahani/bitesofpy
/49/submissions/save1_nopass.py
416
3.671875
4
from collections import namedtuple from bs4 import BeautifulSoup as Soup import requests PACKT = 'https://bites-data.s3.us-east-2.amazonaws.com/packt.html' CONTENT = requests.get(PACKT).text Book = namedtuple('Book', 'title description image link') Book.title = "Tom Sawer" print(Book.title) def get_book(): """...
30ebc3a2c1de50ff96768cbc2b78786ebde5286f
jmatteo/Machine-Learning-Fall-20
/Assignments/Quizzes/Quiz 1/Original Files/Q1.py
1,759
3.515625
4
''' Q1 Data augumentation for the CNN for CIFAR-10 dataset ''' import keras from keras.datasets import cifar10 from keras.models import Sequential from keras.layers import Dense, Dropout, Activation, Flatten from keras.layers import Conv2D, MaxPooling2D import pandas batch_size = 256 num_classes = 10 epochs = 50 (x...
13b274c85b4eebb717db47af06f4d122a8f191d7
dolomaniuk/python_project
/cours/week_1/clock2/solution.py
859
3.578125
4
iSec = int(input()) # сколько прошло секунд всего day = iSec // (24*3600) iSec = iSec - day * 24 * 3600 hour = iSec // 3600 # сколько прошло часов с начала if hour > 0: min = iSec % (hour * 3600) // 60 # сколько прошло минут с начала else: min = iSec // 60 sec = iSec - (hour * 3600) - (min * 60) ...
b7a0b75cd684629ac6eb604b8166091c72d51f5a
xy008areshsu/Leetcode_complete
/python_version/max_product_subarray.py
1,265
4.03125
4
""" Find the contiguous subarray within an array (containing at least one number) which has the largest product. For example, given the array [2,3,-2,4], the contiguous subarray [2,3] has the largest product = 6. """ # idea: # maintain: max_ending_here, min_ending_here, max_so_far # Exactly the same as max_sum_subar...
3013dba5d15a31ab5d83e784ed634a415d903897
ihalage/reinforcement_learning
/math_game/dqn_math_game.py
12,271
3.515625
4
''' ########################################################################################### This math game is developed by Avin to test the performance of Reinforcement Learning(RL). A DQN is used in this project Game Description: Select numbers from a pool of numbers and fill a 3x3 grid such that when the SUM ...
c877d392fa4da88f673456ba859f0c14324e2231
astonshane/DavisPutnamNoCNF
/davisputnam/tests/test_match.py
4,008
3.546875
4
import unittest from match import match class TestMatching(unittest.TestCase): def test_literal(self): val = match("A") self.assertIsNotNone(val) [kind, matches] = val self.assertEqual(kind, "lit") self.assertEqual(matches, "A") def test_negation(self): # defi...
fbb772a93aae8a219997bb8da26fdf8c4f14dd1d
JoelRamirez2016/holbertonschool-higher_level_programming
/0x0B-python-input_output/2-append_write.py
376
4.5625
5
#!/usr/bin/python3 """This module defines the add write function""" def append_write(filename="", text=""): """Appends a string at the end of a text file Args: filename (str): file name text (str): text to write Returns: the number of characters added """ with open(filename...