blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
1fddd1d58c196ffcd4a7c30d50c5061b75c8c4cb
Shunto/jaran_api
/rurubu_get_data.py
9,059
3.53125
4
import sys, getopt import urllib.request from bs4 import BeautifulSoup from xml.dom.minidom import parseString import MeCab import re url_base = "https://www.rurubu.travel" s_url = "" region_id = "" pre_id = "" l_area_id = "" s_area_id = "" d_area_id = "" #inn_id = "" rurubu_inn_data = [] rurubu_inn_urls = [] rurubu_i...
69545ea5114d009c039f75321fd29f237c073fbe
chao-shi/lclc
/042_trap_rain_h/main.py
1,045
3.921875
4
class Solution(object): def trap(self, height): """ :type height: List[int] :rtype: int """ if not height: return 0 vol = 0 peak = height.index(max(height)) highest = 0 for i in range(peak + 1): if height[i] < h...
6febfe6a09ffb7851e8ec2dae3c675dbaca92e01
AdamZhouSE/pythonHomework
/Code/CodeRecords/2900/60749/261540.py
91
3.9375
4
str1=input() count=0 for h in str1: if not h==" ": count+=1 print(count,end="")
22cfe42d38fd1c2c1f148e65294284976acc92f2
ruoyzhang/AI_public_perception_survey_data_analysis
/CN/consolidation.py
2,055
4.375
4
import pandas as pd def group_columns(dataset): """ a function to group together columns returns a dictionary keys refer to the question number values refer to the actual column names """ # locating the columns to be reorganised cols = dataset.columns[6:(len(dataset.columns)-1)] # setting vars to represent...
a01485f350af1ee0bd05aecd10824749f4548dc4
zelikris/popeye
/popeye/web_server/listing_exec_app/objects/matrix.py
7,849
4
4
"""This module provides the matrix class. IMPORTANT NOTICE: Don't use vector, cross, etc. as variable names We have lowercase classes for sake of usability """ from numbers import Number from vector import vector class matrix(object): """matrix class. Attirbutes: values (Vector[]): vector rows ...
4d3ba54a2b7e4445bfb039d8deb18b68dfabf639
MrRuban/lectures_devops2
/Python/samples3/networking/tcp_udp/5.1.1.py
480
3.734375
4
#!/usr/bin/env python3 """ Обратный DNS клиент """ #https://docs.python.org/3/library/socket.html#socket.gethostbyaddr import socket try: result = socket.gethostbyaddr("66.249.71.15") print("Primary hostname:", end=' ') print(result[0]) # Display the list of available addresses that is also returned ...
695afc25a5196b4f6546844b17de4b37e2b64734
1181888200/python-demo
/day1/five.py
942
4
4
# -*- coding:utf-8 -*- # 字符串格式 # 在Python中,采用的格式化方式和C语言是一致的,用%实现 name = input("请输入您的名字:") sex = input("请输入你的性别:") age = input("请输入您的年龄:") age = int(age) chu = ('先生' if sex=='男' else '女士') print("欢迎 %s %s光临,您的年龄是:%d" %(name,chu,age)) # 常见的占位符 # %s 字符串 # %d 整数 # %f 浮点数 # %x 十六进制整数 # 另一种格式化字符串的方法是使用字符串的form...
4d347d45929aae977ed45bf513985a5ac75adf6f
JulyKikuAkita/PythonPrac
/cs15211/PermutationsII.py
6,452
3.890625
4
__source__ = 'https://leetcode.com/problems/permutations-ii/' # https://github.com/kamyu104/LeetCode/blob/master/Python/permutations-ii.py # Time: O(n!) # Space: O(n) # Brute Force Search # # Description: Leetcode # 47. Permutations II # # Given a collection of numbers that might contain duplicates, return all possibl...
fada1884c8be84b5f5af3321b6b69348deb76c48
huwenqing0606/Nonlinear-Optimization-in-Machine-Learning
/4-Backpropagation/plotGD.py
4,666
3.546875
4
# -*- coding: utf-8 -*- """ Created on Thu Feb 13 14:30:29 2020 @author: huwenqing """ import numpy as np import matplotlib.pyplot as plt from activations import Sigmoid, ReLU, Tanh, Exponential from fullnetwork import onelayer, fullnetwork from backpropagation import backpropagation from mpl_toolkits.m...
92d523fc31fec6ebc2cb08ed934369462af49ef9
CodyBuilder-dev/Algorithm-Coding-Test
/problems/programmers/lv3/pgs-12978.py
1,228
3.515625
4
""" 제목 : 배달 아이디어 : 결국, 출발점으로부터 모든 다른 점까지의 최단거리 완전 탐색 (1) 출발점에서 한 도착점까지 최단거리 구하기 - (2) 모든 도착점에 대해 반복하기 아이디어 : 아니면 그냥 BFS를 돌면서, 최소가 될때마다 갱신? - '경주로 건설' 문제의 쉬운맛 버전인듯 """ from math import inf from collections import deque def solution(N, road, K): graph = [[inf]*(N+1) for _ in range(N+1)] cost = [[inf]*(N+1) fo...
cfe17e8faffeac62ab6d4e5c752d095dcb39dd1d
yasmineholb/holbertonschool-machine_learning
/math/0x06-multivariate_prob/1-correlation.py
479
3.625
4
#!/usr/bin/env python3 """ correlation """ import numpy as np def correlation(C): """ Function that calculates a correlation matrix """ if not isinstance(C, np.ndarray): raise TypeError("C must be a numpy.ndarray") if len(C.shape) != 2 or C.shape[0] != C.shape[1]: raise ValueError("C must ...
45baa628e682fd6ad55a6d21f7444f47401ea3c9
zhourunliang/algorithm
/python/linked_list.py
3,277
3.828125
4
class Node(object): def __init__(self, element=-1): self.element = element self.next = None def __repr__(self): return str(self.element) """ 链表 存取是 O(1) 插入删除也是 O(1) python list 有两个部件 数组 存储数据在链表中的地址 链表 实际存储数据 """ class LinkedList(object): def __init__(self): self.hea...
7a63abc8c28d0f801aeabb454d20d536b03aee1e
alans09/PythonAcademyExercises
/Lekcia11/cvicenie_context.py
723
3.8125
4
import re class Splitter: def __init__(self, text): self.text = text def __enter__(self): return self.text def __exit__(self, *args): res = re.match( r"^([\w\s]*)--(.*)--([\w\s]*).$", self.text ) print( [ res.gro...
a900716fb6b8bd1fae1a061c5575b7fc8a7ffe3f
LittltZhao/code_git
/009_Palindrome_Number.py
333
3.90625
4
# -*- coding:utf-8 -*- def isPalindrome(x):#转化为字符串占用了新的空间 s1=str(x) s2=s1[::-1] return s1==s2 def isPalindrome2(x):#通用解法 if x<0: return False temp=x res=0 while temp: res=res*10+temp%10 temp=temp/10 return res==x print isPalindrome2(123201)
8f02ec1c38dfdc1c2193598ae8a8b5fe046e87ea
AndreasWintherMoen/SchoolAssignments
/TDT4110/Oving1/Tetraeder/Tetraeder.py
306
4.09375
4
import math height = float(input("Skriv inn en høyde: ")) a = 3.0 / math.sqrt(6) * height area = math.sqrt(3) * a**2 volume = (math.sqrt(2) * a**3) / 12.0 print("Et tetraeder med høyde ", height, " har areal ", round(area, 2)) print("Et tetraeder med høyde ", height, " har volum ", round(volume, 2))
13f88c2d7f0ee041f9e53614d1b0cae71f608d8b
SelkieAnna/de-computational-practicum
/main.py
2,355
3.6875
4
import plotter import math from tkinter import * def main(): window = Tk() head = Label(window, text = "This application is designed to plot the equation y' = cos(x) - y.") note = Label(window, text = "All graph tabs must be closed in order for the main window to work correctly.") lbl_inp_gr = Label(w...
90a5081ba82facf8188b5a61b8eb38d2435e7822
Mahadev0317/Codekata
/print elements lesser than N.py
115
3.515625
4
n=int(input()) l=list(map(int,input().split())) lis=[] for i in l: if i<n: lis.append(i) print(*sorted(lis))
302f638eaf83f3915992b7ddf3668b6453db91d4
nkrishnappa/ProgrammingLanguageCourse
/Practice Problems/0.2-List/Two-Sum.py
759
3.859375
4
# Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. a = [1, 2, 3, 4, 5 , -3, -4, -6, 10, 20] number = 6 my_list = [] def twoSum(array:list, number:int) -> tuple: global my_list for element_x in range(len(array) - 2): for element_y...
e81e4102701c9a6aba55f8a82b7b7381931053a7
nikhilgajam/Python-Programs
/Addition of matrix program normal method in python.py
997
4.28125
4
print("Matrix Addition Program\n") row = int(input("Enter rows: ")) col = int(input("Enter columns: ")) a = [] b = [] c = [] # To make entered dimensional matrix for i in range(row): a.append(col*[0]) for i in range(col): b.append(col*[0]) for i in range(row): c.append(col*[0...
1d714622a5f7d72f5aa131204b191a941f80491b
rrbarioni/advent-of-code
/src/day1.py
1,709
3.828125
4
def solve_part1(entries): ''' Given a list of integer values, what is the product of the two values whose sum is equal to 2020? ''' entries = [int(e) for e in entries] n = 2020 d = {} for e in entries: if e not in d: d[e] = 1 else: d[e] +...
0f1061f0dd5194eb6c9e14f716a0f9610b68071e
ptemplin/PyNLPTools
/extraction/wordfrequency.py
1,063
4.5625
5
def word_frequency(document, word_to_frequency = {}): """ Computes the frequencies of words in a given document adding to the existing mapping. :param document: to compute word frequencies for :param word_to_frequency: existing mapping of words to frequencies from other documents :return: the modif...
51cc0f96c2390da54a153a4b147d4133435b6f16
n3z0xx/tp_labs1-3
/37.py
601
4.1875
4
# 37. Из англ букв составить 13 элем-ую рандомную строку и убрать все # неуникальные, заменив уникальные символом 0 (ноль). Вывести оставшиеся с их индексами. import random import string s = ''.join(random.choice(string.ascii_lowercase) for _ in range(13)) print(s) known = [] not_uniq = [] for i in s: if i not in ...
60a83b1026b33d16b6f6bbdb4024b9160dc95355
ashokpal100/python_written_test
/python/number/add_digit_sum.py
179
4
4
number=int(raw_input("enter any no: ")) sum = 0 temp = number while number > 0: rem = number % 10 sum += rem number //= 10 print("Sum of all digits of", temp, "is", sum, "\n")
637c586967c320c6f06462fbb34741d7db078f69
yeliuyChuy/leetcodePython
/557ReverseWordsInAString.py
318
3.65625
4
class Solution: def reverseWords(self, s): """ :type s: str :rtype: str """ s2 = s.split(" ") answer = [] for ch in s2: answer.append(ch[::-1]) return ' '.join(answer) #character that joins the elements to make the lise a whole new string
84d49c8061f77d4d942f9975f43a5d4dff77da5f
soraef/nlp100
/6/50.py
1,087
3.703125
4
import re file_path = "../data/nlp.txt" def load_file(path): with open(path) as f: data = f.read() return data # テキストを分割 def split_text(text): return re.findall(r"(.*?[.;:?!])\s\n?(?=[A-Z])", text) text = load_file(file_path) sentences = split_text(text) for sentence in sentences: print(sen...
68f5f06d47c0cdf7ab2bb32f19924c674fdfbd41
Sangee23-vani/python
/section_3/strings.py
268
3.859375
4
name = 'Sangi' print('Hello {}'.format(name)) result = 35678.76546783 print('The result is {r:1.3f}'.format(r=result)) print('The result is {}'.format(result)) print('Hello {}'.format('Jeyasri')) print('The {q} {b} {f}.'.format(f = 'fox', q = 'quick', b = 'brown'))
2a7aaab972c520a16aaa28df67f00b776264be14
vishalsingh8989/karumanchi_algo_solutions_python
/Chapter 4 stacks/prefixtoinfix.py
627
3.796875
4
ops = ["*" , "/" , "-", "+", "^"] def postfixtoinfix(expression): res = "" stack = [] for i in xrange(len(expression) - 1, -1 , -1): #print(expression[i]) if expression[i] in ops: op1 = stack.pop() op2 = stack.pop() stack.append("(" + op1 + "" + express...
2d125d3d345364189ac98a7d9f7d0b73c455b3ff
Vaishnav95/bridgelabz
/functional_programs/simple_array.py
679
4.1875
4
""" 2D Array a. Desc -> A library for reading in 2D arrays of integers, doubles, or booleans from standard input and printing them out to standard output. b. I/P -> M rows, N Cols, and M * N inputs for 2D Array. Use Java Scanner Class c. Logic -> create 2 dimensional array in memory to read in M rows and N cols d. O/P ...
a55da555b043f939b9106277afa4a67fedff107f
shankarapailoor/Project-Euler
/Project Euler/p10-20/p15.py
1,130
3.796875
4
#solved by combinatorics, but this is a coded algorithm using DP def f1(): arr = [] for i in range(0, 20): temp = [] for k in range(0, 20): temp.append(k) arr.append(temp) return arr def find_routes(start, finish): num_paths = {} if start[0] < 20 and start[1] < 20: if (start[0]+1, start[1]) in num_path...
470096826ddb1b3588d8bfb0ee89d4cd1a5f2b8f
FarzanaEva/Data-Structure-and-Algorithm-Practice
/InterviewBit Problems/String/minimum_parenthese.py
1,153
4.09375
4
# -*- coding: utf-8 -*- """ Created on Fri Jul 9 23:15:31 2021 @author: Farzana Eva """ """ PROBLEM STATEMENT: Given a string A of parantheses ‘(‘ or ‘)’. The task is to find minimum number of parentheses ‘(‘ or ‘)’ (at any positions) we must add to make the resulting parentheses string valid. An string is valid if:...
3dd5ca9627832db5cfc422c540491f0499a23a1a
Physopholy/learningmathmethods
/gamma-phi.py
3,458
3.59375
4
import numpy as np #just comment out inputs/routines not needed print('Enter guesses for unknown variables.') #t=float(input("Enter T(degC):")) t=45 t=273+t #p=float(input("Enter P(bar):")) p=1.35 #x1=float(input("Enter x1:")) x1=.259 x2=1-x1 #y1=float(input("Enter y1:")) y1=.735 y2=1-y1 #psat1=float(in...
96dc8d8f2b112303f238e309b85c58ba4d15b941
williamjzhao/ackermann_func
/ackermann.py
909
4
4
def ackermann(m, n): if m == 0: n = n+1 # print("Base Case: " + str(n) + "") return n elif m > 0 and n == 0: # print("Calling Ackermann of " + str(m-1) + " and " + str(n)) result = ackermann(m-1, 1) # print("Result is " + str(result) + "") return result ...
98d48c010e27011118d91421f51d6cc04fd7ca40
Babatunde13/30-days-of-code-python-ECX
/Python Files/day_25.py
776
4.15625
4
def desc_triangle(a, b, c): ''' A function named desc_triangle Parameters: a, b and c, the lenght of each size of the triangle. Returns: The type of triangle and the value of it's area ''' # Using Hero's Formula s = (a + b + c) / 2 area = (s * (s-a) * (s - b) * (s - c)) ** 0.5 i...
a40cdca5fdd8b93c6c0509d59c3f3fef7038e701
Elendeer/homework
/python/5th/test_1.py
330
3.671875
4
#!/usr/bin/python3 import random def getPi(times): hints = 0 for i in range(1, times + 1): y = random.random() x = random.random() if x * x + y * y <= 1: hints += 1 Pi = hints / times * 4 return Pi if __name__ == '__main__': times = int(input()) print(getP...
809716a3819e3e4721363e34da6c5aecb51befde
sbrodehl/hashcode2021
/Practice Round/solver/scoring.py
2,279
3.65625
4
#!/usr/bin/env python3 import logging from dataclasses import dataclass, field from .parsing import parse_input, parse_output LOGGER = logging.getLogger(__name__) @dataclass class Score: scores: list = field(default_factory=list) total: int = 0 def add(self, diff_ingredients_sq): self.scores.ap...
4df3a902fcc70ac01aaaba94b5d623cd87a17202
Priyankakore21/Dailywork
/PYTHON Training/day4/practice/constant.py
477
4.125
4
#we define some options LOWER, UPPER, CAPITAL = 1,2,3 name = 'jane' #we use our constants when assigning these values print_style = UPPER #... and when checking them: if print_style == LOWER: print(name.lower()) elif print_style == UPPER: print(name.upper()) elif print_style == CAPITAL: print(name.capitailze()...
4483aa10e156a3852095d7a9131a409174a51c00
vinuv296/luminar_python_programs
/Advanced_python/test/pgm10.py
312
3.546875
4
# import re # x='^a+[a-zA-A]+b$' # check ending with a # r="antb" # mat=re.fullmatch(x,r) # if mat is not None: # print("valid") # else: # print("invalid") import re x='[A-Z]+[a-z]+$' # check ending with a r="Geva" mat=re.fullmatch(x,r) if mat is not None: print("valid") else: print("invalid")
3ddd46d1d36d182beda5de8c371f49049f4a8656
sampathweb/game_app
/card_games/blackjack/rules.py
2,857
3.828125
4
#!/usr/bin/env python """ A package to wrap the rules of BlackJack. """ from __future__ import print_function import random class BlackJack: def __init__(self, play_computer=True, level=0): self.play_computer = play_computer self.level = level self.card_suits = ['spade', 'heart', 'diamond...
3b103d9ac6191940686a69536097cc0ebde007a7
JackZander/Python-Note
/1.4.3Python小程序/m1.2EchoName.py
231
3.71875
4
name = input("输入姓名:") print("{}同学,学好Python,前途无量!".format(name)) print("{}大侠,学好Python,前途无量!".format(name[0])) print("{}哥哥,学好Python,前途无量!".format(name[1:]))
87b097d7b4dd04c3f2085472e9dd1c079a8104e7
stostat/holbertonschool-higher_level_programming
/0x04-python-more_data_structures/9-multiply_by_2.py
133
3.75
4
#!/usr/bin/python3 def multiply_by_2(a_dictionary): new_dic = {doub: v*2 for doub, v in a_dictionary.items()} return new_dic
9b822bac22a7fe93695c86c879dea97f537680d1
Aminaba123/LeetCode
/166 Fraction to Recurring Decimal.py
3,008
4.0625
4
""" Given two integers representing the numerator and denominator of a fraction, return the fraction in string format. If the fractional part is repeating, enclose the repeating part in parentheses. For example, Given numerator = 1, denominator = 2, return "0.5". Given numerator = 2, denominator = 1, return "2". Giv...
c85e9161e7c5bc2ba49479d7300069c5f42313ad
tinadrew/ECE573_HW
/HW1/ECE573-S18_Drew_HW1/Q4/Q4_GenerateArray.py
849
3.9375
4
"""Tina Drew - 035006375 ECE573 - Spring 2018 Homework 1 This Code is to provide a data set for the Question 4 of homework #1 It create a set random floating point numbers and prints the to file. The size of the list or array is based on the user input value of N. """ import random def getFilePath(): import...
b941a64f9d1e7cf0fe09d4e6cf180261603b86cc
marble-git/python-laoqi
/chap4/sqrt_to_lt_2.py
468
4.25
4
#coding:utf-8 ''' filename:sqrt_to_lt_2.py chap:4 subject:11 conditions:input a int number > 2 solution:sqrt the number until < 2 ,times, .2f ''' import math integer = input('Enter an integer > 2 : ') if integer.isdigit() and (rst:=int(integer)) > 2: count = 0 while rst >= 2: ...
306d28ab735a3a2f0f60dfeb95e9629084da9b4b
scohen40/wallbreakers_projects
/Leetcode/week_1/p0344_reverse_string.py
541
3.8125
4
from typing import List class Solution: def reverseString(self, s: List[str]) -> None: """ Do not return anything, modify s in-place instead. """ if len(s) > 1: slen = len(s) for i in range(slen // 2): s[i], s[slen - 1 - i] = s[slen - 1 - i],...
371a6921887be714784c3e5b9eafb62f8f7356ab
brpandey/fast-hangman-2.0
/Hangman.py
2,088
3.796875
4
from HangmanGame import HangmanGame from HangmanLetterStrategy import HangmanLetterStrategy from HangmanSettings import HangmanSettings class Hangman: """ Abstraction to represent a real hangman game that can be played (is playable) """ def __init__(self, settings): self._settings = settings self._display = ...
da2e9c221cab191a10bfef733792b39679d1cb7f
daniel-reich/ubiquitous-fiesta
/xzisrRDwWT8prHtiQ_9.py
190
3.671875
4
def difference_two(lst): pairs = [] for i, x in enumerate(sorted(lst)): for y in lst[i+1:]: if y == x + 2: pairs.append([x,y]) return pairs
236a572145e6058ad6dac38dd207b672c10a9194
droconnel22/QuestionSet_Python
/HackerRank/python_practice/alphabet_rangoli.py
347
3.828125
4
import string def print_rangoli(size): alphabet = list("abcdefghijklmnopqrstuvwxyz") interval = 1 for _ in range(0,size*size): for i in range(0,size*size): print("-", end = '') print() # your code goes here return alphabet if __name__ == '__main__': ...
e9e7dbbdff4957b0ef715b330a90978fec4a9f86
Argonauta666/coding-challenges
/leetcode/monthly-challenges/2021-mar/w1-set-mismatch.py
879
3.6875
4
# https://leetcode.com/problems/set-mismatch/ """ Topic: Cyclic Sort """ from typing import List class Solution: def findErrorNums(self, nums: List[int]) -> List[int]: # sort the number using cyclic sort i = 0 while i < len(nums): # if not sorted if nums[i] != i + ...
c4cd23cbaf9fd802a8d5afd7019a46b33276a901
zjuzpz/Algorithms
/PalindromePartitioning.py
1,200
3.6875
4
""" 131. Palindrome Partitioning Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s. For example, given s = "aab", Return [ ["aa","b"], ["a","a","b"] ] """ # O(2 ^ n) # O(n) class Solution(object): def partition(s...
4864bc4bb33f44dd21329893f0e496189ee3ed47
AdamZhouSE/pythonHomework
/Code/CodeRecords/2109/60762/241603.py
130
3.546875
4
#!/usr/bin/python # -*- coding: UTF-8 -*- s=input() re=0 for i in range (0,len(s)): re+=int(s[i]) print(int(re//10+re%10))
ae4cd590eb1e5308d1aa35580b89e87146bb0fa3
satoshun-algorithm-example/atcoder
/abc107/b.py
772
3.5
4
def grid_compression(a, h, w): hh = [] for i in range(h): ok = True for j in range(w): if a[i][j] == '#': ok = False break if ok: hh += [i] ww = [] for i in range(w): ok = True for j in range(h): ...
6c73e1155dece199d48ac5462676467eb8550ff9
icelighting/leetcode
/数组与字符串/最长前缀.py
1,324
3.65625
4
'''编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 ""。''' class Solution: def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ if len(strs) == 1 : return strs[0] if not strs: return " " minL = min([len(item) for ite...
d21f86fa6b9ab04c3e8eff343a191c39ae2bb5e9
landeaux/fifteen-solver
/fifteen-solver.py
15,748
3.671875
4
""" Loyd's Fifteen puzzle - solver and visualizer Note that solved configuration has the blank (zero) tile in upper left Use the arrows key to swap this tile with its neighbors """ import poc_fifteen_gui class Puzzle: """ Class representation for the Fifteen puzzle """ def __init__(self,...
0769d3cd2170d8af918a5bc9dc48275d1b413dcd
agarwalsanket/TheBalancePuzzle
/balances.py
10,401
3.875
4
import turtle import os __author__ = "Sanket Agarwal" """ This program is the implementation of the problem stated in HW7. Authors: Sanket Agarwal (sa3250@rit.edu) """ class Beam: """ Beam class contains data about a beam. """ __slots__ = 'beam', 'beam_name_objects', 'beam_draw' def __init__(sel...
8b0d30bada286585d934528aa1d91e7ae299d325
ankerfeng/deerhack
/Email.py
1,590
3.6875
4
#!/usr/bin/env python # coding=utf-8 ''' Created on 2014年12月6日 @author: bkwy.org ''' import re import urllib2 from urllib import urlopen def GetUrl(): urls = [] for i in xrange(65, 91): urls.append("http://homepage.hit.edu.cn/names/"+chr(i)) #print "http://homepage.hit.edu.cn/names/"+ch...
deebe833189905aea943ae22ca59f094e90d23fa
MarianoSaez/regexes-ayg
/8_cp.py
266
3.953125
4
#!/usr/bin/python3 import re regex = re.compile(r"([A-Z]{1}[\d]{4}[A-Z]{3}|[\d]{4})$") while True: cp = input("\ncodigo postal: ") if regex.match(cp): print("Codigo postal Existe") break print('El codigo postal es invalido')
ae9d362359010cc619dfd499f1a37532babf4872
kammitama5/Python6_11_16
/first.py
1,036
4.0625
4
##Welcome message --> game begin print 'Welcome to my game. This game is sweet.' ##ask the player for his name player_name = raw_input('What\'s is your name: ') ## check/ask for player name and display it if player_name == '': print'\n' print 'You entered an empty string!' else: print 'Your name is {}'.format(pl...
2c006793172e757d2005b5f427e3e2966a7ae631
ram5550/Luminardjango
/Luminarproject/flowcontrols/assignment2.py
462
3.984375
4
#Date of birth bdate=int(input("enter your birth date")) bmonth=int(input("enter your birth month")) byear=int(input("enter your birth year")) curdate=int(input("enter current date")) curmonth=int(input("enter current month ")) curyear=int(input("enter current year")) #bday 26-08-2019 #cday 24-07-2020 age=curyea...
d28e684eda7a19d86b951b041ba09ccadaa80aec
agiri801/python_key_notes
/_sample_/File_01.py
645
3.515625
4
# Program extracting all columns # name in Python """import xlrd loc = ('Data') wb = xlrd.open_workbook(loc) sheet = wb.sheet_by_index(0) # For row 0 and column 0 sheet.cell_value(0, 0) for i in range(sheet.ncols): print(sheet.cell_value(0, i)) """ import datetime timestamp = datetime.datetime.fromtimestamp(...
2dbea96827e4f4bc64cc68bd7a9bd88cd3d4de8c
serputko/Recursive_algorythms_tasks
/1_to_n.py
116
3.765625
4
def recursion(n): if n == 1: return '1' return recursion(n-1) + ' ' + str(n) print(recursion(10))
38d4d5ad464eac11e010e0b07f8fb4e8df29bbc1
mylons/pypatterns
/idioms/examples.py
1,380
3.953125
4
__author__ = 'lyonsmr' #white space is everything ####4 spaces is standard indent. #don't mix spaces and tabs for indents #boolean values True and False a = True b = False if a == b: print "a == b" elif a != b: print "a != b" else: print "this shouldn't happen, but this is a common if, else if, and else ...
38bad9c130eb6d1537fbd1947e289b7561c6dfdb
hyuntaedo/Python_generalize
/practice/general_input.py
1,041
3.515625
4
import sys #print("python","java",file=sys.stdout) #출력 #print("python","java",file=sys.stderr) #error 처리 #scores = {"수학":0,"영어":50,"코딩":100} #for subject, score in scores.items(): # key, value를 쌍으로 튜플로 보내줌 # print(subject.ljust(8),str(score).rjust(4),sep=":") #ljust는 왼쪽정렬 #(8)은 8개의 공간을 만들고 난 다음에 정렬을 한다...
85b96d3983eb1391604fe96f454099584335ef5a
paulc1600/Python-Problem-Solving
/H15_PowerSum_hp.py
7,709
4.0625
4
#!/bin/python3 # ---------------------------------------------------------------------# # Source: HackerRank # Purpose: Find the number of ways that a given integer, X, can be # expressed as the sum of the Nth powers of unique, natural # numbers. # # For example, if X = 13 and N = 2, we...
962b94399e132c4c08efed9d256db34338e0417d
svikk92/examples
/Python/usefulmethods.py
1,194
4.1875
4
for num in range(5): print(num) for num in range(2, 5): print(num) for num in range(2, 10, 2): print(num) my_list = list(range(5, 15, 3)) print(my_list) # use of enumerate name = 'abcdef' for item in enumerate(name): print(item) for index, letter in enumerate(name): print(f"index = {index} ,...
13c5a6c03baa060d8a82d0a308aa55884021244f
yuexishuihan/yuexishuihan.github.io
/Python基础/re/re_05.py
111
3.703125
4
#数量词 import re a = 'python 1111java678php' r = re.findall('[a-z]{3,6}',a) #贪婪与非贪婪(?) print(r)
23dfc141078d9e383503b24673154a05da567c67
GustavoLeao2018/aula-algoritimos-estudos
/exercicio_4/Teste.py
332
3.671875
4
from Deque import Deque from random import randint deque = Deque(5) for i in range(5): deque.push_front(randint(0, 100)) print(deque) print(deque.peek_front()) print(deque.peek_back()) print("Final:") print(deque) print(deque.pop_back()) print(deque) print("Começo:") print(deque) print(deque.pop_first()) pr...
beec3f3ad0d379bc2cc0d21aca23f6c3156444d2
schedpy/schedpy
/schedpy/utils.py
7,699
3.953125
4
from calendar import monthrange from datetime import date, timedelta class ScheduleSelectionError(Exception): """Schedule selection exception""" pass def add_months(given_date, months, days): """Function to add months (positive or non-positive) to the date given. Parameters ========== giv...
6c2ff1b3e427324a6deffad96b0e2a9b3d51027f
wc83/catelogue
/find_nearest.py
232
3.53125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Apr 19 16:06:30 2018 @author: william """ def find_nearest(array,value): import numpy as np idx = (np.abs(array-value)).argmin() return (array[idx],idx)
9a2bd24d916f0636a5173bd7e8349cbde3c30202
APARNAS1998/luminardjango1
/object oriented/employee constructor.py
263
3.5625
4
class Employee: def __init__(self,name,ID,salary): self.name=name self.ID=ID self.salary=salary def printval(self): print(self.name,self.ID,self.salary) obj=Employee('aparna',2301,2340000) obj.printval()
c484f3eec58d9562c5a0bf3c6af13f454c4771ca
Tiberius24/Python_Training
/HTLCS - 9.22 Exercises.py
13,648
4.34375
4
# HTLCS 9.22 Exercises # My name: Don Trapp # Problem 1 # What is the result of each of the following: # print("Python"[1]) # print ('Strings are sequences of characters.'[5]) # print (len("wonderful")) # print("Mystery"[:4]) # print("p" in "Pineapple") # print('apple' in 'Pineapple') # print('pear' not i...
4202307f49374e35982f7de0b877fe8fb1d80a66
BobbyAD/Intro-Python-II
/src/item.py
383
3.546875
4
''' create item file let player hold list of items let room hold list of items player can pick up items out of current_room player can drop items in to current_room ''' class Item: def __init__(self, name, description): self.name = name self.description = description def _...
90b35ad573136177c266f7d71fef758e0927ac48
vubon/Python-core
/list example/sort_system.py
164
3.796875
4
letters = ["a","u","v","c","b","d","e","g","r","s","l","i","j","m","o","n","p","q","t","f","h","y","x","w","z","k"] lett = sorted(letters) print(" \n" .join(lett))
e25ee41952793b2e6602b26b1270f29ea5800b18
imsrv01/programs
/datastructure/heap.py
3,049
3.96875
4
class MaxHeap: def __init__(self,items=[]): self.heap=[0] for i in range(len(items)): self.heap.append(items[i]) self.__floatUp(len(self.heap)-1) # 2 - Place it at correct position - Float UP # a. get parent # b. Compare with parent, if greater than swap...
ff23ce33164845445b872590df3fc97832ed5c27
gabriellaec/desoft-analise-exercicios
/backup/user_069/ch34_2019_09_28_01_51_31_030903.py
180
3.765625
4
valor = float(input('Qual o valor do depósito? ')) juros = float(input('Qual a taxa de juros? ')) mes = [valor] i = 0 while 23 >= i: mes.append(mes[i - 1]*juros) print(mes)
42b94b64408fd2bf5fcaae4a87bb7558aff41f7d
jli124/leetcodeprac
/BFS/hw4/105ConstructBTfromPreorderandInorder.py
1,346
3.875
4
#105. Construct Binary Tree from Preorder and Inorder Traversal #Given preorder and inorder traversal of a tree, construct the binary tree. #------------------------------------------------------------------------------- # Approach #------------------------------------------------------------------------------- ...
3edaa447eb008b8344a8c1ebb7a83ad496e02558
jasonmahony/python
/guessing_game.py
421
4.1875
4
#!/usr/bin/python import random number = random.randint(1, 9) guess = None while (guess != number): guess = raw_input('Guess a number between 1 and 9 or "exit" to end the game: ') if guess == "exit": print "Ending the game..." break guess = int(guess) if guess > number: print ...
232b548d454aea36f3191c4464c25ffb8b01707f
mingmang17/Algorithm-Team-Notes
/정렬/chap06_p_176.py
695
3.6875
4
#계수정렬 : 데이터의 크기가 한정되어 있는 경우에만 사용이 가능하지만 매우 빠르게 동작한다. #모든 원소의 값이 0보다 크거나 같다고 가정 array = [7,5,9,0,3,1,6,2,9,1,4,8,0,5,2] # 모든 범위를 포함하는 리스트 선언(모든값은 0으로 초기화) count = [0] * (max(array) + 1) #0부터 시작하기 때문에 for i in range(len(array)): count[array[i]] += 1 # 각 데이터에 해당하는 인덱스의 값 증가 for i in range(len(count)): # 리스트...
34c47790102588d2563cb39ba022d95334acb51f
anurag9099/assignment
/keywordFilter.py
458
3.5625
4
import re import sys import pprint path = sys.argv[1] with open(path, 'r') as file: corpus = file.read().replace('\n', '') def filter_key(key, corpus): pattern = "[^.]*"+key+"[^.]*\." r = re.findall(pattern, corpus, re.IGNORECASE) return r key = str(input("Enter Filter Keywor...
95783d06a3f682ea893c0d7092936681e7ff51a6
knee-rel/Python-For-Everybody-Specialization
/Py4e_files/exercise_11.py
302
3.875
4
import re filename = input('Enter filename: ') try: open_file = open(filename) except: print('File not found:',filename) quit() num_sum = 0 for line in open_file: numbers = re.findall('[0-9]+', line) for number in numbers: num_sum = num_sum + int(number) print(num_sum)
c9b64530a48e28285c10220f72e98e6ed18cea79
galarzafrancisco/dhamma-scraper
/main.py
2,855
3.703125
4
# ======================================== # # Definitions # # ======================================== url = 'https://www.dhamma.org/en/schedules/schbhumi' lookup_location = 'Blackheath' lookup_dates = '27 Jan - 07 Feb' # test # lookup_dates = '09 Feb - 20 Feb' sleep_period = 60 # Time in seconds between pings # =...
57e819ab2e12efa4279216b6bdc8bc549052d56c
danielhrisca/daily_coding_problem
/challanges/problem_1.py
663
4.15625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Sep 26 20:46:03 2018 @author: daniel Given a list of numbers and a number k, return whether any two numbers from the list add up to k. For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17. Bonus: Can you do this in one pass? ...
ae201cc75c6afcc3b95326042a8a4d0df857929a
manicmaniac/Project_Euler
/python/Problem21.py
803
3.734375
4
# coding:utf-8 """ Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). If d(a) = b and d(b) = a, where a b, then a and b are an amicable pair and each of a and b are called amicable numbers. For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44...
05dbf53a183af06dbe2ff284264ebdd1efe45bb0
group9BSE1/BSE-2021
/src/Chapter 8/Exercise 5.py
325
4.28125
4
# prompts the user to enter to file path and the executes it text = input("Enter the file name: ") file = open(text) count = 0 for line in file: words = line.split() if len(words) < 3: continue if words[0] != "From": continue print(words[2]) count = count + 1 print(f"there were {coun...
7f63ba01a106de323fb850b7c3c65b3454da49bc
nykkkk/hello-world
/BFS.py
1,958
3.734375
4
class Graph: #图 def __init__(self): self.adj = {} def add_edge(self, u, v): #临接结点 if self.adj[u] is None: self.adj[u] = [] self.adj[u].append(v) class BFSResult: #宽度优先结果 def __init__(self): self.level = {} #存储各层结点 self.parent = {} #父节点 def b...
135ba190c8dbf769aea5f9260b43cab152750f58
shubh3794/DS-ADA
/Trees and LL/LLoper.py
5,105
4.03125
4
import sys from BaseClass import Node from random import randint class LinkedList: def __init__(self): self.head = None self.tail = None def insertBeg(self,data): temp = Node(data) temp.next = self.head self.head = temp if self.head.next == None: self...
b50ac2af82d585feb9759e3a1bda535521ee143a
95subodh/Leetcode
/191. Number of 1 Bits.py
289
3.78125
4
#Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight). class Solution(object): def hammingWeight(self, n): """ :type n: int :rtype: int """ ans=0 while n>0: if n&1: ans+=1 n/=2 return ans
09e1f78a0ef9a95712783c2ba73474818b2ceeef
ihf-code/python
/session_04/answers/B8.py
224
4.3125
4
#B8 - Create a list of 5 numbers. Write a for loop which appends the # square of each number to the new list numbers = [2, 5, 8, 9, 10] sqr_numbers = [] for i in numbers: sqr_numbers.append(i ** 2) print(sqr_numbers)
7d9fe9b4ed53d3c8ddd6dbd3f3fb18fa3ce98038
drakotech/python_course
/show_notes/class_poly_func.py
619
3.5
4
# Building Polymorphic Functions in Python class Heading: def __init__(self, content): self.content = content def render(self): return f'<h1>{self.content}</h1>' class Div: def __init__(self, content): self.content = content def render(self): return f'<div>{self.content}</div>' div_...
4206b232f0a2dbfa2fa4eb3b05c11fcef085fe69
zhanghongwei125828/python_data
/day1/6-作业.py
2,089
3.890625
4
# day1-作业 ################################################################################ # 1--使用while循环输出1 2 3 4 5 6 7 8 9 10 ''' num = 1 while num <= 10: print(num) num += 1 ''' ################################################################################ # 2--使用while循环输出1 2 3 4 5 6 7 8 9 10 等于7的时候是一个空...
f715c268bffb5cf9189fff334b398feb7bfb876f
GuilhermeRamous/python-exercises
/funcao_pura.py
171
3.515625
4
def double_stuff(lista): lista_nova = [] for i in lista: lista_nova.append(i * 2) return lista_nova lista = [1, 2, 3, 4] print(double_stuff(lista))
c59915516fa461fcfaab1c9272fea0c045e50076
ARASKES/Python-practice-2
/Practice2 tasks/Lesson_15/Task_15_4.py
1,198
3.921875
4
def most_frequent(numbers): most_frequent_element = 0 max_count = 0 for element in numbers: count = 0 for el in numbers: if el == element: count += 1 if count > max_count: max_count = count most_frequent_element = element retur...
8f03736163dbbb76168a24c37162746cbc212704
tadejpetric/math_stuff
/zeroes.py
3,361
3.90625
4
import math def is_prime(num): for i in range(2, math.ceil(math.sqrt(num))): if not num % i: return False return True def field_in(): field = int(input("input the size of field Z: ")) if not is_prime(field): print("this is not a field") return field def polynomial_i...
da90feaed2277bb219798133d9b5aba221d22ddb
jaykhedekar7/D-A-in-python
/linearsort.py
236
4
4
def linearSort(arr, target): length = len(arr) for value in range(length): if arr[value] == target: print("Value found in position: ", value) else: print("Not found")
bdecc90ac4a9682b4fb0ea3980e1d067dcb595e0
cryanperkins/PublicCode
/phonebook.py
1,560
4.1875
4
__author__ = 'Ryan Perkins' phonebook = {} #The intro asks the user who he is looking for and then directs the user to the next function. def intro(): search = raw_input('Who are you looking for?') return check_dict(search) #This function checks to see if the person requested is in the phonebook and if he is...
cfdd54fd36b0d87ebe645c3d767685d84639b12b
r-harini/Code
/Machine_Learning/Regression/Simple_Linear_Regression/template.py
698
3.796875
4
import numpy as np import matplotlib.pyplot as plt import pandas as pd #Importing dataset dataset=pd.read_csv('Salary_Data.csv') X=dataset.iloc[:, :-1].values y=dataset.iloc[:,1].values #Splitting dataset into train and test set from sklearn.model_selection import train_test_split X_train, X_test, y_train,y_test= tra...
c1fe5e1f46a552c6053ea8d5cc774e06f0b3c03b
laughtLOOL/grok-learning-answers
/introduction to programming 2 (python)/1/Up the lift.py
273
3.78125
4
cur_floor = input('Current floor: ') des_floor = input('Destination floor: ') floor_change = int(des_floor) - int(cur_floor) cur_floor = int(cur_floor) for i in range(floor_change): print('Level ' + str(cur_floor)) cur_floor += 1 print('Level ' + str(des_floor))
7a7ce19b1fa99d063e68220dac7482cdab518d4b
athulkumarr/Sudoku-Solver
/sudokuSolver.py
1,857
3.5625
4
def solve_sudoku(self, board: List[List[str]]) -> None: def get_block(i, j): return 3*(i//3)+j//3 def next_empty_cell(i,j): j += 1 if j == 9: j = 0 i += 1 if i == 9: return None if board[i][j] != '.': return next_empty_cell(i, j) ...
d9f05e4040dec49497885e3cab62487e4f92323c
spfantasy/LeetCode
/260_Single_Number_III/260.py
755
3.578125
4
class Solution(object): def singleNumber(self, nums): """ :type nums: List[int] :rtype: List[int] """ total = 0 # get xor of two single numbers for num in nums: total ^= num # get the last digit with '1' # which is the last digit that ...
e25180d7569fc970f36617ccb97a7fd8ff32f904
Justinandjohnson/Python
/Hack.py
449
3.609375
4
import hashlib import re import fileinput n = input('Enter Filename: '); f = open(n, 'r') for line in f: p = line.strip() if len(p) < 6: print(p + " not valid") continue h = hashlib.sha1(p).hexdigest()[6:] passwords = open('combo_not.txt', 'r') found = False for password in passwords: if...
2f901ba4252e6ab908775c76878a5cbd34363856
ElshadaiK/Competitive-Programming
/merge_two_sorted_linked_lists.py
956
3.9375
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def mergeTwoLists(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]: res = ListNode() ptr = res x =...