blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
e26a6b664f9cce631d9f248f321fa5ab35b0366b
TomasWang28/python-2018
/python本机查找文件/找文件效率慢版.py
396
3.9375
4
import os def search(filename, filepath): for d in os.listdir(filepath): path=os.path.join(filepath,d) if os.path.isdir(path): search(filename,path) if os.path.isfile(path): if d.find(filename)!=-1: print(path) filename=input('请输入查询文件名:') filepath=in...
510af4dbc489e2b510eca33a0046dd748b4bd532
rafaelscnunes/hackerrank
/11_ThePrimeGame/test_theprimegame.py
2,588
3.5625
4
""" Created on 13/nov/2019 with PyCharm INPI - Instituto Nacional da Propriedade Industrial @author: Rafael Nunes - rafael.nunes@inpi.gov.br @title: hackerrank - test_theprimegame.py -------------------------------------------------------------------------------- *** Description of the module function *** -----...
b94424fc2d8f781ce1d1723b42aeb39a0318e1e1
kjmjr/Python
/Chapter10/Book.py
611
4.21875
4
''' Defining a book class Kevin McAdoo 4-18-2018 ''' class Book: ''' Defining a book class that has the book's title, author's name, publisher's name''' def __init__(self, title,author,publisher): self.title = title self.author = author self.publisher = pub...
500576a7665085d3862be609af7e2538596d0c78
DarekRepos/PanTadeuszWordFinder
/ptwordfinder/commands/PTWordFinder.py
1,895
3.90625
4
import time import click import re @click.command() @click.argument('words_input_file', type=click.File('r')) @click.argument('searched_file', type=click.File('r')) def calculate_words(words_input_file, searched_file): """ count specific word in "Pan Tadeusz" poem """ # Open the list of words # for which...
e915252f00fca2263ec2267101aecc078b6f3e49
Daria126/Game1
/hw_12.py
6,324
3.734375
4
from abc import ABC, abstractmethod import random class Unit(ABC): _name = None _strength = 0 _health = 0 _defence = 0 _defence_coeff = 0 _double_attack = 0 def _check_name(self, name): if isinstance(name, str) and len(name) <= 15: return name def __...
72e0623db0bef058240f606091131fb15b41041d
pysrc/fractal
/fractal/lsystem.py
3,253
4.21875
4
""" L-System for fractal 已完成功能: 1.简单D0L-系统 2.合成D0L-系统 3.简单分叉结构 待完成功能: 1.带年龄树(分叉)的生成 2.随机L-系统 3.参数L-系统 """ from math import sin, cos, pi import pygame from .base import Base def left(screen, st, angle, d): # st: 起点坐标 # angle: 向左偏转的度数 # d: 距离 ...
4f78059fe849d160bf7345c986865faed04864d3
Kajy/ProjectEuler
/Euler_015.py
529
3.625
4
import math def searchPath(size): paths = [[0 for x in range(size)] for y in range(size)] for x in range(size): for y in range(size): if x == 0 or y == 0: paths[x][y] = 1 else: paths[x][y] = paths[x - 1][y] + paths[x][y - 1] return paths de...
3fee06381349e25f5a9d42fc02ef7ceb93d3924b
SoundaryaJagan/Soundhu
/pro.py
153
3.59375
4
def main(): n=int(input()) l=[] for i in range(n): l.append(int(input())) l.sort(reverse=True) for i in l: print(i) try: main() except: print('invalid')
08b814d21d66522f0521943f3c3e3183405bb629
Iansdfg/9chap
/6DFS/18. Subsets II.py
1,433
3.765625
4
class Solution: """ @param nums: A set of numbers. @return: A list of lists. All valid subsets. we will sort your return value in output """ def subsets_with_dup(self, nums): # write your code here nums.sort() subsets = [] self.dfs(nums, 0, [], subsets) ...
2a78734831305e5a470ffee6b5c4bfafb0899ee8
824zzy/Leetcode
/G_BinarySearch/L1_367_Valid_Perfect_Square.py
446
3.53125
4
# Straight forward solution class Solution: def isPerfectSquare(self, num: int) -> bool: i = 1 while i**2<num: if i**2!=num: i += 1 return i**2==num class Solution: def isPerfectSquare(self, num: int) -> bool: l, r = 0, num while l<=r: m = (l+r)/...
92cd94e3aef0d16c83943c3790a9a92ad21b38b3
TopRamenb0ss/Python-Battleship
/Batlship.py
1,155
4.03125
4
from random import randint board = [] for x in range(5): board.append(["O"] * 5) def print_board(board): for row in board: print " ".join(row) print "Battleship, b0ss" print_board(board) def random_row(board): return randint(0, len(board) - 1) def random_col(board): return randint(0, len(b...
4ac31973e4eac2a952f5939ba848fffb9d966dbe
aleenaadnan15/Class-work
/library.py
706
4.0625
4
#Question num 3: ''' MY LIBRARY ''' bookType = input("Are you looking for a fiction (type F) or a non-fiction book (type NF)?") bookGenre = '' if bookType =="F": bookGenre = int(input("What genre are you looking for: comedy (1), graphic novel (2), science fiction (3), fantasy (4), historial fiction (5)?")) ...
8de7f1b70c332266631805c6f4c37dc457e04cd4
guzhoudiaoke/data_structure_and_algorithms
/coding_interview_guide/2_link_list/5_reverse_partial_linklist/reverse_partial_linklist.py
2,010
3.6875
4
class Node(): def __init__(self, val): self.val = val self.next = None # reverse [from_idnex, to_index] def reverse_partial_list(head, from_index, to_index): # check head if not head: return head # check from_index if from_index < 1 or from_index >= to_index: retur...
12062f9be08a9ffb8c0bb3e6286b3427cad04d88
ColinWan/Algorithm_Practice
/Week 2/Sorts.py
2,205
3.96875
4
import datetime import random def selection_sort(L): L=L.copy() for i in range(len(L)): min_index = L.index(min(L[i:])) L[i], L[min_index] = L[min_index], L[i] return L def insertion_sort(L, h=1): L=L.copy() for i in range(len(L)): j = i while j>=h and L[j]<L[j-h]: ...
68a3765e7a1438f8b9e0223befb898023e3b5e7b
SamuelNunesDev/starting-point-in-python
/venv/Scripts/ex058.py
407
3.71875
4
from random import choice l = list(range(0, 11)) pc = choice(l) p = 0 while True: p1 = int(input('Tente advinhar o número que estou pensando: ')) p += 1 if p1 == pc: print(f'PARABÉNS! Eu estava pensando no número {pc} mesmo! \nVocê precisou de {p} palpites para acertar!') break elif pc ...
984b531f15cd23c2bbed880f116fcfaee1aec13b
JimothyGreene/EE461L-Group2-FinalProject
/server/api/routes/validators/users.py
2,622
3.90625
4
from email_validator import validate_email, EmailNotValidError def check_email(email): """Checks if an email is valid Args: email (str): user's email address Returns: (True, ''): normalized email if it is valid (False, error): error message if it is invalid """ try: ...
d3fa6f30bdd75f1b5265b72e46f784ec34d12d86
josuelegarda/FuturePlannedDevelopmentEstimator
/source.py
2,948
3.78125
4
import pandas as pd import numpy as np import math import matplotlib.pyplot as plt import statistics import scipy.stats from statistics import mean def num_vehicletrip_office_build(df, build_space_est): """ Returns the average of office the office building space: """ avg_office_building_space = df['...
c1945e672f016c8980919c7a939945e77d38b917
Dmitrygold70/rted-myPythonWork
/xxExersises/ex_string.py
12,165
4.28125
4
# 02. Напишите программу на Python для подсчета количества символов (частоты символов) в строке. # Пример строки: google.com ' # Ожидаемый результат: {'o': 3, 'g': 2, '.': 1, 'e': 1, 'l': 1, 'm': 1, 'c': 1} def word_container(line: str): rez = dict() for ch in line.lower(): if ch not in re...
3274795d0e95089617e158508b6a4d98451a24bb
hhhhzy/DS-1003-HW
/hw1/hw1/.ipynb_checkpoints/hw1_code_source-checkpoint.py
1,351
3.59375
4
import numpy as np import matplotlib.pyplot as plt def get_a(deg_true): """ Inputs: deg_true: (int) degree of the polynomial g Returns: a: (np array of size (deg_true + 1)) coefficients of polynomial g """ return 5 * np.random.randn(deg_true + 1) def get_design_mat(x, deg): """ ...
55ac79384aa127a89824fd1cd7cc6bb7f0d847cb
aarbigs/python_labs
/03_more_datatypes/4_dictionaries/04_16_first_dict.py
228
4.03125
4
''' Write a script that creates a dictionary of keys, n and values n*n for numbers 1-10. For example: result = {1: 1, 2: 4, 3: 9, ...and so on} ''' new_dict = {} for i in range(1,10): new_dict[i] = (i*i) print(new_dict)
bb107158f4bd97ec35170f0a9eb643aa32c4d77c
Asaad-E/particles_simulation
/Particles Simulation/utils.py
1,634
4.03125
4
import random import pygame colors = {} colors['white'] = (250, 250, 250) colors['black'] = ( 10, 10, 10) colors['red'] = (200, 40, 40) colors['blue'] = ( 40, 200, 40) colors['green'] = ( 40, 40, 200) def random_color(): """ Choose a random primary color """ return random.choice(list(...
e284f2a3b266ad1dc22b69ee6a3c66efe53ba974
fornext1119/Numeric-calculation
/py/0602.py
390
3.59375
4
# coding: Shift_JIS import math def f(x): return 4 / (1 + x * x) a = 0 b = 1 # _Őϕ n = 2 for j in range(1, 11): h = (b - a) / float(n) s = 0 x = a + (h / 2) for i in range(1, (n + 1)): s += f(x) x += h s *= h n *= 2 # ʂ Ɣr print "%2d : %13...
aab17b75d4ee8f385b2bec47ae316ed55aac100f
luckydimdim/bobel-algo
/python/quick_sort/index.py
355
3.78125
4
def hoar_sort(array): if len(array) <= 1: return barrier = array[0] left = [] middle = [] right = [] for x in array: if x < barrier: left.append(x) elif x == barrier: middle.append(x) else: right.append(x) hoar_sort(left) hoar_sort(right) index = 0 for x in left+middle+right: array[ind...
02a7000a842905deff8a6356bd92fd47e8a9d7cc
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/223/users/4191/codes/1764_1187.py
142
3.625
4
vetor=input("string: ") print(vetor[0]) print(vetor[-1]) print(len(vetor)) s=vetor.lower() print(s) r=vetor.upper() print(r) print(vetor*500)
167315149afc632cedbc0996483f56d10fe700a1
beth98an/eng84_python_data_types_and_operators
/data_types_and_operators.py
701
3.890625
4
# Let's see the data types in action a = 24 b = 16 c = 5.5 print(a + b) print(a - b) print(a * b) print(a / b) print(a + c) # Let's check the boolean values print(a > b) print(a < b) # Let's look at some built in methods for boolean greetings = "Hello world!" # isalpha() helps us find if the variable holding letter...
7c5a18b98e0301fcde2d90d8e76f67c1062a38db
KB-perByte/CodePedia
/local/IMessUpThreading/checkingBooleff.py
981
3.5625
4
''' is bool slower than not not? not not failed when it had to make it as a object''' import timeit import time from threading import Thread prob_slow = """ class SlowClass: def __init__(self): self.data = 5 def __bool__(self): return bool(self.data) sC = SlowClass() """ prob_fast = """ class ...
31b8cfdec5ec798fca960e133205d070522e5fa0
Exprescode/hackerrank
/two_strings.py
661
3.96875
4
#!/bin/python3 import math import os import random import re import sys # # Complete the 'twoStrings' function below. # # The function is expected to return a STRING. # The function accepts following parameters: # 1. STRING s1 # 2. STRING s2 # def twoStrings(s1, s2): # Write your code here for alpha in s1:...
d19c858f4ad2fe521190e0ba7b12dc0bcdecf292
Expert37/home_work_lesson_5
/divisor_master_1.py
468
3.5625
4
def number_div(number): number_list = list(range(2, number)) # включая 1 и само число div_list = [] # создаем пустой список for i in number_list: if number % i == 0: div_list.append(i) # если в итерации находится число, на которое нацело делится number - то этот делитель добавляется в список di...
4105a305d5cac8e6ac70b808f0d9c732dbf9886b
bbbrito1993/Python
/aula08Lambda.py
566
3.828125
4
contador_letras = lambda lista: [len(x) for x in lista] lista_animais = ['cachorro', 'gato', 'pato', 'elefante', 'mamute'] print(contador_letras(lista_animais)) soma = lambda a, b: a + b subtracao = lambda a, b: a - b multiplicacao = lambda a, b: a * b divisao = lambda a, b: a / b calculadora = { 'som...
3f43d6cecc8345a4e38e8f1b818c449540d6100a
Gemper/PGN
/Python/ColeccionesYDiccionarios/Ejercicio10.py
470
4.1875
4
''' Diccionario Español a Ingles. @author: d18cralr ''' diccionario={'gato':'cat', 'perro':'dog', 'casa':'house','carta':'card','arbol':'tree', 'rojo':'red','amarillo':'yellow','verde':'green','mesa':'table','montaña':'mountain','coche':'car'} respuesta = (input("Introduzca la palabra que desea traducir...
507d4dbea60d0342d192d51a7f60495a53f55631
CHOcho-quan/BasicControlAlgorithms
/fuzzyController.py
2,047
3.921875
4
import numpy as np import math class FuzzyController: """ This is a fuzzy controller in 1-Dimensional control """ def __init__(self): """ Initializing a 1 dimensional contrller self.controller : store the information inside each dimension including """ self.con...
dcd6178f8afa9b2b0ab92c3643d7f1800d12a323
zhangran653/leetpy
/algorithm/c02_sortbase/insert_sort.py
671
4.0625
4
""" 插入排序 https://visualgo.net/zh/sorting """ def insert_sort(arr): for i in range(1, len(arr)): for j in range(i, 0, -1): if arr[j] < arr[j - 1]: arr[j], arr[j - 1] = arr[j - 1], arr[j] else: break def insert_sort2(arr): for i in range(1, len(a...
cfd7218615d60a0b956b407befd9af96f201c370
dongkibravo/python_code
/bisect_test.py
213
3.71875
4
import bisect import sys print(sys.version) a = list(map(int, input("enter numbers: ").split(','))) a.sort() print(a) val = int(input("enter a value: ")) print(val) answer = bisect.bisect(a, val) print(answer)
cdb30c0a18f0054c42a257557164fa2aa0a3bf78
sterlinm/PythonClass
/student/exercises/python_language/roman_dictionary/roman_dictionary.py
1,794
4.59375
5
""" Roman Dictionary ---------------- Mark Antony keeps a list of the people he knows in several dictionaries based on their relationship to him:: friends = {'julius': '100 via apian', 'cleopatra': '000 pyramid parkway'} romans = dict(brutus='234 via tratorium', cassius='111 aqueduct lane') countryme...
7e8404a7ae68e6385a78a5ed73d567b91a0355a3
TigiGln/INLO
/TP5/linkedList.py
2,611
3.984375
4
# coding: utf-8 class Node: """ Node of a list """ def __init__(self, data): self.data = data self.next = None def __repr__(self): return self.data class LinkedList: """ Linked list """ def __init__(self, nodes=None): self.head = None if nodes is not None and ...
9b4897875193c85b6a52df3f8ed4aa1110022ddc
Bigbys-Hand/crash_course_git
/class_restaurant.py
552
3.96875
4
class Restaurant: """Following the exercise on pg.162""" def __init__(self, name, cuisine): """Initialize restaurant name and cuisine type attributes""" self.name = name self.cuisine = cuisine def describe_restaurant(self): """Prints name and cuisine type""" print(f...
fe637f4826eaf433e762df520f4eea44d093fad6
witcherwjl/leetcode-
/1_剑指offer/6_面试题11旋转数组的最小数字_二分查找变形_暴力_方法较难多看看.py
1,672
4.09375
4
''' 把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素。例如,数组 [3,4,5,1,2] 为 [1,2,3,4,5] 的一个旋转,该数组的最小值为1。   示例 1: 输入:[3,4,5,1,2] 输出:1 示例 2: 输入:[2,2,2,0,1] 输出:0 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/xuan-zhuan-shu-zu-de-zui-xiao-shu-zi-lcof 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 ''' class Solutio...
40bd6c1060668ad184794201af73f382e479ce5c
jupiterchu/Python005-01
/week03/use_pymysql_insert.py
912
3.625
4
from datetime import datetime import pymysql db = pymysql.connect('localhost', 'root', '123456', 'jove_class') def insert_many(): SQL = """INSERT INTO student (name, age, birthday, sex, edu, create_on, update_on) values (%s, %s, %s, %s, %s, %s, %s) """ values = ( ('Peter', '22', datetime(1998...
c653b4ad30d1a3fce0c86a27e18bd715c26d7986
Dwakar/Memory-based-collaborative-filterng
/movie/moviecolab.py
1,275
3.53125
4
import pandas as pd from math import sqrt import numpy as np from sklearn.metrics import mean_squared_error from sklearn.metrics import mean_absolute_error ratings = pd.read_csv("ratings.csv") movies = pd.read_csv("movies.csv") ratings = pd.merge(movies,ratings).drop(['genres','timestamp'],axis=1) user_ratings = rat...
136dd944041606386a94e85d5937c04c392784f5
Brinews/jacky
/B/Python/P-Easy/P-songs/album.py
805
3.546875
4
# # Album: Song List # Date: 2016-12-10 # from song import * class Album: def __init__(self, title): self._title = title self._songslist = [] def getTitle(self): return self._title def setTitle(self, title): self._title = title def getSongs(self): return self...
e20385f393de35bc969ee75e4fe1875a2b0bbf67
ruan65/python_algorithms_and_problem_solving
/hacker_rank/python_practice/print_rangoli.py
338
3.53125
4
def print_rangoli(size): a = ord('a') for i in range(-size + 1, size): w = '' for j in range(abs(i) + 1, size): w += '-' + chr(a + j) print((w[::-1] + chr(a + abs(i)) + w).center(4*size - 3, '-')) if __name__ == '__main__': # n = int(input()) print_rangoli(5) # ...
256a0ed503a193691b7bf1d798e34c63b07b8db6
leandrotominay/pythonaprendizado
/licoesfacul/verificaMenorNumeroEDivide.py
417
4.03125
4
#Dados dois números diferentes dividir o maior pelo menor valor. num1 = int(input("Digite o primeiro numero: ")) num2 = int(input("Digite o segundo numero: ")) if(num1>num2): divisao = num1/num2 print("O Resultado da divisão de {} por {} é igual a: {}".format(num1, num2, divisao)) else: divisao = num2/num...
9f7aef9fcf02b4089620680d9f23512d15c0686c
RSP123/python_puzzles
/greeting_msg.py
374
3.9375
4
def greeting(name = "Your_Full_Name"): return "Hi " + name.split(" ")[0] + "!" if __name__=="__main__": name = input("Type your Firstname and lastname > ") print(greeting(name)) # # new_str = "Hi jayanth this is sample " # print(new_str, " => ", type(new_str)) # # new_str = new_str.split(" ") # print(...
4b57f98631751389d97ab010cfe80f636d8ed99d
RuthKassahun/PythonLectures
/Intro/Variables.py
904
4.0625
4
# variables are identifies that holds values of diffrent data types age = 10 # Age holds the int value 10 name = "Abebe" # name holds the string value abebe mark = 88.5 # mark holds the float value 88.5 ''' Naming Conventions don't use keywords as a name of a variable like print,float,int,new ...
ff3bfdf5757b7ae2edb376ebd2d10ed6818ac349
hidoos/learn-python
/part1/chapter_10/test/learing_python.py
291
3.65625
4
filename = 'learning_python.txt' with open(filename) as file_object: lines = file_object.readlines() newsLines = [] for line in lines: print(line.rstrip()) newsLines.append(line.replace('python', 'ruby')) print('replace python:') for line in newsLines: print(line.rstrip()
5dc5adbd0be21a5450030b6b612ea705627b178c
chengchengXCC/interview_questions
/LintCode/1st_round_fail/40.py
1,452
4.0625
4
class Stack: def __init__(self): self.stack = [] def push(self, x): self.stack.append(x) def pop(self): tmp = self.stack[len(self.stack) - 1] self.stack.pop() return tmp def peek(self): tmp = self.stack[len(self.stack) - 1] return tmp def isEmp...
9cfe08c67420ff082d8a9005e4e5dbfc5ba4c3b0
fxisco/pdsnd_github
/bikeshare.py
6,798
4.15625
4
import time import pandas as pd import numpy as np CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } VALID_MONTHS_VALUES = { 'all': -1, 'january': 1, 'february': 2, 'march': 3, 'april': 4, 'may': 5, 'june': 6, 'ju...
923a0fc8da115edf1d240dc4cd721a42e04f8ded
hungpchu/code-interview
/Array and String/(HackerRank)FindSubstring.py
1,317
3.53125
4
def count_substring(string, sub_string): count = 0 length = 0 result = 0 if ( len(string) < 1 or len(string) > 200): print(exit) txtLen = len(string) patLen = len(sub_string) # print "hung" for i in range(txtLen): # print (" i = ngaoai j", i) ...
3bcbaca618624a7c1e3ef0f3acf2533b9d126134
phlalx/algorithms
/leetcode/332.reconstruct-itinerary.py
3,114
4
4
# # @lc app=leetcode id=332 lang=python3 # # [332] Reconstruct Itinerary # # https://leetcode.com/problems/reconstruct-itinerary/description/ # # algorithms # Medium (32.48%) # Likes: 928 # Dislikes: 609 # Total Accepted: 94.7K # Total Submissions: 290.8K # Testcase Example: '[["MUC","LHR"],["JFK","MUC"],["SFO",...
40c18d35029600732329dab46047e7c393c0675f
DouglasAllen/Python-projects
/M101_MongoDB/python/other/function_calls.py
267
3.953125
4
fruits = ["apple", "orange", "grape", "kiwi", "orange", "apple"] def analyze_list(list): counts = {} for item in list: if item in counts: counts[item] = counts[item] +1 else: counts[item] = 1 return counts counts = analyze_list(fruits) print counts
46ac18b3c1db06948806284cc1c4b8274ef2a09d
vix95/Algorithmic-graph-theory
/laboratorium-2/2-graph.py
1,031
3.59375
4
def create_list(l, line): for x in range(2): v = int(line.split()[x]) if len(l) < v: for y in range(v - len(l)): l.append([]) return def get_edges(l, line): v1, v2 = map(int, line.split()) v1 -= 1 v2 -= 1 l[v1].append(v2) l[v2].append(v1) ...
8bf5529dfac17626eaa141b30ef3dccde739bfdf
svdani/Processos_DaniSanchez
/Practica5_DanielSanchez/pdb-ThePythonDebugger.py
2,845
3.78125
4
#-*- coding: UTF-8 -*- """Per comencar et demana que junt amb l'execucio del programa indiquis un “argument” que ha de ser un numero entre 0 i 994 sino el programa dona error. El programa mostra la quantitat de nombres primers que tu hagis indicat en ordre de mes petit a mes gran, el programa comenca sempre amb una ll...
a0dcda10f08045aa5ee91eb8818f3948506f8c4e
DatDLuu/Short_Python_Algorithm
/challenge/firstDuplicate.py
234
3.796875
4
# find first duplicate in a given array # if theres none or only 1 elem return -1 def firstDuplicate(arr): unique=set() for elem in arr: if elem in unique: return elem unique.add(elem) return -1
0c7f3df9b70124e7a78dcdd266ca7fdca6fef042
bolddiomedes/AdminGit
/checkCFAR.py
1,614
3.984375
4
###Program to find the number of CFAR members in a list of names. Returns X members out of Y names. reflist = [] testlist = [] def reflistit(): cheese = open("cfarref.txt", "r") for line in cheese: line = line.strip() reflist.append(line.upper()) def isCFAR(name): for each in reflist: ...
df030d3ce6de37818520725460449032d5950c79
snpushpi/P_solving
/1033.py
1,171
4.28125
4
''' Three stones are on a number line at positions a, b, and c. Each turn, let's say the stones are currently at positions x, y, z with x < y < z. You pick up the stone at either position x or position z, and move that stone to an integer position k, with x < k < z and k != y. The game ends when you cannot make any mo...
ca16f2a60355918afcd7a98eab18d56347dca549
BlackBond88/Jackal
/fibonacci.py
601
3.65625
4
def counter(n): """ Вычисляет следующий элемент последовательности """ x1 = 0 x2 = 1 for i in range(n): x2 += x1 print(i, '-й элемент: ', x1, sep='') x1 = x2 - x1 def main(): try: n = int(input('Введите количество элементов последовательности Фибоначчи: ')) ...
387c1e01620b792965da0c096ef1a48eda5f00b4
ws2823147532/algorithm008-class01
/Week_02/[290]单词规律.py
2,253
3.59375
4
# 给定一种规律 pattern 和一个字符串 str ,判断 str 是否遵循相同的规律。 # # 这里的 遵循 指完全匹配,例如, pattern 里的每个字母和字符串 str 中的每个非空单词之间存在着双向连接的对应规律。 # # 示例1: # # 输入: pattern = "abba", str = "dog cat cat dog" # 输出: true # # 示例 2: # # 输入:pattern = "abba", str = "dog cat cat fish" # 输出: false # # 示例 3: # # 输入: pattern = "aaaa", str = ...
c9754729a08251b48b211fcb4eca5bbe277cf573
kosukach/algorithms-and-data-structures
/sorting/Selectionsort.py
404
4.0625
4
def selectionSort(array): for i in range(len(array) - 1): temp = i for j in range(i + 1, len(array)): if array[j] < array[temp]: temp = j if i != temp: tempVal = array[temp] array[temp] = array[i] array[i] = tempVal return ...
55e4e41973ebd416f7d9b22e132bc5cb530ebfc5
Mbote-Joseph/Factorial-of-Number-in-Python
/Factorial.py
281
4.28125
4
num=int(input("Enter the number : ")) fact=1 if num<0: print("There are no factorials for negative numbers") elif num==0: print(f"The factoria of 0 is : {fact}") else: for i in range(1,num+1): fact=fact*i print("The factorial of {} is {}".format(num,fact))
f3362f03685f7087675bd102397d668cd0bee44e
gutaors/DataCamp
/personal-master/DataCamp/training/relational_dbs_Python.py
27,116
4.34375
4
# SQLAlchemy # Engines and Connection Strings # Alright, it's time to create your first engine! An engine is just a common interface to a database, and the information it requires to connect to one is contained in a connection string, such as sqlite:///census_nyc.sqlite. Here, sqlite is the database driver, while cens...
ce6ed26772ee9cb6f9433fe6d7b5290ab22e9bf7
gorigo/Programaci-n
/Práctica 4/exercici 03.py
405
3.96875
4
"""Sergio Rigo Garca - DAW1 - PRCTICA 4 - EJERCICIO 3 - Escriu un programa que demani 2 nombres i escrigui la suma de sencers des del primer nombre fins al segon. """ print "Introduce un nmero" num=int(raw_input()) print "Introduce un nmero mayor que", num num_2=int(raw_input()) aux=0 for i in range(num,num_2...
692f644b87ee754ddd315f121fc0fee67285a7b5
huyngopt1994/Common_pattern_python
/AbstractFactory/connector.py
987
3.734375
4
import urllib2 from factory import HTTPFactory, FTPFactory class Connector(object): """A client.""" def __init__(self, protocol): """Factory is a AbstractFactory instance with creates all attributes of a connector according to factory class.""" if protocol not in [0, 1]: ...
5780ee5782c95186a601f93e23ff34f0ff31cfde
PedroGoes16/Estudos
/Exercicios-Python/exercicios-curso-em-video/d073.py
619
3.515625
4
b = 'Corinthians', 'Palmeiras', 'Santos', 'Grêmio', 'Cruzeiro', 'Flamengo', 'Vasco da Gama', 'Chapecoense', 'Atlético Mineiro', 'Botafogo', 'Atlético Paranaense', 'Bahia', 'São Paulo', 'Fluminense', 'Sport', 'Vitória', 'Coritiba', 'Avaí', 'Ponte Preta', 'Atlético Goianiense' print(30*'-=') print(f'Classificação do Bras...
240f840edb9c3ac6f6ce2dae6169e35688b6ed3f
TinRain/-oj
/算法课代码_持续更新/homework2_7.py
1,098
3.609375
4
def quick_sort(arr): if len(arr) < 2: return arr stack = [] stack.append(len(arr)-1) stack.append(0) while stack: l = stack.pop() r = stack.pop() index = partition(arr, l, r) if l < index - 1: stack.append(index - 1) stack.append(l) ...
c62b3d97993a4d408a1b9f14bc8607b46dce564f
Aasthaengg/IBMdataset
/Python_codes/p02272/s587660246.py
856
3.765625
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys def merge(A, left, mid, right): global count L = A[left:mid] + [1e9] R = A[mid:right] + [1e9] i, j = 0, 0 for k in range(left, right): count += 1 if L[i] <= R[j]: A[k] = L[i] i += 1 else: ...
c8393bcbe18b8c130ad460939f89dce657a6f76f
JomHuang/PythonStudy
/Day_2/Preview/OOP/manager.py
591
3.59375
4
from person import Person """ 继承 1.自定义构造函数 """ class Manager(Person): # 自定义构造函数 def __init__(self, name, age, pay): Person.__init__(self, name, age, pay, 'Manager') # 重写加薪方法 def giveRaise(self, percent, Bonus=0.1): # self.pay*=(1.0+percent+Bonus); Person.giveRaise(self, perce...
921e43e6d08df803396d95efa518f140195457c5
CMPundhir/Shikha-Py
/2021-09-27/lambda_func.py
315
3.984375
4
# lambda function # it's a small anonymous function # A lambda function can take any number of arguments, but can only have one expression. summer = lambda a, b: a+b print(summer(10,21)) def calculateInst(p, r): return lambda t : p * r * t / 100 inst = calculateInst(1000, 10) print(inst(2)) print(inst(20))
198d6d3634d114aef6d7ba6313cb67817f679cee
amiremadz/Python-Beyond-the-Basics
/Chapter 7/pytest-example/myprogram.py
495
3.75
4
#!/usr/bin/python import sys def doubleit(x): if not isinstance(x, (int, float)): raise TypeError var = x*2 return var def doublelines(filename): with open(filename) as fh: num_list = [ str(doubleit(int(val))) for val in fh] with open(filename, 'w') as fh: fh.write('\n'.joi...
d7be9d42cde13ce4a48fdbe66a6421dc9b44f84a
Maverick1998/M03-Python-stuff
/bucle-test.py
694
3.984375
4
# coding: utf­8 ### bucle-test.py ### Robert Rebaza ### Plantilla de bucle ejemplo print "1. Entrar" print "2. Salir" num1 = input("Introduce un numero :") salir = "N" while salir == "N": if num1 == 2 : # Salir del programa salir = "S" else: ...
22864ad257bc1e16d03b5a3d5671b20092aa1459
LouiseJGibbs/Python-Exercises
/Python By Example - Exercises/Chapter 03 - Strings/022 Fullname to title.py
192
3.96875
4
#022 Full name to title firstname = input("Please enter your first name in lower case: ") surname = input("Please enter your surname in lower case: ") print(firstname.title(),surname.title())
2a298a97e8c9cc8cbd4b1ac8b49bcbd12de920eb
edson-onishi/cursoemvideo
/modulos/moeda.py
371
3.5625
4
'''Crie um módulo chamado moeda.py que tenha as funções incorporadas aumentar(), diminuir(), dobro() e metade(). Faça também um programa que importe esse módulo e use algumas dessas funções.''' def aumentar(n): return n + (n * 10/100) def diminuir(n): return n - (n * 10/100) def dobro(n): ret...
9a87c8c46b2d991008dfc6991e16eab62ead250f
RomanPutsilouski/M-PT1-37-21
/Tasks/Ramanenka_Tasks/HT5/HT5_recurs.py
326
4.125
4
"""Recursive function to calculate the sum of all elements in nested list """ def sum_elem_list(lists): summa = 0 for i in lists: if type(i) != list: summa += i else: summa += sum_elem_list(i) return summa lista = [1, 2, [2, 4, [[7, 8], 4, 6]]] print(sum_elem_list(li...
97f02f7148f3afc7bd4b190a20d0b87d30a210f2
fmarculino/CursoEmVideo
/ExMundo2/Ex041.py
812
4.15625
4
""" A confederaçã nacional de natação precisa de um programa que leia o ano de nascimento de um atleta e mostre sua categoria, de acordo com a idade: - Até 9 anos: MIRIM - Até 14 anos: INVFANTIL - Até 19 anos: JUNIOR - Até 24 anos: SENIOR - Acima: MASTER """ from datetime import date dtnascimento = int(input('Digite o...
1ef195c10a3cc7bd65858d5af3a0e88603718506
Hallyson34/uPython2
/function.py
158
3.53125
4
def somasub(x,y): s = x+y sb = x-y return print(f"{s} {sb}") def main(): x = int(input()) y = int(input()) somasub(x,y) main()
6dc152289150a8eac1a3a7e2667596afbc5ab297
ISINth/Labs-HW
/lab2.py
1,156
3.796875
4
def min(arr): #минимальное значение minimal =arr[0]; for i,el in enumerate(arr): if el<minimal: minimal=el return minimal def average(arr): #среднее значение массива summ=0 for i,el in enumerate(arr): summ=summ+el; return (summ/(i+1)) ########################### def reverse(string): #Переворот строк...
9970314b490bf4ec78fdb632aa99cc74965739e7
csaddison/Physics-129L
/Misc/complexplane.py
3,825
3.640625
4
# # 2/19/19 # ------------------------------------- COMPLEXPLANE.PY ------------------------------------- """ Create and plot fractals and complex functions. Contains three methods: .createplane: Creates an xy grid and a null array zmap .cgen: Generates random values of c for julia set .julia: ...
49abdb6f16cd598740c9f0fd5958796f89d93b6f
MuhammadZeeshanNawaz/PythonAssignments
/Assignment no.01.py
915
3.796875
4
#!/usr/bin/env python # coding: utf-8 # Question no 01 print ("Twinkle, twinkle, little star, \n\tHow I wonder what you are! \n\t\tUp above the world so high, \n\t\tLike a diamond in the sky. \nTwinkle, twinkle, little star \n\tHow I wonder what you are ") # Question no 02 print ("My Python Version is:") import ...
1e95c33fc7b44e58ef62f9fc7bb1a3b2843295cd
sky-dream/LeetCodeProblemsStudy
/[0071][Medium][Simplify_Path][String_Stack]/Simplify_Path.py
659
4.125
4
# -*- coding: utf-8 -*- # Time Complexity: O(N) # Space Complexity: O(N) # solution 1, stack class Solution: def simplifyPath(self, path: str) -> str: stack = [] path = path.split("/") for item in path: if item == "..": if stack : stack.pop() elif ...
dcde9ae7a97c4a5209b3898922dce42365f1687a
DCtheTall/mit6.046
/lecture04/vanembdeboas.py
2,885
4.0625
4
""" Lecture 4: van Embde Boas Tree ------------------------------ A vEB tree can do the 3 binary search operations: add, delete, successor In O(log(log(u))) where u is the maximum size of the data structure Recurrence: T'(u) = T(sqrt(u)) + O(1) """ class VEBTree(object): def __init__(self, size): """ Cr...
279b75f58c86773d687c3db55b9b8ea9a7102aa0
thaishankar/Python-Practice-Code
/once_integers.py
360
3.515625
4
def once_integers(arr): d = {} res = [] for i in range(len(arr)): if arr[i] in d: d[arr[i]] += 1 else: d[arr[i]] = 1 print d for key in d: if d[key] == 1: res.append(key) return res if __name__ == '__main__': arr = [1, 2, 3, 5, 2...
98c836d2762b5bbe2100d4418b9f1f2cde0e6c18
dannyvankooten/advent-of-code
/2021/23-amphipod/main.py
1,047
3.578125
4
from pathlib import Path def energy_cost(type: str, steps: int) -> int: costs = { 'A': 1, 'B': 10, 'C': 100, 'D': 1000, } return costs[type] * steps def done(rooms, hallway): if len(hallway) > 0: return False for key in rooms: if len(rooms[key]) !=...
7549bcd41fb6d4aa7881febb3f5d2d7877a5f2f3
8787878877/b04170103_0412
/b04170103_0412.py
7,775
3.703125
4
# coding: utf-8 # In[1]: x,y,z=3,4,5 print(x) print(y) print(z) # In[12]: #交換 x,y=3,4 x,y=y,x print(x) print(y) # In[5]: x,y,z=3,4,5 x+=1 #x=x+1 y*=2 #y=y*2 z**=3 #**(次方) print(x,y,z) # In[16]: x=1 y=10*x x=x+y print(x) print(y) # In[9]: #海龍公式 import math a,b,c=3,4,5 s=(a+b+c)/2 area=math.sqrt(s*(s-...
c63234559f52eecb4de962f2fa9bd91c2cfd127d
petreleon/CodingChallanges
/AoC/2020/19/Untitled.py
185
3.546875
4
import regex import regex # example: example_string = "xababababcdcdcdcdaabby" # regular expression that consumes the whole string print(bool(regex.match("^x()y$", example_string)))
9f85c7674f5944116dc241ff12cc8a0aef89dbef
denizbaltas/blackjack
/blackjack.py
5,420
3.875
4
import time import random class game: def __init__(self): cards = self.cards() balance = 1000 while True : if balance == 0 : print("Your Balance Is 0 You Lost \n ") time.sleep(5) break try: ...
c02934e3f2c70e77acc52c40977b24b83e0d32bc
satyamchaturvedi/datacamp
/2.Python/Intermediate_Python/4.Loops.py
8,528
4.5625
5
#while: warming up The while loop is like a repeated if statement. The code is executed over and over again, as long as the condition is True. Have another look at its recipe. while condition : expression Can you tell how many printouts the following while loop will do? x = 1 while x < 4 : print(x) x = x ...
9dc66fb93b631dc0335a513f0cc0ddf0f369e316
WesleyTi/Exercicios-Python
/exe17.py
736
4.15625
4
#coding: utf-8 #FAÇA UM PROGRAMA QUE LEIA O COMPRIMENTO DO CATETO ADJACENTE DE UM TRIÂNGULO RETÂNGULO, CALCULE E MOSTRE O COMPRIMENTO DA HIPOTENUSA. # 1ª resolução do programa sem módulos '''c_o = float(input('Informe o comprimento do cateto oposto:')) c_a = float(input('Informe o comprimento do cateto adjacente:')) ...
bdbbc798f60f1bc2518546b935cf39548da4d75c
shreyasaswar/PythonHardWay-solutions
/ex2.py
323
3.59375
4
# This snippet is all about comments #shreyas # It tells what a comment does and what are different uses of it #like comment can share some information print("My name is shreyas") #print("my name is not shreyas") # see how we comment out the code , to disable that part print("I'm shreyas again") #we can comment here to...
60acc41ce60e688564aef5848dbf6b81970c8920
linyouwei/pycharm
/uclbrt/auto_test/meizhu/test.py
557
3.84375
4
def get_list_min_num(build_num_list): temp = build_num_list[0] for i in build_num_list: if temp > i: temp = i return temp def generate_num(min_num, build_num_list): # 查找楼栋编号的最小值 num = min_num + 1 if num not in build_num_list: return num elif num == 255: ...
a23e0112a1601786b7fa6b41122fa6058091ac6b
alicefeng/disney-songs-project
/data/createCharacterData.py
1,444
3.6875
4
# -*- coding: utf-8 -*- """ Title: createCharacterData.py This program creates all additional support datasets needed including: - a dataset with all of the unique character names that have singing roles in Disney animated feature films. Extra attributes (gender, protagonist status) about the characters will be add...
1b896aa1bfb35c1350a991a7e61f2e3fa086d361
MagdaLCR/MIPROYECTO
/app.py
1,957
3.5625
4
import streamlit as st st.title ("MI PRIMERA APLICACIÓN") st.sidebar.title ("PARÁMETRO") st.sidebar.header("INICIO") st.write("APLICACIONES") from PIL import Image imagen1=Image.open("IMAGEN.jpg") st.image(imagen1) import pandas as pd df=pd.read_excel("DATA.xlsx") df["CALCULO"]=df.NÚMEROS*3 lista_columna=df...
39f9dfbdfee622c19f53860d7c1254499ab6435c
dcmealey/PythonPrograms
/ContactBook.py
9,993
4.5
4
''' Contactbook Let's build a program to manage a list of contacts. To start, we'll build a CSV ('comma separated values') together, and go over how to load that file. Headers might consist of name, favorite fruit, favorite color. Open the CSV, convert the lines of text into a list of dictionaries, one dictionary for ...
7cc3a6c7aae5a353c5313535155dadacc9e15634
akash123456-hub/hello.py
/inheritance02.py
460
3.78125
4
class Person: def __init__(self,fname,lname,add,city): self.firstname = fname self.lastname = lname self.address = add self.city = city def printname(self): print(self.firstname,self.lastname,self.address,self.city) class Student(Person): def __init__(self,fname,lname...
95a4019120a3323a7de6996e65cda568880bc0b3
E-Asmar/pythonPractice
/ModuleThreeStringVariables/ModuleThreeStringVariables/ModuleThreeStringVariables.py
584
4.09375
4
#takes an input and makes it a variable name = input("What is your name? ") print(name) name = 'CEBOT' print(name) #rules for python variables # 1. cannot contain spaces # 2. Is case-sensitive # 3. cannot start with a number. # 4. discriptive naming message = "Hello World" print(message.lower()) print(message.upper...
19370339b8dcbbbb7e16d4fd5923a8d3d670e2e2
jingwang2/DGLPython
/job2jour02.py
703
3.53125
4
class Personne: def __init__(self,fname,fprenom): self.name=fname self.prenom=fprenom def se_presenter(self): print("My name is",self.name,self.prenom) class Livre: def __init__(self,titre,auteur): self.titre=titre self.auteur=auteur def showtitre(self): ...
28059886f9f837abdf844578997a5aae96b7d00e
milanmenezes/python-tutorials
/solutions/unit2/permutation.py
120
3.734375
4
from itertools import permutations a=raw_input("Enter the string\n") for x in permutations(a): print "".join(x)
f3c791b098e4bdeb1f2176cdad72ddcee11b7cd4
yuzhenpeng/PCircos
/maths.py
11,178
3.5
4
''' This code contains the following functions: theta: convert chromosome accumulative coords to theta complex: convert chromosome coords to complex array list arc: return a list of complex array which can be used to draw an arc based on coordinate intervals heatmap_val: convert input values to heatmap ...
aa48533e9752a012e0fe28913b01b0af21acfff8
amaechichisom/python-datastructure
/502/row_column_major.py
1,250
3.859375
4
array = [ [1,2,3,10], [4,5,6,11], [7,8,9,12], [14,15,13,12] ] print("************************ The array dimensions: *********************************") print(array) print("*******************************************************************************") base_address = array[0][0] # column_maj...
1b2a010d07889ff43291a7a77a3430e5470e4780
bucaimeimei/LeetCode
/LinkedList/T21_mergeTwoLists/demo.py
797
3.671875
4
''' 21. 合并两个有序链表 题目描述 将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 示例: 输入:1->2->4, 1->3->4 输出:1->1->2->3->4->4 ''' class Solution(object): def mergeTwoLists(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ prehead = ListNod...
68421b78e4b8a472decb8418482c57b8f101d027
ChristianBloemhof20/Lists
/linked_list.py
4,299
4.28125
4
# Implements the list ADT using a linked list. # CSC 202, Lab 2 # Given code, Summer '19 class List: """ An ordered collection of elements """ def __init__(self, head = None, size = 0): # The head of the backing linked list: self.head = head # The number of elements in this list: ...
3c9706a562aff0755d49f4e005230cd7b7ef48ae
lixuanhong/LeetCode
/ReverseLinkedList.py
509
3.875
4
""" Reverse a singly linked list. Example: Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL """ class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def reverseList(self, head): if not head: return None pre = N...