blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
d80609efb93c77a0b9ccdf1f878f9ff14b177ea0
pavelchub1997/Software-implementation-of-work-with-elliptic-curves
/NOD.py
2,737
3.59375
4
import time def input_value(msg): while True: try: val = int(input(msg)) break except ValueError: print('Ошибка. Повторите ввод!') return val def gcd(a, b): if b == 0: return a else: return gcd(b, a % b) def extended_gcd(a, b): if b == 0: retur...
f062ed597a64911eda53043d377c5956c5e832ec
3r10/SimPly
/examples/triangle_i_j.py
130
3.5
4
m = 5 n = 4 # matrix triangle i = 0 while i<m: print(i) j = i while j<n: print(j) j = j+1 i = i+1
936733f7ad3bd505a17c069fbb8c36259a15a450
riyaminiarora/python
/companymanager.py
3,514
4.125
4
from abc import ABC,abstractmethod class Employee(ABC): @abstractmethod def calculatesalary(self): pass class HourlyEmployee(Employee): def __init__(self,name,perhrsalary,totalhours): self.name=name self.perhrsalary=perhrsalary self.totalhours=totalhours def calc...
14e10d396411fe185a1e09469effffe296356f99
suppix/zabbifier-web
/utils.py
727
3.921875
4
def human_readable_date(timedelta): age = "" age_length = 0 if timedelta.years != 0: age += str(timedelta.years) + "y " age_length += 1 if timedelta.months != 0: age += str(timedelta.months) + "m " age_length += 1 if timedelta.days != 0: age += str(timedelt...
0f6678e949fba358dd10dbfe95bac5d84e049d50
lukbor2/learning
/Python/tutorial_5_1_3.py
277
3.6875
4
def f(x): return x%3 == 0 or x%5 == 0 def cube(x): return x*x*x a = [] for i in filter(f, range(2,25)): a.append(i) print("Result from the filter function", a) a = [] for i in map(cube, range(1,11)): a.append(i) print("Result from the map function", a)
58db07868d189e9da73d06f92aafd8ac9ec31983
Zitelli-Devkek/Drones-con-Python
/Ejercicios practicos Drones/ej-de-codigo-python drones-concatenar.py
376
3.90625
4
nombreAlumno = input ("Ingrese su nombre de pila: ") apellidoAlumno = input ("Ingrese su apellido: ") print("Bienvenido a Aprendé Programando Virtual" + " " + nombreAlumno + " " + apellidoAlumno) edadAlumno = input ("Ingrese su edad expresada en letras: ") print ("Hola, soy" + " " + nombreAlumno + " " + apellidoAl...
3481a3ec7f7e62db87b4daaa29348341ddffdc04
jamesdeal89/imageWriter
/imageWriter.py
1,983
4.09375
4
# a class which will generate an image and write that image to a file. import random class CreateImage(): def __init__(self, fileLocation, h=640, w=480): self.fileLoc = fileLocation self.height = h self.width = w def save(self): print("\nImage Save Starting...") # here ...
b73c505f544a5d3a4ee7eb7adbfd90351a8f37a5
zelzhan/Challenges-and-contests
/LeetCode/sort_characters_by_frequency.py
451
3.765625
4
from heapq import heappop, heappush from collections import Counter class Solution: def frequencySort(self, s: str) -> str: counter = Counter(s) heap = [] for char, freq in counter.items(): heappush(heap, (-freq, char)) res = "" ...
7ef990e6859448a849bdcfadb67024650f9f6573
MingfeiPan/leetcode
/array/31.py
714
3.5625
4
class Solution: def nextPermutation(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ # reverse # nums[i:] = nums[:(i-1):-1] pivot = len(nums) - 2 while pivot >= 0 and nums[pivot+1] <...
24dd50854e648212add116f24b45ae4e0d8b2ef2
R110/dquest-datastructures
/traversetrees.py
2,509
3.703125
4
level_order = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] class Node: def __init__(self, value=None): self.value = value self.left = None self.right = None def __repr__(self): return "<Node: {}>".format(self.value) class BaseBinaryTree: def __init__(self, values=None): self.ro...
fefdb4d3f17dbf27ca0602862a1c926daeee1e03
1914866205/python
/pythontest/day02.py
1,361
4.1875
4
""" 英制单位英寸和公制单位厘米互换 """ value = float(input('请输入长度:')) unit = input('请输入单位:') if unit == 'in' or unit == '英寸': print('%f英寸=%f厘米' % (value, value*2.54)) elif unit == 'cm' or unit == '厘米': print('%f厘米=%f英寸' % (value, value/2.54)) else: print('请输入有效的单位') """ 百分制成绩转换为等级制成绩 要求: 如果输入的成绩在90分以上(90分)输入A; 如果...
d93da0ddddc75135c8d6305cd13e23c519fa3fdd
SuguruChhaya/python-exercises
/Hackerrank Python/nested lists.py
3,365
4.15625
4
''' # * Approach 1: Don't even use the nested list and use a lot of for loops if __name__ == '__main__': name_list = [] score_list = [] sorted_score_list = [] runner_up_score = 0 dictionary = {} for _ in range(int(input())): name = input() score = float(input()) name_list...
2a2457834bab1bec936359645fd4dde123a0374e
samorajp/reaktorpy
/trener/dzien3/break.py
416
3.59375
4
import random sekret = random.randint(1, 6) proba = 1 while True: wpisana = int(input("Twój strzał: ")) if wpisana == sekret: print("WYGRAŁEŚ W PRÓBIE", proba) break else: print("NIE TRAFIŁEŚ") if wpisana < sekret: print("Za mała!") else: prin...
c65df2de87e164a76b4e1a297516d1dfd20b788e
PeterLD/algorithms
/trees/parse_tree.py
1,824
3.5625
4
from data_structures.linear import Stack from data_structures.trees import BinaryTree import operator def build_parse_tree(expression): expression = expression.split() tree_stack = Stack() parse_tree = BinaryTree('') tree_stack.push(parse_tree) current_tree = parse_tree for token in expressi...
7d5b3b590f4977a8b3d69e82a39ef24505a79c1c
fyabc/BT4MolGen
/fairseq/tasks/dual_translation.py
2,380
3.640625
4
#! /usr/bin/python # -*- coding: utf-8 -*- from .translation import TranslationTask from . import register_task @register_task('cycle_back_translation') class DualTranslation(TranslationTask): r"""A task for cycle-loop dual translation (back translation). Forward model f: x -> y Backward model g: y -> ...
f7c32ab14df3b73cc6ffd8fb01b4f73db85c1ee1
abdullahbilalawan/GAUSS-ELIMINATION-PYTHON-CODE
/gauss elimination.py
2,107
3.984375
4
import numpy import math # defining a matrix #steps of gauss elimination' # 1 make 1st element of row equal to 1 # make elements under it to 0 # make second row pivot be 0 # make zero under it # heading print("============================================GAUSS ELIMINATION FOR 3 VARIABLES ===============...
02af31e3d9a1f5c92efca4b9fa9b01f8108ca690
Zhuogang/Python_Computation
/Python_for_NuclearEngineering/ch20.py
10,375
4.1875
4
import numpy as np import matplotlib.pyplot as plt def swap_rows(A, a, b): """Rows two rows in a matrix, switch row a with row b args: A: matrix to perform row swaps on a: row index of matrix b: row index of matrix returns: nothing side effects: changes A to rows a and b...
164103ed6953c6845460c00331bf2d4ead7dd9d9
8jdetz8/ATBSwPython
/Filling in the Gaps
687
3.625
4
#! python3 #fillingInTheGaps.py-Searches a folder to find files with a given prefix #(spam1.txt, spam2.txt...) finds any gaps (spam3.txt, spam5.txt) and renames #later files to close gaps. import os, shutil, re #TODO open capitals folder folder = os.listdir('C:\\Users\hairy\AppData\Local\Programs\Python\Python37-32\AT...
e5117eda82ee4e5169fc7d57ae740bf013785f7d
meet1993shah/Python_practice
/powerseries.py
250
3.640625
4
import math x = float(raw_input("Enter the value of x: ")) n = term = num = 1 sum = 1.0 while n <= 100: term *= x / n sum += term n += 1 if term < 0.0001: break print "No of times = %d and Sum = %f" % (n, sum) print math.e ** x
1201ad19d5d3455dfebacdd79bd3eab807ad2759
RutyRibeiro/CursoEmVideo-Python
/Exercícios/Desafio_34.py
251
3.84375
4
# Calcula aumento de salario de acordo com a faixa de valores sal = float(input('Digite o salário:')) if sal > 1250.00: print('Novo salário: {}'.format(sal + (10 / 100) * sal)) else: print('Novo salário: {}'.format(sal + (15 / 100) * sal))
4b3f3032529adf5e177ea40dc8d0a76bb7823e0f
tfio17/Python_Basics
/Quiz_One.py
190
3.9375
4
# # #Tom Fiorelli # #Quiz 1 Exercise # # # num = int(input("Input a number: ")) if num > 10 and num < 100: print("This number is in range.") else: print("Out of range.")
a11728c812e443513ed0b8e747865ce26fe0b635
eechoo/Algorithms
/LeetCode/ValidNumber.py
2,371
4.21875
4
#!/usr/bin/python ''' Validate if a given string is numeric. Some examples: "0" => true " 0.1 " => true "abc" => false "1 a" => false "2e10" => true Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one. ''' class Solution: # @param s, a st...
c2727d27c0810536ffca742259caf17a444651c4
GinnyGaga/PY-3
/ex20-2.py
723
3.859375
4
from sys import argv #导入脚本需要用的功能模块 script,f=argv #定义参数变量的参数名 def print_a_line(count_line,f):#定义函数名和函数参数 print (count_line,f.readline()) #f.readline()从文件中读取一 行;如果f.readline()返回一个空 字符串,则文件的结尾已经到达 #def rewind(f): # f.seek(0)##读取定义好的文件的初始位置 current_file=open(f) current_line=0 while current_line <= 2: cu...
05a308adbb6660ce6a5e0693dd1c2e2850f427cd
Divine11/InterviewBit
/Hashing/Longest_Substring_without_repeat.py
932
4.0625
4
# Given a string, # find the length of the longest substring without repeating characters. # Example: # The longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. # For "bbbbb" the longest substring is "b", with the length of 1. def lengthOfLongestSubstring(self, A): n = len...
78b63d34e867db24879649bc6766e570ed6f096b
sheddy20/My-python-projects
/method.py
116
3.953125
4
# Casting In Python num1 = '45' num2 = '34' num1 = int(num1) num2 = int(num2) result = num1 * num2 print(result)
f61a9162bc6d16a35acaa2e175e8ea3097f2100d
hasanozdem1r/Find_Shortest_Distance_from_MKAD
/dir_api/yandex_api.py
4,355
3.90625
4
from dir_api.__init__ import * class YandexGeolocationApi: def __init__(self, geolocator_api_key:str="") -> None: """ __init__ is a constructor is a special member function of a class that is executed whenever we create new objects of that class :param geolocator_api_key: <str>Yandex.Maps...
4e04feea765f873d7d7b3194338d1dd5ef69ec07
pennli/Apache-Spark-2-for-Beginners
/Code_Chapter 7 spark machine learning/Code/Python/PythonSparkMachineLearning.py
9,037
3.65625
4
# coding: utf-8 # In[32]: print("==============Regression Use case==============") # In[33]: from pyspark.ml.linalg import Vectors from pyspark.ml.regression import LinearRegression from pyspark.ml.param import Param, Params from pyspark.sql import Row # In[34]: # TODO - Change this directory to the right loca...
c89f69423cda1bb0901ed4ba74a17fecf78515fe
andrewDeacy/CSVtoJavascriptArray
/main.py
1,352
3.5625
4
__author__ = 'Andrew' #quick tool to create a functional javascript array from a raw csv file format import csv import sys isValid = 0 columns = [] while isValid < 1: try: number = input('Enter the amount of columns in the array: ') if int(number) > 0: for num in range(0,int(number)): ...
ea23e6cf67beafdc74f170326f49b52d4eabc2eb
E-voldykov/Python_Base
/Lesson2/base_les2_4.py
721
3.671875
4
""" Пользователь вводит строку из нескольких слов, разделённых пробелами. Вывести каждое слово с новой строки. Строки необходимо пронумеровать. Если в слово длинное, выводить только первые 10 букв в слове. """ print("-" * 70) input_list = input(f'Введите строку из нескольких значений, разделив их пробелом!\n').split(...
6a91f6d98d25223eb7f76ccb3053f33048e504be
DPGoertzen/PythonExercises
/FunctionPractice.py
3,074
4.28125
4
#Practicing functions in Python # Write your square_root function here: def square_root(num): return num**.5 # Uncomment these function calls to test your square_root function: #print(square_root(16)) # should print 4 #print(square_root(100)) # should print 10 # Write your introduction function here: def introduc...
d7a2d07902abc4d3fb0cfcf52c6e258f86c05d4e
pedroceciliocn/programa-o-1
/monitoria/prova 1/q_1_2020_1_soma_n_termos.py
1,134
3.90625
4
""" Questão 1 - 2020.1 - Faça um programa Python para calcular a soma dos N primeiros termos da série abaixo, onde o valor de N deve ser informado pelo usuário no início. O seu programa deve imprimir o resultado (com 4 casas decimais) da seguinte forma: “O valor da série com ... termos é ...”. S = 19 / 1 – 70 / 5...
6880e6c83281d9f527674779ac4abe170e86a6fd
gunzigun/Python-Introductory-100
/28.py
682
3.734375
4
# -*- coding: UTF-8 -*- """ 题目:有5个人坐在一起, 问第五个人多少岁?他说比第4个人大2岁。 问第4个人岁数,他说比第3个人大2岁。 问第三个人,又说比第2人大两岁。 问第2个人,说比第一个人大两岁。 最后问第一个人,他说是10岁。请问第五个人多大? 程序分析:利用递归的方法,递归分为回推和递推两个阶段。要想知道第五个人岁数,需知道第四人的岁数,依次类推, 推到第一人(10岁),再往回推。 """ nNeed = 1 def Age(n): if n == 1: return 10 return 2+Age(n-1) print "the %dth peop...
baff4bea368f0f0dddbb2cf157cf9dd27ccad88d
raianmol172/data_structure_using_python
/create_stack_using_singly_linkedlist.py
1,655
4.09375
4
class Node: def __init__(self, data): self.data = data self.next = None class Stack: def __init__(self): self.head = None def isempty(self): if self.head is None: return True else: return False def push(self, data): if self.head...
d95ebab51c0a39bc91fe9e361868ca237093dc2a
shalom-pwc/challenges
/Pytho Challenges/08.Is-the-Word-Singular-or-Plural.py
238
4.09375
4
# Is-the-Word-Singular-or-Plural # ----------------------------------------------- def is_singular(text): char = text[-1] if(char == "s") : return "Plular" else: return "Singular" print(is_singular("changes")) # Plular
a445180dc494eecc44273854c43dd05a91612ef6
seeprybyrun/project_euler
/problem0044.py
1,707
3.8125
4
# Pentagonal numbers are generated by the formula, P_n=n(3n−1)/2. The first # ten pentagonal numbers are: # # 1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ... # # It can be seen that P_4 + P_7 = 22 + 70 = 92 = P_8. However, their # difference, 70 − 22 = 48, is not pentagonal. # # Find the pair of pentagonal numbers, P_j...
a0c74be232bee775a9c3d27631f538299204feb7
bielabades/Bootcamp-dados-Itau
/Listas/Tuplas e Dicionarios/13.py
1,770
4.28125
4
# Faça um programa que fique pedindo uma resposta do usuário, entre 1, 2 e 3. # Se o usuário digitar 1, o programa deve cadastrar um novo usuário nos moldes # do exercício 10 e guardar esse cadastro num dicionário cuja chave será o CPF da pessoa. # Quando o usuário digitar 2, o programa deve imprimir os usuários cadast...
453b2442d8aa5836e7ab2650ad043b5f700b23fa
durhambn/CSCI_220_Computer_Programming
/HW 5 weightedAverage.py
1,348
3.984375
4
##Name: Brandi Durham ##weightedAverage.py ## ##problem: Calculates a persons avarage and the class average ##from a set of grades from a file ## ##Certification of Authenticity: ## I certify that this lab is entirely my own work. def weightedAverage(): #ask user for name of file of grades fileName = in...
f6235871117bb6e8e7b8ada3df87f0f24348eae2
Athulya-Unnikrishnan/DjangoProjectBasics
/LaanguageFundamentals/python_collections/set_prgms/removing_du[licates.py
272
3.703125
4
lst=[1,2,3,4,5] num=int(input("Enter a number")) st=set(lst) out=set()#to remove duplicates for s in st: op=num-s if op in lst: if(s>op): out.add((op,s)) elif(s==op): pass else: out.add((s,op)) print(out)
0229d1107dda665ddc09d4314c6b0591736a3928
bsakari/Python-Projects
/User_Defined_Functions/UserInput.py
375
3.921875
4
print("Enter Student One Name") stdt1 = str(input()) print("Enter Student Two Name") stdt2 = str(input()) print("Enter Student Three Name") stdt3 = str(input()) print("Enter Student Four Name") stdt4 = str(input()) print("Enter Student Five Name") stdt5 = str(input()) print("The Names of the Students are \n") print(std...
f5c31cee765a77815e7c861fb98f6b85952a0da9
sonyabrazell/worksheets
/shopping_cart_lab/shopping_cart.py
626
3.546875
4
class ShoppingCart: def __init__(self, products_in_cart, product, product_price): self.products_in_cart = products_in_cart self.product = product self.product_price = product_price self.products_in_cart = [] self.product = '' self.product_price = '' def add_produ...
0796014291e89a4ba311ba1831f1c8e7d1172aaa
requestriya/Python_Basics
/basic56.py
248
4.03125
4
# wap to perform an action if a condition is true # Given a variable name, if the value is 1, display the string "First day of month!" # and do nothing if the value is not equal var = 2 if var == 1: print("First day of month!") else: pass
03d4ecce4f03f8d1d607642825eaf76f33964522
ashwingarad/Core-Python
/function/Recursive.py
145
3.875
4
def fact (n): if n == 0: f = 1 else: f = n * fact(n - 1) return f print('Factorial is ', fact(5))
17bc6183f0e31592ec0b132e76d57bcb5ee7ff37
Asumji/Turn-based-game-thing
/index.py
1,473
3.640625
4
import os import random import time enemy = { "name": "Enemy", "health": 100 } player = { "health": 100, } enemyActions = ["Attack", "Heal", "Heal", "Attack", "Attack", "Attack"] playerActions = ["Attack", "Heal"] clear = lambda: os.system('cls') clear() print(enemy["name"] + " He...
7fd6103933af7a2802e219fa3cfd05a865b67548
Oriolowo-Mustapha/Assignment
/Q7.py
131
4.09375
4
integer1 = int(input("Enter first integer: ")) integer2 = int(input("Enter second integer: ")) add = integer1 + integer2 print(add)
771e8b3ed9e7bcb33ed74279446e79c60d984802
cainingning/leetcode
/array_119.py
541
3.515625
4
class Solution: def getRow(self, rowIndex): """ :type rowIndex: int :rtype: List[int] """ pre_list = [1] if rowIndex < 0 or rowIndex > 33: return [] for i in range(1, rowIndex + 1): now_list = [1] * (i + 1) for j in range(1,...
8739eed36afa03ede22057d8650f14223baa5979
YellowSpoonGang/WeeklyCode
/9-6-20/Kyles.py
881
3.96875
4
# 1.1 def unique(string): sorted(string) for i in range (len(string) - 1): if string[i] == string[i + 1]: return False return True if __name__ == "__main__": string = "abcd" if(unique(string)): print("Yes") else: print("No") #1....
4e6fd96d678dcbbc22d21963875d35cb94e615fd
DrewRitos/projects
/AssignXIV("Number_Analyzer").py
2,606
4.125
4
#_continue is the variable that determines if any while function continues or not _continue = "yes" #default is the callname I put in to any function that requires a parameter for what it will respond with if the #user inputs something that gets caught by exception handling #get and getint are input functions that do ...
05b78bbeadaebb0ce2a2a7ed4c7e315813ec2831
timsergor/StillPython
/301.py
1,117
3.84375
4
# 162. Find Peak Element. Medium. 42%. # A peak element is an element that is greater than its neighbors. # Given an input array nums, where nums[i] ≠ nums[i+1], find a peak element and return its index. # The array may contain multiple peaks, in that case return the index to any one of the peaks is fine. # You may...
06e09975edfc24249bbb11386c0808b3ebfb65dd
HurricaneInteractive/Python-Journey
/basics/calculator.py
1,390
4.21875
4
# imports the regular expression library import re # prints out a welcome message print("Our Magical Calculator") print("Type 'quit' to exit\n") # global functions previous = 0 run = True # Defines the main program function def perform_math(): # get the global functions, they won't be available due to function s...
aada36b3769ce9e60b7f9d52ca00ff9d6c00e095
bhatiamanav/TensorFlowBasics
/graphs_tf.py
893
3.9375
4
#Graphs are created on System backend when a Tensorflow process is done. #They consist of nodes containing values and operations & edges containing results leading out of opeartion nodes #Tensorflow is primarily used for Computation graphs import tensorflow as tf var1 = tf.constant(10) var2 = tf.constant(20) var3 = v...
ca1374426040c822c7a70b39ea2d90e8c97a3f0e
danieltibaquira/Analisis_Numerico
/Talleres/Taller 1/Punto3.1.1.py
879
4.03125
4
#Taller 1 Punto 3.1.1 Convergencia metodos iterativos #Stiven Gonzalez Olaya #John Jairo Gonzalez Martinez #Karen Sofia Coral Godoy #Daniel Esteban Tibaquira Galindo import math import numpy from matplotlib import pyplot def res311(f,a,b,N,E): if f(a)*f(b) >= 0: print("Secant method fails.") return...
ab07218ef7d71aff98a06a2f74c1ddf8db2c5f09
Max143/Python_programs
/List directiry.py
215
3.875
4
# list all files in a directory in python from os import listdir from os.path import isfile, join file_list = [f or f in listdir('/home/students') if isfile(join('/home/students', f))] print(files_list)
258bb59dc75e9f4208595f8437a76960efb934aa
yang529593122/python_study
/study_05/array/一位数组的动态和.py
413
3.609375
4
# 不改变原数据 def oneArr(nums): out = [] temp = 0 for i in range(len(nums)): out.append(temp + nums[i]) temp += nums[i] return out # 改变数据 def yesChange(nums): for i in range(len(nums)): if i == 0: nums[i] = nums[i] else: nums[i] += nums[i - 1] ...
dd040346d45e8ac9509ea64909c7b12f96a611b4
stephen-allison/word-chains
/team_2/wordchainsdijkstra.py
3,270
3.765625
4
import sys import string import heapq # had some time to kill on a flight so thought i would see if i could # get the dojo word-chain program running using dijkstra's algorithm. # this should give the shortest chain between two given words, at the # expense of running time. # it seems quite robust - it does the seven...
46dc6bb09e05d62ef041804d75c3c4d2b557ee59
asharkova/python_practice
/UdacityAlgorithms/lessons1-3/quickSort.py
417
4.09375
4
"""Implement quick sort in Python. Input a list. Output a sorted list.""" import random def quicksort(array): # Randomly select pivot random_element_index = random.randint(0, len(array)) pivot = array[random_element_index] # Move pivot to the end array[random_element_index] = array[-1] array[-...
c7994668fa8e1f34af08e16b0e4ee398d838d150
reyotak/Introducao-Python
/parouimpar.py
142
3.859375
4
#Par ou Impar N = int(input("Digite um numero inteiro ")) n = N / 2 if (n == int(n)): print("par") else: print("ímpar")
af15229dc6885106b5c0d6f49f557c157add5c6e
hanrick2000/LaoJi
/Leetcode/0076.todo.py
1,352
3.65625
4
76. Minimum Window Substring Basic idea: use two pointers and Counter to count all the element inside the window, use another variable to keep track how many char completed Time O(n) class Solution: """ @param source : A string @param target: A string @return: A string denote the minimum window, retu...
b1d6d9756ee3836b775cc7921325444d9a73a521
lncyby/Di-Yi-Ci
/课件/课堂笔记/myfile/function/test6.py
441
3.546875
4
#!/usr/bin/python #coding=utf-8 #输入日期,确定是当年的多少天。 a=raw_input("Please input your date>",) #input date l=a.split('-') #把字符串形式的年月日按-分割并放在列表里。 y=int(l[0]) m=int(l[1]) d=int(l[2]) sum=0 dcount=[31,28,31,30,31,30,31,31,30,31,30,31] if (y%4==0 and y%100 !=0) or y%400==0 : dcount[1]+=1 for i in range(0,m-1): sum+=...
66e05430cfd749e7e430021a114a57435c898f8d
qmnguyenw/python_py4e
/geeksforgeeks/algorithm/hard_algo/2_4.py
7,225
3.578125
4
Sum of all divisors from 1 to N | Set 2 Given a positive integer **N** , the task is to find the sum of divisors of first **N** natural numbers. **Examples:** > **Input:** N = 4 > **Output:** 15 > **Explanation:** > Sum of divisors of 1 = (1) > Sum of divisors of 2 = (1+2) > Sum of diviso...
54371c4bd5de7d3ee85af78ff718eea18352f77f
wakasa-seesaa/Pyformath
/1/2.py
276
3.96875
4
#!/usr/bin/python # -*- coding: utf-8 -*- def multi_table(a,b): for i in range(1, int(b+1)): print('{0} x {1} = {2}'.format(a,i,a*i)) if __name__ == '__main__': a = input('Enter a number:') b = input('Enter a number:') multi_table(float(a), float(b))
d9f177bf406178833e1e374b3abe366cd9619fa1
NARUTOyxj/python
/pythonBase/use_property.py
735
3.578125
4
class Screen(object): """docstring for Screen""" @property def width(self): return self._width @width.setter def width(self, value): if value <= 0: raise ValueError('请输入大于0的数') #'ValueError'首字母要大写,否则出错 else: self._width = value @property def height(self): return self._height @height.sette...
844d8899b300a5bf8d7eaeffb9e3071668f49186
ArhamChouradiya/Python-Course
/27class_05.py
428
3.96875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Aug 4 13:22:58 2019 @author: arham """ class objectcounter: num = 0 def __init__(self): objectcounter.num+=1 @staticmethod #I don't know why it is used def display(): print(objectcounter.num) ...
648f26f5f73a03f5ee4b2e09ce8d03d1a8654ab1
sivatoms/Python_DataStructures
/Heap_Min.py
2,991
4.03125
4
class Heap_Min: def __init__(self, items = []): self.list = [] for i in items: self.push(i) # push an item into the list def push(self, item): if self.list == [] : self.list.append(item) elif self.size(self.list) == 1: if s...
dc68b01cdbe546052934170c7f224b0ee4065720
stasDomb/PythonHomeworkDombrovskyi
/Lesson6FilesDecorators/FilesTask1.py
1,624
3.75
4
# Задача-1 # Из текстового файла удалить все слова, содержащие от трех до пяти символов, # но при этом из каждой строки должно быть удалено только четное количество таких слов. with open("./file.txt") as f_in: array_of_file = [row.strip() for row in f_in] result_in_file = [] for words in array_of_file: ...
ca208bc236899bd18acd0b6d1fe26666704ed026
tyagivipul629/python1
/iterable.py
112
3.609375
4
def iter1(obj): return iter(obj) #def next1(): #return __next__() ab=iter1([1,2,3,4,5]) for i in ab: print(i)
a6145763fd8045dff1c646182df3e007be12f751
ysoftman/test_code
/python/string_replace.py
148
4.0625
4
str1="lemon apple orange" str2 = str1.replace("apple", "---") print(str1) print(str2) print(str1.replace("zzz", "---")) # 못찾으면 변화없음
9d17df5229f8db5a2fb6148f5622995e1a2666e0
sergelemon/python_training
/task4_1.py
681
3.90625
4
'''4. В первый день спортсмен пробежал `x` километров, а затем он каждый день увеличивал пробег на 10% от предыдущего значения. По данному числу `y` определите номер дня, на который пробег спортсмена составит не менее `y` километров. Программа получает на вход числа `x` и `y` и должна вывести одно число - номер дня.'''...
5f6d76714acc96bea13de17b898630687e02a275
is42-2019/-1-
/Задачи по программированию 1 семестр/№35.py
890
4.125
4
#Задача №35 из раздела Циклические алгоритмы. Обработка последовательностей и одномерных массивов #Условие:Дан одномерный массив числовых значений, насчитывающий N элементов. Поменять местами группу из M элементов, начинающихся с позиции K с группой из M элементов, начинающихся с позиции P. import random M = rando...
d0799f182dbb7882a4c3edea246cc86f80f4b1a5
Joe2357/Baekjoon
/Python/Code/2700/2751 - 수 정렬하기 2.py
462
3.578125
4
import sys n = int(input()) arr_1 = [] arr_2 = [] for i in range(n): temp = int(sys.stdin.readline()) if i % 2: arr_1.append(temp) else: arr_2.append(temp) arr_1.sort(reverse = True) arr_2.sort(reverse = True) try: for i in range(n): if arr_1[-1] < arr_2[-1]: print(arr_1.pop()) else: print(arr_2.pop(...
3510136e936785c86cb7f843a266bc1447d73e8a
havsor/middagsplanlegger
/middagsplanlegger.py
2,238
3.65625
4
# -*- coding: utf-8 -*- """ Ukeplanlegger for middagsmat """ import random kjøttretter = open("kjøttretter.txt", encoding="utf-8") kjøtt = kjøttretter.read().splitlines() vegetarretter = open("vegetarretter.txt", encoding="utf-8") vegetar = vegetarretter.read().splitlines() fiskeretter = open("fisker...
383857bb1b8acab94cc93dd0ca664a4df5d9bae4
xyzhangaa/ltsolution
/SpiralMatrix.py
1,118
4.15625
4
###Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. ###For example, ###Given the following matrix: ###[ ### [ 1, 2, 3 ], ### [ 4, 5, 6 ], ### [ 7, 8, 9 ] ###] ###You should return [1,2,3,6,9,8,7,4,5]. #time O(m*n) #space O(1) def SpiralMatrix(matrix): if matr...
b165e89551f6b7c7d3f4e47d0306c65060226418
Nurse-Mimi/from-cel
/2020-10-08/expressions3.py
200
3.796875
4
import re def match_num(string): text = re.compile(r"^5") if text.match(string): return True else: return False print(match_num('5-2345861')) print(match_num('6-2345861'))
d313583272aacf5f9e5337ad2bab98b7ea3bb65b
jcohen66/python-sorting
/matrix/matrix_mult_list_comprehension.py
610
3.6875
4
# x = [[12, 7,3], # [4, 5, 6], # [7, 8, 9]] # y = [[5, 8 ,1, 2], # [6, 7, 3, 0], # [4, 5, 9, 1]] x = [[0,3,5], [5,5,2]] y = [[3,4], [3,-2], [4,-2]] def dot_product(x, y): sum = 0 for i in x: for j in y: sum += i * j return sum # E x D # E cols must...
82f2c18dbab3dd0bd82e206e1559d121736a75c2
ryanchang1005/ALG
/string/LeetCode 14 Longest Common Prefix.py
896
4.09375
4
""" 找出最長的前綴 Input: ['flower','flow','flight'] Output: 'fl' Input: ['dog','racecar','car'] Output: '' 思路 A=Input 先找出長度最小字串, shortest_str 回圈shortest_str: 回圈A: 如A[i]==shortest_str[i]下一圈(不寫) A[i]!=shortest_str[i]回傳shortest_str[0:i](不含i) """ def solve(A): if len(A) == 0: return '' #...
7b6b38bfb96e6375d78a71a6014f758c58517a03
perrymant/CodeWarsKataStuff
/CodeWarsKataStuff/Postfix eval.py
612
3.671875
4
def eval_postfix(text): s = list() plus = None for symbol in text: if symbol in "0123456789": s.append(int(symbol)) elif not s: if symbol == "+": plus = s.pop() + s.pop() elif symbol == "-": plus = s.pop() - s.pop()...
7bf0e80b53cc0af7cdcbe40237ac4d9fd1647aba
rayfengleixing/learnPy
/Basic/CaiNum.py
293
3.890625
4
#!/usr/bin/env python # -*- coding:utf-8 -*- import random s = random.randint(0,101) while True: n = int(input("Input a number between 0~100>> ")) if n > s: print("bigger") elif n < s: print("smaller") else: print("Yes it's %s"%s) break
b5eeb96eea44331f08867a296e57f66d2a8e82fd
Sunqk5665/Python_projects
/Python课余练习/lect02.汇率兑换/currency_converter_v5.0.py
1,373
3.65625
4
""" 作者:Sunqk 功能:汇率兑换 版本:2.0 日期:2019/7/30 2.0 新增功能:根据输入判断是人民币还是美元,进行相应的转换计算 3.0 新增功能:程序可以一直运行,直到用户选择退出 4.0 新增功能:将汇率兑换功能封装到函数中 5.0 新增功能: (1)使程序结构化(2)简单函数的定义 Lambda """ # def convert_currency(im,er): # """ # 汇率兑换函数 # """ # out = im * er # return out def main(): """ ...
443fa5e0b58e4cb4e94fd894b2e0a0394d5485b7
greenfox-velox/attilakrupl
/break/Python CW practice/IntToEnglish.py
2,357
3.734375
4
ones = {"1":"one", "2":"two", "3":"three", "4":"four", "5":"five", "6":"six", "7":"seven", "8":"eight", "9":"nine", "0":"zero"} tenToTwenty = {"0":"ten", "1":"eleven", "2":"twelve", "3":"thirteen", "4":"fourteen", "5":"fifteen", "6":"sixteen", "7":"seventeen", "8":"eighteen", "9":"nineteen"} tens = {"2":"twenty", "3":"...
ad2f57884492307777b2f179cf35ccda0132970c
gustavogneto/app-comerciais-kivy
/funcaovariadica.py
421
3.640625
4
# exemplo de funcões variadicas def valores(*arqs): print(arqs) def listadeargumentroassociativos(**kwarqs): print(kwarqs) def argumentos(*args, **kwargs): print(args, kwargs) valores(1,2,3,4,5,6) valores("um", "dois", "tres", "quatro") listadeargumentroassociativos(a=1,b=2,c=3,d=4,e=5,f=6) listadearg...
d49d881952994de6f1e4d2d35c5dc718eb1577be
prestwich/bitcoind_mock
/bitcoind_mock/utils.py
530
3.59375
4
import random from hashlib import sha256 from binascii import unhexlify, hexlify def get_random_value_hex(nbytes): """ Returns a pseduorandom hex value of a fixed length :param nbytes: Integer number of random hex-encoded bytes to return :type nbytes: int :return: A pseduorandom hex string representi...
67e247c190d218fbb83eee4e025219cfa5f68ace
ckdrjs96/algorithm
/programmers/level3/정수 삼각형.py
382
3.5
4
def solution(triangle): n=len(triangle) add=triangle[n-1] for row in range(n-2,-1,-1): new=[] for col in range(row+1): #현재값과 자식노드 왼쪽 오른쪽의 최댓값을 저장 new.append(triangle[row][col]+max(add[col],add[col+1])) # 하위문제를 모두 풀어 add에 저장 add=new return add[0]
836beb4ba7d7f37a8b2c1e20c9dcb33d258eb342
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/225/users/3994/codes/1791_3140.py
164
3.78125
4
from numpy import* v=array(eval(input("Digite os numeros: "))) i=0 M=0 while(i<size(v)): M=(v[i])**5 M=M+ () i=i+1 M =(M/size(v))**1/5 print(round(M,2))
fbbdd32d0497eb42211024de77d9def98d5976ba
Abhinav-Kamatamu/Linux
/Python_Code/print[s] a[s]dimond.py
314
3.875
4
# -*- coding: utf-8 -*- """ Created on Sun May 27 12:35:17 2018 @author: abhinav """ numberOfLines =int(input('enter the number of lines:')) for i in range(1,numberOfLines+1): print((numberOfLines-i)*" "+(2*i-1)*"*") for j in range(1,numberOfLines): print((j)*' '+(2*(numberOfLines-j)-1)*"*") 1
64de19894bc10c102381c47aa2ae14bf601f7874
yourshadypast/FaceRecon
/face_recon.py
1,599
4
4
import face_recognition from tkinter.filedialog import askopenfilename # Load the known images image_of_person_1 = face_recognition.load_image_file(askopenfilename()) image_of_person_2 = face_recognition.load_image_file(askopenfilename()) image_of_person_3 = face_recognition.load_image_file(askopenfilename()) #...
379d91797e1ce3e91782458372d34ae34ea98e91
ornichola/learning-new
/pythontutor-ru/09_2d_arrays/05_secondary_diagonal.py
1,260
3.796875
4
""" http://pythontutor.ru/lessons/2d_arrays/problems/secondary_diagonal/ Дано число n. Создайте массив размером n×n и заполните его по следующему правилу: Числа на диагонали, идущей из правого верхнего в левый нижний угол равны 1. Числа, стоящие выше этой диагонали, равны 0. Числа, стоящие ниже этой диагонали, равны 2....
651993421642a921012640f31911fb7f44292aa1
matthijskrul/ThinkPython
/src/Eighteenth Chapter/Exercise4.py
638
3.890625
4
# Write a function count that returns the number of occurrences of target in a nested list: from unit_tester import test def count(target, data): tally = 0 for e in data: if e == target: tally += 1 elif type(e) == list: tally += count(target, e) return tally tes...
e447f6b38c0d004b18f70214fd3b70c268a2fa7d
manbalboy/python-another-level
/python-basic-syntax/Chapter08/03.상속.py
609
3.796875
4
# 생성자 # : 인스턴스를 만들 때 호출되는 메서드 class Monster: def __init__(self, health, attack, speed): self.health = health self.attack = attack self.speed = speed def move(self): print("이동하기") class Wolf(Monster): pass class Shark(Monster): def move(self): print("헤엄치기") ...
1df1bf758500f1beeb8f5f0de69e9a25e1a1265d
dbanerjee/ctci-5th-ed
/chp01_arrays_and_strings/1_3.py
689
3.84375
4
# Solution to Exercise 1.3 from Cracking the Coding Interview, 5th Edition # Nitin Punjabi # nptoronto@yahoo.com # https://github.com/nitinpunjabi # # Assumptions: # - whitespace is significant # - case-sensitive def is_permutation_sort(s1, s2): if len(s1) != len(s2): return False return sorted(s...
92d80868d8b1c1c3cb8ea48397b6103fe6801a81
redashu/shubhredhat
/file_operations.py
1,308
3.859375
4
#!/usr/bin/python2 import time # creating an empty file # file name , file mode ==(r,w,a) f=open('/tmp/myfile1.txt','w') print "file is created.." f.close() # create file and write some data f=open('/tmp/shubhdha.txt','w') #print "file is created..." #print "writing some random data .." time.sleep...
2ea650efc17f31b2eb72c7c9b0749611525d4092
tliu57/Leetcode
/Easy/HappyNumber/test.py
379
3.609375
4
from sets import Set from math import pow class Solution(object): def isHappy(self, n): used_digit = Set([]) used_digit.add(n) while n!= 1: result = 0 while n != 0: result += int(pow(n%10, 2)) n /= 10 if result in used_digit: return False else: used_digit.add(result) n = result ...
52acd89ed6598ba501d5fe3701d7860c86f18f26
stephen1776/Python-for-Biologists
/03 - Working With Files/P4B0302_writingFASTAfile.py
1,028
3.890625
4
''' Writing a FASTA file Write a program that will create a FASTA file for the following three sequences – make sure that all sequences are in uppercase and only contain the bases A, T, G and C. Sequence header DNA sequence ABC123 ATCGTACGATCGATCGATCGCTAGACGTATCG DEF456 actgatcgacgatcgatcgatcacgact HIJ789 ACTGAC-...
d91dae77fbc7e6e7700f75159b96e9dd42daa2dc
chapmanbe/BMI_6018_Final_Project
/caloriedb.py
784
4.34375
4
"""import sqlite3 to use with the sqlite database""" import sqlite3 class Database: """database object that stores the user's balance for the date""" def __init__(self): self.connection = sqlite3.connect("calorie.db") self.cursor = self.connection.cursor() def updatedb(self, bal...
b58ffcc6e946be821ceb77d53b7d9989335c5e6a
Yuxuan-Chan/algorithm-and-data-structure
/python/Leetcode/Leetcode_292_Nim_Game.py
651
3.828125
4
#! python3 # -*- coding: utf-8 -*- class Solution(object): def canWinNim(self, n): """ :type n: int :rtype: bool """ return n % 4 != 0 """ 这题概述的其实有点问题, If there are 8 stones, I can pick 3 Opponent can pick 3 I can pick 2 stones . I win. So how is this solution valid. In th...
5de4005b58d525f6ea6afa852134eb64582e3e36
WYWAshley/Python-100-Days
/Day080910.py
8,354
4.21875
4
# coding=utf-8 # import time # # class clock(object): # def __init__(self, hour=0, minute=0, second=0): # self._hour = hour # self._minute = minute # self._second = second # # def show(self): # print("%02d:%02d:%02d" % (self._hour, self._minute, self._second)) # # def run(sel...
d18d10a6fe1ce761b70b798e27754f497579011f
kengo-0805/pythonPractice
/day3.py
520
3.953125
4
''' # 問題3-1 x = input("1つ目の数字:") y = input("2つ目の数字:") s1 = float(x) s2 = float(y) if s2 == 0: print("0での割り算はできません") else: print("足し算:{} 引き算:{} 掛け算:{} 割り算:{}".format(s1+s2,s1-s2,s1*s2,s1/s2)) ''' # 問題3-2 text = input("文字を入力してください:") count = len(text) if count < 5: print("短い文章") elif 5 < count < 20: prin...
6bde94d9bec059befa3ecd59964d526f9a00f7ab
suman0204/p2_201611119
/w5Main8.py
342
4.21875
4
height=input ("input user height (m) : ") weight=input ("input user weight (kg): ") print "%s" %height, "%s" %weight BMI=weight/(height*height) print "%s" %BMI if BMI<18.5: print 'Low weight' elif 18.5<= BMI <23: print 'normal weight' elif 23<= BMI <25: print 'over weight' else: prin...
b12094f251f8e2830fe46cc7fb4c220599c17aa1
aschey/cs260
/makeintegers.py
701
4.03125
4
import sys import random if len(sys.argv) == 1: print("usage: python3 makeintegers.py count start step swaps") exit() def main(): #gets the command-line arguments count = int(sys.argv[1]) start = int(sys.argv[2]) step = int(sys.argv[3]) swaps = int(sys.argv[4]) ints = [] #generates ...
353ef118306930c4d49970bc6c03b2e6369bc83f
prabhurd/DataScientistPython
/4LetterCombination.pyi
152
3.640625
4
import itertools d ={'2':['a','b','c'], '3':['d','e','f']} for combo in itertools.product(*[d[k] for k in sorted(d.keys())]): print(''.join(combo))
5dbd255635a948cdf7be350f58361066acdb7a54
av9ash/DSwithPython
/mQueue.py
715
3.765625
4
class mQueue(object): def __init__(self): self.queue = [] def enqueue(self,data): self.queue.append(data) def dequeue(self): x = self.queue[0] del self.queue[0] return x def isEmpty(self): return self.queue ==[] def peek(self): if not self....
f4a2a3802f785b235c8b473633e7e068b840edbb
denkovarik/Machine-Learning-Library
/linearRegressionDemo.py
4,053
4.0625
4
# File: linearRegressinDemo.py # Author: Dennis Kovarik # Purpose: Run the Linear Regression model on examples # Usage: python3 linearRegressinDemo.py from ML import LinearRegression import numpy as np from sklearn.datasets import make_regression from utils import * import matplotlib.pyplot as plt from mpl_toolkits.m...