blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
8d5d8070f520cec5997e38ca104053fa4aef6df1
blairg23/Project-Euler
/Problem12.py
2,987
3.8125
4
# -*- coding: utf-8 -*- #Problem 12 from projecteuler.net #Author: Blair Gemmer """Description of Problem 12, Highly divisible triangular numbers: The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten te...
2239ce7bbf4d2dce4aeb37ae5c8685658f1659d4
DRay22/COOP2018
/Chapter02/U02_Ex10_Kilo_to_Mile.py
794
4.09375
4
# U02_Ex10_Kilo_to_Mile.py # # Author: # Course: Coding for OOP # Section: A3 # Date: ${19} ${Sept} ${2018} # IDE: PyCharm # # Assignment Info # Exercise: Kilometers to miles # Source: Python Programming # Chapter: 2 # # Program Description # This program converts Kilometers to Miles # # # # Algorith ...
08683002e5359e0d8747a79c7b3caba28a962952
FisherDengfromChina/Python
/15-HandleErrors/Except.py
619
3.671875
4
#一个except子句可以同时处理多个异常,这些异常常被放在一个括号里成为一个元组 #except(RuntimeError, TypeError, NameError) #最后一个except子句可以忽略异常的名称,它将被当作通配符使用。 #可以使用这种方法打印一个错误信息,然后再次把异常抛出。 import sys try: f=open('mylife.txt') s=f.readline() i=int(s.strip()) except OSError as err: print("OS error:{0}".format(err)) except ValueError: print("Could not co...
9f869df085ad70f799036bb3f317ba5ee35cf4a6
DariaKlimanova/chastotniy_analiz
/decryption.py
2,563
3.625
4
def decrypt(a, m, ru, t): letters_ru = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ" if t == 1: if m.isalpha() and m in letters_ru: k = int(letters_ru.index(m)) - int(letters_ru.index(ru[0])) elif t == 2: if m.isalpha() and m in letters_ru: k = int(letters_ru.index(m)) - int(l...
96f7cf55c5f63843aa847ecb55f90cb048a2ff98
VaibhavDhaygonde7/Coding
/Python Projects/P53OverridingAndSuper().py
882
4.0625
4
class A: classvar1 = "I am a variable in class A" def __init__(self): self.var1 = "I am inside class A's constructor" self.classvar1 = "I am a instance variable in class A" self.special = "Special" class B(A): classvar1 = "I am in class B" def __init__(self): self....
9a4cb2212e56f22f786ab270173eb918261ede81
henryherzfeld/pali
/alg/dp_r_pali.py
594
4.0625
4
def pali(word): return pali_helper(word, 0, len(word)-1) def pali_helper(word, start, end): # base case 1: single character string if start == end: return 1 # base case 2: two character string if word[start] == word[end] and start + 1 == end: return 2 # recursive calls to cons...
48e10101a4fa89ffa2bea45a8ceade75abd32cec
assafZaritskyLab/Intro_to_CS_SISE_2021-2022
/week_4/Did_you_know.py
579
3.71875
4
# # ##### Did you know? # # def div_with_portion_and_reminder(num, div): # """num and div are positive integers""" # return num // div, num % div # # # res = div_with_portion_and_reminder(50, 7) # print(res) # print(type(res)) # # def build(n): if n == 0: return [] x = build(n-1) x.append(n...
e64485e3c01a06384528cd6dc839251aa36fa3d6
delphienator/all_possible_combinations
/all_combinations.py
2,457
4.28125
4
import csv def generate_combinations(list1, list2, list3): ''' This function will do a combination of input data into a matrix. Each combination should represent a row. Since, we don't know how many elements we will have on input - we can't define how many arguments to have. Input: as input shou...
8b22227c7fb73a500bcc76e69a859faf49a0b1c0
leoloo0510/Enterprise
/2-work/Python/10pcs proj/10samples/square_calc_3.py
314
3.71875
4
# -*- coding: utf-8 -*- import math def func(n): # if isinstance(math.sqrt(n+100),int) and isinstance(math.sqrt(n+268),int): if int(math.sqrt(n+100))== math.sqrt(n+100) and int(math.sqrt(n+268))== math.sqrt(n+268): return n for i in range(0,10000): if func(i) is not None: print(i)
e5a45b2e98cd4f383a502548e58734d439e607bc
Rockyzsu/StudyRepo
/python/ac/键盘行.py
1,123
3.8125
4
# coding:utf-8 """ 给定一个单词列表,只返回可以使用在键盘同一行的字母打印出来的单词。键盘如下图所示。 示例1: 输入: ["Hello", "Alaska", "Dad", "Peace"] 输出: ["Alaska", "Dad"] 注意: 你可以重复使用键盘上同一字符。 你可以假设输入的字符串将只包含字母。 """ class Solution(object): def findWords(self, words): """ :type words: List[str] :rtype: List[str] """ ...
92f6b90d53a48c1655f3ee959f771c43e4eee30c
jackpick/Language-Analysis-Of-TV-Shows
/If you are from reddit, please help me with this code here.py
3,389
3.671875
4
# importing the required modules import matplotlib.pyplot as plt import numpy as np # open the txt file containing the words you are searching for words = open ("Words.txt", encoding="utf-8") # open the txt file containing the titles you are looking for titles = open ("Titles.txt", encoding="utf-8") # open the ...
dee13a52e65ebf2b5c4b969d7bcb21bbedf57933
Yashwant-Tailor/LeetCodeSolution
/python_solutions/2527.py
1,442
3.53125
4
class Solution: def xorBeauty(self, nums: List[int]) -> int: # Solution Overview # the idea is to find the answer for each bit separately # as per given constraint in the problem we will at most have 32 bit in any number # for each bit we will calculate that this bit will be set or ...
c6702a5e41f2534182243e13ff98e83ccd3f950c
subratcall/Learning_Python
/LeetCode/p009_palindrome_number.py
463
3.78125
4
# p009 Palindrome Number # Easy # Determine whether an integer is a palindrome. Do this without extra space. # Negative integer will not be a palindrome class Solution(object): def isPalindrome(self, x): """ :type x: int :rtype: bool """ if x < 0: return False ...
e7bc2c5e659cccce5ff3d0ae436c6a2c2b6d89ab
biswaranjanroul/Python-Logical-Programms
/Exprience Lavel Logical Programms/program to find maximum difference between two elements in given Array.py
648
3.75
4
# Write a java program to find maximum difference between two elements in given Array? # Input = { 2, 5, 1, 7, 3, 9, 5} # Output = 8 # Explanation : The maximum difference is between 1 and 9 # Input = { 9, 2, 12, 5, 4, 7, 3, 19, 5} # Output: 17 def maxDiff(arr, arr_size): max_diff = arr[1] - arr[0] min_eleme...
43987a107ff0b9211cb1697c89e39ad668c21ed2
gitaperdani/bigdata
/minggu-04/praktik/src/fancierOutput.py
415
4.0625
4
s = 'Hello, world.' str(s) repr(s) print(s) str(1/7) x = 10 * 3.25 y = 200 * 200 s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...' print(s) # The repr() of a string adds string quotes and backslashes: hello = 'hello, world\n' hellos = repr(hello) print(hellos) # The argument to repr() m...
6d320295bc44747b04f04540cd77c6318447c78c
basdijkstra/python-for-testers
/examples/examples_08.py
470
3.703125
4
class Car: def __init__(self, make, model, year): if make == "Ducati": raise ValueError("Ducati does not make cars!") self.make = make self.model = model self.year = year def get_info(self): return "This is a %d %s %s" % (self.year, self.make, self.model) t...
26065ac07ef9954e06c13a20cbb5963ccaa1922f
sarsembin/webdev2019
/week10/Informatics/loops/loop while/c.py
103
3.9375
4
n = int(input()) power2 = 1 while power2 <= n: print(power2, end =" ") power2 = power2*2
f0b6c26532492a3b31fdc0422d2d45165905f220
bob92-dev/datacleaner
/velo.py
6,314
3.515625
4
#!/usr/bin/python # coding:utf-8 import datetime import os import csv import shutil import mail # TODO : ajouter dans les fichiers de sortie, la premiere ligne du fichier initial qui contient le nom des col ################################# FONCTIONS###################################################### ##...
12c0d1426d06df87835a304862bdd3f83f980001
daheige/python3
/part2/yield_demo.py
1,526
4.15625
4
# coding:utf-8 # 在 Python 中,这种一边循环一边计算 # 的机制,称为生成器:generator # 函数是顺序执行,遇到 return 语句或者最后 # 一行函数语句就返回。而变成 generator 的函数,在每次调用 next() 的时候执行,遇到 yield # 语句返回,再次执行时从上次返回的 yield 语句处继续执行。 def odd(): print('step1') yield (1) print('step2') yield (2) o = odd() print(next(o)) print(next(o)) # 通过迭代器实现反向打印 cla...
ac0a0292d31c3738c8b5e9c08140ed40a220783b
chunche95/ProgramacionModernaPython
/Proyectos/ProgramacionVintage/Factura/tablaTemperaturasºF-ºC.py
1,837
4.125
4
# Ejercicio while I - Tabla de temperaturas. # # Construir un programa que muestre a peticion del usuario: # - La tabla de conversion de grados Centigrados en Fahrenheit desde 0 a 230 en multiplos de 10. # - La tabla de conversion de grados Fahrenheit a Centigrados desde 0 a 100 en multiplos de 100. # # F --> C # ...
3240d7f7c7183c5cc0bdfce09b0bd3be9e027681
pawan9116/UnitTestDemo
/ShoppingCart.py
307
3.5625
4
class ShoppingCart: def __init__(self): self.quantity=0 def additems(self,quantity): if quantity>5: return "cart cannot have more than 5 items" else: suffix = '' if quantity == 1 else 's' return f'Successfully added {quantity} item{suffix} to cart!'
144dafae5b31c2a76fda9dbc8eabadd90c23eb67
GanLay20/the-python-workbook
/Cap_3_Repetition/ex_78_TODO.py
372
3.921875
4
# EXERCISE 78 : The Collatz Conjecture # TODO NEW_BASE = 2 num = int(input('Enter a non-negative integer: ')) result = "" q = num r = q % NEW_BASE result = str(r) + result q = q // NEW_BASE while q > 0: r = q % NEW_BASE result = str(r) + result q = q // NEW_BASE print(f"{num} in decimal is {result} in...
01c53d01d879fb6e14cbbfe9e62609b9015d3871
Pouf/CodingCompetition
/CiO/brackets.py
761
3.578125
4
from re import findall def checkio(s): s = findall("[\(\)\[\]\{\}]", s) keepGoing = True while s and keepGoing: keepGoing = False if s[0] in [']', '}', ')']: return False if ']' in s: loc = s.index(']') if s[loc-1] == '[': del s[loc] ...
f25937b31f3506e54d2445ff0d75d8337e79c008
shahuji/hello-world
/part-1/faulty_calc.py
1,684
3.84375
4
# faulty calculator program import random print('1. Addition(+) \n2. Subtration(-) \n3. Multiplication(*) \n4. Division(/) \n5. Modulus(%) \n6. Multiple(**) ' '\n7. Exit ') n = input('Enter your choice: ') while n != 'j': i = 0 n = int(n) if n == 1: x = int(input('Addition \nEnter...
f169aa58381665542f3e1bddfcb583516892bea9
marcos-tic/curso_python_completo
/aula 07 - Números e operações aritméticas/Código/aula-07-numeros-operacoes-aritmeticas.py
3,049
3.984375
4
# Tipo de dado Inteiro idade1 = 20 idade2 = int(20) print(type(idade1)) print(type(idade2)) print(idade1, idade2) idade3 = input('Digite a sua idade: ') print(type(idade3)) #soma = idade3 + 10 idade4 = (int(input('Digite a sua idade novamente: '))) print(type(idade4)) soma1 = idade4 + 10 print('Somando idade: ' +...
b9598821713e0cc1b6dcaf5c888e0a7dee5bb672
MrHamdulay/csc3-capstone
/examples/data/Assignment_3/mjlkhw001/question1.py
259
4.15625
4
# Program to create a rectangle # Khwezi Majola # MJLKHW001 # 20 March 2014 def rec(): h = eval(input('Enter the height of the rectangle:\n')) w = eval(input('Enter the width of the rectangle:\n')) for i in range(h): print('*' * w) rec()
f4ea8a4493f121c3e0509bf102efdb4fe539f34e
mkdirJava/pythonPractice
/entry/entry.py
726
3.90625
4
class thing: def __init__(self,counter, name): self.name = name self.counter = counter def __str__(self): return self.name def __repr__(self): return self.name def __eq__(self, other): return self.name == other.name def __hash__(self): return sel...
0e5c82af77f8dd46de9e829048f3e61d07992600
PinillosDev/PythonBasics-es
/2nd_module/IV-TiposDatos.py
1,390
4.28125
4
""" Los datos son pieza fundamental en la programación. Por ahora, distingiremos entre datos numéricos, de cadena y lógicos NUMÉRICOS: - int: Número entero, como 1, 54, -23, 24624362 - float: decimal. Se llama float por el punto 'flotante'. Ej 3.1516 CADENAS: - texto: Cualquier caracter que esté entre comillas...
56530d66bd24a21d158a1fe27ce49529cff17765
andriinovak/learn_python
/lesson_11.py
888
3.65625
4
from random import randint class movie: def __init__(self, title, genre = 'action'): self.title = title self.budget = randint(100, 1000) self.genre = genre self.__director = 'roman' self.has_seen = False def print_movie(self, count = 1): for i in range(count): print(f'movie: {self.title}, (${self.bud...
5f284751ae43e42c45859506989d2cf907bf1722
Kawser-nerd/CLCDSA
/Source Codes/AtCoder/abc011/C/4896069.py
371
3.5
4
n = int(input()) ng = [int(input())for _ in range(3)] if n in ng: print('NO') exit() cnt=0 while n != 0: if n - 3 not in ng and n - 3 >= 0: n -= 3 elif n - 2 not in ng and n - 2 >= 0: n -= 2 elif n - 1 not in ng and n - 1 >= 0: n -= 1 else: print('NO') exit() cnt += 1 ...
a9eaa7daf0580470c05cc681b69e54d27e12538c
hsuan81/Python-2019fall-hw
/hw6/hw6-3.py
322
3.78125
4
def find_factor(number): factorlis = [] for i in range(2, number): while number % i == 0: factorlis.append(i) number = number//i if number == 1: break print('*'.join(str(x) for x in factorlis)) number = int(input()) factor = find_factor(numbe...
75f9d23dac2bf833b34456dab7039d7cb73f9092
Poobalan1210/data-structures-python
/leetlist.py
2,399
3.890625
4
class Node: def __init__(self,data=None,next=None,prev=None): self.data=data self.next=next self.prev=prev class doublylist: def __init__(self): self.head=None def insertatbeginning(self, data): if self.head is None: node = Node(data) self.he...
676f68aabfe43d4b015f3c79caf6832aa00bb6ca
iamJohnnySam/WebScraping
/02_ScrapingUniversityCourses/BaseCode3.py
1,063
3.609375
4
# https://johnsamarasinghe.blogspot.com/2020/12/scraping-university-courses-part-1.html from selenium import webdriver from bs4 import BeautifulSoup as BS driver = webdriver.Chrome("chromedriver.exe") courses = [] def getSite (name, web, tag, value="none"): driver.get(web) content = driver.page_source s...
ff89f97e2d37726cdb0965a001b62e7fc80157aa
Chaudoreille/python-exercises
/lawn_mower/v1/lawn_mower/input_file_lexer.py
6,733
3.96875
4
import fileinput from lawn_mower.error import error class InputFileLexer(): """ Lexes a Lawn Mower input file, using a generator that returns a list of tokens for each line of the file. To program the mower, the input file must be constructed as follows: The first line corresponds to the coor...
c0b5a2d5d3fd3fa148f1ad5786e5836a509c808e
ShaneKelly89/IrisDataSet-Project
/analysis.py
9,199
4.125
4
#This is a program created for the purpose of pands 2021 coursework using the Iris Dataset #Rough work code for this program was carried out within 'roughwork.py' to allow this program to remain cleaner #Author Shane Kelly import numpy as np import pandas as pnd import matplotlib.pyplot as plt #Importing the need...
d700118f96e4ca5cf7f615b8d4fbdb54ed70fef0
Kavya-gupta-200000/end.py
/land s.py
1,039
3.96875
4
# -*- coding: utf-8 -*- """ Created on Sun Sep 19 02:00:33 2021 @author: kcs """ # List thislist = ["apple", "banana", "cherry"] print(thislist) #list length thislist = ["apple", "banana", "cherry"] print(len(thislist)) #types thislist = ["apple", "banana", "cherry"] print(type(thislist)) #list ...
dcdb4f3cb8d8363d5d2f6e86ec4fa5fdabb60b4f
Buremoh/fibonacci-ageFind-timeZone
/time-zone.py
1,011
3.546875
4
from datetime import datetime from pytz import timezone fmt = "%Y-%m-%d %H:%M:%S %Z%z" # get the current time in UTC now_utc = datetime.now(timezone('UTC')) print('UTC :', now_utc) # Convert this to EST now_est = now_utc.astimezone(timezone('US/Eastern')) print('EST :', now_est) # Convert this to Berlin now_berlin ...
501582951118c606ca207e1022050e29682d451f
kmartinez33/MIStest
/session8.py/excercise5.py
584
3.671875
4
def any_lowercase1(s): for c in s: if c.islower(): return True else: return False any_lowercase1(k) def any_lowercase2(s): for c in s: if 'c'.islower(): return 'True' else: return 'False' def any_lowercase3(s): for c i...
7d324c80b65461a24d1d11c5008d971acc4d85f8
will8889/assortedproblem
/no5.py
179
3.515625
4
def is_member(list_a:list,list_b:list): for data_a in list_a: if list_b.__contains__(data_a): return True return False print(is_member([12,4],[31,4]))
a03a6767614df8bf3faada2e6c3dd76123cd12fc
Kaloslmr/Python-Pensamiento
/15_scopeTypes.py
750
4.25
4
#Differents type of scope #---------- GLOBAL SCOPE: Puedes usar la variable donde quieras! ---------- x = 'Esta es una variable global' #Funcion en variable LOCAL def globalScope(): print(x) #Imprimimos la variable global en la funcion y en el codigo global globalScope() print(x) #---------- LOCAL SCOPE: S...
da1696aaa355c6497137860e7d612d7e4d29abcc
sawood14012/lab-progs
/bellmanford.py
727
3.515625
4
def bf(adj_list, n, s): distance = [999 for i in range(n + 1)] distance[s] = 0 for i in range(n - 1): for pair in adj_list: distance[pair[1]] = min(distance[pair[1]], distance[pair[0]] + pair[2]) del (distance[0]) print(distance) def main(): adj_list = [] n = int(input(...
16ee71730920153e88ac2f0d33b88023838f8150
jkh-code/data_science
/solutions/graphs-searching/src/shortest_path.py
4,557
4.03125
4
from collections import deque from src.load_imdb_data import load_imdb_data from sys import argv, exit def shortest_path(actors, movies, actor1, actor2): """Return the shortest path from actor1 to actor2. If there is more than one path, return any of them. Parameters ---------- actors: dictionar...
bec008bd69b3d71139c6b843253ae4bbf7fe22a3
HaoyuHou/Linear-Regression
/linear_regression.py
4,629
3.59375
4
""" Do not change the input and output format. If our script cannot run your code or the format is improper, your code will not be graded. The only functions you need to implement in this template is linear_regression_noreg, linear_regression_invertible,regularized_linear_regression, tune_lambda, test_error and mappin...
ee82c01db2506f9073ad4926376e5683fff71b3a
siFeiden/riskasecond
/risk/board.py
1,257
3.65625
4
from collections import defaultdict class Country(object): """A Country in a Risk Map""" def __init__(self, name, owner=None, troops=0): self.name = name self.owner = owner self.troops = troops def __eq__(self, other): return self.name == other.name def __ne__(self, o...
49a594c51b305f5854841b6e21b31836cef9e36f
CodyValle/Homework
/DataMining/hw6/hw6.py
22,809
3.953125
4
""" Cody Valle, Andrew Burke, Katreina Carpenter Data Mining Homework 6 Program """ import copy import math import random import operator # Some index references to use globally global MPG MPG = 0 global CYLINDERS CYLINDERS = 1 global DISPLACEMENT DISPLACEMENT = 2 global HORSEPOWER HORSEPOWER = 3 g...
ca4ba1bbd6872cc2fd727ab6c5be08a7f439b312
CodingForChange/praquemdoar
/flask/lib/site-packages/TwitterAPI/TwitterRestPager.py
1,859
3.578125
4
__author__ = "Jonas Geduldig" __date__ = "June 8, 2013" __license__ = "MIT" import time class TwitterRestPager(object): """Continuous (stream-like) pagination of response from Twitter REST API resource. :param api: An authenticated TwitterAPI object :param resource: String with the resource path (ex. search/tw...
38ea64c9e90dced78d42c5114c6377f242c182dd
ViartX/PyProject
/lesson5_5.py
628
4.25
4
# 5. Создать (программно) текстовый файл, записать в него программно набор чисел, разделенных пробелами. # Программа должна подсчитывать сумму чисел в файле и выводить ее на экран. import random numbers_sum = 0 f_text = open("lesson5_5.txt", 'w') for i in range(1, 101): new_number = random.randint(1, 10...
c68b89f9a8b258340b5dc8bbbc2a865a21d92536
norajuanjuanjuan/python-learning
/basic/PythonApplication1/PythonApplication1/PythonApplication1.py
97
3.5625
4
print('Hello World') def abs(a): if a<0: print(-a) else: print(a) abs(-9)
4552adaac9b14197ca6c2c8e8554f96c8778f5c9
agapeteo/python-data-algo
/sort/merge_sort.py
1,283
3.53125
4
def merge(input_list, tmp_list, low_idx, mid_idx, high_idx): for i in range(low_idx, high_idx + 1): tmp_list[i] = input_list[i] left_idx = low_idx right_idx = mid_idx + 1 cur_idx = left_idx while left_idx <= mid_idx and right_idx <= high_idx: if tmp_list[left_idx] <= tmp_list[right...
ce8c91df978c1e9440d682ee15ea343f9764cf2e
huynhtritaiml2/Python_Basic_Summary
/numpy/num5_filter_image.py
1,261
3.671875
4
""" Filter Image ------------ Read in the "dc_metro" image and use an averaging filterto "smooth" the image. Use a "5 point stencil" where you average the current pixel with its neighboring pixels:: 0 0 0 0 0 0 0 0 0 0 x 0 0 0 0 0 x x x 0 0 0 0 0 x 0 0 0 ...
638dbcd6183a47b3f23dc50d22c4a86ea9533a6b
shchukinde/basic_python
/lesson_6/task6.1.py
1,284
3.8125
4
# Создать класс TrafficLight ( светофор) и определить у него один атрибут color ( цвет) и метод # running ( запуск). Атрибут реализовать как приватный. В рамках метода реализовать # переключение светофора в режимы: красный, желтый, зеленый. Продолжительность первого # состояния (красный) составляет 7 секунд, второго (ж...
983d895a911a9f5d2cc7425bdd244a781333ce4f
guveni/RandomExerciseQuestions
/arrays.py
890
3.984375
4
# !/usr/bin/env python # -*- coding: utf-8 -*- """ """ __author__ = 'guven' def swap(input_array, first_index, second_index): temp = input_array[first_index] input_array[first_index] = input_array[second_index] input_array[second_index] = temp def find_multiple_duplicates(input_array): if input_arra...
07a12be8adf286d79096f9bced5ad13cf752d0d7
jkosterhale/ExampleCode
/surveyFunc.py
19,759
4.0625
4
#!/usr/bin/python #prints the initial form. a minor convenience. #prints the initial form. a minor convenience. def welcomeToSurveyForm_d(): print 'Please enter your User Name and a Section Name. <br>Remember to do the sections in order. Thanks!<br><br>' print '<form action="survey.py" method="post"><br...
40fb887f74f5e0666b9d86ce7ad6fdd2b3cc8f57
mohitsh/python_work
/recursion/test.py
304
3.625
4
def listSum(alist): if len(alist) == 1: return alist[0] else: return alist[0] + listSum(alist[1:]) print listSum([1,2,3,4,5]) print listSum([100]) def fact(num): if num <= 1: return 1 else: return num*fact(num-1) print fact(1) print fact(2) print fact(3) print fact(4) print fact(5)
6bf62f4bb335b54ae587faeea5644f2a1deda1fe
dreamapplehappy/python3-tutorial
/liaoxuefeng-tutorial/day-10/map-and-reduce.py
3,672
3.546875
4
# map函数 l = list(range(10)) def f(x): return x * x print(map(f, l)) # <map object at 0x10373c7f0> print(list(map(f, l))) # [0, liaoxuefeng-tutorial, 4, 9, 16, 25, 36, 49, 64, 81] print(list(map(str, l))) # ['0', 'liaoxuefeng-tutorial', 'official-tutorial', '3', '4', '5', '6', '7', '8', '9'] # reduce from func...
44e1b10721d694d678f37f3d74e97322987d5cb9
MiroVatov/Python-SoftUni
/Python Basic 2020/Exersice exam 06 - Salary - fine.py
497
3.671875
4
open_tabs = int(input()) salary = int(input()) fine = 0 total_fine = 0 for i in range(1, open_tabs + 1): website = input() if website == 'Facebook': fine = 150 total_fine += fine elif website == 'Instagram': fine = 100 total_fine += fine elif website == 'R...
628b85d9efaf78a5d7f96bd510f4c69a6dfe00d3
savva-kotov/python-intro-practise
/2-1-4.py
271
3.75
4
''' Считайте цифру, выведите её название на английском (zero, one, ..., nine). Sample Input: 8 Sample Output: eight ''' a = int(input()) l = ['zero','one','two','three','four','five','six','seven','eight','nine'] print(l[a])
6205015e4c706a1b629674ff224ebb0bbcd50845
haritak/py4hs
/chapter3/ex3.9.py
1,231
3.640625
4
import random def flipBiased(p): l = random.randint(1,100) if (l<p): return 0 else: return 1 def flipFair(p): while True: n1 = flipBiased(p) n2 = flipBiased(p) if n1!=n2: return n1 print("Δώσε την τιμή του p (πιθανότητα στα 100 να έχει 0)") ...
09bb4ed0da3c8d9738d51647419bf2262689e04f
981377660LMT/algorithm-study
/4_set/有序集合/字典加SortedList设计类/dict.py
157
4.09375
4
d = dict() d["a"] = 1 d["c"] = 3 d["v"] = 2 # 获取最后一次插入的值(top) print(next(reversed(d.values()))) # print(list(d.values())[-1])
6595fdca418d8e776de0aeb349a3435f2ad29c17
watermelon-lee/leetcode
/code_twice_analysis/List/31_下一个排列.py
1,972
3.671875
4
""" @File : 31_下一个排列.py @Time : 2019-12-10 14:25 @Author : 李浩然 @Software: PyCharm @Email: leehaoran@pku.edu.cn """ # 类型 数组 # 技巧 逆向思考 # 我们从最后开始找,找到第一个逆序的二元组(即nums【i】>nums[i-1])。 # 然后我们在i-1之后的位置,找到比nums【i-1】大,但是最接近的与nums【i-1】交换 # 然后排列nums【i-1】之后的所有元素即可。 # 如 [1,2,3,5,4,3,2,1] # 我们从后向前遍历首先找到第一个逆序[5,3],以3所在位置为分界向右找...
6ab345e77a8aca4237c630a42b78b17414e6e0c6
kolevatov/python_lessons
/week_2/2_2.py
755
4.125
4
# Какое число больше? # Даны два целых числа. Программа должна вывести число 1, # если первое число больше второго, число 2, # если второе больше первого или число 0, если они равны. # Формат ввода # Вводятся два целых числа. # Формат вывода # Выведите ответ на задачу. # Примечания # Эту задачу желательно решит...
36408cae5458e4bed341b52f3e6648a23b9959e5
caiosainvallio/estudos_programacao
/curso_em_video/exe075.py
749
4.28125
4
"""Exercício criado por: https://www.cursoemvideo.com/ 075: Desenvolva um programa que leia quatro valores pelo teclado e guarde-os em uma tupla. No final, mostre: A) Quantas vezes apareceu o valor 9. B) Em que posição foi digitado o primeiro valor 3. C) Quais foram os números pares.""" num = [int(input('Digite um n...
55e514640ffe139d7ead929c9f9652bea78d133b
OswaldoMP/DSI.C1.A2
/board.py
340
3.640625
4
from math import sqrt class Coordinate: def __init__(self, row, column): self.row = row self.column = column self.neighbors = [] def __repr__(self): return str([self.row, self.column]) def distance(self, other): return sqrt((self.row - other.row)**2 + (self.column ...
c07e65969cf5c5a6475daff51b623aedc5e23b87
ColeRichardson/CSC148
/mini-exercises/mini exercise 1/buildings.py
7,414
4.125
4
class Building: """A building Precondition: no rooms can have the same name, all room names must be unique >>> Building1 = Building('1234 thomas st', 5) >>> Building1.address '1234 thomas st' >>> Building1.num_rooms 5 """ def __init__(self, address: str, num_rooms: int): ""...
bf6d400318514a6c0e287baf7959780256f411ef
jzhanay001/Python-Bootcamp
/week_one/conditional.py
540
3.859375
4
"""number= int(input("Enter a number:")) min_num=3 max_num=10 if number>min_num and number < max_num: print("nice") elif number > (min_num-2) and number < (max_num+2): print("Kinda nice") else: print("not nice")""" """ class Hello: def __init__ (self, name): self.name=name self.age=10 h...
407764a74fc19b548d8e9de09487ac9451922491
SmileShmily/LaunchCode-summerofcode-Unit1
/ClassExercise & studio/crypto_app/caesar.py
1,403
4
4
import sys def normalize(byte, min_byte, max_byte): ''' Normalizes byte so that it falls within byte range ''' # inclusive range byte_range = max_byte - min_byte + 1 normal_byte = (byte - min_byte) % byte_range return normal_byte + min_byte def cipher(message, shift): ''' Returns a...
681084cbae70f2c30723f270de66c7148267f00f
daniel-reich/ubiquitous-fiesta
/hZi6AhWEzGASB7tWR_1.py
132
3.875
4
def check(lst): if len(set(lst)) < len(lst): return 'neither' return 'increasing' if lst == sorted(lst) else 'decreasing'
411562ddd2774ddd6478849d23dfdf93a9178dfa
m-joon-ixix/2021Winter-MachineLearningStudy
/Kaggle-IntroToML/tutorial4.py
1,357
3.671875
4
import pandas as pd melbourne_file_path = "./Kaggle-IntroToML/melb_data.csv" melbourne_data = pd.read_csv(melbourne_file_path) melbourne_data = melbourne_data.dropna(axis = 0) y = melbourne_data.Price # going to predict the Price melbourne_features = ["Rooms", "Bathroom", "Landsize", "Lattitude", "Longtitude"] X = mel...
49afd16d34a7c275af0d6bbaaf568acbe3413223
yk0817/python_study
/basic/,threading6.py
785
3.6875
4
import threading,time global_counter = 5 class MyThread(threading.Thread): def __init__(self,name,sleep_time): threading.Thread.__init__(self) self.name = name self.sleep_time = sleep_time def run(self): global global_counter # read count = global_counter ...
f1822a552fa6a4dfed525bdd9981a999f617a51a
dmitrij-rmshv/python486
/task2.py
912
4.40625
4
""" Для списка реализовать обмен значений соседних элементов, т.е. Значениями обмениваются элементы с индексами 0 и 1, 2 и 3 и т.д. При нечетном количестве элементов последний сохранить на своем месте. Для заполнения списка элементов необходимо использовать функцию input(). """ my_list = list(input('Введите произвольну...
d89fb973674b49584ea70d6ff08fbcbfc5af9ed5
hiys/PYTHON
/pythonScripts/day04/listforinif.py
1,797
3.890625
4
#!/usr/bin/env python import keyword print(keyword.kwlist) # 遍历key值,value值(下面写法完全等价): a = {'a': '1', 'b': '2', 'c': '3'} for key in a: print(key+':'+a[key],sep=' -- ',end=' $') print('directory 方式一 for key in a') for key in a.keys(): print(key+':'+a[key],sep=' -- ',end=' $') print('directory 方式2 for key ...
b7b9b36c090dffc536da7a6e2d730a79bcf3122d
Alberto-Oliveira-Barbosa/Desafios
/Python2/1014.py
83
3.578125
4
# -*- coding: utf-8 -*- x = input() y = input() print("%.3f km/l" % (x/y))
92b78bc44693d566c495f24ef95feda39bfb9df0
alexcrist/neural-network
/code/model/loader.py
2,610
3.609375
4
import numpy as np import csv import random class CSVLoader(object): '''Contains common operations for loading and processing CSV data files. Attributes: data - a list of dictionary entries representing numerical data outputKeys - list of keys corrs...
343c132532c5c32593493c6bbfc1e5b8f4cfbe07
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_34/374.py
1,084
3.5
4
import re class run(): def __init__(self, file): line = file.readline() [L, D, N] = [int(i) for i in line.split(" ")] self.words = [] for word in range(D): self.words.append(file.readline()[:-1]) self.output = "" for case in range(N): ...
132fafe57cd64db58e2a092189b7d618683fdf0a
kate-gordon/firstweek_Python
/Tip_Calculator2.py
554
3.9375
4
amt_of_bill = float(input("Total bill amount? ")) rank_service = input("Good, Fair, or Bad Service? ") split_amt = int(input("Split how many ways? ")) def tip(rank_service): if rank_service == "Good": return amt_of_bill * .2 elif rank_service == "Fair": return amt_of_bill * .15 elif rank_s...
df6956451e8ef89307ac9709823dc727b325335b
valeriacavalcanti/IP-2020.2---R
/semana_11/exemplo_08.py
608
4.0625
4
''' simbolos numéricos simbolos maiusculos simbolos minusculos caracteres especiais ''' qtde_num = qtde_maiuscula = qtde_minuscula = qtde_especial = 0 frase = input('Frase: ') for i in range(len(frase)): if (frase[i] >= 'A') and (frase[i] <= 'Z'): qtde_maiuscula += 1 elif (frase[i] >= 'a') and (frase...
2629745498547470c06a17587dc57964bf2f93a0
benjaminhuanghuang/Statistics
/ten_days_statistics/day04/day04_Binomial Distribution II.py
850
4.125
4
def factorial(n): return 1 if n == 0 else n * factorial(n - 1) def combination(n, x): return factorial(n) / (factorial(x) * factorial(n - x)) def binomial(x, n, p): ''' x : The number of successes n : The total number of trials p : The probability of success of 1 trial ht...
322cc76715aaa3d4bd05616ce07b2fd41b3ffc98
pavanimallem/pavs1
/guvi72.py
207
4.03125
4
string=raw_input() c=0 for x in string: if(x=='a' or x=='A' or x=='e' or x=='E' or x=='i' or x=='I' or x=='o' or x=='O' or x=='u' or x=='U'): c+=1 if(c>=1): print("yes") else: print("no")
0e30b54d8a99979d5168a36d9d436989bb3c647a
SabithaSubair/pythonpgms
/dictonarypgms/dictionarypgm1.py
536
4.15625
4
#values of dictionary in the form of keyvalue pairs students={"roll":100,"name":"ajay","course":"mca"} print(students["roll"]) print(students["name"]) print(students["course"]) for key in students: print(key,students[key]) #another method for k,v in students.items(): print(k,v) #checking for specific key print(...
90133b0b44d74d9851a9f58f0b069e06da1cfad3
tsytsy/python-study
/python_full_statck/fuction/homework.py
3,367
3.78125
4
#1. 写函数,用户传入修改的文件名,与要修改的内容,执行函数,完成批了修改操作 # def modifyFileContent(file, old_content, new_content): # ''' # 文件的修改是需要重复覆盖的,不需要修改的内容保存下来,需要修改的内容找到后也保存下来,然后写到文件中 # 首先打开文件 # 找到文件位置,然后替换 # :param file:文件名 # :param old_content:旧内容 # :param new_content:新内容 # :return:None # ''' # L = [] ...
90f037399934cdd4ed9f284df2eb8142b9419e44
samarink/mit-6.0001
/ps1/ps1c.py
1,503
4.125
4
portion_down_payment = 0.25 annual_return = 0.04 total_cost = 1_000_000 semi_annual_raise = 0.7 epsilon = 100 starting_salary = int(input('Enter your annual salary: ')) target_amount = total_cost * portion_down_payment number_of_steps = 0 # the upper and lower bounds of search low = 0 high = 10000 while True: a...
1aa1d60cbe9c142f4e4405699297083956c574dd
mw-pp/zdalne
/qqqq.py
1,338
3.625
4
haslo=input("Podaj hasło\n") proba="" licznik=3 while proba!=haslo and licznik!=0: proba=input("Zgadnij hasło\n") if proba!=haslo: licznik-=1 ##licznik=0 ####while licznik<100: #### print("JEDEN. hej") ## ##while licznik>100: ## print("DWA. hej") ## ##while licznik!=10: ## print(...
557bc156988c53c6c12f9e57e5c5e573a7a0fb5d
MatthewGoodall/PythonRPGGame
/CollisionObject.py
3,521
3.546875
4
import pygame import Player class CollisionObject(pygame.sprite.Sprite): def __init__(self, x_pos, y_pos, width, height): super().__init__() self.image = pygame.Surface([width, height]) self.image.fill((255, 255, 255)) self.rect = self.image.get_rect() self.rect.x =...
2fbe13fa280ce2899aa8ebefa22bfd976479d8f2
motovmp1/udemy_selenium_2020
/19_python_basic.py
965
3.921875
4
############################################################ # # Vinicius Miranda de Pinho # # Python3 and Selenium test webdriver # # udemy class # # basics pythons commands class 18 # # Lenovo I5 - New lesson # # tuple data type (immutable) (tuples) # # Function is a statements that perform a specific task ##########...
fffcd7750d46a1b0b77b970d12a03ac31b402eef
odanado/nlp100
/ch01/sec04.py
418
3.515625
4
# -*- coding: utf-8 -*- import re first = [1, 5, 6, 7, 8, 9, 15, 16, 19] s = "Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can." arr = re.split('\W+', s) dist = {} print(arr) for i in range(len(arr)): if len(arr[i]) > 0: if i in fir...
dd853ca32bb9d336a6f5b8fa83b8d72e2c0a6dc1
Pmogi/rpgCharacterGenerator
/rpg.py
2,067
3.71875
4
# RPG Character Sheet Generator import random class sheet: def __init__(self, name, hp, mp, strength, magic, dexterity): self.name = name self.hp = hp self.mp = mp self.strength = strength self.magic = magic self.dexterity = dexterity # based on what c...
2d31ecdac76900756489ef0045ba88ab7a53e361
ldhldh/py
/myScript.py
7,999
3.5
4
#!/usr/bin/env python # #coding=utf-8 dict_de = {} dict_de[''] = '' dict_en = {'0':'0000','1':'0001','2':'0010','3':'0011','4':'0100','5':'0101','6':'0110','7':'0111','8':'1000','9':'1001','a':'1010','b':'1011','c':'1100','d':'1101','e':'1110','f':'1111','A':'1010','B':'1011','C':'1100','D':'1101','E':'1110','F':'1...
a009489c9818834b68b5979333c757c4c968f036
chunoxie/ideas
/URL-Parse-Python3.py
2,936
3.921875
4
# coding: utf-8 # In[2]: import urllib.request import sys # these import statements allow us to use 'modules' aka 'libraries' .... # code written by others that we can use # In[3]: urlToRead = 'http://www.google.com' # This value won't actually get used, because of the way the while loop # below is set up. But w...
73d0f8bbf4f65f11b1dbf02b3b5d2526e7b8e1e6
ahartz1/project-euler
/python/e029distinct_powers.py
1,232
3.84375
4
""" Project Euler #29: Distinct Powers From the description: How many distinct terms are in the sequence generated by a**b for 2 ≤ a ≤ 100 and 2 ≤ b ≤ 100? """ from __future__ import (absolute_import, print_function) from ensure_integer import ensure_integer class NonOddInputError(Exception): pass def...
03cd27f683a45e08bf268076307f2ab6fadd7fb6
NSMobileCS/pyfun
/pyfun9.py
430
4.09375
4
from random import randrange def genTen(): for _ in range(10): grade = 'A' score = randrange(60,101) if 80 < score <= 90: grade = 'B' elif 70 < score <= 80: grade = 'C' elif score <= 70: grade = 'D' print("Score: {}; Your grade is ...
558c269865e6fa6122bb4bc78f33e7755c0c7429
Raniac/NEURO-LEARN
/env/lib/python3.6/site-packages/dipy/segment/threshold.py
3,031
3.6875
4
import numpy as np def otsu(image, nbins=256): """ Return threshold value based on Otsu's method. Copied from scikit-image to remove dependency. Parameters ---------- image : array Input image. nbins : int Number of bins used to calculate histogram. This value is ignored f...
350b2495cb74cca6249830fae20556832b35ebc4
snehalvartak/Python-Challanges-HackerRank
/textwrap.py
324
4.1875
4
""" You are given a string S and width w . Your task is to wrap the string into a paragraph of width w. """ # Enter your code here. Read input from STDIN. Print output to STDOUT import textwrap S= raw_input() w = int(raw_input()) if len(S) > 0 and len(S)<1000 and w <len(S) and w> 0: print textwrap.fill(...
e07e83df26e497bc04d707dd31099c76416fb4cb
mouhdjouab/ElZero_Python_Course
/Assignment-051 - 055 - 11.py
3,308
3.671875
4
#First my_nums = [15, 81, 5, 17, 20, 21, 13] num2 = [] num3 = 0 for num in my_nums : if num % 5 == 0 : num2.append(num) num2.sort(reverse=True) for num in num2 : num3 =num3+ 1 print(f"{num3 } => {num}") print("=" * 40) #Second num2 = 0 while num2 < 21 : num2 = num2 +1 ...
f2a8ac4733ff6291192ea3bac94fd050307405ea
Utkarsh101/LeetCode-Problems
/Python/Missing Number.py
472
3.96875
4
''' Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. Example 1 Input: [3,0,1] Output: 2 Example 2 Input: [9,6,4,2,3,5,7,0,1] Output: 8 Note: Your algorithm should run in linear runtime complexity. Could you implement it using only con...
1e273348b83b7eeeae28d86fa9fbca4603bfcc3d
Aigarsss/py
/ATBS/08_paths_and_writeFile/MadLibs/mad.py
778
4.40625
4
#! python3 # Program to create madlibs. it reads Source_lib.txt and offers to replace adjective, # noun, verb, noun # open and read a file openSource = open('Source_lib.txt', 'r') readSource = openSource.read() openSource.close() # get user input for the words that need to be replaced and replace in the strin adj = ...
495a5301fe59dff59b3359491b712cea79d1c22b
GLAU-TND/python-lab-SaurabhChhonkar
/custumeception.py
260
3.53125
4
class MyException(Exception): def __init__(self,v): self.v=v def xyz(): a = int(input("Enter first number: ")) b = int(input("Enter secand number: ")) c = a+b if c < 150: raise MyException('Custom Exception Occurred') xyz()
bb4b21910aaef88383f0875fb96e3245a1d03699
IvanKonkin/geekbrains_homework
/lesson01/home_work06.py
345
4.0625
4
first_day = int(input("Введите результат первого дня ")) result = int(input("Введите желаемый результат ")) day_number = 1 while first_day < result: first_day *= 1.1 day_number += 1 print(f"Вы достигнете желаемого результата на {day_number} день")
2945e71819ee69ee02086465fad9b3392d9a793f
Yemte/PythonClub-Anders
/easymode/person_class.py
1,622
3.75
4
import random class person: def __init__(self, name, hp, mp,attack): # Health is usually measured in hit points or health points, # shortened to HP which lowers by set amounts when the entity is attacked or injured # which indicates their continued ability to function. # Magic or mana is an attribute assigned to ...
03d6eaeaddda021353c799b7fcad4e6e4c58b48d
SAIKUMARAR7/Python
/sum_integers.py
91
3.78125
4
a=int(input()) b=int(input()) if a+b in range(15,20): print("20") else: print(a+b)
32247c28ed5cfb8e69c5cba5a23d2c19a8643261
su-ohkubo-lab/PDF_fill_white
/fill_white.py
2,596
3.640625
4
""" Script for making white-painted papers from a PDF file * PDFファイルを読み込んで、一部分を白塗りにするためのスクリプト * [for Python 3] * インストールが必要なもの (pip3経由など): PyMuPDF, PyPDF2 * 特徴 - 読み込んだPDFファイルの、指定された座標を白塗りにする。 - 画像として保存する(・・となっているはず)。 - zoom で出力の解像度を指定可能 (整数: 1,2,3 くらいがよい。1が粗く、3が詳細) - color で塗りつぶす色を指定(RGB)。塗りつぶす領域のチェック用に利用。白は(255,255,2...