blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
ff0a00a84d4f70123af40759e45177c01b39675b
magicleon94/farmaci
/Menu.py
2,743
3.578125
4
import os def clear(): os.system('cls' if os.name=='nt' else 'clear') def getChoice(): while (True): clear() print "---- MENU ----" print "1. Ricerca farmaci per principio attivo" print "2. Ricerca equivalenti ad un farmaco specificandone il nome" print "3. Impostazioni...
9e537cb4ebfd0da0101a1a4d4c44ed5ea79022dd
xhwupup/xhw_project
/64_Minimum Path Sum.py
896
3.640625
4
# 时间:20190510 # Exampole1: # Input: # [ # [1,3,1], # [1,5,1], # [4,2,1] # ] # Output: 7 # Explanation: Because the path 1→3→1→1→1 minimizes the sum. # 难度:Medium(0.5) class Solution: def minPathSum(self, grid: List[List[int]]) -> int: """ :type grid: List[List[int]] :rtype: int ...
0109648e62e7b17582b9c171c9050c19a64ce337
anujkumarthakur/Assignment-Python-Django-Developer-Startxlabs
/question_no_1.py
2,144
4.09375
4
'''QUESTION-1 Write a function which takes two arguments: a list of customers and the number of open cash registers. Each customer is represented by an integer which indicates the amount of time needed to checkout. Assuming that customers are served in their original order, your func...
923c82150361b7f2b74d525278d73f8bd9e95325
AdityaKumar123-aks/tathastu-week-of-code
/Day 2/program1.py
953
4.3125
4
# WRITE A PROGRAM TO CHECK WHETHER INPUT NUMBER IS ODD/EVEN,PRIME,PALINDROME,ARMSTRONG. num=int(input("enter the number you want to check : ")) # TO CHECK EVEN/ODD a = num%2 if a == 0: print("even number") if a != 0: print("odd number") # TO CHECK PRIME if num < 2: print("not a prime number") else: ...
d072eced58d6f874a9305ab2630629f050109670
harshil1903/leetcode
/Math/0168_excel_sheet_column_title.py
639
3.859375
4
# 168. Excel Sheet Column Title # # Source : https://leetcode.com/problems/excel-sheet-column-title/ # # Given an integer columnNumber, return its corresponding column title as it appears in an Excel sheet. # # For example: # A -> 1 # B -> 2 # C -> 3 # ... # Z -> 26 # AA -> 27 # AB -> 28 # ... class Solution: d...
3b6bb8142db8f495ddd70a39096df313cd01a223
yaggul/Programming0
/week2/2List-Problems/sorted_names.py
228
4.09375
4
n=int(input("Please insert number of names: ")) count=1 names=[] while count<=n: name=input("Please insert a name: ") names=names+[name] count+=1 names=sorted(names) print("Sorted names are: ") for name in names: print(name)
a186d087a75b642bf7be296c426f35576c04b0ac
wanga0104/learn
/chapter_1/hello.py
216
3.84375
4
start = int(input('请为《叶问》的电影评分(请输入1-10):')) if start > 10 or start <= 0: print ('数字不能大于10或者小于0') else: print('您为《叶问》的电影打分为',start*'⭐')
b21bf8de43fa044671a84141fde120f3284619d1
kwx4github/facebook-hackercup-problem-sets
/2015/qualifying_round/1.Cooking_the_Books/solutions/sources/6170.Michał
885
3.796875
4
#!/usr/bin/env python import unittest def readints(): return list(map(int, input().strip().split())) def swapped(s, p1, p2): l = list(s) l[p1], l[p2] = l[p2], l[p1] return ''.join(l) def testcase(num): min_num, max_num = num, num num = str(num) for p1, _ in enumerate(num): for p...
f47d104a40c5642b93d586118504fd2e09f7ae2d
AaronRanAn/Python_Programming_MSU
/assignment 4.1.py
335
3.84375
4
def computepay(h, r): if h <= 40: p = r * h else: p = 40 * r + (h - 40) * r * 1.5 return p hrs = raw_input("Enter Hours: ") h = float(hrs) rate = raw_input("Enter Rate Per Hour: ") r = float(rate) if h <= 40: p = h * r else: p = computepay(h, ...
dbe92111cc82700c07cdf243972b26d26feebb24
altro111/Home_work
/Задание 2, Пункт 1.py
544
4.21875
4
# 1. Создать список и заполнить его элементами различных типов данных. Реализовать скрипт проверки типа данных каждого элемента. Использовать функцию type() для проверки типа. Элементы списка можно не запрашивать у пользователя, а указать явно, в программе. my_list = ["abc", 1, 1.1, True, -11] for el in my_list: pr...
e28fb68217079bc0ec94540a8153f462cc81f280
krishnamanchikalapudi/examples.py
/PythonTutor/session-6/HomeWork.py
781
4.375
4
""" Session: 6 Topic: Homework """ a = 21 b = 10 if ( a == b ): print ('a is equal to b') else: print ('a is not equal to b') if ( a != b ): print ('a is not equal to b') else: print ('a is equal to b') if ( a < b ): print ('a is less than b') else: print('a is not less than b') if ( a > b ): ...
abbe16904eb288172898b33b2a1724d07b126f39
jordanlui/DailyCodingProblem
/Prob1.py
672
4.09375
4
# -*- coding: utf-8 -*- """ Created on Sun Jun 10 21:54:00 2018 @author: Jordan Given a list of numbers and a number k, return whether any two numbers from the list add up to k. For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17. Bonus: Can you do this in one pass? Hash table (Python Dict...
f6d0770e01e04ff7d3bcdd1d43041835e84e7ce8
metinsenturk/review-analysis
/src/data/data_builder.py
678
3.640625
4
import json import pandas as pd def create_dataset(from_path, to_path): """ Creates a comma seperated value (CSV) file from JSON file. Handles reviews and status during conversion. from_path: The path to get JSON file for conversion. to_path: The path to place the CSV file. """ with open(f...
ae7a9f1f467034915f105d414f389dec07db0036
mveselov/CodeWars
/katas/kyu_6/arabian_string.py
155
3.625
4
from re import split def camelize(string): return ''.join(a.capitalize() for a in split('([^a-zA-Z0-9])', string) if a.isalnum())
bf4028f5d624fd9d8d30e327562d9447b89d18ff
wenxingjiang/MIT6_0001F16
/MIT60001 HW PS1.py
1,760
3.734375
4
##Problem set 0 import math def homework_0(): x = int(input("input value for x")) y = int(input("input value for y")) z1 = x**y z2 = math.log(x,10) print('Enter number x:', x) print('Enter number y:', y) print('x**y = ', z1) print('log(x) = ', z2) homework_0() ##Problem s...
85bf5d7f7fc5a470a870703dc2e35e1d78df01ab
Vinicius-Reinert/PythonLearning
/variaveis .py
341
3.828125
4
x = 20 y = 50 print(x) print(y) soma = x + y print("soma: {}".format(soma)) subtracao = x- y print("subtracao: {}".format(subtracao)) multiplicacao = x * y print("multiplicacao: {}".format(multiplicacao)) divisao = x / y print("divisao: {}".format(divisao)) potencia = x**2 print("potencia: {}"....
dfbb229e443f4ded326ae4e1a294357cc177c963
mtakanen/tiny-etl
/test/test_queries.py
2,104
3.65625
4
import sqlite3 DB_FILENAME = 'db/tiny_etl.db' def game_gender_ratio(): print('Gender ratio in each game:') sql = '''select game, cast(sum(case when gender = 'female' then 1 else 0 end) as float)/count(*) as female_ratio, cast(sum(case when gender = 'male' then 1 else 0 ...
81d228264f2c454d22dbb1ab63eb844fd86cbe34
JaehoonKang/Computer_Science_110_Python
/FinalProject/Pers_test.py
3,206
3.65625
4
from tkinter import * class GUI: global points points = 0 def __init__(self): self.__window = Tk() self.__label = Label(self.__window, text = "Question 1") self.__label.grid(columnspan = 3) #self.__entry.config("<Return>", self.action) self.__button1 = Button(self.__window) self.__...
d0af5fd66c6960be4c0db52efef84edcaf579b9f
theboocock/python_introduction
/lesson/boiler_plate.py
854
4.5
4
#!/usr/bin/env python # # @date 25 Sept 2015 # @author james Boocock # import argparse def print_file(input_file): """ Function opens a file and prints the results to stdout. @param input_file """ with open(input_file) as f: for line in f: print line def mai...
06e9bcd7f3e63b94ca5e1f7ccbe2c058a83fde64
jonad/udacity_aipnd_mentorship
/myscript.py
288
3.703125
4
def greetings(name): ''' Say hello to someone :param name: name of the person :return: ''' print(f'Hello {name}!') def add(x, y): ''' Add two integer :param x: first integer :param y: second integer :return: ''' return x + y
241097457c81609be674b349aa293218d516734f
mietINFO/feedbackBot
/db.py
3,080
3.96875
4
# -*- coding: utf-8 -*- import sqlite3 class DataBase: def __init__(self, db_path, db_file): self.db_file = db_path + db_file self.db = None def create_db(self): """ Создание необходимых таблиц для работы с ботом """ self.db = sqlite3.connect(self.db_file) ...
c4e9c3faddee78bae52949a55fe0c53702c37743
nuria/study
/EPI/string_dictionary.py
1,891
3.875
4
#!/usr/lib """ You are given a dictionary of words and a large input string. You have to find out whether the input string can be completely segmented into the words of a given dictionary. dictionary = ['apple', 'apple', 'pear', 'pie'] string ="applepie' =>Y string =applepeer=>no this is called word break on let code ...
f7cc4911e72d857cfe9bf6b6d65f339a3adf6f47
Reena-Kumari20/FunctionQuestions
/more_exercise/question7.py
897
3.75
4
#Socho aapke paas 2 lists hain. Aapne aisa code likhna hain jisse ek nayi list banne # jisme inn dono lists ke woh item hone chaiye ho dono list mein aa rahe hain. # Socho aapki do list yeh hain: #list1 = [1, 342, 75, 23, 98] #list2 = [75, 23, 98, 12, 78, 10, 1] #Inn dono list se aapki nayi list yeh banni chaiye: ...
6088665f00977ed53ad97605266556048012ce80
XiaoqinLI/-Python-Web-Developing-and-Programming-Language
/Building_Web_browser/ProgrammingLanguages_Udacity/List_comp_map.py
692
3.640625
4
## Programming Language Python ## List_Comprehention_map analyzer ## Author: Xiaoqin LI ## Created Date: 03/23/2014 grammar = [ ("exp", ["exp", "+", "exp"]), ("exp", ["exp", "-", "exp"]), ("exp", ["(", "exp", ")"]), ("exp", ["num"]), ] def expand(tokens, grammar): for pos in range(len(tokens)...
eba12bef29d577a7d5a276697963da757d0463b7
UnSi/2_GeekBrains_courses_algorithms
/Lesson 3/hw/task3.py
686
4.03125
4
# 3. В массиве случайных целых чисел поменять местами минимальный и максимальный элементы. from random import randint rand_array = [randint(1, 100) for _ in range(100)] min_el = max_el = rand_array[0] min_idx = max_idx = 0 for i, num in enumerate(rand_array): if num > max_el: max_el, max_idx = num, i ...
bdd71107a665c61d34660bd7be19e8d2d9d042ee
adampower48/codeforces
/Chat Room.py
201
3.765625
4
hello = "hello" word = input() index = 0 for letter in word: if letter == hello[index]: if index == 4: print("YES") break index += 1 else: print("NO")
5ef621350a817e0e3ab644085d7204824e095469
VivianaMontacost/ProyectoBancoEAN
/BancoEAN.py
5,292
4.09375
4
""" Juandabu """ persona= ['clark kent', 'Bruce Wane' ] usuario= ['superman' , 'batman' ] contraseña= [1111 , 2222 ] numero_de_cuenta= [ 3115996681 , 32221822 ] tipo_de_cuenta= [ 'corriente', 'ahorros' ] dinero= ...
085177c3192c6ac4f13f07826c64222f6e86e220
c-maragh/blackjack
/Blackjack.py
4,948
3.59375
4
# blackjack import random suits = ('Hearts', 'Diamonds', 'Clubs', 'Spades') ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace') values = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8, 'Nine':9, 'Ten':10, 'Jack':10, 'Queen':10, '...
3ecf2fe80d4b46dfe585690ced9a4ccd3503c2c4
s-passalacqua-iresm/AlgoritmosyEstructuraDatos1
/Actividad 1- Decisión simple/ACTIVITY 1- EX 1.py
305
3.96875
4
#Algotimo que lea entero y verifique sea mayor a 10. #Si lo es, escribir el número, si no, mensaje que diga que es menor o igual numeroentero=int(input("Ingrese un número entero: ")) if int(numeroentero) >10: print(f"{numeroentero}") else: print(f"El número ingresado es menor o igual a 10")
d626aa2c9f60825cc273e3f91d20c9a7b0cb9c9b
AFLANSODEV/MetaLex
/dicOcrText/wordsCorrection.py
4,508
3.546875
4
#! usr/bin/env python # coding: utf8 """ Implémentation des outils de correction orthographique. Usage: >>> from MetaLex.wordsCorrection import * >>> correctWord(word) """ # ----Internal Modules------------------------------------------------------ import MetaLex # ----External Modules----...
26a8d753caec82fc78e8087396eeebd01b7e072c
voyager1684/Basic-Physics
/CentripetalAcceleration.py
1,862
4.28125
4
print("\nSet the friction coefficient, mass of the object and the radius of the corner.\n") # Prints the protocol. key = int(input("Press 1 to check the speed. \nPress 2 to get the technical information. \nPress 0 to exit.\n")) if key == 0: exit() µ = float(input("Enter µ, the constant of static friction: ")) m...
f231d571cc9898da801e17f8476653c99727a9a1
IanRivas/python-ejercicios
/tp2-Listas/7.py
646
4.34375
4
''' 7. Intercalar los elementos de una lista entre los elementos de otra. La intercalación deberá realizarse exclusivamente mediante la técnica de rebanadas y no se creará una lista nueva sino que se modificará la primera. Por ejemplo, si lista1 = [8, 1, 3] y lista2 = [5, 9, 7], lista 1 deberá quedar como [8, 5, 1, 9...
cc6fcf9f15861328fb0dd2504e2b9f6cc3bf63c3
pradeep1412/Coursera-Algorithmic-Toolbox
/week2_algorithmic_warmup/lcm.py
370
3.609375
4
# Uses python3 import sys import time def gcd(a, b): if a < b: temp = a a = b b = temp while b != 0: temp = a % b a = b b = temp if a == 0 and b == 0: a = 1 return a if __name__ == '__main__': a, b = map(int, input().split()) print((a *...
a5b08cbd86cae62c07cc6489d31bced424dbf6b0
isaacdelarosamendez/CursoPythonAbril2019
/Clase_04_05_2019/persona.py
431
3.5
4
class Persona: def __init__(self,estatura, peso,tes): self.estatura = estatura self.peso = peso self.tes = tes def Pesar(self): print("Peso "+str(self.peso)) class Hombre(Persona): def __init__(self,estatura,peso, nombre): self.nombre = nombre Persona.__init__(self,estatura,peso) def Descripcion(self)...
b057fc8b1c35f94fd19b70ea86c0fe05901c21a0
KevinLAnthony/learn_python_the_hard_way
/ex20/ex20.2.py
1,974
4.3125
4
#import the argv module / library from sys import argv #hold arguments in argv module. Also, consider that script and filename are being declared as #variables and are each being set to the argv module script, input_file = argv #create function and add parameter(s). def print_all(f): #run print() function using valu...
2d93353c50743f5009df79f68123d9f72bbe22ef
Sleeither1234/t0_7_huatay.chunga
/huatay/bucle_para_02.py
242
3.734375
4
#tabla de multiplicar import os #Asignacion de valores numero=int(os.sys.argv[1]) valor=range(1,13) #bucle para for elemento in valor: producto=numero*elemento print(numero,"x",elemento,"=",producto) #fin_for print("fin del bubcle")
41154e5ebc6e43884cafeb9931375b474374cda5
submarrin/numerical_methods_Cauchy_problem
/main.py
2,537
3.875
4
import math import numpy as np import matplotlib.pyplot as plt from matplotlib import mlab # начальные условия n = int(input('Введите число отрезков n = ')) x0 = 0 y0 = 0.1 xn = 1 h = (xn-x0)/n x_list = np.linspace(0, 1, n + 1) # n отрезков, следовательно n + 1 точка print(x_list) def func(x, y)...
28e02b18cdaa0e4a1667ca4219bc21bf14b9be83
rudrasingh21/Spark-2-Applications-
/PySpark Basic Spark SQL Operations JANANI RAVI.py
4,051
3.8125
4
---------------------------------- Querying Data Using Spark SQL : Demo: Basic Spark SQL Operations:- Janani Ravi ---------------------------------- >>> from pyspark.sql.types import Row from datetime import datetime ##### Creating a dataframe with different data types record = sc.parallelize([Row(id = 1, ...
e3cca4a15af61ffd345322fa017c89c966381b89
jbro885/gigatron
/data/convert.py
857
3.765625
4
import argparse def main(): parser = argparse.ArgumentParser() parser.add_argument("--binary", action="store_true", help="convert to binary") parser.add_argument("filename", type=str, help="the filename to convert") args = parser.parse_args() filena...
4cdd2bd068483d2c8989a639fc02fd75e402811f
camiloprado/Curso-Python
/Aula 21.py
286
3.90625
4
frase = str(input('Digite uma frase: ')).upper().strip() print('A letra "A" aparece no total de {}'.format(frase.count('A'))) print('Sua primeira aparição foi na posição {}'.format(frase.find('A') + 1)) print('Sua ultima aparição foi na posição {}'.format(frase.rfind('A') + 1))
b4a5b022a40baa969e3c9ac74983176d544eb7c7
eileenjang/algorithm-study
/src/sunwoo/source_code/week8/괄호_변환.py
753
3.5
4
def solution(p): if len(p) == 0: return '' left, right = p[0], '' count = 1 if left == '(' else -1 for c in p[1:]: if count == 0: right += c else: count += 1 if c == '(' else -1 left += c if valid(left): return left + solution(right) ...
b567e9fabdb4d55a83788a21e3a2166bcef5386d
yanbinkang/problem-bank
/coderust/arrays/rotate_array_in_place.py
1,004
4.125
4
def rotate_array_in_place(nums, k): """ algorithm: let a= [1,2,3,4,5,6,7] k = 3. 1. we have to first reverse the whole array by swapping first element with the last one and so on.. you will get [7, 6, 5, 4, 3, 2, 1] 2. reverse the elements from 0 to k - 1 reverse the elements 7, 6, 5 ...
9717ad2bf4fbc412980b022dbfa2fb1487f70fb3
Deepakvm18/luminardeepak
/flowcontrols/decisionMaking/largestamong3.py
337
4.15625
4
n1=int(input("ENTER FIRST NUMBER: ")) n2=int(input("ENTER SECOND NUMBER: ")) n3=int(input("ENTER THIRD NUMBER: ")) if (n1>n2)&(n1>n3): print("FIRST NUMBER IS LARGEST") elif (n2>n1)&(n2>n3): print("second number is largest") elif (n3>n1)&(n3>n2): print("third number is largest") else: print("numbers repe...
614a65779ba6014cd58944da58ae13722f014e06
TakahiroSono/atcoder
/practice/python/ABC159/B.py
296
3.703125
4
S = input() N = len(S) def isPalindrome(s): n = len(s) re_s = s[::-1] for i in range(n // 2): if re_s[i] != s[i]: break else: return True return False if isPalindrome(S) and isPalindrome(S[:N // 2]) and isPalindrome(S[(N + 1) // 2:]): print('Yes') else: print('No')
8ae81d05b480e2cc0e1776813012587349c38557
PrestonGetz/ProgrammingAssignments
/A10.py
181
3.578125
4
ans = 0 for i in range (0,500): if(i % 3 == 0 or i % 5 == 0): ans = ans+i print(ans) #ans2 = sum(set(list(range(0,500,3)) + list(range(0,500,5)))) #print(ans2) this is faster
3dd2c78024750c1506039c23eaf1415fc3d785b9
pyupya/code_study
/programmers/sort/biggest_number_lv2.py
823
3.515625
4
def solution(numbers): answer = '' numbers = list(map(str, numbers)) # 숫자를 string으로 변환 --> 사전식 역순으로 정렬하기 위해서 numbers.sort(key = lambda x: x*4, reverse=True) # 문제에서 요구하는 제한사항 중, 원소가 0~ 1000의 수 # 1의 자리 수와 그 이상의 자리 수들을 비교하기 위함 ...
dff8ddb6ad86bd4e05429a92a07beec034c21f58
NikiDimov/SoftUni-Python-Advanced
/error_handling_10_21/email_validator.py
642
3.8125
4
class NameTooShortError(Exception): pass class MustContainAtSymbolError(Exception): pass class InvalidDomainError(Exception): pass mail = input() valid_domains = {"com", "bg", "net", "org"} while not mail == "End": if '@' not in mail: raise MustContainAtSymbolError("Email must contain @") ...
37f2e3de29f728283749c62ae2ea835cc5e0599c
hmoshabbar/PracticeProgramAll
/dictMethod.py
688
4.1875
4
my_dict={"ID":123,"Name":"Moshabbar","Dept":"IT","Salary":12000} # print my_dict.keys() # print my_dict.values() # # # Only Keys output purpose... # for i in my_dict.keys(): # print i # # # Only Values output showing Purpose.... # for j in my_dict.values(): # print j # For Key value output Purpose......
d6b330ec737ee0781fbefe9135e47a3a1671f699
omartorrado/di_ejerciciosRepaso
/Ejercicio8.py
155
3.53125
4
def consonantes(frase): for l in frase: if(l!="a" and l!="e" and l!="i" and l!="o" and l!="u"): print(l) consonantes("logaritmo")
e6187a38cc8f35a52ff323c0330ecbd4ce544a4d
mbaseman1918/testrep
/piglatin.py
806
3.921875
4
import string answer = "yes" while answer.lower() == "yes" or answer.lower() == "y": word = input("Word? ") word_list = list(word) if word[0].lower() not in ["a", "e", "i", "o", "u"]: for i in word: if i not in ["a", "e", "i", "o", "u"]: word_list.append(i) ...
2f4af82e77bdfdb5aeda452321a7c174419af2bb
jjlehner/ML_cw_dec_tree
/source/draw/label.py
2,254
3.671875
4
import typing import matplotlib import numpy from matplotlib.textpath import TextPath from matplotlib.path import Path from matplotlib import patches # Height of all labels rendered, in points _height = 0.5 def label(axes: matplotlib.axes, origin: typing.Tuple[int, int], text: str, colour: ...
714169151a858730b28f2c503f089b53fe602e41
a1774281/UndergraduateCode
/Python/Practicals/Prac 2/prac2exe12.py
690
3.578125
4
# # File: Prac2Exc12.py # Author: Ethan Copeland # Email Id: copey006@mymail.unisa.edu.au # Version: 1.0 16/03/19 # Description: Practical 2, exercise 12. # This is my own work as defined by the University's # Academic Misconduct policy. # temperature = int(input("Please enter the temperature: ")) if temp...
e68cc580c8c3f06c0742f9de9e129cd477fcf33c
4mayet21/COM404
/TCA practice/Q1.py
168
3.78125
4
#asking question and waiting for input print("What Happens when the last petal falls? ") response = input() print("My dear Bella when the last petal falls " + response)
bc0e52f8c19254ae51d68bc18228ad18cb1f4665
cwlseu/Algorithm
/leetcode/sumoftwointeger.py
420
3.78125
4
#!encode=utf-8 """Note: the computer save negative number using code """ def getSum(a, b): """ :type a: int :type b: int :rtype: int """ MAX_INT = 0x7FFFFFFF MIN_INT = 0x80000000 MASK = 0x100000000 while b: a, b = (a ^ b) % MASK, ((a & b) << 1) % MASK #print (a % MIN_INT) ^ MAX_INT return a if a <= MA...
2400fd9095510118252f87557f3aad4912df5ba1
sviridchik/prep_for_isp
/isp/14.py
727
3.8125
4
class Singleton(): data = {} def __new__(cls, *args, **kwargs): name = cls.__name__ if name not in Singleton.data: l = object.__new__(cls) res = [args, kwargs, l] Singleton.data[name] = res return Singleton.data[name][-1] class Person(Singleton): ...
cea532ccff335d6bd32c407d0e9f3af938f836c1
r3do2/LeetCode-Solutions
/cycleLinkedList.py
440
3.765625
4
''' Cycle in a linked LIST head -> NULL id LIST is empty ''' # cheacking for cycle method def has_cycle(head): if (head == None): return False else: slow = head fast = head.next while (slow != fast) : if (fast == None or fast.next == None): retu...
34d1a459d83bb9eb06dd2341aba3ce057351298e
FcoAndre/DI_Bootcamp
/Week7/Day2/Exercise/Exercise.py
1,464
4.25
4
# # Exercise 1 : What Are You Learning ? # def display_message(): # return('I am learning python! =)') # display_message() # # Exercise 2: What’s Your Favorite Book ? # def favorite_book(title) : # print (f"One of my favorite books is {title}”.") # favorite_book("title") # # Exercise 3 : Som...
f13add4fcfa747dce7c79f528ab5ff0b80af15b7
MothishMC/Python
/OOPs/Class_instances.py
2,050
4.25
4
# class --> blueprint # Object --> instance # class data --> Attributes # class function --> methods class Employee: ''' When we Create a method inside a Class ,by default ,it takes the instance as its first argument ''' # Initialize -Similar to constructor def __i...
85e5c239aec663a3f870dbb9cff4df14181bedaa
lipingx/python_code_snippets
/logging_advanced/util.py
661
3.515625
4
import logging def SetLogConfig(log_file_name): # The log file will be in the current directory where you run this main file. logging.basicConfig( level=logging.DEBUG, format='%(asctime)s,%(levelname)-6s [%(filename)s:%(lineno)d] %(message)s', filename=log_file_name, ) # Set up logging to console b...
9863f3802e871464a25689280d7d165654eb0e52
visor517/GeekBrains_python
/lesson3/task5.py
1,583
3.765625
4
# 5. Программа запрашивает у пользователя строку чисел, разделенных пробелом. При нажатии Enter должна выводиться # сумма чисел. Пользователь может продолжить ввод чисел, разделенных пробелом и снова нажать Enter. Сумма вновь # введенных чисел будет добавляться к уже подсчитанной сумме. Но если вместо числа вводится сп...
4a26a686aeac3333fa58088898c39fed9096d6bf
moqi112358/leetcode
/solutions/0387-first-unique-character-in-a-string/first-unique-character-in-a-string.py
532
3.71875
4
# Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1. # # Examples: # # # s = "leetcode" # return 0. # # s = "loveleetcode" # return 2. # # #   # # Note: You may assume the string contains only lowercase English letters. # class Solution: def firstUni...
c9d93620c58543d1b489fb39838502681801382d
Mat4wrk/Data-Types-for-Data-Science-in-Python-Datacamp
/5.Answering Data Science Questions/Find the Months with the Highest Number of Crimes.py
546
4.03125
4
# Import necessary modules from collections import Counter from datetime import datetime # Create a Counter Object: crimes_by_month crimes_by_month = Counter() # Loop over the crime_data list for row in crime_data: # Convert the first element of each item into a Python Datetime Object date = datetime.str...
6043c42ea5c9922a655c443d8ca84b7792ff3c42
farstas/Les1_Reposit
/funk.py
317
3.90625
4
def get_summ(one, two, delimeter=' '): return str(one) + str(delimeter) + str(two) one=input('Введите аргумент 1: ') two=input('Введите аргумент 2: ') delimeter=input('При необходимости введите аргумент 3: ') print(get_summ(one, two, delimeter).upper())
47c8022c2b4ff08d56e1e7c875303f5576ebdc77
philippe-lemaire/katas
/inverse-slicer.py
1,085
4.25
4
''' You're familiar with list slicing in Python and know, for example, that: >>> ages = [12, 14, 63, 72, 55, 24] >>> ages[2:4] [63, 72] >>> ages[2:] [63, 72, 55, 24] >>> ages[:3] [12, 14, 63] write a function inverse_slice() that takes three arguments: a list items, an integer a and an integer b. The function should ...
ad44ffb660be83a772157defd1821c2fc9e16dd8
KaranKendre11/cloudcounselage_intern
/CloudConselage/SOLN/problem8.py
131
3.765625
4
def sum_series(n): s = n; for i in range(2,n,2): s += (n - i) return s; n = int(input()) print(sum_series(n))
c1be1093da2d83bfbbf554dee3b2841987667e2e
santiagocantu98/Multivariate-Linear-Regression
/artificial.py
9,338
4.03125
4
import numpy as np import math import pandas as pd import time """ This Python script was done for the second practical exam of Artificial Intelligence class, the exam consists of creating functions in order to train the algorithmn so it can find the optimal w0 and w1 of the data set Author: San...
70cba8735fb8bdca4c57e137769305000a31ded3
Willy-C/AdventOfCode2019
/day3/day3.py
1,117
3.546875
4
with open('input.txt', 'r') as f: wires = [[(path[0], int(path[1:])) for path in wire.split(',')] for wire in f.readlines()] def get_coords(wire) -> list: x, y = 0, 0 coords = [] for step in wire: for _ in range(step[1]): if step[0] == 'U': y += 1 elif s...
4b9d8db6035698c814d61062da11ad338d2ddca8
Cameron-Calpin/Code
/Python - learning/test.py
1,234
3.609375
4
theIndex = {} # def addword(word, pagenumber): # if theIndex.has_key(word): # theIndex[word].append(pagenumber) # else: # theIndex[word] = [pagenumber] def addword2(word, pagenumber): try: theIndex[word].append(pagenumber) except AttributeError: theIndex[word] = [pagenumber] def addword3(word, pagenumber)...
946d59849eda610436aca175263e5f044b4de6eb
samuelrslz/cse210-tc04
/game/thrower.py
1,853
4.3125
4
import random class Thrower: """A code template for a person who throws a card. The responsibility of this class of objects is to throw the card, keep track of the value, the score and determine whether or not it can throw again. Attributes: card (int): An int between 1 and 13. """ ...
35750c7861871845d9b095b4e9c1d8be0bc50471
yossizap/UV-Bicycle
/src/infra/lib/display/graphics/text2bitmap.py
2,241
3.59375
4
''' Description: Converts a given text to a BMP file Requirements: Pillow ''' import PIL import PIL.Image import PIL.ImageFont import PIL.ImageOps import PIL.ImageDraw from optparse import OptionParser PIL_GREYSCALE = "L" DEFAULT_FONT = "arial.ttf" DEFAULT_FONT_SIZE = 10 def points_to_pixels(points): """ Con...
a094cdfc2bf05ff2c65d8100078bdfce8549a429
Abhijith-1997/pythonprojects
/object oriented/constructor/student.py
401
3.71875
4
class Student: def __init__(self,name,rollno,course): self.name=name self.rollno=rollno self.course=course def printval(self): print("name of student",self.name) print("rollno",self.rollno) print("course",self.course) def __str__(self): return self.nam...
d6e651e7a3c63bc5baeebdc20acd200dacb1eae5
seObando19/holbertonschool-higher_level_programming
/0x02-python-import_modules/3-infinite_add.py
259
3.578125
4
#!/usr/bin/python3 if __name__ == "__main__": import sys argv = sys.argv size = len(argv) acum = 0 if size == 1: print(0) else: for i in range(1, size): acum += int(argv[i]) print("{}".format(acum))
b7927011b27caf819fc1b43a2d4ad72051dfad12
handsome-fish/tips-python
/element_frequency.py
511
3.8125
4
# 统计列表中元素的频率 # 直接调用collections中的Counter类来统计元素的数量 # 也可以自己来实现这样的统计 # 但是从简洁性来讲,还是以Counter的使用比较方便 # 方法一 from collections import Counter lst = [2, 1, '3', 3, 3, 2, 3, 1, 5, 6] count = Counter(lst) print(count) print(count[2]) print(count.most_common(2)) # 方法二 dic = {} for i in lst: if i in dic: dic[i] += 1 ...
a960381442fd4a5551709cb3e1c22c31adf932be
sudacake/War_of_Aircraft
/War_of_Aircraft/player.py
1,697
3.5
4
import pygame class Player(): def __init__(self, screen, game_settings): """初始化玩家并设置其初始位置""" self.screen = screen #获取游戏设置 self.game_settings = game_settings #加载飞船图像并获取其外接矩形 self.image = pygame.image.load('images/player.png') self.rect = self.image.get_rect(...
9a74757c3f83a0e9caec875304e935bd71d0910c
echo9527git/haige_selenium
/test_javascript_demo.py
1,949
3.6875
4
''' WebDriver有两个方法来执行JavaScript来使页面滚动: execute_script:同步执行 execute_async_script:异步执行 ''' ''' JavaScript滚动页面及点击事件API: 1、滚动到文档中的某个坐标 window.scrollTo(x-coord,y-coord ) window.scrollTo(options) ·x-coord 是文档中的横轴坐标。 ·y-coord 是文档中的纵轴坐标。 ·options 是一个包含三个属性的对象: ·top 等同于 y-coord ...
1f8a4a5306953435ae7fd52afe33b79378d2520b
fjh1997/Learn-Python
/analysis/pydata_book
752
3.703125
4
#!/usr/bin/python import json from collections import Counter def get_count(sequence): counts = {} for x in sequence: if x in counts: counts[x] += 1 else: counts[x] = 1 return counts def top_counts(count_dict, n=10): value_key_pairs = [(count, tz) for tz, co...
fef22469e1d323fce3db7e05a05e3a23632c6545
a8346517/ML100days
/homework/Day9.py
1,124
4.09375
4
#HW1 請建立類似提供結果的 DataFrame # Apples Bananas # 0 30 21 import pandas as pd df = pd.DataFrame({'Apples': [30] , 'Bananas' : [21] }) print(df) # Apples Bananas # 2017 Sales 35 21 # 2018 Sales 41 34 df = pd.DataFrame({'Apples': [35,41] , ...
8cf717197f2401ad4e314f85b1d57ffe8b28d336
CODE-Lab-IASTATE/MDO_course
/04_programming_with_scipy/newton_conjugate_gradient.py
1,066
3.875
4
#Tutorials for optimization in python #2D #Newton Conjugate gradient #This is a modified Newton algorithm that uses the CG algorithm to approx invert the local hessian #Requires both the gradient and hessian information #Import libraries from scipy import optimize import numpy as np #Objective function def f(x): # ...
51e9fd840a7ca2bc35347597cf6a5ea572d7aa78
Gendo90/HackerRank
/Strings/matchingStrings.py
816
3.625
4
#!/bin/python3 import math import os import random import re import sys # Complete the matchingStrings function below. # NOTE: Not optimized, could probably run faster if each string is placed # in a hash map and counted, and then see which queries match strings in the # hash map for O(n) running time, but O(n) space...
47ae3be952025c5473fad5229ef23c5cb2423d75
Vigyrious/python_fundamentals
/Dictionaries-Lab/Odd-Occurrences.py
257
3.609375
4
elements = input().split(" ") diction = {} for word in elements: lower = word.lower() if lower not in diction: diction[lower] = 0 diction[lower] += 1 for (key, value) in diction.items(): if value % 2 != 0: print(key, end=" ")
dcf083614a98c7b49d8914eba9c9491179900315
daveh19/foxy-predictor
/Python_Gui/examples/ex_buttons_frames.py
838
4.125
4
from tkinter import * root = Tk() #myLabel = Label(root, text = 'text and stuff') #myLabel.pack() #upper half of window topFrame = Frame(root) topFrame.pack() #lower half of window bottomFrame = Frame(root) bottomFrame.pack(side = BOTTOM) #create buttons in topFrame button1 = Button(topFrame, text = 'Button1', fg =...
3a0d5a79d3e80f57c2d9f953e6cf0e35aded4853
ksreddy1980/test
/General/Fibnoic.py
397
4.15625
4
n = int(input("enter the value:")) if(n <=0): n = int(input("enter the value that greater than Zero:")) def fib(n): first = 1 second = 1 if(n <=2): return 1 else: for i in range(n-2): current = first + second first = second second = current ...
fa3fc58ba206c45902da1766b2d024aea87636a4
detel/Miscellaneous
/Mind == Blown.py
338
3.53125
4
""" Raghav Passi(@grebnesieh)'s solution """ def move(A, B, C): #print "A = %s B = %s C = %s"%(A,B,C) if not A and not B: if C == S: count[0] += 1 distinct.add(C) else: if A: move(A[1:], B + A[0], C) if B: move(A, B[:-1], C + B[-1]) S, distinct, count = raw_input(), set(),[0] move(S, "", "") print ...
f1621328203f355f6ba236bd40e53e73a32931e6
FriendedCarrot4z/Final-Project-CSE-212
/QueueMusicProblem.py
2,908
3.515625
4
import pygame from pygame import mixer pygame.mixer.init() class Priority_Queue: class Node: def __init__(self, song, priority): self.song = song self.priority = priority def __str__(self): return "{} {}".format(self.song, self.priority) def __init__(self)...
66635f92a5357ddc553795796026d7cc56186921
jinurajan/Datastructures
/LeetCode/mock_interviews/next_permutation.py
1,365
4.1875
4
""" Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. If such an arrangement is not possible, it must rearrange it as the lowest possible order (i.e., sorted in ascending order). The replacement must be in place and use only constant extra memory Inp...
f47492080834d35eb46a797c3dbca6d770b4fc41
AmritaDeb/Automation_Repo
/PythonBasics/py_programas/Generic/printList.py
54
3.59375
4
n=[1,2,3,4,5] A=[i for i in range(1,6)] print(list(A))
58173560c190f8c317f2e0211f22ce41eb849767
lubyliao/cs305
/HTMLgen/htmlgen.py
5,789
3.546875
4
""" Factor generic code from subclasses such as Href, Table, etc into a superclass to achieves code reuse and avoid code duplication. """ class HTMLElement: def __init__(self, **kw): for attr in kw: try: getattr(self, attr) setattr(self, attr, kw[attr]) ...
9536eae63d56d960f43e8ef6c8386883a4e9cf08
cmu-db/noisepage
/script/self_driving/modeling/data/data_util.py
592
3.921875
4
def convert_string_to_numeric(value): """Break up a string that contains ";" to a list of values :param value: the raw string :return: a list of int/float values """ if ';' in value: return list(map(convert_string_to_numeric, value.split(';'))) try: return int(value) finall...
2efaaf8f615e333f67526fb3a04f8a7a66e921b4
alrahmanak/python_bgn
/matplot1.py
120
3.5625
4
import matplotlib.pyplot as plt # matplot lib Pyplot tutorial plt.plot([1,2,3,4]) plt.ylabel('some numbers') plt.show()
d7e350f56360448abe18b02748b00f0c40cf4d20
17602515236/Python_exercise
/test.py
1,021
3.765625
4
""" name2 = ['old_driver', 'rain_jack', ['old_boy', 'old_girl'], 'shanshan', 'peiqi', 'alex', 'black_girl', 1, 2, 3, 4, 2, 5, 6, 2] print(name2) index_2 = name2.index(2) print(index_2) index_22 = name2.index(2,index_2 + 1) print(index_22) for i in name2: n = name2.index(i) if n%2 == 0: name2[n]=-1 ...
0a2d8675e5241667bbb9c7c60713c4cff61551a9
ZaatarX/time-calculator
/time_calculator.py
2,686
3.8125
4
def add_time(start, duration, day=None): hours = [] minutes = [] if day: day = str(day) weekdays = { 0: 'Sunday', 1: 'Monday', 2: 'Tuesday', 3: 'Wednesday', 4: 'Thursday', 5: 'Friday', 6: 'Saturday' }...
1b16e1a96de8c7b648c53a4981c71c3e0eceb3c5
kettu-metsanen/python_course
/kierros4/2.py
1,173
3.8125
4
""" COMP.CS.100 Ensimmäinen Python-ohjelma. Tekijä: Anna Rumiantseva Opiskelijanumero: 050309159 """ import math def tarkista(yht, on): """tarkista onko mollemmat positivinen ja onko lottopallojen kokonaismäärä isompi entä arvottavien pallojen määrän""" if on > yht or on < 0 or yht < 0: return Fals...
c5aaa218c5fb897e2bad6d80b7a24a97b7973e7a
jgarte/aoc-2
/aoc/year_2020/day_08/accumulate.py
585
3.546875
4
from typing import List, Set, Tuple from .parse import Cmd Result = Tuple[int, int] def loop_accumulate(commands: List[Cmd], idx_set: Set[int], values: Result) -> Result: """Accummulate values while iterating/jumping through commands""" idx, acc = values if idx in idx_set: return idx, acc idx...
7e3649f19a94bbc4a2de984f5bd20655e1b1d505
catalystfrank/LeetCode10Py
/[OPEN--]LEET0214_SHORTEST_PALINDROME.py
370
4.125
4
#coding=utf-8 ''' Given a string S, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest. ''' def shortestPalindrom(s): n = len(s) l, r = int(n/2), int((n+1)/2) while l > 0: if s[:l] == s[r+l-1: r-1: -1]: break elif l == r: l -= 1 else : r -= 1 lef...
6316f3926bf976630c877384afc7eda94c11ac57
zhaolanqi/C.C
/作业/04.py
130
3.625
4
i = '亚瑟' u = input('请输入英雄') if u == i: print('%s是死亡骑士'%i) else: print('我不知道什么意思')
c3c7459ef1989a5ae114ce45aeecf17cff44ba04
YilK/Notes
/Python-Crash-Course/第一部分 基础知识/第04章 操作列表/4-04 一百万.py
276
3.65625
4
''' 创建一个列表,其中包含数字1~1 000 000,再使用一个for 循环将这些数字打印出来 (如果输出的时间太长,按Ctrl + C停止输出,或关闭输出窗口)。 ''' numbers = list(range(1, 1000001)) for number in numbers: print(number)
9287be3b87f10caddcbe58bbf686d2a72542a541
stefanyl/python-challenge
/PyBank/main.py
2,411
3.84375
4
#Import the os module import os #Import module for reading in CSV file and set path. import csv csvpath = os.path.join('Resources', 'budget_data.csv') #Set variables for Financial Analysis total_months = [] total_profit = [] profit_change = [] #Read in the CSV and store the header row. with open(csvpath, newline="",...
be3bc4ed381168508dda0629089d683dfe475672
JackMGrundy/coding-challenges
/companies-leetcode/amazon/trees/binary-tree-maximum-path-sum.py
1,996
3.828125
4
""" Given a non-empty binary tree, find the maximum path sum. For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root. Example 1: Input: [1,2,3] ...
ea6a3e6825f84c56041527dfc286a1372f014d57
PROxZIMA/Python-Projects
/Fibonacci Series.py
248
4.125
4
n = int(input('Enter how many number in Fibonacci Series you want: ')) a, b = 0, 1 print(f'Fibonacci Series is given by: ') for i in range (1, n+1): if i == n: print(b) else: print(f'{b}, ', end='') a, b = b, a+b
33296949d3cf049e945ec102558d77e668e96c53
Rudya93/Python1
/test.py
1,132
3.8125
4
class Simple: def __init__(self): self.list = [] def f1(self): self.list.append(123) def f2(self): self.f1() s = Simple() s.f2() print (s.list) q = Simple() print(q) # a = 'ZENOVW' # b = sorted(a) # print (b) # #...