blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
e0fc1d62963d1aa138c71380f71d844872d1e0bb
KingAshiru/Leetcode-weekly-Medium
/3Sum.py
1,206
3.71875
4
class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: nums.sort() triplets = [] for i in range(len(nums)): if i > 0 and nums[i] == nums[i-1]: # skip same element to avoid duplicate triplets continue self.search_pair(nums, -nums[i], i...
e6d3eef9d9a2699c50e6b286e2850d2ad1fd6bc0
jpars26/Python_Training
/JetBrains/Conditions & nested lists.py
162
3.828125
4
students = [["Will", "B"], ["Kate", "B"], ["Max", "A"], ["Elsa", "C"], ["Alex", "B"], ["Chris", "A"]] print([name for name, grade in students if grade == 'A'])
477295c4221b6c83bbf1229150dcfd3930ceed0b
mission-learning/Algorithms
/Graph algorithms/Eulerian graph.py
2,113
3.5
4
#IS EULERIAN class Graph: def __init__(self,vertices): self.V = vertices self.graph = [[] for i in range(verticles)] def addEdge(self,u,v): self.graph[u].append(v) self.graph[v].append(u) def DFS(self,v,visited): visited[v] = True ...
9c0071d2f764fc0db1631c1b8fea65c094227ee3
rekbun/project-euler
/src/python/problem41.py
625
3.875
4
from itertools import * def getPandigitalList(length): num='' for i in range(1,length+1): num+=str(i) return (''.join(each) for each in list(permutations(num,length))) def isPrime(n): if n==2 or n==3 or n==5 or n==7: return True if n%2==0 or n%3==0 or n%5==0: return False k=5 while k*k<=n: if n%k==0...
a28c7a16f077e5b86188fc90bd4562c3be4c2ab3
1040979575/baseDataStructureAndAlgorithm
/algorithm/dynamicProgramming.py
546
3.515625
4
''' 给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和 示例: 输入: [-2,1,-3,4,-1,2,1,-5,4], 输出: 6 解释: 连续子数组 [4,-1,2,1] 的和最大,为 6 ''' # 一维变换dp def dp(arr): temp = [] for i in range(arr.__len__()): if i == 0: temp.append(arr[i]) else: temp.append(max(temp[i - 1] + arr[i], arr[i...
494fee0ae500bc6a26bcb2752d7aa7f95b7b3f39
tyler7771/learning_python
/num_repeats.py
753
4.1875
4
# Write a method that takes in a string and returns the number of # letters that appear more than once in the string. You may assume # the string contains only lowercase letters. Count the number of # letters that repeat, not the number of times they repeat in the # string. # # Difficulty: hard. def num_repeats(string...
fc30a90635d2fe46b03ba33ae0111dbf7275bb89
VovaPicha/VovaPicha
/task1.py
880
3.65625
4
def main(): s = input() nums = [] words = [] for word in s.split(): try: nums.append(int(word)) except ValueError: words.append(word) print(' '.join(words)) # виводим числа print(nums) words = list(map(lambda x: x.upper() if len(x) == 1...
8bb7dc7a74c7e30363d83a82d92e06992b5fb261
brenomacedodm/pca
/k_nn.py
1,093
3.5625
4
#função para cálculo da distância euclidiana import math def distancia_eucl(item_1, item_2): somatorio = 0 for i in range(len(item_1)-1): somatorio += pow((float(item_1[i]) - float(item_2[i])),2) return math.sqrt(somatorio) #Função do K-NN para comparar com o desempenho do método proposto def kn...
48bb8ca03de943b1d0892886124f7860005b58ef
surinder1/new-file
/assignment_no_13.py
2,014
4.28125
4
#Q.1- Name and handle the exception occured in the following program: #a=3 #if a<4: # a=a/(a-3) # print(a) # try: # a=3 # if a<4: # a=a/(a-3) # print(a) # except Exception: # print("Hello") # Q.2- Name and handle the exception occurred in the following program: # l=[1,2,3] # print(l[3]) # try: # l=[1,2,...
af5f83a9fb74aa1f0a30c879267ca7dc46994712
naedavis/BMI_Calc
/main.py
4,914
4.1875
4
#Naeemah Davis #BMI Calculator import tkinter as tk from tkinter import * from tkinter import INSERT from tkinter import messagebox top = tk.Tk() stvar = StringVar(top) top.title("Naeemah Davis") #size of the window on which everything will be displayed top.geometry("700x700") #made it non-resizable so the user cannot...
d6104a2860598ea81698c9f527063fdefc7579c3
carloshssouza/UniversityStudies
/COM220/T8/com220_trab08.py
3,993
3.921875
4
from abc import ABC, abstractmethod #Definição de exceptions class TitulacaoNaoPermitida(Exception): pass class IdadeInvalida(Exception): pass class CursoNaoPermitido(Exception): pass class CpfDuplicado(Exception): pass #Classes class Pessoa(ABC): def __init__(self, nome, endereco, idade, cpf)...
473994573de4b5aa397f5ae4c644f648cc685227
dharness/ctci
/Chapter 1 - Arrays and Strings/question_4.py
568
4.34375
4
# Write a method to replace all spaces in a string with'%20'. You may assume that # the string has sufficient space at the end of the string to hold the additional # characters, and that you are given the "true" length of the string. (Note: if implementing # in Java, please use a character array so that you can perform...
833e1994cb43dc28266dce0e573162cb7fd892d3
BrendanStringer/CS021
/Assignment 03.0/BMICalc.py
819
4.5625
5
#Brendan Stringer #CS 021 #Assignment 3.1 #This program will calculate a person's BMI and determine if it is within the correct range. #Get input from the user WEIGHT = int(input('What is your weight in pounds? ')) HEIGHT = int(input('What is your height in inches? ')) #Is weight < 50 lbs if WEIGHT < 50: print...
5fcd3c0e284a6ef85783f640154cfe2222270733
thariqkhalid/TwitterHateSpeech
/notebooks/spell check.py
1,255
3.59375
4
#!/usr/bin/env python # coding: utf-8 # In[1]: def edit_distance(s1, s2): m=len(s1)+1 n=len(s2)+1 tbl = {} for i in range(m): tbl[i,0]=i for j in range(n): tbl[0,j]=j for i in range(1, m): for j in range(1, n): cost = 0 if s1[i-1] == s2[j-1] else 1 tbl[i,j] = ...
e66c0a6095395928a19c56f86828db476a3ff891
chan-alex/python-explorations
/pythonic_practice/properties.py
1,856
4.0625
4
# In python, it is possible to make class method appears as if they are class attributes # this is one way: using the "property" declaration. # With this method it is important to name the actual data attribute and the getters/setters # correctly or risk infinite recurision. class Complex1: def __init__(self, re...
4b661d0e0d118e01226b602987aaf7bf7988a983
Kodermatic/SN-web1
/06_HW - Python (Conditions and loops)/06_Converter.py
880
4.3125
4
# Plan: # The program greets user and describes what's the purpose of the program. # The program asks user to enter number of kilometers. # User enters the amount of kilometers. # The program converts these kilometers into miles and prints them. # The program asks user if s/he'd want to do another conversion. # If yes,...
105958c2547ccba9bea40558cd6fff0314a4f753
MiguelAtencio/Tableaux
/tableaux.py
5,341
3.546875
4
#-*-coding: utf-8-*- from random import choice ############################################################################## # Variables globales ############################################################################## # Crea las letras minúsculas a-z letrasProposicionales = [chr(x) for x in range(97, 12...
639e410593253471dcafc79f2c012efe4fc7a0f7
BenjaminKamena/pythonadvanced
/Computation+with+NumPy/main.py
2,971
3.953125
4
import numpy as np import matplotlib.pyplot as plt from scipy import misc from PIL import Image #create new ndarray from scatch my_array = np.array([1.1, 9.2, 8.1, 4.7]) #show rows and columns my_array.shape #accessing elements by index print(my_array[2]) #show dimensions of an array my_array.ndim my_array1 = np...
423e63dc94967c21e3b8e6f53d65557a4911ac79
kinjal2110/PythonTutorial
/37_introspection.py
749
3.71875
4
# python in everything is object # object introspection means everything know about object that which class those object is derived # and anything info. which type object. class Employee: def __init__(self, fname, lname): self.fname = fname self.lname = lname self.email = f"{fname}.{lname}@9...
156289934213a7230f1c68a2bd37d4e6a41698f1
mtreviso/university
/Machine Learning/K-Nearest-Neighbors/knn.py
1,853
3.625
4
import numpy as np import scipy.io, math, sys, time from matplotlib import pyplot from utils import Utils from statistics import Statistics from features import Features from reader import Reader from plots import Plots from keras.datasets import cifar10 # http://machinelearningmastery.com/tutorial-to-implement-k-n...
af15139e7fe599db8a6360337e42f241832fea5d
sidneycadot/nexstar
/Coordinates.py
821
3.703125
4
#! /usr/bin/env python3 import math def to_dms(x): sign = (x > 0) - (x < 0) # Python lacks a sign() function. x *= sign # make sure that x is non-negative d = math.floor(x) x = (x - d) * 60.0 m = math.floor(x) x = (x - m) * 60.0 s = x d *= sign # correct sign of the result ret...
36f67efc7b52f48d2ec173d775a3fcdc93b8d500
vvspearlvvs/CodingTest
/2.프로그래머스lv1/문자열_내림차순/solution.py
153
3.671875
4
def solution(s): answer = '' tmp=sorted(list(s),reverse=True) answer = "".join(tmp) return answer print(solution("Zbcdefg")) #"gfedcbZ"
cda9333b4408b96baa766d1203afe2ec8feb9ce0
pooja13196/102
/findingWord.py
452
4.25
4
import os import shutil file_name = input('Enter you file name: ') f = open(file_name) file_lines = f.readlines() found = False search_string = input('Enter the word you want to search: ') for lines in file_lines: print(lines) words = lines.split() for word in words: if(word == sear...
533b2b48101e62c5bf8f6d66f6f5b90afba1de6f
AnthonyFloyd/2015-AdventOfCode-Python
/day08.py
12,034
3.84375
4
# Day 8 # 2015-12-07 # # Matchsticks # def countCharacters(totalString, debug=False): ''' Counts characters in given string, counting the number of characters in the literal string, in memory, and if the string were to be encoded. ''' # convert the string to a list totalStrin...
c1d5f5e5998d51d9b7806dda45ac3c59692dd9dd
patterson-dtaylor/python_work
/Chapter_6/favorite_number.py
444
4.34375
4
# 10/6/19 Exercise 6-2: Using a dictionary to poll people's fav number. favorite_numbers = { 'carrie': ['12', '4'], 'scout': ['11', '21'], 'emaline': ['3', '12'], 'taylor': ['33', '11'], 'nikki': ['69', '99'], } # 10/7/19 Exercise 6-10: Using a list in a dictionary. for name, numbers in favorite_nu...
90d91ed5fa7c45c509f5635ba7d85a2f066dcfe1
daniel-reich/ubiquitous-fiesta
/KcnQtNoX5uC6PzpEF_6.py
335
3.640625
4
import itertools from itertools import combinations ​ def check_sum(lst, n): ​ Duets = list(combinations(lst,2)) Counter = 0 Length = len(Duets) while (Counter < Length): Pair = Duets[Counter] Total = sum(Pair) if (Total == n): return True else: Counter += 1 ret...
941c9f44f14d8db9ca0ecc334b9a516eb5544c29
SanjithMohanan/Game
/Puzzle.py
10,150
4.28125
4
#I ran this code using Python 3.6 in PyCharm #How to run the code # Compile the code # Run the code # Give initial state and goal state respectively as input # examaple: """ Enter the initial state :: 1,0,3,8,2,4,7,6,5 Enter the goal state :: 1,2,3,8,0,4,7,6,5 <built-in function input> Input state :: 1 0 3 8...
d153a3d97cbe94a091a73ced8ac641390a1339d9
Anshuman-Chiranjib/heads-or-tails
/BM .PY
457
4.125
4
from random import randint num = input('Number of times to flip coin: ') num = int(num) flips = [randint(0,1) for r in range(num)] results = [] for object in flips: if object == 0: results.append('Heads') elif object == 1: results.append('Tails') print (results) # IT W...
bf4b4ea77822c54bece715de3f1ad3974d0fba97
mattheww22/COOP2018
/Chapter07/U07_Ex11_LeapYr.py
1,358
4.28125
4
""" U07_Ex11_LeapYr.py Author: Matthew Wiggans Course: Coding for OOP Section: A2 Date: 2019-02-21 IDE: PyCharm Assignment Info Exercise: 11 Source: Python Programming Chapter: 07 Program Description This problem computes whether the year entered was a leap year. Algorithm Print int...
e7fe8ffa16f0c95d77d5949aa4b352a1646dfb3b
AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges
/Challenges/trappingRainWater.py
1,647
4.03125
4
""" Trapping Rain Water Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trappe...
67c16be359e48c150b89f3bcb315b9af69794996
levinyi/scripts
/python_tricks/pytricks_dict_if.py
812
4.21875
4
# Because python has first-class functions they can # be used to emulate switch/case statement. def dispatch_if(operator, x, y): """docstring for dispatch_if""" if operator == 'add': return x + y elif operator == 'sub': return x - y elif operator == 'mul': return x * y ...
807d1766069218f99b86e2555db266df3c5fcde9
marcosfsoares/INTRO-COMPUTER-SCIENCE-WITH-PYTHON
/63_maiusculas_frase.py
320
4
4
def maiusculas(frase): ''' Recebe uma frase como parâmetro e devolve uma string com letras maiúsculas que existem na frase, na ordem em que elas aparecem''' retorno = "" for caracter in frase: if ord("A")<= ord(caracter)<= ord("Z"): retorno += caracter return retorno
88fd9b3255161daccb913dc25f44d07e3d811e99
lucasgarciabertaina/hackerrank-python3
/set/mutations.py
737
3.640625
4
# https://www.hackerrank.com/challenges/py-set-mutations/problem?h_r=next-challenge&h_v=zen def setOperation(a_list, n_list, operation): if operation == 'update': a_list.update(n_list) elif operation == 'intersection_update': a_list.intersection_update(n_list) elif operation == 'difference_u...
86f1a4590815515cbe2f2ffdf4d43e6072c2dab2
SlavXX/w3Python
/04.numbers.py
1,915
4.5625
5
#Python Numbers """ There are three numeric types in Python: """ int float complex """ Variables of numeric types are created when you assign a value to them: """ #Example x = 1 # int y = 2.8 # float z = 1j # complex """ To verify the type of any object in Python, use the type() function: """ #Example print(typ...
8278fc8d96206bc8bb48545d1c1045a230868fb0
ZeeshanSameed/1stWeek
/python/word_search.py
271
3.90625
4
from PyDictionary import PyDictionary search = input("Enter a word:") try: myDict = PyDictionary(search) print("Meanng") meaning = myDict.getMeanings() print("Synonym") print(myDict.getSynonyms()) except: print("Not a legal word")
1b47d1690294b5a96f60b4a2540ff898c7e7932f
tiaotiao/leetcode
/218-the-skyline-problem.py
4,294
3.640625
4
import heapq class PriorityQueue: def __init__(self): self._queue = [] self._index class Solution: def getSkyline(self, buildings): pass lines = [] #List[(pos, height, id, isStart)] for i in range(len(buildings)): left, right, height = buildings[i] ...
9d3981bd48dfed8402146c156b65c526b37e8284
olamug/kurs_python
/06_lesson(28_10)/06_credit_cards/06_cards.py
1,889
3.84375
4
def is_visa(is_card, number): if not is_card: # wcześniej if is_card == False: return False if len(number) == 16 or len(number) == 13: if number[0] == '4': return True def is_mastercard(is_card, number): if not is_card: return False if is_card and len(number) == 16:...
f085dd0f0b9a3fad3f58c11f642306b5f20af8fa
Frendy222/Assignment-vero-
/Assignment 1 driving simulator.py
611
3.734375
4
t = int(input('Time spend on road :'))+1 a = int(input('Acceleration :')) d = int(input('Distance :')) speedlimit = 60 iv = 0 v = 0 s = 0 for i in range (t) : v = iv*a s = a/2*iv*iv star=s/10 print('Duration:',i,'Distance:','*'*int(star)) iv+=1 if (v>speedlimit): print('\nThis person went over ...
d611898493757cbd4bf0028414fc77e64e681ecc
Ryrden/Projetos-em-Python
/Algoritmo-RSA/Bloco-Decodificado-Em-Texto.py
867
3.546875
4
import os bloco = [] texto = [] frase = [] bloco.append(int(input("Digite o primeiro bloco codificado: "))) while bloco[-1] != 0: os.system("cls") print("Caso não queira Digitar mais nenhum bloco, digite 0\n") print("Blocos Digitados até o momento: -> ", end="") for x in range(len(bloco)): pr...
5ef1a0c929c931daa68a94b2b5b6c88b2a19f63e
viz06/python_codes
/rearrange_set2.py
675
3.53125
4
def rearrange(arr,n): min_index=0 max_index=n-1 max_elm=arr[n-1]+1 for i in range(0,n): if(i%2==0): arr[i]+=(arr[max_index]%max_elm)*max_elm max_index-=1 else: arr[i]+=(arr[min_index]%max_elm)*max_elm min_index+=1 for i in ra...
dd40c1e1f65d3f32fc092f43632052074b96806c
tyler-patton44/CodingDojo-Sept-Dec-2018
/Python/python_fundamentals/intermediate1.py
166
3.515625
4
import random def radInt(min=50, max=100): x = random.random()*max while x < min: x = random.random()*max x = int(x) print(x) radInt(50,500)
572960476db9cb5ef790c0db6b57eaa43e731c08
cyrsis/TensorflowPY36CPU
/_1_PythonBasic/_5_FunctionalApproach/Calculator.py
615
4.28125
4
OPERATORS = "+", "-", "*", "/" def f_calculate(number1, operator, number2): return number1 + number2 if operator == "+" \ else number1 - number2 if operator == "-" \ else number1 * number2 if operator == "*" \ else number1 / number2 if operator == "/" \ else None def f_get_number(): return i...
bf43167f2a4c3b759d0c4e801f8c7ae7875fa6b4
bobmayuze/RPI_Education_Material
/CSCI_1100/Week_7/HW_4/hw4Files/hw4Part1.py
1,352
3.96875
4
# Author: Yuze Bob Ma # Date: Oct, 7th, 2016 # This code is written for RPI_CSCI_1100 HW4 Part 1 # Import modules import sys # define functions def is_alternating(word): word_test = word.lower() length = len(word) word_l = list(word_test) vowels = ['a', 'e', 'i', 'o', 'u'] # test the length if length < 8: ...
4c6d30440bbab9d597de4045aa9ea52425f1ebd0
akankaku1998/Turtle-Random-Walk
/main.py
578
3.609375
4
import turtle as t import random tim = t.Turtle() # colours = ["CornflowerBlue", "DarkOrchid", "IndianRed", "DeepSkyBlue", "LightSeaGreen", "wheat", "SlateGray", "SeaGreen"] t.colormode(255) def random_color(): r = random.randint(0, 255) g = random.randint(0, 255) b = random.randint(0, 255) return tim.pencol...
b71416d8a6e0362822fa33a7b9c9ac40e4a9e27a
liushuangfromwh/python
/py5/chapter4/py5.4.6_operator.py
523
3.8125
4
# 运算符 # == # is 比较地址值(比较同一性) x = y = [1, 2, 3] z = [1, 2, 3] print(x == y) # True print(x == z) # True print(x is z) # False # in # 字符串和序列比较 : 字符串可以按照字母顺序排列进行比较 print('alpha' < 'beta') # True # and 类似于 java&& 已结包含了短路. number = 11 # if number > 10 and number < 20: if 10 < number < 20: print(number) # 断言 asser...
6784ebdad8e3275931b7b1c62601e90eea0a2a69
Valery-Bolshakov/learning
/theory/lesson_26.py
3,852
3.578125
4
print('Пользовательские функции. Часть 1\n') ''' Последовательность инструкций, возвращающая некое значение. В функцию могут быть переданы ноль и более аргументов, которые могут использоваться в теле функции. Для возврата значения из функции используется инструкция return. Допускается использование нескольки...
996ca72cb7c2ad8481d096a1ad2de4c73e00a323
JakubCzerny/02443-stochastic-simulation
/sim_event_handler.py
7,723
3.671875
4
import matplotlib.pyplot as plt import pandas as pd import numpy as np class SimEventHandler: """ A simulation handler allows you to add additional behavior to the base simulation, e.g. to collect statistics or modify car behavior. It contains a bunch of methods that are called by the simulation at ...
e412602003ad88e2608b666ef86266bd1708e085
chichutschang/6.00.1x-1T2014
/Week 4/ProblemSet4/ProblemSet4/Problem Set 4 Computer Chooses a Word.py
4,549
3.75
4
# 6.00x Problem Set 4A Template # # The 6.00 Word Game # Created by: Kevin Luu <luuk> and Jenna Wiens <jwiens> # Modified by: Sarina Canelake <sarina> # import random import string VOWELS = 'aeiou' CONSONANTS = 'bcdfghjklmnpqrstvwxyz' HAND_SIZE = 7 SCRABBLE_LETTER_VALUES = { 'a': 1, 'b': 3, 'c': 3...
82bf64e651d21cfb1c373aefa95f02a86b646345
whatsreal/CIS-120-Assignments
/Guttag Finger Exercises/FE9.py
266
3.8125
4
#Finger Exercise 6 #Chapter 4 Secition 1.1 """Implement a function that meets the specification below. Use a try-except block. """ def sumDigits(s): """Assumes s is a string Returns the sum of the decimal digits in s For example, if s is 'a2b3c' it returns 5"""
cbfd0427d255ac0d03457ce96225de831e2c905d
camilabraatzz/Trabalho1.2
/07.py
640
4.15625
4
# Faça um programa que mostre todos os primos entre 1 e N sendo N um número inteiro fornecido pelo usuário. # O programa deverá mostrar também o número de divisões que ele executou para encontrar os números primos. # Serão avaliados o funcionamento, o estilo e o número de testes (divisões) executados. num = int(input(...
51c5798fab967e98a510bd02042fd6b123d546df
1i0n0/Python-Learning
/practices/lcm.py
825
4.3125
4
#!/usr/bin/python3 # -*- coding: utf-8 -*- # Determine the least common multiple of two positive integer numbers. import sys def lcm(num1, num2): _lcm = max(num1, num2) while True: if _lcm % num1 == 0 and _lcm % num2 == 0: break _lcm += 1 return _lcm if __name__ == "__main...
501ffc427f99c4ddacfdcc867ef90ac9051c274a
gschen/sctu-ds-2020
/1906101019-贾佳/Day0303课后作业/test3.py
1,260
4
4
#第一种方法 class Person(): def __init__(self): self.name = "贾佳" self.age = 19 self.gender = "male" self.class_ = "信管01" self.college = "信息与工程学院" def personInfo(self): return self.name,self.age,self.gender,self.class_,self.college class Student(Person): def __init...
4b05235328ff2e14dfe47ede5c9547cbc3cce746
zhengjiani/pyAlgorithm
/leetcodeDay/May/prac221.py
2,745
3.5625
4
# -*- encoding: utf-8 -*- """ @File : prac221.py @Time : 2020/5/8 8:13 上午 @Author : zhengjiani @Email : 936089353@qq.com @Software: PyCharm """ from typing import List class Solution: """动态规划""" def maximalSquare(self, matrix: List[List[str]]) -> int: if not matrix: return 0 ...
f8c47d41b6ccab3b1c8297e53a9d22bdcb082e20
Bernatovych/DZ_11
/phone_book.py
3,567
3.625
4
from datetime import datetime from collections import UserDict class AddressBook(UserDict): def add_record(self, record): self.data[record.name] = record def iterator(self, n): data_list = list(self.data.values()) while data_list: for i in data_list[:n]: yi...
8e75fa1548e6ef6fc059d53689727a3bbc8a0f2a
pranaymate/PythonExercises
/ex042.py
611
4.09375
4
a = float(input('Type a number to form a Triangle: ')) b = float(input('Type a number to form a Triangle: ')) c = float(input('Type a number to form a Triangle: ')) if (b - c) < a and a < (b + c) and (a - c) < b and b < a + c and (a - b) < c and c < (a + b): if a == b and a == c: print('These three numbers...
dd9eee804fc24593bb24eb65c33088e31f3781f0
dalehuangzihan/vidBarcodeReader
/OpenCV_Tutorials/geometric_shapes_tutorial.py
1,448
3.53125
4
import numpy as np import cv2 #img = cv2.imread('lena.jpg',1) ## Draw image using numpy array (mtx of 0s gives a black image) img = np.zeros([512,512,3], np.uint8) # z-coord = 3 to indicate 3-channel image ''' Top-left-hand corner of image has coordinate (0,0). Bottom-right-hand corner of ia...
ff7623fe38966e4b3d0c91a6340cf583d06376ef
dakshitgm/Specialization-Data-structure-and-Algorithm-Coursera
/algorithmic toolbox/week4_divide_and_conquer/closest2.py
1,084
3.953125
4
#Uses python3 import sys import math from collections import namedtuple point=namedtuple('point', 'x y') def minimum_distance(points): #write your code here n=len(points) if n==1: return float('inf') if n==2: return distance(points[0], points[1]) mid=n//2 d1=minimum_distance(points[0:mid]) d2=minimum_dis...
6cc35c51e504d53853e2ab6e5c0f44bb858959a8
muhammaduamirkhalid/Assignment-1
/Area calculator.py
203
4.125
4
import math b = float(math.pi) a = int(input("Enter the radius of the circle here in meters:")) area = b * a * a print("The area of the circle of radius" + str(a) + " " + "is" + " " + str(area) + "m")
3817250afcb67ab9f46731bb90cd63fb3ef2b70f
quqixun/Hackerrank_Python
/Algorithm/Implementation/grading_students.py
554
3.578125
4
#!/bin/python3 import sys def solve(grades): # Complete this function for i in range(len(grades)): if grades[i] < 38: continue else: mod = grades[i] % 5 multi5 = int(((grades[i] - mod) / 5 + 1) * 5) if multi5 - grades[i] < 3: gra...
e5169e586cab560dd18ca38147523b06ecc46c51
Vuntsova/first-repo-feb-2020-ev
/prework.py
466
3.765625
4
def display_name(user_name): print(user_name) display_name("Emiliya") def print_odd(): for num in range(1, 100): if num % 2 == 0: print(num) print_odd() def max_num_in_list(a_list): print(max(a_list)) alist = [ 1,2,3,4,888] max_num_in_list(alist) def is_leap_year(a_year): if ...
aa7764079381361088cae881afbc7634ce07f204
johnehunt/computationalthinking
/week5/books.py
245
4.15625
4
books = set() user_input = input('please enter name of book: ') while user_input != 'x': books.add(user_input) user_input = input('please enter name of book: ') print('Print books entered:') for book in books: print('Book: ', book)
37c0cd3097bf56c976f141fb34e06efeb9e7de25
victord96/advanced_level_python
/iterators/iterators.py
974
4.09375
4
import time class FiboIter: """Iterator that prints the fibonacci sequence up to a specified number """ def __init__(self, limit): self.limit = limit def __iter__(self): self.n1 = 0 self.n2 = 1 self.counter = 0 self.aux = 0 return self def __...
d925b5c5557ebc641c4c3d1b342a23edaf83b036
reshavcodes/python
/Prime_Game.py
2,520
3.921875
4
''' Prime Game Rax, a school student, was bored at home in the pandemic. He wanted to play but there was no one to play with. He was doing some mathematics questions including prime numbers and thought of creating a game using the same. After a few days of work, he was ready with his game. He wants to play the game wi...
28848e87a7e2f1152bf260c19bd065ab35838ba8
rrebase/algorithms
/d13_coin_change.py
2,178
4
4
# Dynamic programming coin change problem def coin_change(coins, n): """ Returns the minimum amount of coins to get the sum of n. Recursive solution. coins is a tuple or list n is the sum to get """ values = {} # cached results def solve(x): if x < 0: return float...
8ac8dd8ce68d1015c4b1b7ae71a86f8dc9bddf50
saviovincent/DSA
/basic_ds/LinkedList.py
1,990
4.21875
4
# LinkedList Implementation class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None self.current = None def addLast(self, node): if self.head is None: self.head = node ...
1021c28fe92598f2c4799aa873af5ca77eaadb86
MathieuCNC/AdventOfCode2019
/Condition.py
312
4.0625
4
#!/usr/bin/python2.7 # -*-coding:Utf-8 -* print("Hello!") year = input("Saisissez une année pour vérifier si elle est bisextile: ") print(type(year)) if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0): print("L'année ", year, " est bisextile") else: print("L'année ", year, " n'est pas bisextile")
01dbb0092405a78aecf180008520a6a9643797ad
Riotam/competitive-pg-py
/utils.py
1,915
4.03125
4
def get_lines(count: int) -> list: """ get_lines は引数に与えられた値の行数だけ、標準入力を取得する :param count: 取得したい行数 :return input_list: 取得した行数strのlist """ lines = [] for _ in range(count): line = input() lines.append(line) return lines def get_lines_by_first_line() -> list: """ g...
5adc13e1c9ce5526a57e8aa18f3ed16e80e6af5d
Andrew-Zarenberg/Scheduler
/utils.py
1,797
4.09375
4
# Utility functions to handle parsing dates and times # Converts a time string (from data) to an integer. def time_to_int(n): spl = n.split(':') return int(spl[0])*60+int(spl[1]) # Converts a day (from data) to an integer. def days_to_ints(data): days = "MTWRFS" r = [] for x in data: r.ap...
c4aa7e5cedc073199a1ea4139eb586f07ee7e448
dkothari777/pacmanAI
/multiagent/multiAgents.py
12,755
3.5625
4
# multiAgents.py # -------------- # Licensing Information: Please do not distribute or publish solutions to this # project. You are free to use and extend these projects for educational # purposes. The Pacman AI projects were developed at UC Berkeley, primarily by # John DeNero (denero@cs.berkeley.edu) and Dan Klein (k...
ad5db63a06a6274c13120b7a6b36c343b33002f8
bermec/challenges
/re.test.py
507
3.546875
4
import re ''' words = '*-5=3-8*-5' # pick out a neg number preceded by an operator ans = re.findall('([^\d](-\d)[^\d](\d)[^\d](\d))|(^\d](-\d))', words) ans2 = re.findall('[^\d](-\d)|(\d)', words) print(ans) print(ans2) ''' words = '*-5+4-3' ans3 = re.findall('\W(-\d)|(\d)', words) print('ans3: ', ans3) strng = '' f...
104294d02998d058cff093f3accdf43d3b8dc0ea
zhawj159753/PythonEveryday
/0006/frequency.py
597
3.6875
4
# coding = utf-8 import re def read_file(path): f = open(path) return f.read() def get_all_words(string): words = re.findall(r'[a-zA-Z]+\b', string) return words def get_frequent_word(words): word_dic = {} for word in words: if word in word_dic: word_dic[word] += 1 else: word_dic[word] = 1 reverse ...
058b0855068574fab8994ad483dc4fbf9486e2fc
tengr/Algorithms
/LeetCode/303.Range-Sum-Query-Immutable.py
1,069
3.625
4
class NumArray(object): def __init__(self, nums): """ initialize your data structure here. :type nums: List[int] """ self.nums = nums self.sums = [None for x in xrange(len(nums) + 1)] def sumRange(self, i, j): """ sum of elements nums[i..j], inclu...
539cbacc92c44078b6b6852e25807ffc47454c11
iampaavan/Pure_Python
/Exercise-72.py
712
3.640625
4
"""Write a Python program to get a directory listing, sorted by creation date.""" from stat import S_ISREG, ST_CTIME, ST_MODE import os, sys, time # Relative or absolute path to the directory dir_path = sys.argv[1] if len( sys.argv ) == 2 else r'.' # all entries in the directory w/ stats os.chdir('C:\\Users\\...
65c159f0162be7118153d0386c472f799fd134d6
leopoldmiao/PythonDemo
/src/subclassTest.py
2,564
3.546875
4
#coding=utf-8 class InventoryItem(object): def __init__(self, title, description, price, store_id): self.title = title self.description = description self.price = price self.store_id = store_id def __str__(self): return self.title def __eq__(self, other): i...
369b988a796a48aef91baebab6762e8619eacd1f
xettrisomeman/pythonsurvival
/listcompre/conditional_inclu.py
659
4.1875
4
#include positive number only #HARD WAY num_list = [1,-1,2,-2,5,-7] pos_list = [] for i in num_list: if i>0: #include positive numbers only pos_list.append(i) #append each positive number print(pos_list) #print [1,2,5] #EASY WAY #if, else in list comprehension #syntax: [value+1 if value>0 else value+...
8223230f67ae686185f0f011441c83f2b8aed713
SylvainGuieu/path
/api.py
5,009
3.546875
4
import os from .dfpath import fpath,dpath def exists(path): """Test whether a path exists. Returns False for broken symbolic links""" if isinstance(path, (fpath, dpath)): return path.exists() return os.path.exists(path) def splitext(path): """Split the extension from a pathname. ...
93cb5a731b8f5636b42a384e39544db29ca85881
xsl521/Assignment
/Prj01-1.py
357
3.65625
4
import numpy as np def is_prime(a): r=a%np.arange(2,a) return np.all(r!=0) def search(): counter=1;record=(None,None) for i in range(1000,1000000): if is_prime(i): if is_prime(i+2): record=(i,i+2) counter+=1 print('{}:\t{}'.format(count...
8b81d2945fb078808234c72a851d3f777462c476
Huijiny/TIL
/algorithm/kakao/4.py
1,412
3.6875
4
import heapq def change_adj(trap_num, adj): for i in range(len(adj)): if adj[trap_num][i]: adj[trap_num][i], adj[i][trap_num] = adj[i][trap_num], adj[trap_num][i] for i in range(len(adj)): if adj[i][trap_num]: adj[trap_num][i], adj[i][trap_num] = adj[i][trap_num], adj[tr...
512196dcfc9fe61ab8be2ce2e982e7f70231a0dd
Abarthra/Protothon01
/permutations.py
205
3.78125
4
from itertools import permutations def Permutations(string): permList=permutations(string) for perm in permList: print(''.join(perm)) string='Protosem' Permutations(string)
ee27305ea4a56f2e282de366e26592766e239b7b
anuragpatil94/coursera-python
/Lists/lists1.py
290
3.71875
4
#fname = raw_input("Enter file name: ") fh = open("romeo.txt") lst = list() i=0 for line in fh: line.rstrip() x=line.split() for i in range(len(x)): print x[i] if x[i] not in lst: lst.append(x[i]) #lst.append(x[0]) lst.sort() print lst
877415dd41813f7419546597316d485822a58b3c
Ved005/project-euler-solutions
/code/sum_of_a_square_and_a_cube/sol_348.py
831
3.671875
4
# -*- coding: utf-8 -*- ''' File name: code\sum_of_a_square_and_a_cube\sol_348.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #348 :: Sum of a square and a cube # # For more information see: # https://projecteuler.net/problem=348 # Prob...
8a5b8d91457b75159eb3df09f02db3aab7d0ceb1
aishwaryabhalla/mapquest_api
/outputs.py
2,531
3.734375
4
"""implements various outputs as a separate class""" import api_interactions class steps: ''' information about steps taken from api_interactions ''' def output(self, json): ''' prints out steps info ''' print() print("DIRECTIONS:") for line in api_interactions.st...
44b866b67043ed6894734f4cf5d0f44ac669a5c8
MrVeshij/Michael-Dawson
/_Chapter_9_ACTIVE_USE_CLASSES/simple_game.py
520
3.859375
4
import games, random print("Welcome to simple game!\n") again = None while again != 'n': players = [] num = games.ask_number(question = 'How much player play? (2-5): ', low = 2, high = 6) for i in range(num): name = input('Name player: ') score = random.randrange(100) + 1 player = ga...
1d18d32c9a102cf04d770a817b5186c97a9ab33d
s-kyum/Python
/ch05/lambda_exp/lambda_ex4(map).py
306
3.921875
4
#map() - 값을 매핑(맞춰서 계산) li = [1,2,3,4,5] li2 = map(lambda x : x*3, li) #map(함수,자료형) print(list(li2)) print((list(map(lambda x : x*3,li)))) #filter() - 어떤 조건으로 값을 필터링 li3 = filter(lambda x : x <4,li) print(list(li3)) print(list(filter(lambda x : x<4,li)))
0fdade07c2cd2f7202cafbf6a1e17b60c3766bfb
EduardoSantos7/Algorithms4fun
/Cracking_the_coding_interview/Linked list/2.6 Palindrome/solution2.py
607
3.609375
4
# Iterative approach def iterate_and_compare(items): if len(items) == 1: return True mid = len(items) // 2 stack = [] for i in range(mid): stack.append(items[i]) start = mid if not len(items) % 2 else mid + 1 for i in range(start, len(items)): if items[i] != stack.pop...
e5a2f4f647647d8f44293cfbab8eed1f37dfa139
jassler/dailycodingproblems
/problem_002/jassler.py
518
3.53125
4
def with_division(input: list): result = [] product = 1 zeros = 0 for x in input: if x is 0: zeros += 1 else: product *= x if zeros == 0: for x in input: result.append(product / x) elif zeros == 1: for n in input: ...
21117c34ce099935032224aa80560e86a3e4beb0
kotternaj/py-exercises
/dist_slope.py
621
3.9375
4
class Line: def __init__(self, coor1, coor2): self.coor1 = coor1 self.coor2 = coor2 # d is sqrt of (x2-x1)^2 + (y2-y1)^2 def distance(self): return ((self.coor2[0] - self.coor1[0])**2 + (self.coor2[1] - self.coor1[1])**2) **.5 # slope is y2 - y1 / x2 - x1 def slope(self): x...
dcb36d80190c57a56cf9b9617b4950ec0ba39745
ndenefe/python
/MATH_3315/Lecture/examples/feb_3.py
1,824
3.8125
4
#Feb 3, lecture #example: find the smallest integer n such that #1**3 + 2**3 + 3**3 + ... + n**3 < 10**6 #solution 1: use for loop s = 0 for i in range(1, 100): s += i**3 if (s >= 10**6): print('largest n=', i-1) s -= i**3 break #this is an important command t...
26bdb07e3fd53d10c5b0fff8b73b55a940549f8d
renzowesterbeek/phonebook
/phonebook.py
1,151
3.90625
4
# Define lists, dicts, functions etc. f = open('phonedata.txt', 'r') book = eval(f.readline()) menu = ['A - Add a person/number', 'D - Delete a person/number', 'P - Print out phonebook'] # Print functions def printNames(dic): print "Names in book: " for i in sorted(book): print i def printContent(dic): print "P...
f729053d9cd8d2bdcd1d64322d3fdbcc0e4e2ec6
hmc-koala-f17/CTCI-Edition-6-Solutions-in-Python
/Array_Strings/string_permutation.py
471
3.734375
4
# Cracking the Coding interview Problems # find all permutation of the string def permutation(remaining,prefix=""): remaining = list(remaining) if(len(remaining)==1): return list(remaining) else: permutations = [] for i,_ in enumerate(remaining): tmp_set = [] prefix = remaining[i] rem = remaining[0:i...
bd1bde36921395521fa4be79bb89e56859f598dc
Raghu1505/guvi-task
/uber billing.py
1,528
4.28125
4
print("Welcome to uber services!!!") sp= int(input("Enter starting point in km")) #user input for starting point in integer dp= int(input("Enter destination point in km")) #user input for destination point in integer dist=dp-sp #computing total distance print("1.Two wheeler...
08af8e9f93505bf0e1123119d3694cef1f693f7c
lulalulala/leetcode
/1--50/49. Group Anagrams.py
842
3.9375
4
""" Given an array of strings, group anagrams together. Example: Input: ["eat", "tea", "tan", "ate", "nat", "bat"], Output: [ ["ate","eat","tea"], ["nat","tan"], ["bat"] ] """ class Solution: def groupAnagrams(self, strs): """ :type strs: List[str] :rtype: List[List[str]] """ ...
3f68c25a3a368433bdb393c0b516842dfc09d467
MathieuPinger/PythonSpielwiese
/pycourse_chap8_functions.py
1,968
4
4
# -*- coding: utf-8 -*- """ Created on Thu Oct 15 15:13:07 2020 @author: mathieu.pinger """ # Function with optional arguments # '' and none create optional arguments # None acts as a logical False def name_infos(first_name, last_name, middle_name='', age=None): info = {'first': first_name, 'last': l...
e3bd13a1f2265a4736130e0d35a7c7a4bfed29d6
WangXiaoyugg/python-journey
/demo/decorator.py
825
3.765625
4
# 装饰器 import time def decorator(func): def wrapper(*args,**kw): print(time.time()) func(*args,**kw) return wrapper # 装饰器没有改变函数原来的调用方式 # 装饰器利用可变参数,解决参数不一致的问题 # 不知道参数是什么,抽象用 *args,**kw @decorator def f1(func_name): print('this is a function ' + func_name) # f = decorator(f1) # f() ...
ee0f7ff820065c43058b9d2f3ebe0818ae84528a
Letris/Encoding2
/Ceasar Cypher.py
2,251
3.875
4
alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m', 'n','o','p','q','r','s','t','u','v','w','x','y','z'] text = 'move your troops to the designated location' encryption_letter_move = 13 decryption_letter_move = 13 def encrypt(message): encrypted_text = '' for letter in message: ...
5d9338af5b916b7f27bb56cdc6c87db80c1b7fff
Wafflya/python_pract
/brain_games/service.py
1,271
3.703125
4
import random import prompt def ask_question(question): print(f"Question: {question}") answer = prompt.string('Your answer: ') return answer def check_answer(answer, right_answer, name): if answer == right_answer: print("Correct!") return True else: print(f"'{answer}' is...
6d380a1df7357839519d29e23a6cf5397246b135
bksahu/dsa
/dsa/patterns/k_way_merge/k_pairs_with_largest_sum.py
2,098
4.15625
4
""" Given two sorted arrays in descending order, find ‘K’ pairs with the largest sum where each pair consists of numbers from both the arrays. Example 1: Input: L1=[9, 8, 2], L2=[6, 3, 1], K=3 Output: [9, 3], [9, 6], [8, 6] Explanation: These 3 pairs have the largest sum. No other pair has a sum larger than any of t...
ba1ad681208acacd47a6c40fe06f748542687572
trangnth/hoc_python
/Code/Lab/300718/bai2.py
398
4.375
4
# Write a Python program to get a string from a given string where all occurrences of its first char have been changed to '$', except the first char itself. Go to the editor # Sample String : 'restart' # Expected Result : 'resta$t' def convert_str(stri): ch = stri[0] stri = stri.replace(ch, '$') stri = ch + stri[1...
bbbcbcd4c6b6ae894163fdc9b39c96c9297c5ef8
kenji132/AtCoder
/2022/11-05/ABC276/A.py
99
3.5
4
S = list(input()) cnt = 0 ans = -1 for s in S: cnt += 1 if s == "a": ans = cnt print(ans)
fb4b284b16e81054e751fadee879dadd4439c6f4
marcusorefice/-studying-python3
/Exe027.py
320
3.921875
4
'''Desafio 027 Faça um programa que leia o nome completo de uma pessoa, mostrando em seguida o primeiro e o último nome separadamente. Ex.: Ana Maria de Souza Primeiro = Ana Último = Souza''' n = input('Digite seu nome completo: ').strip() m = n.split() print(f'O primeiro nome é: {m[0]} \nO ultimo nome é: {m[-...