blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
d8c7e58fc8a1272a49085c370747e703213ceaf4
Kiran-Karadia/DataAnalysisWithPython
/Mean-Variance-Standard-Deviation-Calculator/mean_var_std.py
788
3.515625
4
import numpy as np def calculate(list): try: input = np.reshape(list, (3,3)) except ValueError: raise ValueError("List must contain nine numbers.") calculations = { 'mean': [np.mean(input, 0).tolist(), np.mean(input, 1).tolist(), np.mean(input).tolist()], 'variance': [np.var(input, 0)...
f84745a2ba61855d764435c44543fb231c8c3b2d
SamuelLarkin/AdventOfCode2018
/02/code.a.py
451
3.65625
4
#!/usr/bin/env python3 from __future__ import print_function from collections import Counter with open('data.txt', 'r') as f: data = [ Counter(l.strip()) for l in f ] #print(data) twos = 0 threes = 0 for d in data: print(d.most_common()) # find the counts of counts coc = Counter(c for l, c in d.most...
b4f63c8d5c514d5998dc25e44f7049c55459e75e
tlicata/jumble
/jumble.py
2,927
4.5
4
#!/usr/bin/python import sys # Script accepts one argument that is a string of letters. It will # output a list of words that can be generated from those letters. # The original input will not be included in the output, even in the # case that it is a valid word. Ispell word lists are used to test if a # string is a ...
c03c1c126cae2053bb8060c2e673a7f4f765431f
MthwBrwn/data_structures_and_algorithms
/data_structures/stacks/stack.py
1,573
4.28125
4
from .node import Node class Stack(object): """This class is used to build stack objects. Each object has a top and a size when instantiated """ def __init__(self, iterable=None): self.top = None self.stack_size = 0 if iterable is None: iterable = [] if type(i...
1c8cfe4eff336b230f111045a2c66a0879645e01
nikkirethyo/CS61A
/lab07.py
2,468
4
4
# List Mutation def reverse(lst): """Reverses lst using mutation. >>> original_list = [5, -1, 29, 0] >>> reverse(original_list) >>> original_list [0, 29, -1, 5] """ lst.reverse() def map(fn, lst): """Maps fn onto lst using mutation. >>> original_list = [5, -1, 2, 0] >>> map(l...
78a62291ce1eec74f1aa669e12519a6d9018f325
Arepallyrakesh/cspp-1
/cspp1-assignments/m5/p1/p1/perfect_cube.py
734
3.984375
4
''' @author : Areapallyrakesh # Write a python program to find if the given number is a perfect cube or not # using guess and check algorithm # testcase 1 # Input: 24389 # Output: 24389 is a perfect cube # testcase 2 # Input: 21950 # Output: 21950 is not a perfect cube ''' def main(): ''' Write a python prog...
0712167e240dc2ac01233b3ec47f64d2b04b9d14
soupam05/Python
/Practice Programming/braces validation.py
288
3.578125
4
def braces_validation(braces_str): braces_dict = { '(': ')', '[': ']', '{': '}' } stack =[] for i in braces_str: if i in braces_dict.keys(): stack.append(i) else: if i == braces_dict[stack[-1]] and stack: stack.pop() if len(stack)>0: return False else: return True
cf8f65d4d28bdc98a8a7cc9cf2ce7d0453bfb980
hudaoling/hudaoling_20200907
/Python全栈_老男孩Alex/3-列表-字典-字符串-购物车/String_UseMethod.py
2,733
4.21875
4
# Author:Winnie Hu name="My Name is {name},She is a worker and She is {year} old" print(name.capitalize())#首字母 print(name.count("i")) print(name.center(50,"-")) #打印50个字符,不够用-补齐,并摆放中间 print(name.endswith("ker")) #判断是否以什么结尾 print(name.expandtabs(tabsize=30))# \ 把这个键转换成多少个空格 print(name.find("is")) #取字符的索引位置,从0开始计算 print...
d4693e99c11e6731d6c8175b1600eedd6a338c66
vibhatha/PytorchExamples
/test/oop/Alphabet.py
933
3.84375
4
class Alphabet: def __init__(self, value, key): self._value = value self._key = key # getting the values @property def value(self): print('Getting value') return self._value # setting the values @value.setter def value(self, value): print('...
7671ea6add71ba7cad3114927351afa9e6c3728c
Takuma-Ikeda/other-LeetCode
/src/easy/answer/two_sum_ii_input_array_is_sorted.py
727
3.765625
4
from typing import List class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: head = 1 tail = len(numbers) while head < tail: # number の中身は必ず昇順 # 先端の値 (最小値) と最後尾の値 (最大値) を足していく # 2 つの合計値が小さすぎれば最小値を大きくして再計算 # 2 つの合...
efdf0ad5eb20f97890057c32b13521cf49bf64be
seongkevinlee/python-practice
/lists.py
1,361
4.21875
4
# names = ["Kevin", "John", "Sarah", "Maddie", "Mary"] # names[0] = 'Kev' # print(names) #! PROGRAM TO FIND THE LARGEST NUMBER IN A LIST # list = [34, 64, 83, 13, 47, 463, 473, 457] # max = list[0] # for number in list: # if number > max: # max = number # print(max) #! 2D Lists # matrix = [ # [1, 2, 3...
37732912b9a5ec2c63c511cb4223d688404b409c
gaurav-dalvi/codeninja
/python/matrix_diagonal_print.py
1,321
4.4375
4
# https://www.ideserve.co.in/learn/print-matrix-diagonally#algorithmVisualization # Key points to remember: # 1: to understand what was the exact order of printing, had to watch video. Ask interviewer # 2: these two loops are very tricky # 3: understand to split this problem into two separate pair of for loops is the b...
69c2b7b38b1670d25e2e3482551c80036830c76c
athul1/akcb
/learn/tuple.py
90
3.796875
4
fruits=("orange","apple","khgsdjgaj") print(fruits) print() for i in fruits: print (i)
f4819adad0d36d47437bc477403bf385a67969cd
guimafelipe/genetic-queens
/src/population.py
3,329
3.578125
4
from src.state import * import random import math def get_fitness(x): return x.fitness() class Population: def __init__(self, k, n, m): self.states = [] self.n = n # board size self.k = k # population size self.m = m # mutation probability self.base = [i for i in range(self.n)] self.generate_random() ...
7bc9ffcf2fe423739f820e5cffc28e9f632039e5
shwetachhabbra/fibonacci
/t.py
113
3.8125
4
def fibonacci(i): if i<2: return i return fibonacci(i-2) + fibonacci(i-1) print(fibonacci(42))
35b9e08cef4362d0a12187b1e1b6617329016894
shyam-98/CS50x-2020
/pset6/credit/credit.py
1,345
3.890625
4
def main(): ccnumber = input("Number: ") if luhn_check(ccnumber=ccnumber): print_card_issuer(ccnumber=ccnumber) else: print("INVALID") # Checksum implmented using luhn's algorithm - checks syntactic validity of credit card numbers def luhn_check(ccnumber): sum1 = 0 sum2 = 0 s...
ac36241daf60d4549711f73351b00be12c66afb9
k-bodapati/UB_Masters_Courses
/CSE 573 - Computer Vision and Image Processing/Project 3 - Image Clustering/task1.py
5,169
3.53125
4
""" K-Means Segmentation Problem (Due date: Nov. 25, 11:59 P.M., 2019) The goal of this task is to segment image using k-means clustering. Do NOT modify the code provided to you. Do NOT import ANY library or API besides what has been listed. Hint: Please complete all the functions that are labeled with '#to do'. You a...
ae11a3b6f5d23c91741d9c38e9fb336515457d5d
MetaCell/HNN-UI
/hnn_ui/model_utils.py
1,304
3.53125
4
import os import json import operator from functools import reduce def push_keys(dicctionary={}, keys=[]): ''' It creates all keys listed in "keys" nesting them inside "dicctionary". It does not affects what already exists ''' if not keys[0] in dicctionary.keys(): dicctionary[keys[0]]...
a61b3b94a11c31d281d986f8bcd5927ac1f13dbf
awanshrestha/algorithm-labs
/BST/additional_test.py
3,516
3.6875
4
import unittest from bst import BinarySearchTree class BSTTestCase(unittest.TestCase): def setUp(self): self.bst = BinarySearchTree() self.bst.add(20, "Value for 20") self.bst.add(12, "Value for 12") self.bst.add(3, "Value for 3") self.bst.add(7, "Value for 7") self...
9c2327023b335a57e6059fca6c6ff269d815019e
junyang42/python-challenge
/PyBank/main.py
1,996
3.65625
4
import os import csv budget_csv_path = os.path.join('..', 'Resources', 'budget_data.csv') # how to use direct path to open csv? with open(budget_csv_path, newline="") as csvfile: csv_reader = csv.reader(csvfile, delimiter=",") budget_list = list(csv_reader) csv_header = budget_list[0] new_list_M = ...
7afa8590921e4531299b2cbce174637535cab9bb
mollymh/misc_image_processing
/quantize.py
3,233
3.78125
4
import numpy from types import * def quantize(im, levels, qtype='uniform', maxCount=255, displayLevels=None): """ Title: quantize Description: Returns given image quantized at set number of levels, using either a uniform or IGS method. Attributes: im - ndarray, can be grayscale or color of any size levels - ...
5de4eaf37d62c92c04f29cc0106b236021036827
hellion86/pythontutor-lessons
/6. Цикл while/Числа Фибоначчи.py
723
3.921875
4
''' Условие Последовательность Фибоначчи определяется так: φ0 = 0, φ1 = 1, φn = φn−1 + φn−2. По данному числу n определите n-е число Фибоначчи φn. Эту задачу можно решать и циклом for. ''' #Мое решение r = int(input()) s1 = 1 s2 = 1 if r == 0: print(0) elif r == 2: print(1) elif r == 1: print(1) e...
80ace125cfbd2b13ffe98ae0c1640c64e7f25ea9
dallasmcgroarty/python
/DataStructures_Algorithms/searching/binary_search.py
957
4.03125
4
# binary seach method, uses divide and conquer # divides the search space in half at each step # O(logn) worst case # list must be sorted in order to work def binary_search(arr, target): first = 0 last = len(arr)-1 found = False while first <= last and not found: mid = (first + last) // 2 ...
5a33f97495f5f993a22c527c3084f2e4d4d82435
antradzerve/RTU_Python
/3rd/3rdlesson.py
250
4.125
4
userTemperature= float(input("What is your temperature?")) lowTemp = 35 highTemp = 37 if userTemperature < lowTemp: print("Nav par aukstu?") elif lowTemp<=userTemperature<=highTemp: print("Viss kārtībā!") else: print("Iespējams drudzis!")
1371c0475a729474edba61a071b512804917f58b
makolyte/57exercises-python
/lesson35-pickawinner.py
326
4
4
import random names = [] while True: input = raw_input("Enter a name: ") if input == "": if len(names) == 0: print "No names to choose from" else: winner = names.pop(random.randint(0, len(names) - 1)) print "Winner: " + winner else: names.append(...
97acd579bb8e3a318bf00ae87ab133b4af4e8a08
nitin989/pythonic
/src/python/26_break_continue_keyword.py
185
3.921875
4
# break and continue keyword for i in range(1,11): if i==5: break print(i) # print 1 to 10 but not 5 for i in range(1,11): if i==5: continue print(i)
b6238bb09008ec3c326af80c98c238402ec7a603
realRichard/-offer
/chapterFive/timeEfficiency/median/median.py
1,386
3.984375
4
''' 题目: 如何得到一个数据流中的中位数?如果从数据流中读出奇数个数值, 那么中位数就是所有数值排序之后位于中间的数值。 如果从数据流中读出偶数个数值,那么中位数就是所有数值排序之后中间两个数的平均值。 ''' import heapq class Solution: def __init__(self): self.min_heap = [] self.max_heap = [] def insert(self, num): if not isinstance(num, int): raise TypeErro...
bcd46d1622a008906aa6ec4987baa3034d913a47
mavalliani/deterministic_poker
/main/main.py
3,174
3.640625
4
from util.poker_util import * class Solution: p_util = poker_util() cards = p_util.create_card(range(1, 14), ["h", "c", "d", "s"]) # creates tuples of cards 1 to 13 of the 4 suits (hearts, clubs, diamonds, spades). Aces is encoded as 1 hands_num = {"high card": 1, "...
9aa77220aa91b8dfc5853f95a49088b529f0ff83
ediltwwj/PythonLab
/labfour/two.py
609
3.71875
4
import time import datetime """实验四第二题""" def bin_valid_date(date): """输入日期判断格式是否合法,合法输出季节""" month = ["", "冬季", "冬季", "春季", "春季", "春季", "夏季", "夏季", "夏季", "秋季", "秋季", "秋季", "冬季"] try: time.strptime(date, "%Y-%m-%d") validData = time.strptime(date, "%Y-%m-%d") print("日期合法,是{}".form...
e68a05db1d10bebd98ee696faf24947828a8cc31
igotthisbros/cit_jlko
/20200822/recursion.py
750
3.9375
4
num =7 def fact_i(num): result = 1 while num > 0: result = result * num num -= 1 return result def fact_r(num): if num == 1 : return 1 else: return num * fact_r(num -1) def fibo_i(num): first = 1 second = 1 while num > 2: hi = second seco...
c3a8b50d465623624cfba80357b464e04c7d1b2e
YuiFutao/seccon-tool
/caesarDecrypt.py
213
3.734375
4
print('type encorded string here, then I will return candidates.') encorded_string = str(input()) for i in range(26): print ( i, ": " + "".join(chr((ord(x)-ord("a")+i)%26+ord("a")) for x in encorded_string) )
3e31dc04dfa6df8cc9954537709406e8341e08a3
thiiagoms/python-brasil
/Lista03_Estruturas_De_Listas/exercicio04.py
568
3.6875
4
# -*- coding> utf-8 -*- """ Faça um Programa que leia um vetor de 10 caracterese diga quantas consoantes foram lidas. Imprima as consoantes. """ consoantes = [] vogais = ['a', 'e', 'i', 'o', 'u'] novasConsoantes = [] for letra in range(0, 10): consoantes.append(input("Digite o " + str(letra) + " caractere: "...
23772e843ad847ad1ca566eb56111aa69765df73
sungminoh/algorithms
/leetcode/solved/529_Minesweeper/solution.py
4,500
3.90625
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2020 sungminoh <smoh2044@gmail.com> # # Distributed under terms of the MIT license. """ Let's play the minesweeper game (Wikipedia, online game)! You are given a 2D char matrix representing the game board. 'M' represents an unrevealed mi...
5aee516f1ab337adf1bdd7ade298011510640034
jusijegeni/git-python
/exercise4.py
122
3.984375
4
def is_Power(x): while (x%2 == 0): x = x / 2 return x == 1 print(is_Power(int(input("Jep nje numer : "))))
74317ff94be104e4838f6ccc00384d8f1d93388f
Python-lab-cycle/AparnnaPython
/CO2.10.FACTORS.py
163
3.8125
4
def factors(a): for i in range(1, (a + 1)): if a % i == 0: print(i) return; a = int(input("Enter a Number :\n")) factors(a)
3da8773bed08c8bbf5dc8b700004f26dab3ac5c4
matheusfelipeog/uri-judge
/categorias/iniciante/uri2760.py
232
3.546875
4
# -*- coding: utf-8 -*- v = [input() for i in range(3)] for i in range(4): if i == 3: print('{:.10}{:.10}{:.10}'.format(*v)) continue print('{}{}{}'.format(*v)) v[0], v[1], v[2] = v[1], v[2], v[0]
264ff86cfabdca22083f86716f5072b69fbd00d5
wangkai997/leetcode
/107.二叉树的层序遍历-ii.py
882
3.5
4
# # @lc app=leetcode.cn id=107 lang=python3 # # [107] 二叉树的层序遍历 II # # @lc code=start # 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 levelOrderBottom(s...
889195452db5ab484fff1762953c940a5bad1976
Hubwithgit89/PythonLearn
/may20/InnerClass.py
520
3.578125
4
class Student: def __init__(self,name,rollNo): self.name=name self.rollNo=rollNo self.lap=self.Laptop() def show(self): print(self.name,self.rollNo) self.lap.show() class Laptop: def __init__(self): self.brand="Dell" self.cpu="i5" ...
3f7a7a3242362de9b70d759b70b8cd90899e0699
javierfraga/python
/bucky34/lesson07ifelifelse.py
174
3.984375
4
age = 27 if age<21: print("No beer for you") elif age>75: print("Awwwe come on! You shouldn't be drinking any more.") else: print("cool you can have some beer")
6da3b96fd944774af8dc3264087f2e8d3affcc2c
tangx/python-devops-basic
/day7/属性方法.py
975
3.78125
4
#!/usr/bin/env python # encoding: utf-8 """ @author: tangxin@haowan123.com @python_version: python2.7 @file: 属性方法.py @time: 2017/7/20 14:37 """ import os import sys class People(object): def __init__(self, name): self.name = name self.__food = None # 设置一个属性方法 @property def eat(self)...
cd3e604ac69323d2db6a94c4080484aefe22d2dd
lingxinglovecode/git_test
/python_100days/process_thread.py
5,489
3.71875
4
import multiprocessing import threading import time # def func(): # print('ran') # time.sleep(1) # print('done') # time.sleep(0.85) # print("now down") # # x = threading.Thread(target=func,args=()) # x.start() # print(threading.activeCount()) # time.sleep(0.9) # print('finally') # # # def count(...
25759e73f662b13004ae9fc7c75814a552a272ef
SiluPanda/competitive-programming
/google/cj2.py
235
3.734375
4
def find_path(s): n = len(s) p = "" for i in range(n): if s[i] == 'E': p += 'S' else: p += 'E' return p t = int(input()) for q in range(t): l = int(input()) s = input() print("Case #{}: {}".format(q+1, find_path(s)))
8f3b6143ed8b6f952e148b99f048097e856a2f7b
colinmiller94/Project_Euler
/e36.py
242
3.84375
4
def is_palindrome(string): if string == string[::-1]: return True return False total = 0 for i in range(1,10** 6 + 1): print(i) if is_palindrome(str(i)) and is_palindrome(bin(i)[2:]): total += i print(total)
51ead622feafb9c7e03af09e95ad15328ed328af
AnnYN/python
/import_classes/useronly.py
520
3.71875
4
class User:#不继承不需要括号 def __init__(self,first_name,last_name,**other_info): self.first_name=first_name self.last_name=last_name self.other_info=other_info def des_user(self): profile={} profile['first name']=self.first_name profile['last name']=self.last_name ...
2366b00152bba7e2f2589c719bce7cac225e5530
cassiodamacena/wttd
/1-python-power/2080_1-maisDoQueStrings.py
2,848
4.125
4
# Módulo: Os 20% de código que dão 80% de resultado # Tema 1: Mais do Que Strings # Strings print('Hello world.') # String com aspas simples print("This is Alice'sgreeting.") # String com aspas duplas (não tem diferença) print('This is Bob\'s greeting') # String com aspas simples com aspas de texto ...
7f44427511bb3c7e9ff773987948d52383f1ba1f
knaranjo357/introduccion-a-programacion
/Python/histories/PENSAMIENTO COMPUTACIONAL/fibonacci.py
250
4.09375
4
def fibonacci(n): """ Calcula el fibonacci de n n int > 0 return int n! """ if n==0 or n==1: return 1 return fibonacci(n-1) + fibonacci(n-2) n = int(input('escribe un numero entero : ')) print(fibonacci(n))
4d4106f74fc9fdbd3fd11bc120d7d29c8a51f244
ArtemisZGL/leetcode
/py/brackets.py
991
3.953125
4
class Solution: def isValid(self, s): """ :type s: str :rtype: bool """ if s.strip() == '': return True stack = [] for c in s: if c == '[' or c == '(' or c == '{': stack.append(c) if c == ']': ...
b4c0a9012d9a4beef7731ab681a7192492e917a9
disaisoft/python-course
/project14/num_primos.py
349
3.8125
4
inf = int(input("Limite inferior del intervalo: ")) sup = int(input("Limite superior del intervalo: ")) print("Los numeros primos entre",inf,"y",sup,"son: ") for num in range(inf,sup+1): es_primo=True i=2 while (es_primo and i<num): es_primo=(num%i)!=0 i+=1 if es_primo: prin...
f88f03d0e44aa03cda1ced68febaeb5aafc3639e
MarieKelling/Python
/Assignments/A 11.py
1,759
4
4
#A11 print("Program Written by Marie Kelling") while True: temp = input("Input the temperature you like to convert? (e.g., 45F, 102C) : ") degree = temp[:-1] #Set degree to the user's inputted string minus the last character if temp[-1].upper() == "X": break; #Added Exception Handling eli...
8da19cfea1485af066c281321f405425ecacea4a
IngaleOmkar/CZ2101-Algorithm-Design-and-Analysis
/Trial_error/q2new.py
3,903
3.8125
4
import time import random class Node(): def __init__(self, index, weight): self.index = index self.next = None # This weight is the weight of edge between # the source index and the node index. self.weight = weight def add_connection(self, next_node): sel...
bd563a72e3adeca8bf708f09a878f6d1cdea33ac
arglbrce/google-python-exercises
/babynames/babynames.py
3,819
3.828125
4
#!/usr/bin/python # Copyright 2010 Google Inc. # Licensed under the Apache License, Version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # Google's Python Class # http://code.google.com/edu/languages/google-python-class/ import sys import re """Baby Names exercise Define the extract_names() function below and c...
214d619cf2812dbfb57c75bc53300c9243343eca
xxcocoymlxx/Study-Notes
/CSC108/labs/lab3_materials/code/distance_converter.py
335
4.15625
4
def km_to_miles(km): ''' (number) -> float Return the number of miles equivalent to km kilometers. >>> km_to_miles(16) 10.0 ''' return 1000.0 def miles_to_km(m): ''' (number) -> float Return the number of kilometers equivalent to m miles. >>> miles_to_km(10) 16.0 ''' re...
4d69162ae0906e4d220fd2e70525a03179b31731
Kawser-nerd/CLCDSA
/Source Codes/AtCoder/arc045/A/4833455.py
165
3.859375
4
S = list(input().split()) ans = [] for s in S: if s == "Left": ans.append('<') elif s == "Right": ans.append('>') else: ans.append('A') print(*ans)
0333470edac01461a7854f5244adb855d1ad06ea
organization-look/crash-course2-modularisai
/modularisasi_tahap1.py
781
3.921875
4
"""" Program menghitung luas segitiga luas segitiga = alas * tinggi /2 """ print('menghitung luas segitiga 1') alas = 10 tinggi = 6 menghitung_luas_segitiga = alas * tinggi /2 print(f' segitiga yang memliki tinggi ={tinggi} dan memiliki alas={alas} adalah ={menghitung_luas_segitiga}') print('menghitung luas segitiga...
37886ae3dcbed14a453a33adc2f0cbfd5027f68a
willowxiaohuihui/Python1
/for_3.py
3,347
3.609375
4
#coding:utf-8 #已知大公鸡5元,母鸡3元,小鸡1元,我有100块,可能买几只公鸡,几只母鸡,几只小鸡,把所有的可能都显示出来。 #i 表示公鸡,j表示母鸡,k表示小鸡 # for i in range(0,21): # for j in range(0,34): # for k in range(0,101): # #pass #空操作,占位 # if 5*i+3*j+k==100: # print u'公鸡有:%d只,母鸡有:%d只,小鸡有:%d只'%(i,j,k) #百元买白鸡,已知大公鸡5...
c03bf790d4109810b92f7447e11c7b925a95223d
udhayprakash/PythonMaterial
/python3/16_Web_Services/f_web_application/a_static_web_pages/b_hello_web.py
883
3.625
4
pageTemplate = """ <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta content="text/html; charset=ISO-8859-1" http-equiv="content-type"> <title>Hello</title> </head> <body> Hello, {person}! </body> </html> """ # NEW note ’{person}’ two lines up ...
9fc35d53fe19352f1fafbfa86194d2fb7ee1953a
wtkn25/python_design_patterns
/chain_of_responsibility/chain_of_responsibilty.py
2,269
3.5625
4
# chain_of_responsibility.py from abc import ABC, abstractmethod from dataclasses import dataclass @dataclass class User: name: str age: int gender: str class Handler(ABC): _next = None def set_next(self, handler): self._next = handler return handler def handle(self, user:...
174c129f424019516e0466c52c5c9f98d48018aa
Meicq/AID1811
/代码/day1/d0101.py
525
3.9375
4
#name = '梅超前' #sex = '男' #birthdate = '1994,5,7' #age = 24 #height = 1.70 #weight = 175 #print('姓名:',name) #print('性别:',sex) #print('出生日期:',birthdate) #print('年龄:',age) #print('身高:',height) #print('体重:',weight) print('What is your name?') name = input() print('How old are you?') age = input() print('How tall are yo...
c8e7809f0b1b42796611d682fdde9b4f5d98a12c
vishnoiprem/pvdata
/lc-all-solutions-master/081.search-in-rotated-sorted-array-ii/test.py
566
3.71875
4
class Solution(object): def search(self,nums,target): start=0 end=len(nums)-1 while start+1<end: mid=start+(end-start)//2 if nums[mid]==target: return True if nums[start]<nums[mid]: if nums[start]<=target<=nums[mid]: end=mid else: start=mid elif nums[start]>nums[mid]...
d6caa9c5e0dd6f07fc9849d9c6194e97305eb8e1
aasthaagrawal/Algorithms_and_Data_Structures
/leetcode/123_Best_Time_to_Buy_and_Sell_Stock_III.py
865
3.703125
4
#https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/ #Time complexity: O(n) #Space complexity: O(n) class Solution: def maxProfit(self, prices: List[int]) -> int: n = len(prices) if n <= 1: return 0 dp = [0]*n lowest_price = prices[0] for i in rang...
ba2dc050bbbe1da3aadd997f136914919dfff5c3
apex-structure-intern/PW_II_EN16CS301300_288_280_EN17CS3L1002_Digital_Marketer
/images.py
775
3.890625
4
from tkinter import * # tkinter does not support much of the image types and there we will be using PIL(python image library) now known to be as PILLOW from PIL import ImageTk, Image root = Tk() root.title('Learn to code') # Add Icon to program, pass the path of image #img = PhotoImage(file='index.png') #root.tk.call(...
b340175cb949ac00c98e6f551cdfce7207d5a42f
SrilekhaSundara-git/Srilekha
/learn-to-code-with-python-incomplete/27-Exception-Handling/catching-one-or-more-specific-exceptions.py
748
3.8125
4
def divide_5_by_number(n): try: calculation = 5 / n except (ZeroDivisionError, TypeError) as e: return f"Something went wrong. The error was {e}" return calculation print(divide_5_by_number(10)) print(divide_5_by_number(0)) print(divide_5_by_number("nonsense")) def divide_5_by_number(n): ...
9afe11e969ef404b10c8fce2eb1cc93ab328551c
HyoHee/Python_month01_all-code
/day18/exercise01.py
1,292
3.53125
4
""" 在商品列表,获取所有名称与单价 在商品列表中,获取所有单价小于10000的商品 对商品列表,根据单价进行降序排列 获取元组中长度最大的列表 """ from common.iterable_tools import IterableHelper class Commodity: def __init__(self, cid=0, name="", price=0): self.cid = cid self.name = name self.price = price list_commodity_infos = [ Com...
a07934c6c1cc052e18297e81f10397c6ad636bed
rafaelmorgado/logica-algoritmos
/EstruturaDeRepeticao/l3ex02.py
534
4.46875
4
''' 2) Faça um programa que leia um nome de usuário e a sua senha e não aceite a senha igual ao nome do usuário, mostrando uma mensagem de erro e voltando a pedir as informações. ''' usuario = str(input("Entre com um usuário: ").upper()) senha = str(input("Entre com uma senha: ").upper()) while usuario == senha: pr...
2db30cdc7545cc4665f2d6b68466d857fad669ad
AlexEshoo/projectEuler
/euler031.py
216
3.5
4
target = 200 denominations = [1, 2, 5, 10, 20, 50, 100, 200] ways = [0] * (target + 1) ways[0] = 1 for d in denominations: for j in range(d, target+1): ways[j] += ways[j - d] print("Answer:", ways[-1])
97dbaa8054beaa8f1b627f2d2bf2bd91c0a81e79
marieigoe/marieigoe.github.io
/softwareAndDesign.py
1,625
4.21875
4
def inputGallons(): isgood = False while not isgood: s = input("Enter the total number of gallons used, divided by 1000: ") try: # try to convert to float num = float(s) # number (no exception occurred), is it positive? if num > 0: ...
5ce28d61332402c828a14b4a71e46953f9b926cb
njoubert/UndergraduateProjects
/CS188_p6/trunk/src/mira.py
5,028
3.515625
4
# Mira implementation import util import math PRINT = True class MiraClassifier: """ Mira classifier. Note that the variable 'datum' in this code refers to a counter of features (not to a raw samples.Datum). """ def __init__( self, legalLabels, max_iterations): self.legalLabels = legalLabels sel...
5bb7f7fa0c3c639e0050262a7a9467668b865672
Lyondealpha-hub/Python-Programs
/countVowels.py
465
4.1875
4
def _vowels_count() : userinput = input("Enter a message here : ") arr = list(userinput) length = len(arr) vowel_arr = [] for letter in arr : if letter in "aeiou" : vowel_arr.append(letter) lent = len(vowel_arr) print("there are ", lent, " vowels in this ar...
f12ee36fc6740a788397b89b981312de112a0495
Haidram/codeforces_prblm_solutions
/borze.py
441
3.578125
4
def findStr(s): flag = 0 arr = [] for i in s: if i is '.' and flag == 0: arr.append('0') elif i is '-' and flag == 0: flag = 1 elif i is '-' and flag == 1: arr.append('2') flag = 0 elif i is '.' and flag == 1: ...
b7d0922182b7e181bbe2a2886a626f271e7d35a3
Code-Frederick/Cadet-CSHS
/Week 1/Python/studentcard.py
1,353
3.578125
4
""" This program prints information that would be found on a typical Student Information Card. """ # Creates the student card def create_student_card(): #Header/Banner print("***********************"); print("**Student Information**"); print("***********************"); #Vital Information print("Vital...
b044ca3d9128be8c5aa7a3cccc8c57ac9573fc1e
jainamshah95/CodeEval
/count_stairs.py
943
4.28125
4
''' Author: Sheldon Logan Climbing stairs(iterative) Description: You are climbing a stair case. It takes n steps to reach to the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? Input sample: Your program should accept as its first argument a path to a filename....
5b40e1b987327bb629cc7e9e3b605a2fe1bbc490
smahamkl/ScalaSamples
/BoatsToSavePeople.py
1,192
3.765625
4
from typing import List ''' LeetCode 881: You are given an array people where people[i] is the weight of the ith person, and an infinite number of boats where each boat can carry a maximum weight of limit. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most...
fffab7164020e8a05e812fb57be6695d8d17d803
michaelzh17/think_python
/buggy_break.py
398
4.0625
4
#!/usr/bin/env python3 # Demo of use of break # Does the list have any odd numbers? numbers = [6, 8, 34,7, 18] for number in numbers: if number%2 == 1: print(True) break else: print(False) count = 0 for number in numbers: if number%2 == 1: count += 1 print(count > 0) counte...
baac65dd2adff9aedb46983be49f9dfbfb1025ba
okrysiuk/lpthw
/24_more_practice.py
951
3.65625
4
print("Let's practice everything.") print('You\'d need to know \'both escapes with \\ that do \n and \t tabs.') poem = """ \tThe lovely world with logic sp firmly planted cannot discern \n the needs of love not comprehend passion from intuition and requires an explanayion \n\t\twhere there is none. """ print("------...
4272aef5fc5572305bb8fe509ef35db1a3553c4e
g2des/taco4ways
/hackerrank/algorithm/betweenTwoSets.py
1,134
3.6875
4
#!/bin/python3 import math import os import random import re import sys # # Complete the 'getTotalX' function below. # # The function is expected to return an INTEGER. # The function accepts following parameters: # 1. INTEGER_ARRAY a # 2. INTEGER_ARRAY b # def lcm(x, y): return int(round(x*y / math.gcd(x,y))) ...
439fd1508300d5f26f1e90cf6dc3c66a56d4bb8b
yogeshkhola/python1
/Datastructure/functions/keywords parameter and default parameters.py
2,159
4.03125
4
# to make function much more flexible def about(name,age,likes): sentence="Meet {} They are {} years old and they like {}".format(name,age,likes) return sentence # print(sentence) # about("Yogesh",32, "Pyhton") # /*this can't woek as we use return keyword*/ print(about("Yogesh", 288, "Pyhton")) ...
baf4eb73c7a9ed2adf0055a12cbb7aabda392fee
MdMotahir/Notes
/MY Packages/Mypackage/package/utility.py
306
3.5
4
def add(val1,val2): try: result=val1+val2 return result except: return "invalid input" #here we wrie same thing which is writen in the test file. def sub(val1,val2): return val1-val2 def mul(val1,val2): return val1*val2 def div(val1,val2): return val1/val2
597c5282c79bd75148643b3e630885a62ba2b6f0
kihyeonkwon/SWEA
/8. 함수/8. 제곱.py
124
3.59375
4
a = input().split(', ') b=len(a) for i in range (0, b) : print("square({0}) => {1}".format(a[i], int(a[i])**2))
d469ff31d0ec75df96ce0a1645130cf73f406c19
lcs-amorim/Exercicios
/Aplic.Distribuidas/forum/acesso.py
1,556
3.6875
4
import requests ''' Nesse arquivo, vamos acessar o servidor "controle_pessoas". A idéia é que estamos contruindo uma aplicacao "cliente", que está em outro servidor, mas precisa das informacoes de controle_pessoas. Devemos, entao, acessar controle_pessoas via rede, nao usar algum tipo de import (já feito na aula p...
592dc961d8d9e9db46df11b19426edd9aebfc9b1
libaiyu/testpaper
/ReadDocxClass.py
1,730
3.625
4
# _*_ coding: utf_8 _*_ #! python3 # read and print the docx successfully. 2017-2-26 # this program can get text in document by several mathods. # but 若用p=ui算得的功率值为 -_ 5W, before 5W a symbol is missing. import docx import getfile_fun class ReadDocx(): ''' Read the given document by different ways. ''' ...
1d4c9acecaf4813f0e7a7e90f5974f301de22f15
Purushotham-D/Basic_Programming
/Conversion_Programming/binToDec.py
339
3.96875
4
# -*- coding: utf-8 -*- """ Created on Thu Jul 22 09:52:24 2021 @author: PURUBOI """ def binaryToDecimal(n): i=len(n)-1 j,res=0,0 while i>=0: res+=((2**i)*int(n[j])) i-=1 j+=1 print(res) n=input("Enter the positive number to convert from bin to decimal: ") bin...
07a2de18839d3a84ec5965e0852c9d2fdf8b68fb
intzzz/Advent_Of_Code
/Day 11/main.py
5,390
3.546875
4
def read_input(file_name): with open(file_name, "r") as file: result = [str(x) for x in file.read().split('\n')] return create_correct_list(result) def create_correct_list(first_list): rows = len(first_list) columns = len(first_list[0]) correct_list = [[] for _ in range(len(first_list))] ...
057a82ca9d277c9dfd5ffe0b2076b881cf7a0637
ernestas-poskus/codeacademy
/Python/project_translator.py
243
3.859375
4
print "Welcome to the English to Pig Latin translator!" original = raw_input("Your prompt message") def check(): if len(original) != 0 and original.isalpha(): return original else: return 'empty' print check()
440bb8a4bc7fded9cfa7fd9b3bbf29c50dc7c91f
jonasring96/Statemachine-modul2.1
/Regnemaskine.py
1,607
3.90625
4
#Regnemaskine Menutal=0 #tal1=0 #tal2=0 def Plus(x,y): resultat =x+y return resultat def Minus(x,y): resultat = x-y return resultat def Gange(x,y): resultat=x*y return resultat def Divider(x,y): if y==0: print("Kan ikke lade sig gøre, der divideres med 0!!") return re...
2f2e4a4890527e7d993899c96c5336505cfc042b
chaoluond/OnlineFoodOrderingSystem
/sourcecode/createDB/populateDB.py
4,412
3.5
4
#e this script to populate the |restaurant| table of the database import mysql.connector import json from decimal import * import random #Define database variables DATABASE_USER = 'root' DATABASE_HOST = '127.0.0.1' DATABASE_NAME = 'foodND' #Create connection to MySQL cnx = mysql.connector.connect(user=DATABASE_USER,...
c8095feb172e51b5b3e08ae23a0cf0f9a3bc5f84
HaydenBlack/Homework
/guess_a_number.py
460
3.953125
4
import random def main(): ranNum = random.randint(1,10) print("I thought of a number between 1 and 10.") g1 = int(input("what is your guess? ")) while(g1 != ranNum): if(g1 < ranNum): print("Your guess was too low.") else: print("Your guess was too high.") keep_playing = str(input("Do you want to keep gu...
b56ed973244db9d4a3144e61eda1aea45b21077d
abdullahtamimi/ROSALIND
/LEXF.py
1,590
3.765625
4
def LEXF(s,n): '''input:A collection of at most 10 symbols defining an ordered alphabet and a positive integer n output: all strings of length n that can be formed from the alphabet ordered lexicographically''' s=oneWord(s) rolls=len(s) lessRolls=rolls...
5db03164ea0c81f65266b2c900a05f0aecebdc39
gradampl/MONTY
/Lab_4/dac.py
309
4.09375
4
def calculate_factorial_recursively(x): if x == 0 or x == 1: return 1 else: return x * calculate_factorial_recursively(x - 1) for i in range(0, 7): print(str(calculate_factorial_recursively(i))) # Result: # # 1 # 1 # 2 # 6 # 24 # 120 # 720 # # Process finished with exit code 0
9c8ca6f6294f897915ecc76962e78cf89ba86a6b
awanshrestha/algorithm-labs
/BST/bst.py
4,354
3.84375
4
class BinarySearchTree: def __init__(self): self._size = 0 self._root = None class _BSTNode: def __init__(self, key, value): self.key = key self.value = value self.left = None self.right = None # Add a node to the BST def add...
63bfc428714fda200a6ef906fe8e45b327aafe58
wupei93/black-jack
/player.py
2,576
3.5
4
import random import string from abc import abstractmethod from poker import Pile, ConsoleCard, Card, ConsoleCardBack class BasePlayer: def __init__(self, name, token=1000): self.name = 'unknown' self._cards = [] self.name = name self.token = token def __str__(self): ...
7543e947e50457115198af68e9c35a2cffe754c7
inaveen9/PythonBasicToAdvance
/python_comments_multiline.py
587
4.1875
4
#program to understand the multi-line comments in python ''' Since python will ignore string literals which are not assigned to a variable,you can add a multi-;ine string (Triple quotes) in your code, and place your comments inside it. ''' ''' As long as the string is not assigned to a variable, python read the code,...
4bbe318eb403c13a0aebf0ed9c57aeb3d2f992e3
marcoamorales/rackspace-api-challenges
/challenge3.py
1,396
3.671875
4
''' Write a script that accepts a directory as an argument as well as a container name. The script should upload the contents of the specified directory to the container (or create it if it doesn't exist). The script should handle errors appropriately. (Check for invalid paths, etc.) ''' import pyrax import os def a...
704d1240c5975fb4f65875c3c3ec3e5d6c5255a7
leinian85/year2019
/month01/code/day16/test.py
181
3.515625
4
list01 = [51,2,3,9,4] # listiter = list01.__iter__() # while True: # try: # item = listiter.__next__() # print(item) # except StopIteration: # break
d3437f487da91075e5b9893daf914f3ad6756e7f
mike-011/TheBestAlexandr
/strs.py
5,073
3.96875
4
# str() - type # to check typy of obj usualy use funk type(obj) # 1. 'str' in single quote # 2. "str" in double quote # 3. "'str' in str" or '"str" in str' or '''"str" in str'''to use some quote in str use ather quote """ print('\n','############ str in str ###########') print("'str' in str") # 'str' in str print(...
4ceeb5dfe5e5c754e9d215ac5c513d145603aae2
junaidiqbalturk/python-foundation
/control-flow.py
297
4.1875
4
#Control FLow Statements if- then else number = 10 if (number > 0): print(f"{number} is positive") elif (number == 0): print(f"{number}") else: print(f"{number} is negative") #TERNANRY IF STATEMENTS my_num = -2 message = "positive" if my_num > 0 else "0 or negative" print(message)
fbef3ddafeb7a6a5e643128204aea22818ef97bc
heatherstafford/unit5
/listdemo.py
290
4.15625
4
#Heather Stafford #4/13/18 #lsitDemo.py - print out first and last work in a list words = input('Enter some words: ').split(' ') print(words) print('The first word was: ', words[0]) print('The last word was: ', words[-1]) #print out the list one item at a time for item in words: print(item)
d1cddff9294a4ec92e7e672b906744f3ace2be10
jasimdipu/django_batch_6th
/tenth_cls_13_08_21/sqlite_db.py
1,650
3.953125
4
import sqlite3 try: conn = sqlite3.connect(database='employee') cursor = conn.cursor() sql = "CREATE DATABASE employee" cursor.execute(sql) print("employee database created") cursor.close() conn.close() except Exception as e: print(e, " database already exists") try: conn = sqlite3...
6635c9375773718356225e5ae1d618ace87f472c
linfengzhou/LeetCode
/archive/python/Python/unsorted/57.insert-interval.py
1,067
3.703125
4
# Definition for an interval. # class Interval(object): # def __init__(self, s=0, e=0): # self.start = s # self.end = e class Solution(object): def insert(self, intervals, newInterval): """ :type intervals: List[Interval] :type newInterval: Interval :rtype: Lis...
72e67524c9912f7ef00f68fc710964b16463679f
nickbuker/machine_learning_from_scratch
/src/LogisticRegression.py
5,664
3.75
4
from scoring import log_loss, accuracy import numpy as np class LogisticRegression: """ Logistic regression implemented in Python using numpy """ def __init__(self): pass def fit(self, X, y, learning_rate=0.001, converge_change=0.001, max_iter=10000): """ Takes in tra...
7dffb5324c57d7adcf50353c0644b1669b64166b
olegleyz/data-structures-and-algorithms
/merge_sort.py
1,646
4.03125
4
from random import randint from random import random from time import time def merge_sort(arr): # recursively divide arrays into 2 halfs and merge if len(arr)<=1: return arr middle = len(arr)/2 left = arr[0:middle] right = arr[middle:] left = merge_sort(left) right = merge_sort(right) retur...