blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
8d0e0484f0ab22e0a866b9861a1226c74bd57215
snehadasa/holbertonschool-low_level_programming
/0x1C-makefiles/5-island_perimeter.py
685
4.09375
4
#!/usr/bin/python3 """to calculate the perimeter of an island that is described in the grid""" def island_perimeter(grid): perimeter = 0 for row in range(len(grid)): for column in range(len(grid[row])): if grid[row][column] == 0: continue if column == 0 or grid[...
6e05bf9215f6fb061724959f3cb2de1fb4c5bf39
Rxdxxn/Operatori-Python
/problema 2.py
157
3.734375
4
a=10 b=3 print(a,"+",b,"=",a+b) print(a,"-",b,"=",a-b) print(a,"//",b,"=",a//b) print(a,"%",b,"=",a%b) print(a,"*",b,"=",a*b) print(a,"**",b,"=",a**b)
8ffdf6884cf30dc7561e207ccb7bde5585fcb35a
nijinchandran/pythonprograms
/data collections/list/limit.py
111
3.78125
4
limit=int(input("enter limit")) for i in range(limit): e=int(input("enter elmnt")) l.append(e) print(l)
2254917d4778a811f2c891a09041aed3ee42dd48
peterg79/regenmaschine
/regenmaschine/watering.py
1,902
3.6875
4
"""Define an object to interact with generic watering data/actions.""" import datetime from typing import Awaitable, Callable class Watering: """Define a watering object.""" def __init__(self, request: Callable[..., Awaitable[dict]]) -> None: """Initialize.""" self._request: Callable[..., Awa...
07a9ebd9f3068629a84f9a6939c58e0d7e3878e9
bakil/pythonCodes
/turtle/turtle_miniTrangle.py
1,049
3.859375
4
import turtle def draw_trangle(temp_t,length): temp_t.begin_fill() temp_t.fillcolor("green") for i in range(3): temp_t.forward(length) temp_t.left(120) temp_t.end_fill() def draw_threeTrangle(temp_t,length): draw_trangle(temp_t,length) temp_t.forward(length) draw_trangle(t,length) temp_t.left(120) temp...
8fb142d6e4f207faeb43db8661cc26395096311a
MRivadavia/Math-With-Python
/Aula4.py
1,080
4.46875
4
""""Programa que trabalha com funções II """ from fractions import Fraction a = Fraction() # Por definição, o numerador é zero e o denominador é 1. A variável 'a' recebe a fração 0/1. print(a) # Portanto, retorna zero. b = Fraction(3 / 4) # A função Fraction recebe em seu argumento uma fração e retorna a m...
bcdc76eb3b35a975f9cb4138d767326da5966f20
joaopvgus/ADS
/10 - padaria.py
2,145
3.828125
4
## menu: 1 - cadastrar produto, 2 - venda de produto, 3 - total de vendas, 4 - ver estoque 0 - sair ## CADASTRAR PRODUTO ## pedir NOME ## pedir PRECO ## pedir QUANTIDADE ## imprimir NOME - PRECO - QUANTIDADE ## VENDA DE PRODUTO ## pedir NOME ## pedir QUANTIDADE ## imprimir valor tota...
e7ee8b0d81417998498c14211746d96433d69348
BeauNimble/KEEEPERAI
/mould.py
14,247
3.609375
4
# Importeren van packages import pandas as pd import datetime from timey import new_time def mouldChangeCapacity(start_date, end_date): mould_change_capacity = pd.read_excel('Mould change capacity.xlsx', header=0) # The amount of mould changes that can be done ...
a756d666a66345272980aa0c0af9232fe8b2d0e1
rohithkumar282/K-Nearest-Neighbour-DigitsMNIST
/KNN_SML_Assignment3.py
3,003
3.53125
4
#!/usr/bin/env python # coding: utf-8 # In[5]: import numpy as np import pandas as pd import math from sklearn import metrics from sklearn.preprocessing import scale from collections import Counter from scipy.spatial import distance Xtrain= pd.read_csv('mnist_train_digits.csv',header =None) Xtest= pd.read_csv('mnist...
29691b448c5ef4ac3801cd8b34934bb1e8faf689
jiwoo-kimm/dsc-algorithm
/kimna/keypad.py
1,494
3.75
4
def handlength(hand, number): number = str(number) location_x = {'1': 0, '2': 0, '3': 0, '4': 1, '5': 1, '6': 1, '7': 2, '8': 2, '9': 2, '*': 3, '0': 3, '#': 3} location_y = {'1': 0, '2': 1, '3': 2, '4': 0, '5': 1, '6': 2, ...
bd920c03cf3c4d7eb66f97f07833dc78cba5edf5
maximkavm/ege-inf
/23/Количество программ с обязательным этапом/7 - 13633.py
442
4.0625
4
""" Сколько существует программ, для которых при исходном числе 2 результатом является число 30 и при этом траектория вычислений содержит число 15? +1 *2 *3 """ def f(x, y): if x < y: return f(x + 1, y) + f(x * 2, y) + f(x * 3, y) elif x == y: return 1 else: return 0 print(f(2, 15) * f(15, 30)) # Ответ: 4...
b04d98143b8d793056e17f5549edd13102312387
harsilspatel/ProjectEuler
/58. Spiral primes.py
736
3.875
4
#def isPrime(n): # # Assuming inputs are non-even numbers # for i in range(3, int(n**(1/2)) + 1, 2): # if n % i == 0: # return False # return True def eratosthenesSieve(n): primesDictionary = {i:True for i in range(2, n+1)} rootN = n**(1/2) for i in range(2, int(rootN) + 1): if primesDictionary[i]: j = i...
a40d51e273b75dc835273118df49a0aa04dfe01a
shalu169/lets-be-smart-with-python
/GUI1.py
237
3.640625
4
import math def squares(a, b): count = 0 for i in range(a,b+1): p = i**.5 print(p) inti = int(p) deci = p- inti if deci == 0: count = count + 1 print(count) squares(1,10)
93afa044a3497155faa2582dd682bbc1f1db701b
peitaosu/Cardiff
/diff.py
1,025
3.515625
4
import os, sys, importlib, time def diff_file(file_before, file_after, file_output_name = None): """diff file and save as file args: file_before (str) file_after (str) file_output_name (str) returns: saved_file (str) """ file_name = os.path.basename(file_before...
01211fd4c4b41a98fdf04b8ea03cf6435f906ff1
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4160/codes/1836_2603.py
194
3.734375
4
from numpy import* from numpy.linalg import* a = array(eval(input("Digite uma matriz: "))) #vetor auxiliar pra coluna: a= a for i in range(4): a[:,i] = sorted(a[:,i],reverse=True) print(a)
a05af100906f069f8c59c5001740a18be8119b84
bloomfieldfong/Mancala
/prueba_mancala.py
5,430
3.875
4
from funciones import valid_move, print_board, play, winner, corrida_juego, possible_movess import random import copy # Funciona porque el random es uniforme y esto hace que en muchas # iteraciones el valor esperado sea aproximado a 1/6 de la cantidad de iteraciones ##Define el board que tendremos y el turno del jug...
7375ed056f4eb4787daf75f91d00719cde81bed7
yangxiaodong1/ygblcrm
/test/day9.6晚上/直接插入.py
362
3.734375
4
'''扫描,当前元素''' def insert_sort(arr): count = len(arr) for i in range(1,count): j=i-1 # 扫描元素 key = arr[i] # 比较元素 while j>=0 and key<arr[j]: arr[j+1] = arr[j] j -=1 arr[j+1] = key return arr if __name__=="__main__": arr = [12,33,4] print(insert...
796db3056ae4bb4fcdc8e363ea3c18a06bb12cc4
ISPritchin/Olympiad
/800/Оформлено/Эпическая игра.py
289
3.5625
4
def gcd(a, b): if b == 0: return a else: return gcd(b, a % b) a, b, n = map(int, input().split()) while True: r = gcd(a, n) if r > n: print("1") break n -= r r = gcd(b, n) if r > n: print("0") break n -= r
3f3d82d40c4ac46bdb0874b71b0a3958668238a3
dngur807/ScriptTermProject
/공부내용/Practice/PythonPractice_Jeasun/클래스 상속.py
834
4
4
class Person: #부모 클래스 def __init__(self, name, phoneNumber): self.Name = name self.PhoneNumber = phoneNumber def PrintInfo(self): print("name : {0} , PhoneNumber : {1}".format(self.Name, self.PhoneNumber)) class Student(Person): #자식클래스 (Person에서 상속받음) def __init__(self, name, phon...
9da472b410593f5298a1e7cc921073c0c5789084
TravenYu/ICS4U1c-2018-19
/Working/OOP/practice_address.py
1,137
3.921875
4
class Address(): def __init__(self): self.address_line1 = "" self.address_line2 = "" self.postal_code = "" self.city = "" self.province = "" self.country = "" def print_address(addr): print(addr.address_line1) if addr.address_line2 != "": print(addr...
a6cd8ac9bd933f28e6fcce888187b16e1d3764c1
drakohha/Python
/Test/Game_kosti.py
7,846
3.609375
4
from random import * import os def fun_proverki(i,j): #функция проверки ввода в заданном диапозоне while True: try: n=int(input()) if n>=i and n<=j: break else: print("Не верный ввод, введите число в диапозоне от ",i," до ",j) ...
8fa6c697be99474bb7db1c4d4c6b987498ec5c9f
saurabhmehta04/charming_python
/basics/designPatterns/StructuralPattern/decorator.py
950
4.09375
4
from functools import wraps def make_blink(function): ''' Defines the decorator''' # This makes the decorator transparent in terms of its name and docstring @wraps(function) # Define the inner function def decorator(): ret = function() return "<blink>" + ret + "</blink>" ret...
bc6c9c4eaabf75764d2fdebac69264b54da7179f
jjkyun/tensorflow
/2._cost.py
1,115
3.6875
4
''' Lecturer: Sung Kim 여기서는 Cost Function을 조금 더 깊게 살펴본다 - Cost Function 설계할 때 산꼭대기 경사가 하나(Convex Function)인지 확인!! ''' import tensorflow as tf import matplotlib.pyplot as plt x_data = [1,2,3] y_data = [1,2,3] W = tf.Variable(tf.random_normal([1]), name = 'weight') X = tf.placeholder(tf.float32, shape = [None]) Y = tf....
3315ce6d3b7ad68c4e5beea0f8af95b3d40ef7ac
franklingu/leetcode-solutions
/questions/wiggle-sort-ii/Solution.py
826
3.953125
4
""" Given an integer array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3].... You may assume the input array always has a valid answer.   Example 1: Input: nums = [1,5,1,1,6,4] Output: [1,6,1,5,1,4] Explanation: [1,4,1,5,1,6] is also accepted. Example 2: Input: nums = [1,3,2,2,3,1] Output: [2,3,1,...
d8a0754e9e9b5c2bd8c46d3ee9bca5d84576a40b
kyzhouhzau/Python
/frequence statistic.py
473
3.578125
4
#!/usr/bin/env python3 # -*- coding:utf-8-*- # 词频统计 import collections import re def get_words(file): with open(file) as f: words_box = [] for line in f: words_box.extend(re.split(r'[;\.\s]*', line)) new_words_box = [] for word in words_box: if word.isalpha(...
6d55447ab313a2be076ab47aea35f60d61f27e83
erjan/coding_exercises
/count_items_matching_rule.py
1,205
3.921875
4
class Solution: def countMatches(self, items: List[List[str]], ruleKey: str, ruleValue: str) -> int: num_items = 0 for item in items: type_i = item[0] color_i = item[1] name_i = item[2] print(type_i, color_i, name_i) rule1 =...
83cf547fa636612c4013167b131e133fbcc2510e
NoahLE/Coding-Challenges
/hr-Python-String-Validators.py
866
4.34375
4
def StringValidator(VString): # --- print True of the string contains any of the following characters, otherwise, print False --- isAlphaNum = False isAlpha = False isDigit = False isLower = False isUpper = False for character in VString: # True if alphanumeric if character....
64a7d2aa44754d2a192ec13aad3418a8defd09e0
107318041ZhuGuanHan/TQC-Python-Practice
/_6_list/609/main.py
2,797
4.34375
4
# matrix_1 = [[1, 2], [3, 4]] # matrix_2 = [[5, 6], [7, 8]] # matrix_3 = matrix_1 + matrix_2 # -> ★不能這樣搞,這樣會變成 matrix_3 = [[1, 2], [3, 4], [5, 6], [7, 8]] # ★要用元素相加的方式 # 1.建3個 2*2 的矩陣 2. 可以試著把那3個 2*2 的矩陣放在同一個list裡面 matrix_1 = [[0 for column in range(0, 2)] for row in range(0, 2)] matrix_2 = [[0 for column in range(0, ...
3f09a29ce6f3d26cfc470b3f532e25dddcacc9c0
sknaht/algorithm
/python1/data_structure.py
375
3.609375
4
class ListNode: def __init__(self, x): self.val = x self.next = None def __repr__(self): if self: return "{} -> {}".format(self.val, repr(self.next)) class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class ...
823990477f7dbcbc9bdf6e6912e35a92ed274dc1
monikpatel125/monik
/matrix.py
192
3.765625
4
#!/usr/bin/env python # coding: utf-8 # In[2]: x=int(input("enter row:")) y=int(input("enter col:")) def a(x,y): l=[i*j for j in range(y) for i in range(x)] return l print(a(y,x))
6247f75781854cb241e943491db4de59ab57ae44
bnavalniy/PyClass
/homeWorks/2/Task5Reiting.py
420
3.625
4
my_list = [7, 5, 3, 3, 2] num = int(input("Enter the N: ")) if num in my_list: position_to_insert = my_list.index(num) + my_list.count(num) my_list.insert(position_to_insert, num) else: for ind, el in enumerate(my_list): if num > el: my_list.insert(ind, num) break eli...
d09e645bdcec69cb9cf80bbcf97e2699faf3485f
rfaulkner/project_euler
/p19.py
583
3.53125
4
#/env/bin/python # -*- coding: utf-8 -*- """ Project Euler - problem 14 """ __author__ = "ryan faulkner" __date__ = "12/3/2012" __license__ = "GPL (version 2 or later)" import sys from datetime import datetime, timedelta def main(): end = datetime(year=2000, month=12, day=31) cur_time = datetime(year=19...
1a775713a7e1d3297d1601ad308b098b5c8c3479
sastafeva/GB_Algorithms
/Lesson_1_scheme/les_1_task_8.py
1,212
4.3125
4
# Вводятся три разных числа. # Найти, какое из них является средним (больше одного, но меньше другого). # В условиях задачи не указано, что на вход подаются целые числа. Принимаем любые. # По условиям, мы не делаем проверку на корректность ввода. # Значит на вход подаются точно числа и они все разные. a = float(input(...
f3f427e6d78ec38f98eea3ea0bb15a3ef89c3190
MifengbushiMifeng/Pygo
/practice/practice3/first_PY_11.py
606
3.78125
4
# coding=utf-8 # practice Generator in Python # list L = [x * x for x in range(10)] print L g = (x * x for x in range(10)) print g for n in g: print n def fib(max): n, a, b = 0, 0, 1 while n < max: print b a, b = b, a + b n = n + 1 fib(100) def fib2(max): n, a, b = 0, 0,...
051c46b199dc610419248e1f41fb1e3e1b1ebb7e
ivanbelichki/flash_cards_app
/flash_cards.py
4,342
3.609375
4
import random # CONSTANTS CARDS_FILE = 'cards.txt' QA_DIVIDER = ':' ADD_KEY = 'a' PLAY_KEY = 'p' VIEW_KEY = 'v' REMOVE_KEY = 'r' QUIT_KEY = 'q' VALID_KEYS = [ADD_KEY, REMOVE_KEY, PLAY_KEY, VIEW_KEY, QUIT_KEY] # driver def __main__(): choice = '' while choice != QUIT_KEY: choice = start() if ...
c9a2fc2908535238c16306a2c1e30de6a396a392
HamzaIlyas/EventRegistration
/main.py
6,462
3.53125
4
import json ContactsList = [] LeadsList = [] class Contacts: contactscount = 0 def __init__(self, name, email, phone): self.Name = name self.Email = email self.Phone = phone Contacts.contactscount += 1 def getcontactscount(self): print("Total Contacts %d" % Cont...
62442337801a9008bacb26a6306274202eff2e31
Tokyo113/leetcode_python
/暴力递归到动态规划/code_04_cardsinLine.py
1,181
3.53125
4
#coding:utf-8 ''' @Time: 2019/11/17 10:18 @author: Tokyo @file: code_04_cardsinLine.py @desc: 给定一个整型数组arr,代表数值不同的纸牌排成一条线。玩家A和玩家B依次拿走每张纸 牌,规定玩家A先拿,玩家B后拿,但是每个玩家每次只能拿走最左或最右的纸牌,玩家A 和玩家B都绝顶聪明。请返回最后获胜者的分数。 ''' def win1(arr): if len(arr) == 0 or arr is None: return 0 return max(f(arr, 0, len(arr)-1), s(arr...
d55fd3f5e9604b19b1f569b6657cd83164c488b1
nhatminh2h/LiDAR
/writetofile.py
1,234
3.609375
4
import serial import numpy as np from math import cos, sin,radians, pi print("Enter name of file to write to: ") filename = input() f = open(f'{filename}.txt',"w+") #Arduino port here port = 'com3' ArduinoSerial = serial.Serial(port, 115200)#serial port object #data arrays #theta, phi, r = ([0] for i in rannge(3))#...
8ad816ec9ccc197d330eb8a57bbad01099bacc63
136772/MyPython
/Mycode/learn/3.py
366
3.90625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' @author:JaNG @email:136772@163.com ''' ''' name = iter(['jang','rourou','book']) print(name.__next__()) print(name.__next__()) print(name.__next__()) ''' def cash_money(amount): while amount>0: amount -= 1 yield '取了{},还剩{}'.format(1,amount) temp ...
828989ed02016bba346d6773417ac75d19341812
aneverov/python_stepik
/2_3_1.py
242
3.578125
4
a=int(input()) b=int(input()) c=int(input()) d=int(input()) print(end='\t') for i in range(c,d+1): print(i,end='\t') print() for j in range(a,b+1): print(j,end='\t') for k in range(c,d+1): print(k*j,end='\t') print()
b909624061d689f0a821a6d4c79a71e0c0d08702
Ghong-100/Python
/Practice/Exception.py
1,235
4.03125
4
class Overflow(Exception): def __init__(self, msg): self.msg = msg def __str__(self): return self.msg try: print("한자리 숫자 계산기") num1 = int(input("첫번째 :")) num2 = int(input("두번째 :")) if num1 > 9 or num2 > 9: raise Overflow("입력값 : {0}, {1}".format(num1, num2)) print("{...
56630c725dfd1089707b6acbc7915e33fba79ee5
dylanlee101/leetcode
/code_week16_810_816/clone_graph.py
1,807
3.9375
4
''' 给你无向 连通 图中一个节点的引用,请你返回该图的 深拷贝(克隆)。 图中的每个节点都包含它的值 val(int) 和其邻居的列表(list[Node])。 class Node { public int val; public List<Node> neighbors; }   测试用例格式: 简单起见,每个节点的值都和它的索引相同。例如,第一个节点值为 1(val = 1),第二个节点值为 2(val = 2),以此类推。该图在测试用例中使用邻接列表表示。 邻接列表 是用于表示有限图的无序列表的集合。每个列表都描述了图中节点的邻居集。 给定节点将始终是图中的第一个节点(值为 1)。你必须将 给...
6ed47cda0891e8accd10dc2437f6f3ba5f0c1be9
Douphing/Python
/desfio008.py
181
3.71875
4
medida = float(input(' Uma distancia em metros: ')) cm = medida * 100 mm = medida * 1000 print('a medida de {}m cor' 'responde a {:.0f}cm e {:.0f}mm'.format(medida, cm, mm))
2a2b51427baf92beeb239794ef6ab544bc52ce2e
alecownsyou/Programming-11-Files_
/alec.py
2,128
3.890625
4
count = 0 print ("\nBonjour") print ("Question 1: Qu'elle années est-ce que chapitre est sur?") answer1=input("Mis seulement les numéros\nExample: 1990\n") if answer1.lower()== "1920": print ("Correcte") count += 1 else: print ("Incorrect") print ("\nQuestion 2: Vrai ou faux: Est-ce qu'il y a du racisme dans Canad...
5e94cd487cb871407c1b21b157822f6a9a7b3a57
madeibao/PythonAlgorithm
/py股票的最大利润2.py
399
3.53125
4
from typing import List class Solution(object): def maxProfit(self, prices: List[int]) -> int: if len(prices)==0: return 0 profit = -float("inf") temp = prices[0] for i in range(1, len(prices)): temp = min(temp, prices[i]) profit = max(profit,prices[i]-temp) return profit if __name__ == "__...
b4075e145f757632bd4549fd94a15ceeee864967
pele98/Object_Oriented_Programming
/OOP/Exercise5/Excercise5_5/main.py
886
3.953125
4
# File name: main # Author: Pekka Lehtola # Description: main file for player dictionary game. from player_class import * from dice_class import * #Creating all of the objects. matti = Player(1, "matti", "koskinen") pekka = Player(2, "pekka", "lehtola") linda = Player(3, "linda", "laine") #Creating list of players a...
bce71f36112cbef787a50ffa8dffb444c50f5ce5
phporath/GIS-Tools
/ArcPy/calculoAzimute.py
674
3.6875
4
-Em "Pre-Logic Script Code" digite: def LookUp(eInic, eFim, nInic, nFim): eFimInic = eFim - eInic nFimInic = nFim - nInic rumo = abs(math.degrees(math.atan(abs(eFimInic / nFimInic)))) if (eFimInic>0 and nFimInic>0): azimute = abs(rumo) elif (eFimInic>0 and nFimInic<0): azimute = a...
b717c00c5b9d44d9837f1fc2c40d46e1710c54b9
BaoLocPham/ThePongGame
/Ball.py
628
3.875
4
from turtle import Turtle class Ball(Turtle): def __init__(self): super().__init__() self.shape('circle') self.color('white') self.penup() self.x_move = 10//2 self.y_move = 10//2 def move(self): self.goto(self.xcor()+self.x_move, self.ycor()+self.y_move...
4044156bfd391934aafdd18c791f65dc5725f3c9
ybai62868/heterocl
/tvm/tests/verilog/unittest/testing_util.py
2,177
3.53125
4
"""Common utilities for test""" class FIFODelayedReader(object): """Reader that have specified ready lag.""" def __init__(self, read_data, read_valid, read_ready, lag): self.read_data = read_data self.read_valid = read_valid self.read_ready = read_ready self.read_ready.put_int(1...
af51195335f604dfa270c2f8ca55ac1c9d396101
Meao/py
/repl/4-3Memorizing.py
1,008
3.640625
4
from collections import deque # queue LIFO & FIFO # LIFO - Last in first out # FIFO - First in first out class MemorizingDict(dict): history = deque(maxlen=10) def set(self, key, value): self.history.append(key) # MemorizingDict.history self[key] = value # memDict = dict() memDict[key] =...
cb507a83ea7c686115f9a4c3b3f0ae7ec9c111aa
paulohenriquegama/Blue_Modulo1-LogicaDeProgramacao
/Aula16/oo1.py
1,238
4.0625
4
'''class Heroi: def __init__(self,nome, idade = 30,habilidade = 'magia'): self.nome = nome self.idade = idade self.habilidade = habilidade def usar_habilidade(self): print(f"{self.nome} está usando sua habilidade: {self.habilidade}.") nome = input("Digite o nome: ") he...
9303781bcce886a995672e64f3f5278a17f1a2d6
mareliefi/code-wars
/find_odd_even.py
292
3.8125
4
def find_outlier(integers): array_even = [] array_odd = [] for i in integers: if i % 2 == 0: array_even.append(i) else: array_odd.append(i) if len(array_even) == 1: return array_even[0] else: return array_odd[0]
bd43b876e62f971bfb2461cd678ee86b508b8e13
sanusiemmanuel/DLBDSMLUSL01
/Unit_4_Feature_Engineering/4_1_Numerical_feature_scaling.py
2,189
3.71875
4
# IU - International University of Applied Science # Machine Learning - Unsupervised Machine Learning # Course Code: DLBDSMLUSL01 # Numerical feature scaling #%% import libraries import pandas as pd from sklearn.preprocessing import MinMaxScaler from sklearn.preprocessing import StandardScaler from sklearn.preprocess...
d0c74d45d1f300ce6590ff145e6af834330b1165
mkm14/store
/创作.py
1,656
3.8125
4
brand = ("欢迎来到娱乐商城") print("--------------------------",brand,"----------------------") tips = ("未成年人禁止娱乐") print("--------------------------",tips,"---------------------------") nem = input("请输入您的名字:") if nem=='阮红英': print('欢迎荣耀段位的大神来到娱乐城') elif nem=='张宇航': print('欢迎王者20性段位的大神来到娱乐城') elif nem=='王赛':...
3f20a0d4af6f64d76cd4c4f9fe0a838f6a4b4693
shaan2348/hacker_rank
/itertools_product.py
297
4.25
4
# we have to print the cartesian product of two sets # using product function from itertools module # "*" infront of any thing in print unpacks the list or tuple or set from itertools import product a = [int(x) for x in input().split()] b = [int(x) for x in input().split()] print(*product(a,b))
b1fd94840c71bff364a7edbd2239c073352e856a
cassiocamargos/Python
/learn-py/listas-py/a5.py
680
3.921875
4
# 5- O cardápio de uma lanchonete é dado pela tabela de preços abaixo. Escreva um programa que leia a quantidade de cada item comprado por um determinado cliente e imprima o valor total da sua compra. # Hambúrguer R$ 8,00 # Batata frita R$ 12,00 # Refrigerante R$ 3,00 # Cerveja R$ 5,00 # Doce R$ 3,00 h ...
36a43e1fdfb944d3937d2da8a5308f10c9f3f020
AshishMaheshwari5959/InfyTQ
/Programming Fundamentals using Python/Day 5/Exercises/Exercise 29: Collaborative Exercise – Level 2.py
1,408
4.3125
4
''' Write a python program which merges the content of two given lists and sorts the merged list. Write the following functions to achieve the above functionalities: def merge_lists(list1,list2): Returns the merged list. Use keyword arguments to pass the lists in method invocation Note: Merge the lists such that elem...
484df1a1d7072e8dd44e42d2fe96c67cfe54d23f
Cutshadows/productHunt
/ejercicio.py
212
3.625
4
from random import randrange inputvalue="" while inputvalue != "n": dado1=randrange(1, 7) print("dado2:", dado2) print("suma:", dado1+dado2) inputvalue=input("quires tirar otra vez los datos (s/n)")
b74a24fcc0251b5b7b3e1f5c37aeefcfe249cfe7
priyancbr/PythonProjects
/ListOperations.py
666
3.953125
4
MyList = ['One','two',3] print(MyList) MyList[1] = 'TWO IN CAPS' MutatedList = MyList print(MyList) NextList = [4, 'five'] print(NextList) LatestList = MyList + NextList print(LatestList) LatestList.append('Six') print(LatestList) Vari = LatestList.pop() print(Vari) print(LatestList) PoppedItem = LatestList.pop(3) prin...
d36d8b215b10220a6e4d7ced418d84426fedd63d
superstones/LearnPython
/Part1/week2/chapter9/exercise/User.py
540
3.609375
4
class User(): def __init__(self, first_name, last_name, age, sex): self.first_name = first_name self.last_name = last_name self.age = age self.sex = sex def describe_user(self): print("\nfirst_name:" + self.first_name.title()) print("last_name:" + self.last_name....
9506986694271d7e0a6bd18395ba81464af03027
e-hamilton/hello_ml
/Log_Regression.py
2,745
3.875
4
""" This is a basic Logistic Regression program I wrote in an effort to dip my toes into Scikit-learn's machine learning tools. It evaluates unigrams and bigrams in several categories of the 20 Newsgroups dataset and produces a confusion matrix. This project doesn't follow a single tutorial; I looked at several and pi...
fe2e44c4b877dd8b8527b67af51fa7ac962227b4
xaviergoby/Helicopter-Emergency-Medical-Service-HEMS-Drone
/flight_performance.py
4,500
4.125
4
"""This file calculates the following flight performance parameters: Max ascent speed, Max Descent speed, Max horizontal flight speed, Max ascent acceleration, Max Descent acceleration, Max horizontal flight acceleration, Max range, Hovering endurance, Cruising endurance, Wind speed resistance.""" import numpy as np ...
0c44d8b7fa9c8db3c7cab1467653a7bc37d2a9c0
bevishe/Leetcode
/leetcode/easy/demo1.py
1,092
3.546875
4
class Solution: def countAndSay(self, n: int) -> str: string = '' for i in range(1, n + 1): # 每层返回一个字符串 if i == 1: string += '1' else: len_string = len(string) new_string = '' for j in range(0, len_st...
e073ffc77039e43a6e8819512eb2aa795e289294
waleed-aa/SQL
/db.py
1,551
4
4
import sqlite3 #Connect to sqlite and create sales db file #connection = sqlite3.connect('sales.db') # Cursor object to invoke methods for SQL #cursor = connection.cursor() class Customer: def __init__(self, cust_id=-1, name="", age=-1, gender="", city=""): self.cust_id = cust_id self.name = na...
672920d6ef0503145714305b35b3d3687b1268c3
Horn1998/LeetCode
/树/144.二叉树的前序遍历(树,栈).py
664
3.859375
4
#参考答案 time 87 room 5.34 # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def preorderTraversal(self, root): if root == None: return [] stack, ans = [root, ], ...
5c99a4dea2cea6cc872657deff79c22a42b2321a
alu0100757507/prct06
/src/ aproximacionpi.py
337
3.6875
4
#!/usr/bin/python import sys def aproximacion(n): suma=0.0 for i in range(1,n+1): x_i=(i-1.0/2)/float(n) fx_i=4.0/(1+x_i**2) suma=suma + fx_i pi=(1.0/float(n))*suma return pi n=int(sys.argv[1]) veces = int(sys.argv[2]) for repetir in range(1,veces+1) print'El valor de pi es:pi=%1.35f' ...
0bd4b19898f239e8374cb3f6e28c3eb1c6134466
mrjamrd/diplopython
/cap10/practica.py
522
3.90625
4
import sqlite3 conexion = sqlite3.connect("persona") cursor = conexion.cursor() cursor.execute("""CREATE TABLE IF NOT EXISTS personas( id_persona INTEGER PRIMARY KEY AUTOINCREMENT, nombre varchar(255), apellido varchar(255), edad varchar(255) ) """) conexion.commit() cursor.execute("INSERT INTO personas VALUES(nu...
f94e27071f3211ce7928b6c5c203c28d4ea3e9be
Dmitrygold70/rted-myPythonWork
/Day07/execption_examples/ab_menu/ab_menu_with8.py
1,567
3.8125
4
FILENAME = "data.txt" a = b = 0 while True: print(""" A = {}; B = {} Set (A) Set (B) (S)ave (L)oad (Q)uit """.format(a, b)) option = input("enter option:").lower() if option == 'a': try: a = int(input("enter a new value for A:")) except ValueEr...
ee33b62f4ef3e6784c0aa32be6050caa9281e220
shivamkc01/MachineLearning_Algorithm__from_scratch
/Decision_Tree_scratch.py
6,062
3.53125
4
""" Decision Tree implentation from scratch This code you can use for learning purpose. programmed by Shivam Chhetry ** 11-08-2021 """ import numpy as np from collections import Counter from sklearn import datasets from sklearn.model_selection import train_test_split """ Calculating Entropy -> Entropy measure of puri...
62dcc3715eeda8479f378e7b984c82932c852f53
zubairwazir/code_problems
/classical_algorithms/python/kadanes_algorithm.py
724
4.25
4
''' Kadane's Algorithm is a standard technique used majorly for problems like: Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. ''' def kadanes_algorithm(nums): max_ending_here = 0 max_so_far = float('-inf') ...
c6473ab50e311b26b10d9a8591a8fa2581677eb6
gutierrezalexander111/PycharmProjects
/homework/Agutierrez_homework_3_09_27.py
1,611
3.984375
4
VOWELS = 'aeiou' def AskUserForSentence(): while True: word_list = raw_input('Please enter exactly 3 words followed by a space or type to quit to exit' "\n") if not word_list: continue elif word_list == 'quit': exit() word_list4 = LowercaseSentence(word_list...
91eac07c8f414968f39a2a1788b4588f675eb563
ebertn/Neural-Network-Color-Picker
/python/neuralnetwork.py
4,326
4.125
4
import numpy as np from scipy.optimize import minimize import math class NeuralNetwork: # Format is the number of units in each layer, ex: (5, 5, 3) for 3 layer NN # with 5 inputs, 5 units in hidden layer, and 3 outputs def __init__(self, format, X, y): self.format = format self....
f81941c7510ca1c3d2fae55b7e738ca7a4b25e1f
kate-whalen/fibonacci
/tests/test_app.py
533
3.78125
4
import unittest from app.app import fibonacci class TestApp(unittest.TestCase): def test_fibonacci(self): reader = fibonacci() self.assertEqual(next(reader), 0), "Should be 0" self.assertEqual(next(reader), 1), "Should be 1" self.assertEqual(next(reader), 1), "Should be 1" ...
13423657952cfb9ed72e0de81e56b392157c0d25
Oleg-Lo/Home_tasks
/Урок 4. Практическое задание/task_3.py
991
4.34375
4
""" Задание 3. Приведен код, формирующий из введенного числа обратное по порядку входящих в него цифр и вывести на экран. Сделайте профилировку каждого алгоритма через cProfile и через timeit Сделайте вывод, какая из трех реализаций эффективнее и почему """ def revers(enter_num, revers_num=0): if enter_num == ...
6598a77630a3f5b1062aa4984631d35524047d2c
mike10004/adventofcode2017
/advent04/count_valid_passphrases.py
1,410
4.0625
4
#!/usr/bin/env python3 import re import sys def to_multiset(token): """ Creates a multiset from a string. A multiset is a set of tuples (c, n) where c is a character and n is a count of that character in the string.""" counts = {} for ch in token: try: count = counts[ch] excep...
cf35247077964ded1a604d3b2c4de53c120ba3eb
binh748/queer-asian-stories
/src/web_scraping.py
7,412
3.734375
4
"""This module contains functions to scrape gaysiandiaries.com and https://gaysianthirdspace.tumblr.com/.""" # Need to go back and clean this code so I'm not creating a soup every time. # I should just pass soup into the function. from bs4 import BeautifulSoup import requests def create_soup(url): """Creates a B...
910f11ecb2eb361038bbcff8e72b1646b30c0c02
Princeshaw/Algorithmic-problems-with-python
/leetCode Solutions/98 Validate Binary Search Tree.py
752
3.828125
4
# url : https://leetcode.com/problems/validate-binary-search-tree/ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isValidBST(self, root: TreeNode) -> b...
78c7ea3ad609b9ba0ddf901063d9d52a0cdde1eb
kittykatcode/Tkinter_projects
/ProjectFiles/buttons.py
325
4.0625
4
from tkinter import * root = Tk() def myclick(): mylable = Label(root, text="i clicked a button", fg='green').pack() mybutton = Button(root, text='Click me', command=myclick , fg='black', bg='red') #SHORTER WAY OF RIITING SAME THING #mybutton = Button(root, text='Click me').pack() mybutton.pack() root.mainl...
25ba0293602d3424dd1ea12a7c7c4a3ed38438cb
Manoj431/Python
/Basics/Solution_1.1.py
295
3.796875
4
#Defining a Class, Object, Method and its Signature class Solution: def area(self,side): calc = side**2 print(f"The area of a square field is {calc} sq.metre") sol = Solution() #Object creation of class Solution sol.area(8) #Calling the method through object
a8aff1bbde01deb84541dd3cd6ba3d0e59a882be
Arnav235/ESC180
/lab8/main.py
2,172
3.515625
4
import numpy as np def print_matrix(m_lol): for i in range(len(m_lol)): print(m_lol[i]) def get_lead_ind(row): for i in range(len(row)): if row[i] != 0: return i return len(row) def get_row_to_swap(M, start_i): left_most_0 = len(M) -1 left_most_idx = start_i for i in range(start_i, len(M)): for j in r...
fdd88ac43cd14c21c4ee0c78a8625aea38e6d274
jianyu-m/plato
/plato/algorithms/base.py
836
3.9375
4
""" Base class for algorithms. """ from abc import ABC, abstractmethod from plato.trainers.base import Trainer class Algorithm(ABC): """Base class for all the algorithms.""" def __init__(self, trainer: Trainer, client_id=None): """Initializing the algorithm with the provided model and trainer. ...
4ca7cdf873629be20298399a03ddc3bc56b4b704
mathvolcano/leetcode
/0429_levelOrder.py
638
3.5625
4
""" 429. N-ary Tree Level Order Traversal https://leetcode.com/problems/n-ary-tree-level-order-traversal/ """ """ # Definition for a Node. class Node: def __init__(self, val=None, children=None): self.val = val self.children = children """ class Solution: def levelOrder(self, root: 'Node') -> L...
6bc804cc9cadc5e44fab604a09ff2dd2b4cd80d6
wawdh01/Shell-Scripting
/prog3.py
135
4.21875
4
n = int(input("Enter a Number:")) if (n % 2 == 0): print("The given number is EVEN") else: print("The given number is ODD")
49a8697d8f43c031ea5b5ae11e756b612a75df42
Predator111111/store1
/多线程_抢面包.py
1,360
3.828125
4
from threading import Thread import time bread = 0 #面包 money = 10000 class MakeBread(Thread): def run(self) -> None: global bread,money while True: if bread <500 and money>0: time.sleep(0.5) bread += 1 print("做了",bread,"个面包") ...
7fb5b25047718b5c7850a31069bb6e04342167eb
AK-1121/code_extraction
/python/python_17942.py
145
3.8125
4
# Compare values of keys in Python list with multiple dictionaries for dd in List1: if dd["a"] &gt; 1.3 * dd["b"]: print dd["value"]
e72daa9cae0a8a785c7560b49fa653911dfe5a19
seattlechem/Python2
/Week5/MathDojo.py
797
3.671875
4
class MathDojo(object): def __init__(self): self.total = 0 def add(self, *args): for arg in args: if type(arg) == list or type(arg) == tuple: for i in arg: self.total += i else: self.total += arg return self ...
929e1aab0104f454a9340e681cc8affaf047b412
Explorerqxy/review_practice
/001.py
716
3.78125
4
#数组中重复的数字 def duplicate(numbers, length): if numbers == None or length <= 0: return False for i in range(length): if numbers[i] < 0 or numbers[i] > length -1: return False res = [] for i in range(length): while numbers[i] != i: if numbers[i] == numbers[num...
ad1cd419424da71ce78d01dd3d990aab1ea92b0d
hmchen47/Programming
/Python/MIT-CompThinking/MIT6.00SC/quizs/quiz1/q2.py
211
3.828125
4
#!/usr/bin/python # _*_ coding: utf-8 _*_ # Quiz 1 2011 - Q2 # # What does the following code print? T = (0.1, 0.1) x = 0.0 for i in range(len(T)): for j in T: x += i + j print x print i
f11d9eedd3036ee28ceb0065e3ad8a9f2f2e2300
RadkaValkova/SoftUni-Web-Developer
/Programming Basics Python/Exam Problems 20042019/Easter Bake.py
602
3.6875
4
import math cakes_number = int(input()) total_sugar = 0 total_flour = 0 max_sugar = -100000000 max_flour = -100000000 for i in range(1, cakes_number + 1): sugar = int(input()) flour = int(input()) if sugar > max_sugar: max_sugar = sugar if flour > max_flour: max_flour = flour total_...
5c60113a4638b37853590d42046bd551f0f322d5
igorvalamiel/material-python
/Exercícios - Mundo 2/042.py
607
4.0625
4
print('Digite o valor dos três lados de um triângulo.') x = float(input('Primeira medida:')) y = float(input('Segunda medida:')) z = float(input('Terceira medida:')) a = x + y b = x + z c = y + z if a >= z and b >= y and c >= x: if x == y == z: print('Você poderá construir um triângulo equilátero.') e...
229ae899b0038d651e8771869a9d87cf209456bd
TrangDuLam/Numerical-Analysis
/midtern02/Q6.py
351
3.890625
4
#!/usr/bin/env python3 # Q6, 106061121, 莊裕嵐 # solving nonlinear equation # Please solve the following equation: # # exp(x) + log(x) = 0.9 # import numpy as np from ee4070 import * def function(x) : return np.exp(x) + np.log(x) - 0.9 def main() : x0 = 1 zero = Newton_root(x0, function, epsilon = 10 ** -9 ) ...
cfa695f34c280123c50a58520e48c2f906d764c3
BrayanKellyBalbuena/Programacion-I-ITLA-
/Fundamento Programacion/Tarea 4 desiciones/48.py
675
3.84375
4
def cont(): m = input("Digite S para continuar o N para salir\n") if m == "S": cal() elif m == "N": print("Goog bye") else: print(" !Error !Debe ser S o N\n") cont() def cal(): try: num = int(input("Digite un numero entero\n")) if num == 0: print ("Numero no ...
a0b8af0da4bfed01008a2675af76192eb19a32c3
am8265/BioinformaticsAlgorithms
/Course1/FrequentWords.py
1,046
4.09375
4
#!/usr/bin/env python #####Frequent Words Problem######### import re import sys from PatternCount import PatternCount# A module that has a function that computes count of pattern in a given Text def FrequentWords(text,k): count=[]#a list to store the pattern count for each kmers freq_patterns=[]#stores Most fre...
acd6a391bfd54f419aa667eefbb1a028ea39bef0
Rock-it-science/capstone-individual-exercise
/sortArray.py
497
4.0625
4
def sortArray(int_arr): # Super quick bubble sort implementation isSorted = False while not isSorted: isSorted = True # Changes to false if we have to swap; if we don't swap that's a clean pass and we can break for i in range(0, len(int_arr) - 1): if int_arr[i] > int_arr[i+1]: # ...
945d70868ce14d6726bdfbc2d14ec98eca8e4b7a
KadeWilliams/us_states_map_game
/main.py
1,078
3.703125
4
import turtle import pandas as pd screen = turtle.Screen() screen.title("U.S. States Game") image = 'blank_states_img.gif' screen.addshape(image) turtle.shape(image) count = 0 df = pd.read_csv('50_states.csv') states = df.state.to_list() correct_answers = [] while len(correct_answers) < 50: answer_state = scr...
73fb901a37579b7a12f20fcc3cd29a10a93cd2f6
chengwenhua626/data_structure
/10.15/遍历二叉树.py
758
3.8125
4
# 前序遍历复杂方法 def perOrder1(self, node): if not node: return None print(node.data) self.perOrder(node.left) self.perOrder(node.right) # 前序遍历数(简单方法) def perOrder(self, node): stack = [node] while len(stack) > 0: print(node.data, end=' ') if node.right: stack.app...
6275d4e14c8f6937903e43f54c97d4181aaacecb
bearbin/gcse-cs
/countUntilZero.py
218
3.75
4
#!/usr/bin/python3 import sys sum = 0 while True: userI = input() try: userI = int(userI) except: sys.stderr.write("Non-integer entered!\n") break else: sum += userI if userI < 1: break print(sum)
4e66a8a78084b1b46a4b8522c8d517699b8796bf
KelvinTMacharia/learningpy
/fxnassignment2.py
511
3.90625
4
class Mydict(): def __init__(self): pass def add(self, key, value): self[key] = value dictone = Mydict() dictone.key = input("enter Key: ") dictone.value = input("enter value: ") dictone.key1 = input("enter key1: ") dictone.value1 = input("enter value1: ") c=dictone.add = {dict...
351e0c7d87f0da9211c12753b7d39c3641e941e5
almiradecena/vigenerecipher
/kasiski.py
4,385
4.09375
4
## Get the longest repeated substring in a string ## https://www.geeksforgeeks.org/longest-repeating-and-non-overlapping-substring/ def longestRepeatedSubstring(str): n = len(str) LCSRe = [[0 for x in range(n + 1)] for y in range(n + 1)] res = "" # To store result res_length = 0 # To...
3ebb9d37b812b188e08c1d66ac7d3dc63517f20b
pombredanne/MI
/ankit/BitManipulation/BitSwapOddEven.py
473
3.953125
4
#!/usr/local/bin/python2.7 def update(num,ithPos,upBit): mask=~(1<<ithPos); return (num & mask)|(upBit<<ithPos); def swapOddEven(num): i=0; odd=0; even=0; while(i<32): odd=(num & (1<<(i+1))); even=(num & (1<<(i))); if(odd!=even): # swap odd and even bits odd will have even n even odd ...