blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
8ec16f85a9d50dd2e38f76ba3316d2191e8e8efd
EastTown2000/ITGK
/Øvinger/Øving 3/Alternerendesum_a.py
328
3.53125
4
def altnum(n): """ gir en liste(int) av funksjonen i oppgaven """ a = [] for i in range(1, n + 1): if i%2 == 0: s = - i**2 else: s = i**2 a.append(s) return a a = int(input('Hvilket tall i tall-serien vil du ha summen av: ')) print(sum(alt...
d0b440603d159f4791f9965325e71827b18e55da
ibarchakov/Stepik---Algorithms.-Methods
/heapq first try.py
777
3.9375
4
"""The first line contains the number of operations 1≤n≤10**5. Each of next n lines specifies the operations one of the next types: Insert x, where 0≤x≤10**9 — integer; ExtractMax. The first operation adds x to a heap, the second — extracts the maximum number and outputs it. Sample Input: 6 Insert 200 Insert ...
8ffb8acf399b2dc836c6b390072eece66c1e51c4
MDRCS/pyregex
/re-basics.py
2,048
3.921875
4
import re """ Bytecode is an intermediary language. It's the output generated by languages, which will be later interpreted by an interpreter. The Java bytecode that is interpreted by JVM is probably the best known example. """ # RegexObject: It is also known as Pattern Object. It represents a compiled re...
a588eb9088de56096f90119b4193087ce7ee6a58
setsunaNANA/pythonhomework
/__init__.py
663
4.1875
4
import turtle def tree(n,degree): # 设置出递归条件 if n<=1and degree<=10: return #首先让画笔向当前指向方向画n的距离 turtle.forward(n) # 画笔向左转20度 turtle.right(degree) #进入递归 把画n的距离缩短一半 同时再缩小转向角度 tree(n/2, degree/1.3) # 出上层递归 转两倍角度把“头”转正 turtle.left(2*degree) # 对左边做相同操作 tree(n / 2, degree / ...
a91bad82a5c65180440b412be2b3d9e6b9c661e0
kshm2483/ssafy_TIL
/Algori/AD/B/B6_marble1.py
261
3.578125
4
def DFS(n, k): if n == k: for i in range(N): print(marble[i]*(i+1), end=' ') print() return else: marble[k] = 1 DFS(n, k+1) marble[k] = 0 DFS(n, k+1) N = 3 marble = [1, 2, 3] DFS(3, 0)
f01c35ee2dad4a6e1908364f0133a90d00c8182e
ashish-mj/Data_Science
/Pandas.py
4,504
3.546875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Mar 24 12:11:42 2021 @author: ashish """ import pandas as pd ########################################################Series a=["a","B","c","D","e"] print(pd.Series()) print(pd.Series(a)) x=pd.Series(a,index=[100,101,102,103,104]) print(x) data={'a':2...
850c9b5747a330256c90c047f0ef1f601b14af8c
sjs521/BIS-397-497-SomanSebastian
/assignment 3/assignment 3 - exercise 5.15.py
998
3.53125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jun 8 17:08:03 2020 @author: sebastian_soman """ from operator import itemgetter invoice_tuples = [(83, 'Electric sander', 7, 57.98), (24, 'Power saw', 18, 99.99), (7, 'Sledge Hammer', 11, 21.50), ...
0cec6e966c788756c9abdc7c6381bbc2fc22c475
sjs521/BIS-397-497-SomanSebastian
/assignment 4/assignment 4 - exercise 7.3.py
278
3.75
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jun 15 18:52:19 2020 @author: sebastian_soman """ import numpy as np numbers = np.arange(2,19,2).reshape(3,3) numbers numbers2 = np.arange(9,0,-1).reshape(3,3) numbers2 product = numbers * numbers2 product
b4cea7cbeda845b7df310f85ecc1fee04284404e
belledon/hdf5_dataset
/h5data/hdf5.py
3,007
3.640625
4
""" HDF5 Creator. This script converts an arbitrary directory to an hdf5 file. Classes: Folder File """ import os import h5py import argparse import numpy as np class Folder: """Group analog of hdf5 structure. Represents a directory as a hdf5 group. The source directory's name is the name of...
2250c751a45b78eff1e2807b30f681161bb5f245
claudiama09/python_learning_note
/turtle/main.py
945
3.953125
4
from turtle import Turtle, Screen my_turtle = Turtle() screen = Screen() # W = Forward # S = Backward # A = Counter-Clockwise # D = Clockwise # C = Clear Drawing #--------------------------------------------------- # def move_forward(): # my_turtle.forward(10) # # def move_backward(): # my_turtle.backward(1...
e91613869c1751c8bb3a0a0abaeb1dfb9cafa5c3
MingCai06/leetcode
/7-ReverseInterger.py
1,118
4.21875
4
""" Given a 32-bit signed integer, reverse digits of an integer. Example 1: Input: 123 Output: 321 Example 2: Input: -123 Output: -321 Example 3: Input: 120 Output: 21 Note: Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the pu...
169aab304dfd600a169822c65e448b7e4a4abeb3
simgroenewald/Variables
/Details.py
341
4.21875
4
# Compulsory Task 2 name = input("Enter your name:") age = input ("Enter your age:") house_number = input ("Enter the number of your house:") street_name = input("Enter the name of the street:") print("This is " + name + " he/she is " + age + " years old and lives at house number " + house_number + " on " + stree...
56cd6db7536a1d79bed71596980631462d0c6c64
destinyc/leet-code
/leetcode/数字在排序数组中出现次数.py
1,509
3.671875
4
def findFristIndex(List, num): #这个函数用二分查找来找这个数的起始索引 if len(List) == 0: return 0 begin, end = 0, len(List) - 1 while begin <= end: mid = (end + begin) // 2 if List[mid] < num: begin = mid + 1 elif List[mid] > num: end = mid - 1 el...
9b0e0cd3ca37622fb85d312dd7e5e2efe12023de
destinyc/leet-code
/leetcode/螺旋矩阵.py
1,368
3.828125
4
def _bianli(List, rows, columns, index): #这个函数根据index位置遍历这一圈 #正向先走第一行 output = [] for i in range(index, columns - index): output.append(List[index][i]) #当前要遍历的一圈大于等于两行时才有向下的遍历 if rows - index - 1 > index: for i in range(index + 1, rows - index): output.append(List[i]...
ce72f53c88a6b57659b77c4cf2dee1bff7378c70
destinyc/leet-code
/leetcode/最接近的三数之和.py
902
3.828125
4
#列表中最接近target的三个数之和,跟三数之和一个意思 def threeSumClosest(nums, target): nums.sort() output = nums[0]+nums[1]+nums[2] min_diff = abs(target - (nums[0] + nums[1] + nums[2])) for i in range(len(nums)): left, right = i + 1, len(nums) - 1 while left < right: diff = abs(target - (nums[...
4b38ad8416a5cdf3fb3820065674c94ce6307970
destinyc/leet-code
/leetcode/二叉树所有左叶节点之和.py
355
3.640625
4
#看到二叉树就先思考一下递归 def _sum(root): if root is None: return 0 if root.left and root.left.left is None and root.left.right is None: return root.left.val + _sum(root.right) #是左叶节点,就把它的值加上右子树的左叶节点 else: return _sum(root.left) + _sum(root.right)
52723de95d7497fe45003144be92b5971c325fa9
destinyc/leet-code
/leetcode/最长回文子串.py
468
3.859375
4
#暴力查找法:容易超出时间限制 def search(S): if S == S[::-1]: return S output = '' for left in range(len(S)): for right in range(left, len(S)): if S[left : right + 1] == S[left : right + 1][::-1] and len(S[left : right + 1]) > len(output): output = S[left : right + 1] re...
46b52ac9272886aabbe1a85c239d0ae342e8c7f9
destinyc/leet-code
/leetcode/第n个丑数.py
1,799
3.890625
4
#先写一个简单的问题,判断一个数是否是丑数(只包含因子2,3,5)leetcode263 def isuglynum(num): if num == 1: return True if num == 0: return False while num % 2 == 0: num = num // 2 while num % 3 == 0: num = num // 3 while num % 5 == 0: num = num // 5 if num == 1: return T...
8de43bac6026bbb9158f1066f2d201695b9ee3e4
destinyc/leet-code
/leetcode/两数之和三数之和.py
3,749
3.5
4
#两数之和,返回两个数的索引,使用字典做 def find(List, add): if List == []: return None dic = {} for index, num in enumerate(List): diff = add - num if diff in dic: return [dic[diff], index] dic[num] = index #三数之和 def _find(List, add): #注意数组中可以存在重复元素 List.sort() ...
41569ee202a6d5a68ce4d2f217a76e762a9c821b
spd94/Marvellous_Infosystem_Python_ML_Assignments
/Marvellous_Infosystem_Assignment_1/Assingment1_2.py
157
3.84375
4
def ChkNum(n): if(n%2==0):print("Output : Even number",end=" ") else:print("Output : Odd number",end=" ") print("Input:",end=" ") x=int(input()) ChkNum(x)
e2e9e0822f868d43f96f7adb3e5c885159db227b
spd94/Marvellous_Infosystem_Python_ML_Assignments
/Marvellous_Infosystem_Assignment_4/Assignment4_5.py
664
3.5625
4
from functools import reduce import math def ChkPrime(n): c=0 for i in range(2,int(math.sqrt(n))+1): if(n%i==0):c=1 if(c==0):return(n) def max_list(n,y): if(n>y):return(n) else: return(y) def accept_N_elem(n): ls=list() i=0 sum=0 print("Input Elements :",end=" ") while(i<n): ls.append(int(input())) ...
d5b42355b1136deef409b9bd892ed04d7daebd8b
spd94/Marvellous_Infosystem_Python_ML_Assignments
/Marvellous_Infosystem_Assignment_3/Assignment3_3.py
331
3.515625
4
def accept_N_min(n): ls=list() i=0 print("Input Elements :",end=" ") while(i<n): ls.append(int(input())) i+=1 i=0 sum=ls[0] while(i<n): if(sum>ls[i]):sum=ls[i] i+=1 return(sum) if __name__ == "__main__": print("Input : Number of Elements :",end=" ") x=accept_N_min(int(input())) print("Output :"...
20f4e8a0618bd5f9a0a9beeb9b7851d0af09dcdc
spd94/Marvellous_Infosystem_Python_ML_Assignments
/Marvellous_Infosystem_Assignment_2/Assingment2_7.py
197
3.6875
4
def print_pattern(n): i=0 print("Output :") while(i<n): j=0 k=1 while(j<n): print(k,end=" ") k+=1 j+=1 print("") i+=1 print("Input :",end=" ") x=int(input()) print_pattern(x)
cede3101dcebb7ca00c09dbf06c620664e444bc6
farzaa/AlmostUnlimited
/FileController.py
2,177
3.6875
4
import json import os class FileController: links = {} def __init__(self): self.filename = 'links.json' FileController.links = FileController.links def process_json(self): """ Processes the json file as a python dictionary for O(1) lookup """ if os.path.isfi...
b9309e29726fbdd81593c7584f10bba6b3b39e8b
Herraiz/eoi
/12-testing/learning_python.py
1,243
3.890625
4
import unittest def suma(a, b): return a + b def resta(a, b): return a - b def check_equality(a, b): if a != b: raise Exception (str(a) + ' is not equal to ' + str(b)) print('Check equality') def multiplicacion(a, b): return a * b def division(a, b): if b == 0: raise Arit...
dcbe358f8337658a190aa6ec199638eebd75178f
PohSayKeong/python
/practical4/q5_count_letter.py
156
3.625
4
def count_letter(str,ch): if len(str) == 0: return 0 return (str[0] == ch) + count_letter(str[1:],ch) print (count_letter("Welcome", 'e'))
af36097ff4c7e7b24a376723a19a37ad652b32b6
PohSayKeong/python
/practical3/q7_convert_ms.py
314
3.859375
4
import math n = int(input("please enter time in ms: ")) def convert_ms(n): second = math.floor(n/1000) second_final = second % 60 minutes = second // 60 minutes_final = minutes % 60 hour = minutes // 60 print(str(hour) + ":" + str(minutes_final) + ":" + str(second_final)) convert_ms(n)
79445ff503849570898444870ad4881f5c9b3216
PohSayKeong/python
/practical2/q11_find_gcd.py
259
3.921875
4
n1 = int(input("first integer: ")) n2 = int(input("second integer: ")) minimum = min(n1,n2) def gcf(minimum,n1,n2): if n1 % minimum == 0 and n2 % minimum == 0: return minimum else: return gcf(minimum-1,n1,n2) print(gcf(minimum,n1,n2))
5e8fe335b23c11406377182f99d4205c739b414f
oneNutW0nder/config-dns
/dnsconfig.py
5,540
3.90625
4
def readHeader(): """ This function reads the "header.conf" file which is where the dns options for the zone file :return: (string)the contents of the "header.conf" file """ with open("./header.conf", "r") as fd: header = fd.readlines() return header def backup(zoneFile, rever...
4e8834fd82ae0c6b78a0d134058afbdb11d2da95
MaxiFrank/calculator-2
/new_arithmetic.py
1,560
4.28125
4
"""Functions for common math operations.""" def add(ls): sum = 0 for num in ls: sum = sum + num return sum def subtract(ls): diff = 0 for num in ls: diff = num - diff return diff # def multiply(num1, num2): def multiply(ls): """Multiply the two inputs together.""" res...
cdfa4e30f49d0b3c920cad94865be8647920b54c
rashid32/python_nov_2017
/Rashid_Ashfaq/OOP/add.py
746
3.859375
4
class Vehicle(object): def __init__(self,wheels,capacity,make,model): self.wheels=wheels self.capacity=capacity self.make=make self.model=model self.mileage=0 def drive(self,miles): self.mileage+=miles return self def reserve(self,miles): self.mileage -=miles return self class Bike(Vehicle): def v...
691c4a41c38d1d260cfc11e7a5ca119ec1a74159
jerseymec/Orapy
/loop.py
155
4.15625
4
for i in range(1,22): if (i % 2 != 0): print(str(i) + " is Odd") elif (i % 2 == 0): print(str(i) + " is Even") print("\n")
5432f1d6e0171b8ff7ff86533e4bf32f6afceef7
jerseymec/Orapy
/DoorMat.py
921
3.65625
4
def draw_pattern(n,m): for i in range(0,n//2): for j in range(0,(m//2)- (i*3+1)): print("-", end="") for k in range(i*2 +1 ): print(".", end="") print("|" , end="") print(".", end="") for j in range(0,(m//2) - (i*3+1)): print("-...
5098723d0627372bda3626de4491fde1defaf3b7
beka1cfc/first_week
/dom.py
4,536
3.734375
4
#задача 1 #list: ordered, changeable, allow duplicates #tuple: ordered, allow duplicates #set: changeable #dict: ordered, changeable #задача 2 a = "HELLO I AM WRITING CODE" b = ("HELLO" , "I" , "AM" , "WRITING" , "CODE") print(sorted(b)) #задача 3 names = ["Beks" , "Zhenya" , "Dana" , "Alibek"] job = ["программис...
4c7f7cb569736ce96f619dba622cf735ac06215a
PMiskew/Python3_Turtle_Code
/TurtlePolygon.py
200
3.96875
4
import turtle import math bob = turtle.Turtle() n = 80 side = 3 angle = (180 * (n-2))/n print(angle) for i in range(0,n,1): bob.right(180 - angle) bob.forward(side) turtle.done()
be4af2cdcda36c58fc8be5211a4f09e31a26119c
ishtiaque06/problems_python
/printPascal.py
538
3.78125
4
""" >>> printPascal(5) """ def printPascal(n): if n == 0: return [] pascal = [[1]] for i in range(1, n): if i == 1: pascal.append([1, 1]) else: previous = pascal[-1] new = [0] * (len(previous)+1) new[0] = 1 new[-1] = 1 ...
6d95e49a3e9aad5a1f77b435e15ae00775377f78
shrekchan259/MyProjects
/Tic_Tac_Toe.py
4,931
4.0625
4
print('Welcome to Tic Tac Toe !') def replay(): return input('Would you like to play again? y/n : ').lower() while True: test_board = ['#',' ',' ',' ',' ',' ',' ',' ',' ',' '] print('Kindly note the following positions for your choice of input\n') print(' 1 '+'|'+' 2 '+'|'+' 3 ') prin...
2813d77e5130bafe428f16f0347b81786b4971b9
OskarSliwinskiPK/JS-Automat-MPK
/src/mpk_exceptions.py
931
3.625
4
class Error(Exception): """ Raise for an exception in this app """ pass class NotValidCoinValue(Error): """ When the value does not match the available ones. """ def __init__(self): super().__init__("The value is not available") class CoinAttributeError(Error): """ Only Coin object avail...
4d24eb2e43a3f1fc37132ab82470f0127b4535e1
kunata928/python_functions
/leetcode_solutions(1).py
1,194
3.75
4
import itertools import math def multiply1(num1, num2) -> str: res = str(int(num1) * int(num2)) return res def multiply2(num1: str, num2: str) -> str: if num1 == '0' or num2 == '0': return '0' num = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9} ...
e85d275232a800eb6961bced98ee841dd0fd7f5d
KevinTsaiCoding/LiveCoding
/Python/Tutorial/003_list-tuple.py
582
3.96875
4
# 有序可變動列表 List (列表意思類似 C語言的陣列) grades=[12,60,15,70,90] print(grades[0]) # 變更列表裡的值, 把 55 放到列表中第一個位置 grades[0]=55 print(grades[0]) grades[1:4]=[] """ 列表名稱[?:!]=[] 意思是把 列表中第?個位子 到第!個位子刪除 """ print(grades) # 有序不可動列表 Tuple (列表意思類似 C語言的陣列) data=(3,4,5) print(data) print('\n') # 換行 print(data[0:2]) """ data[0]=5 錯誤...
5e7b6a828549f431d40fa054c50450c24f6d6e79
madara-tribe/AlphaZero_TicTacToe
/LR-algorithms/Tic-Tac-Toe/mini_max_action.py
1,369
3.53125
4
import random # ミニマックス法で状態価値計算 def cal_value_by_mini_max(state): # 負けは状態価値-1 if state.is_lose(): return -1 # 引き分けは状態価値0 if state.is_draw(): return 0 # 合法手の状態価値の計算 best_score = -float('inf') for action in state.legal_actions(): score = -cal_value_by_mini_max(st...
df285e765e14c3e52ad754416131402c786dd4ed
brandle26/Learning
/Section 4 - Pandas/Lec 18 - Drop Entry/Drop_Entry.py
650
3.796875
4
import numpy as np from pandas import Series,DataFrame import pandas as pd ser1=Series(np.arange(3),index=['a','b','c']) print(ser1) print("="*50) #dropping an index print(ser1.drop("b")) print("="*50) #dropping on dataframe dframe1=DataFrame(np.arange(9).reshape((3,3)),index=["SF","LA","NY"],columns=["...
f2f72ff26c869436946fa208fd716396f67d2b69
brandle26/Learning
/Section 4 - Pandas/Lec 23- MIssing Data/missingData.py
1,412
3.609375
4
import numpy as np from pandas import Series,DataFrame import pandas as pd data=Series(["one","two",np.nan,"four"]) print(data) print("="*50) #chekcing if there is a null value in the serices print(data.isnull()) print("="*50) #dropping null value print(data.dropna()) print("="*50) #working with dat...
3264f6baf0939442a45689f1746d62d6be07eece
aacampb/inf1340_2015_asst2
/exercise2.py
2,014
4.5
4
#!/usr/bin/env python """ Assignment 2, Exercise 2, INF1340, Fall, 2015. DNA Sequencing This module converts performs substring matching for DNA sequencing """ __author__ = 'Aaron Campbell, Sebastien Dagenais-Maniatopoulos & Susan Sim' __email__ = "aaronl.campbell@mail.utoronto.ca, sebastien.maniatopoulos@mail.utoron...
9e588c6baf50932fa110c6f72645a6ae2c9274b8
jdpoints/python
/roll.py
3,164
3.53125
4
import sys import re from random import randint pattern = ( r"^(?:(?:\[([1-9][0-9]{1,2}|[2-9])" #match.group(1) 2-999 valid "/([1-9][0-9]{0,2})" #match.group(2) 1-999 valid "([\+\-])?\])" #match.group(3) + or - valid "|([1-9][0-9]{0,2}))?" #match.group(4) 1-999 valid "d([1-9][0-9]{1,2}|[2-9])"...
313f48aadc4c94d41ee421e57984c8489d3ee4d4
zerosai7/scenic_tourist_information_system
/test4.py
134
3.53125
4
import re string=input() result=re.search(re.compile('(.*?)/(.*)/(.*)'),string) print(result) print(result[1],result[2],result[3])
6a23fff85f3e17d471083c8b8ef6dcd64c75b329
LiuYyunHao/PythonDemo
/Person.py
691
3.734375
4
class Person: def __init__(self): self.__age = 20 # @property # def age(self): # return self.__age # # @age.setter # def age(self, value): # self.__age = value def get_age(self): return self.__age def set_age(self, value): ...
a4796c4173346b3045f83184127312e5083e4b42
ngxson/edu-insa-3a
/python/ex34.py
1,363
3.59375
4
print(set('totto')) # erreur car set([iterable]) # on doit écrire set(('totto')) print({'totto'}) # affiche {'totto'} print({{'toto'}, {'tata'}}) # TypeError: unhashable type: 'set' print('abcde'[-1]) # affiche 'e' print({'abcde'}[0][1]) # erreur car 'set' n'a pas de ordre print('abcdefg'[2:5]) # ...
af799dec3e9a457c8304ed8e9a178e15b31b1782
bboats/trabFormais
/src/menu.py
2,332
3.734375
4
#!Python3 import AutomataClasses from os import system, name ########################### ##### main menu class ##### ########################### class Menu: """text-based menu class, receives a list of options and a title as init arguments""" def __init__(self, options, title='|'): self.options = options self.ti...
052c75ab47504d71824eaf54d2333a6b71c5a3d3
Sekinat95/May-30-day-leetcode
/day9.py
308
3.8125
4
def isPerfectSquare(self, num: int): #using binary search if num<2: return True L,R=2,num while L<=R: mid=(L+R)//2 if mid**2 == num: return True elif mid**2 > num: R = mid-1 else: L = mid +1 return False
2e4390f52c1c87a8430e3ddd099c74ce74a67b0c
RiccardoTonini/algo_think_2014
/week1/project1.py
2,206
3.78125
4
""" This modules exposes 3 functions: make_complete_graph, compute_in_degrees, in_degree_distribution """ # Represents graph 1,2,3 as adjancency lists EX_GRAPH0 = {0: set([1, 2]), 1: set([]), 2: set([])} EX_GRAPH1 = {0: set([1, 4, 5]), 1: set([2, 6]), 2: set([3]), 3: set([0]), 4: set([1]), 5: set([2]), 6: set([])} ...
af0b765e91865a5b1ab26e54593e65af36066423
dongso/Python-Project
/day4.py
3,658
3.734375
4
i = 0 while True: print(i) i = i+1 if i == 100: break for i in range(10000): print(i) if i==100: break # **** # **** # **** for i in range(3): for j in range(4): print("*",end='') print("\n") # * # ** # *** # **** for i in range(1,5): for j in range(i): ...
b355ffb5f1e84b9f6ec449c9fc0c6319c6e54e21
dongso/Python-Project
/day4-prac.py
1,817
3.890625
4
#문제 1 print("문제 1번 ******************") for i in range(1,6): for j in range(0,i): print(" ",end='') print("*\n") #문제 2 print("문제 2번 ******************") for i in range(2,10) : print("%i단 시작 -->"%i) for j in range(1,10): print("%s * %s = %d"%(i,j,i*j)) #문제 3 print("문제 3번 ***************...
d2aa07f91a4fff951d42cb84bde47fe9ae61c0d9
dongso/Python-Project
/day6.py
6,627
3.640625
4
# #정규표현식 : 패턴(규칙)을 가진 문자열을 표현하는 방법 # #규칙이 있는 문자열을 추출, 변경 등의 작업을 수행하기 위해 작성 # #re module을 사용해서 정규표현식 작성. # #re.match('패턴','문자열')을 사용. # import re print(re.match('Hi', 'Hello, hi, world')) print(re.match('hi', 'hi, world')) #문자열의 첫번째부터 비교해서 있으면 span(0,n) return print('hello hi, world'.find('hi')) #문자열의 시작위치가 나옴 # #re.mat...
8dff4ae8dc22466b0feaa8abb4a1e421ea4401e8
sesch023/Python-Uebungen
/Übung (Übersetzer Schwierigkeit 4)/Lösung.py
479
4.0625
4
dictionary = { "Zug": "train", "Hochschule": "university", "Küche": "kitchen", "Tisch": "table", "Computer": "computer" } eingabe = input("Bitte geben sie ein Wort zum Übersetzen ein: ") while eingabe != "ende": if eingabe in dictionary: print(f"{eingabe} -> {dictionary[eingabe]}") ...
21b82a9809a13020bb6e3f6cec6dacb75bd638f1
sesch023/Python-Uebungen
/Übung (Vergleich Nutzereingaben Schwierigkeit 2)/Lösung.py
284
3.984375
4
x = float(input("Bitte geben Sie die erste Zahl an: ")) y = float(input("Bitte geben Sie die zweite Zahl an: ")) if x < y: print("Kleinere Zahl: " + str(x)) print("Größere Zahl: " + str(y)) else: print("Kleinere Zahl: " + str(y)) print("Größere Zahl: " + str(x))
23fc2ba6008d38ce8aec051f0400efe197442efb
klfoulk16/mazes
/util.py
13,133
3.78125
4
import random from PIL import Image """Contains the objects necessary to create and solve various mazes. Order from top to bottom: Cell, StackFrontier, Queuefrontier, Maze""" class Cell(): """Structure to keep track of various cells in the maze and which cell we used to get there""" def __init__(self, locatio...
1e4dfefa54c79312347a8f47d26993530358041a
graceke/TowerBlaster
/towerblaster.py
12,324
3.90625
4
import random turn_count = 0 def setup_bricks(): '''sets up the game main pile with 1-60 in a list and discareded empty then return them as a tuple''' main_bricks = list(range(1, 61)) discarded_bricks = [] return main_bricks, discarded_bricks def shuffle_bricks(bricks): '''shuffl...
a37130786c5c2843c24c631a50f50252f46d6038
wenima/codewars
/kyu4/Python/src/holdem.py
2,473
3.78125
4
"""Solution for https://www.codewars.com/kata/texas-holdem-poker/python.""" from collections import Counter, defaultdict from operator import itemgetter CARDS = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'] class PokerHand(object): def __init__(self, hand): self.values = sorted([CAR...
d01bb2f5979a27a5effb327f51e40ea9402906fa
wenima/codewars
/kyu4/Python/src/test_next_bigger.py
846
3.609375
4
"""Tests for codewars kata https://www.codewars.com/kata/next-bigger-number-with-the-same-digits.""" import pytest TEST_BIGGEST = [ (9, True), (111, True), (531, True), (123, False), (9998, True), (54321, True), ] TEST_INPUT = [ (999, -1), (12, 21), (513, 531), (2017, 2071), ...
ffd69ed1f0ce038a4e5856193af501b38e3df2db
wenima/codewars
/kyu3/src/sudoku_solver_hard.py
12,269
4.03125
4
"""Module to solve the code-kata https://www.codewars.com/kata/sudoku-solver.""" from math import sqrt, ceil from itertools import islice, chain, groupby from operator import itemgetter from collections import defaultdict def sudoku_solver(m): """Return a valid Sudoku for a given matrix. Store all startin...
e88fde32a4ed8daa66714905a4d258032ec9a473
wenima/codewars
/kyu5/python/src/best_travel.py
418
3.625
4
"""Module to solve the code-kata https://www.codewars.com/kata/best-travel/train/python.""" from itertools import combinations def choose_best_sum(t, k, ls): """Return a value closest to, but not great than, t out of a combination of elements in ls with size k. """ best = 0 for c in combinations(l...
9b5b28301d930fefb61ae250b93fe05e7fb34bd8
wenima/codewars
/kyu5/python/src/prime_factorization.py
954
4
4
"""Module to solve https://www.codewars.com/kata/prime-factorization.""" from collections import defaultdict class PrimeFactorizer(int): def __init__(self, n): """Initialize a Prime object.""" def prime_factors(self): """Return a list of prime factors for a given number in ascending order....
7c423e6b96739cfdfe456783f34bb3b1d95c7d07
wenima/codewars
/kyu5/python/src/domain_name.py
673
3.84375
4
"""Module to solve the code-kata https://www.codewars.com/kata/extract-the-domain-name-from-a-url-1/train/python. This is just a proof of concept/prototype. The correct solution covering all domain names as well as private domains is alot more complicated. It would involve getting the current viable top-level domains a...
e900d08e1f44c4ca6fa0a6a451bc9d379e346c1a
SwierkKlaudia/python
/basics/lists.py
11,112
3.734375
4
# 1 def L1(elements): sum_elem = 0 for list_elem in elements: sum_elem += list_elem return sum_elem print("L1:",L1([1, 4, 19])) # 2 def L2(elements): mult_elem = 1 for list_elem in elements: mult_elem *= list_elem return mult_elem print("L2:",L2([1, 4, 19])) # 3 def L3(el...
02bebd11b10ef4d17d530355ec86707b9057900e
ijazali5555/my-project
/loops.py
89
3.5625
4
for i in range (1, 10+1): print (i) print("Hello") for i in range (10): print(i)
dcfe8eb511f4b1a89852df183bb01fcd35d9d924
sxhmilyoyo/Algorithm_Python
/topologicalSort.py
1,325
3.53125
4
class DirectedgraphNode(): def __init__(self, x): self.label = x self.neighbors = [] class Solution(): def dfs(self, i, countrd, ans): ans.append(i) countrd[i] -= 1 for j in i.neighbors: countrd[j] = countrd[j] - 1 if countrd[j] == 0: ...
72c683ad118af4ccde4a1b82886052c2e1a06046
sxhmilyoyo/Algorithm_Python
/parseMathExprTree.py
2,143
3.671875
4
from Tree import * from Stack import * import operator def parseTree(expr): exprList = expr.split() r = Tree('') s = Stack() s.push(r) currentTree = r for i in exprList: if i == '(': currentTree.inserLeft('') s.push(currentTree) currentTree = current...
ee72d040abf29e921923c49602687d93fb4ae955
sxhmilyoyo/Algorithm_Python
/test.py
2,256
3.546875
4
def recMinCoin(availableCoins, money): # baseline: use the penny minNumber = money # subproblems # recMinCoin(money-i) if money in availableCoins: return 1 # choices else: for i in [c for c in availableCoins if c <= money]: # recursive number = rec...
3c6dc004885df3bd3ea923b825914c23d1a5e824
tomaswender/praktic2
/lesson3/task_7.py
1,005
3.796875
4
#7. В одномерном массиве целых чисел определить два наименьших элемента. # Они могут быть как равны между собой (оба являться минимальными), так и различаться. import random arr=[] arr2=[0,0,0] for i in range(30): arr.append(random.randint(0, 10)) for i in range(0, len(arr)): if arr[i]>0: arr2[0], a...
c7bcfb032cb28fd655e128c0438245b08d4b44b6
tomaswender/praktic2
/lesson3/task_1.py
412
3.6875
4
#1. В диапазоне натуральных чисел от 2 до 99 определить, сколько из них кратны каждому из чисел в диапазоне от 2 до 9. list1 = [] list2 = {2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0} for i in range(2, 100): list1.append(i) for n in list1: for i,y in list2.items(): if n%i==0: list2[i]=list2[i]+1 print(...
976fa3e3320c3f98d38e73de80a3ca7d37c3ae14
RinatZialtdinov/Codewars
/ex14/First_nonrepeating_character.py
371
3.640625
4
def first_non_repeating_letter(string): if len(string) == 0: return "" copy_s = list() for i in string.lower(): if i not in copy_s: copy_s.append(i) else: copy_s.remove(i) if len(copy_s) == 0: return "" if copy_s[0] in string: return co...
ad8fcd08ed6d77c4072cf02aa16394ba4d28ecd6
kaamayao/AlgorithmsUN2021I
/Lab13/2_primitive_calculator/primitive_calculator.py
899
3.515625
4
# Uses python3 import sys d = {} def fillCache(cache): for i in range(1, len(cache)): min_operation = cache[i-1] + 1 if i % 3 == 0: min_operation = min(cache[i // 3] + 1, min_operation) elif i % 2 == 0: min_operation = min(cache[i // 2] + 1, min_operation) ...
44909bca4f4dfb10a59c009503d9fca298f80155
Amoghk18/AI_1BM18CS014
/tic-tac-toe.py
5,859
3.640625
4
import random import time def printBoard(board): print() print("----------------------- Board ----------------------------") print() print() for i in range(3): print(" ", end="") for j in range(3): print(" " + str(board[i][j]) + " ", end=...
3c4eb1005c04b680331f97fcfb3f09e45b0b7c3d
beng0/my_python_leaning
/t01/practice.py
2,440
3.640625
4
#coding=utf-8 # num = 2 # if num%2 == 0: # print '{}是偶数'.format(num) # if num%2 == 1: # print '%d是奇数'%(num) # str = 'hello' # flag = False # list = ['apple','pear','helloo'] # for n in range(len(list)): # if list[n] == str: # print '有这个数了' # flag = True # break # if flag == False: ...
c710946ade385e713a64c29018a7d3e6c131d51b
metatoaster/IdleISS
/src/idleiss/battle.py
15,527
3.53125
4
from __future__ import division import random import math from collections import namedtuple from idleiss.ship import Ship from idleiss.ship import ShipAttributes from idleiss.ship import ShipLibrary SHIELD_BOUNCE_ZONE = 0.01 # max percentage damage to shield for bounce. HULL_DANGER_ZONE = 0.70 # percentage remain...
ea75860295faafad4a689deb8145f0c822b93910
ozhatuka/oz
/python_part2B.py
6,401
3.796875
4
import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib def find_most_frequent_year(df, n): ''' :param df: pd.Dataframe :param n: positive, integer; n'th most frequent year :return: int; the n'th most frequent year :raise: ValueError - if n is not a posi...
e13e24bf0755c4702df538be012150898740dc46
lakshmivisalij/dicesimulatorpython
/dice simulator.py
929
3.84375
4
import random print("Let's roll the dice!") i = 'y' while i == 'y': x = random.randint(1,6) if x==1: print(" ---------") print("| |") print("| O |") print("| |") print(" ---------") if x==2: print(" ---------") print("| |") print("| O O |") print("| ...
5fe747190880d0c7a78641be6b47217b1584a863
enginSacan/RobotFrameworkExample
/lib/Check_firmware_size.py
939
3.84375
4
"""This file is created for checking file size in a specific limit for file specified.""" import os FIRMWARE_MAX_LIMIT = 40000000 TARGET_PATH = "D:/DM/LSD/MSPS_ITEST/DAT/AutoDAT/" def file_size(target, file_name, threshold): """This function is checking file size under the target folder.""" THRESHOLD = 400*102...
77ebd8b2998277bbe8377055c10f429680bd833a
witalomonteiro/testes-automatizados
/tests/test_dominio.py
2,721
3.609375
4
from unittest import TestCase from src.leilao.dominio import Lance, Leilao, Usuario from src.leilao.excecoes import LanceInvalido class TestLeilao(TestCase): def setUp(self): self.leilao_teste = Leilao("Cavalo") self.witalo = Usuario("Witalo", 1000) self.witalo.propor_lance(self...
c82c07f64dcfb548733526cdb88a990074b57520
akshatasawhney/BFS-3
/Problem1.py
2,066
3.703125
4
""" // Time Complexity : o(n) // Space Complexity : o(n), queue // Did this code successfully run on Leetcode : yes // Any problem you faced while coding this : no // Your code here along with comments explaining your approach """ from collections import deque class Solution: def is_valid(self, s): #function to c...
70c4989fada0dd3800427c2da1038807d5abb88a
anhlh93/Techkids
/Season 4/Session4-Assignment 4.4.py
232
3.765625
4
from turtle import* color("blue") bgcolor("green") speed(-1) def square(length): for i in range(4): forward(length) left(90) number=20 length=100 for i in range(number): square(length) left(360/number)
67ec1c51f1bf73cf5f944ace9a89e95882e94250
kemoelamorim/python_URI
/exercicios_URI/URI_1013.py
667
3.890625
4
""" Faça um programa que leia três valores e apresente o maior dos três valores lidos seguido da mensagem “eh o maior”. Utilize a fórmula: maiorAB = (a + b + abs( a - b))/2 Obs.: a fórmula apenas calcula o maior entre os dois primeiros (a e b). Um segundo passo, portanto é necessário para chegar no resultado esperado...
9faf895647e7eb6f6a0fa1f00a4b38bb5bd7ffe9
sicou2-Archive/pcc
/python_work/part2/alien_invasion/alien_invasion/laser.py
1,088
3.75
4
import pygame from pygame.sprite import Sprite class Laser(Sprite): """A class to manage lasers fired from the ship.""" def __init__(self, ai_game): """Create a laser object at the ship's current position.""" super().__init__() self.screen = ai_game.screen self.settings = ai_...
10e9d887ece56205449d1c3412d614e91bc723ee
sicou2-Archive/pcc
/python_work/part1/ch05/c5_8.py
1,590
3.859375
4
usernames = ['admin', 'todd', 'betty', 'adam', 'scott', 'sally'] def looping(names): if names: for name in usernames: if name == 'admin': print("Welcome, keeper of the keys. The motor is still " "running!") else: print(f"Welcome u...
bb81d71014e5d45c46c1c34f10ee857f5763c75a
sicou2-Archive/pcc
/python_work/part1/ch03/c3_4.py
1,813
4.125
4
#Guest list dinner_list = ['Sam Scott', 'Tyler Jame', 'Abadn Skrettn', 'Sbadut Reks'] def invites(): print(f'You want food {dinner_list[0]}? Come get food!') print(f'Please honor me {dinner_list[1]}. Dine and talk!') print(f'Hunger gnaws at you {dinner_list[2]}. Allow me to correct that.') print(f'Poi...
f5e0dd2d5fa00bff0eeac7772b2fc041a1c6d2b1
sicou2-Archive/pcc
/python_work/part1/ch06/c6_1.py
4,170
4.3125
4
alice = {'first_name': 'alice', 'last_name': 'maple', 'city': 'springfield', 'age': 25, 'hair': 'brown',} for num in alice: print(alice[num]) #6_2 print("\nNEXT 6_2 and 6-10") numbers = {'todd': [3, 4, 6, 8,], 'sammy': [5, 7, 3, 8,], 'joe': [6,], 'kyle': [...
bc7185beb2e51477149df4606d5976d7bd8607bc
sicou2-Archive/pcc
/python_work/part2/alien_invasion/alien_invasion/diy/target_14_2.py
991
3.59375
4
import pygame class Target: """A class for the target in Target Practice.""" def __init__(self, ai_game): """Initialize target settings and position.""" self.screen = ai_game.screen self.settings = ai_game.settings self.color = self.settings.target_color self.screen_r...
f644021c93bb0affb75399edf463fcb554c56ddf
sicou2-Archive/pcc
/python_work/part1/ch11/city_functions.py
336
3.890625
4
"""A module for returning a 'City, Country' string.""" def a_city(city, country, population=None): """Generate a neatly formatted 'City, Country'""" if population: city_country = f"{city}, {country}, population: {population}" else: city_country = f"{city}, {country}" return city...
a4d7377ac20dd283f71b0101c05f6ed682a4e849
sicou2-Archive/pcc
/python_work/part1/ch05/amusement_park.py
622
3.890625
4
age = 12 if age < 4: print("Your admission cost is $0.") elif age < 18: print("Your admission cost is $25.") else: print("Your admission cost is $40.") #Better way to do this. print("Better\n") age = 12 if age < 4: price = 0 elif age < 18: price = 25 elif age < 65: pri...
a2ddf6304441dfd004e6d90802554d4dca90467a
ayymk/code-algo-dicho
/find_the_number.py
403
3.671875
4
from random import * x =randint(0,100) y=int(input("Trouve le nombre entre 0 et 100: ")) z=0 while y!=x and z<7: z=z+1 if y<=x: y=int(input("Le nombre recherché est plus grand, réessaye: ")) else: y=int(input("Le nombre recherché est plus petit, réessaye: ")) if x==y: print ("bravo c'est bien...
91d8233f7d92a9b1a60d8a8d4226b250cc4833df
dilynfullerton/vpython
/projectile.py
4,065
3.75
4
__author__ = 'Alpha' from visual import * # Simple program where projectile follows path determined by forces applied to it # Velocity is vector(number, number, number) # Force is vector(number, number, number) # Momentum is vector(number, number, number) # Mass is number # Position is vector(number, number, nu...
35d5bf06474999e2fdb2d06b16b2081abd52ca9d
Ashikur-ai/Starry-sky-with-python
/Game development 6.py
544
3.9375
4
import turtle as t import random as r # defining screen win = t.getscreen() win.bgcolor("black") # defining turtle rock = t.Turtle() rock.color("yellow") rock.speed(0) # get random cordinate for i in range(50): x = r.randint(-300, 300) y = r.randint(-300, 300) # Turtle up down and...
7d8db8c7e276d208bb4e6fa3b92539e76cb9ff71
anantkaushik/stein
/python/problems/array/reverse.py
262
3.96875
4
def reversed_arr(arr,count): if count==len(arr): return arr temp = arr[count] count += 1 reversed_arr(arr,count) arr[len(arr) - 1 - (count - 1)] = temp return arr arr = [22, 11, 20, 76, 123, 70] count=0 print ("Reversed array: ",reversed_arr(arr,count))
e38fec0a8e17078c5e29d5c2bbd6e1db604a1af7
alexandermfisher/cs50_artificial_intelligence
/01 - Knowledge/minesweeper/minesweeper.py
11,932
4.3125
4
import itertools import random class Minesweeper(): """ Minesweeper game representation """ def __init__(self, height=8, width=8, mines=8): # Set initial width, height, and number of mines self.height = height self.width = width self.mines = set() # Initializ...
d56a0b6bc5da1d2a3e7000ac10738c93caf7875a
diacarcor/day-3-5-exercise
/main.py
890
4.09375
4
# 🚨 Don't change the code below 👇 print("Welcome to the Love Calculator!") name1 = input("What is your name? \n") name2 = input("What is their name? \n") # 🚨 Don't change the code above 👆 #Write your code below this line 👇 #Combine both lower names names = name1.lower() + name2.lower() #Calculate digit one digit...
a30f252bdb52d336ef70f5d1e7f7deaf388568a3
bmasse/Dev
/Python/L_Intro_A_Python/code/chap5/pipoem.py
1,424
3.703125
4
#!/usr/local/bin/python # Contribution to the forever lasting discussion on indentation! # After Petrarca, Shakespeare, Milton, Drs. P and many, many others, # a sonnet has 14 lines and a certain rhyme scheme. # Jacques Bens presented in 1965 in Paris the pi-sonnet with # 3,1,4,1 and 5 lines, but the ultimate pi-poem...
25dbf9ad6efbef56ef718b4c0c8095b38cc4e933
TroyCode/Super-Blinder
/app/stastics.py
1,158
3.609375
4
import time class Words: def __init__(self): self.count_list = [] def add_list(self, word_array, time): for word in word_array: is_inside = False for item in self.count_list: if word in item["Name"]: is_inside = True item["Count"] = item["Count"] + 1 item[...
b7df9f711fba030043cb701c961918d9ff2d51f2
diegoasanch/Project-Euler
/16 - Power Digit sum.py
115
3.765625
4
def digit_sum(number): digits = [int(x) for x in str(number)] return sum(digits) print(digit_sum(2**1000))
e6873cf3124c7d86f97c7a744f6e6da908a908c4
sun1218/MyTest
/fab_test.py
676
3.515625
4
class Fab(object): def __init__(self, max): self.max = max self.n, self.a, self.b = 0, 0, 1 def __next__(self): if self.n < self.max: r = self.b self.a, self.b = self.b, self.a + self.b self.n += 1 return r raise StopIteration() ...