blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
7e802ce085193cac5098e64709fa11ad4ea246eb
rubikscube09/Project-Marco
/oursite/question/kiwi.py
4,936
3.65625
4
import requests from geopy.geocoders import Nominatim geolocator = Nominatim(user_agent='Marco') def get_flights(fly_from, fly_to, date_from, date_to, roundtrip = False, return_from=None, return_to=None, adults=1, children=0, infants=0, ...
762a1b5d1654d176b398914124e72c0af16f5277
sarae17/2019-T-111-PROG
/assignments/sets/set_operations.py
873
4.09375
4
def get_list(): a_list = input("Input a list of integers separated with a comma: ").strip().split(",") a_list = [int(elem) for elem in a_list] return a_list def get_operation(): def print_menu(): print("1. Intersection") print("2. Union") print("3. Difference") print("4....
44d5182e00bd1b634123bf5feef610e4ab00fa95
fusion-jena/JenTab
/services/Solver/preprocessing/type_prediciton/concreteTypes/distance_type.py
1,472
3.515625
4
from ..supported_types import DISTANCE from ..abstractType import Type import re class Distance(Type): def get_type(self, input_str): try: if self.__valid_distance(input_str) or self.__fuzzy_distance(input_str): return DISTANCE return False except: ...
df9729e3325905c6b28dafb759ab454fb14b8562
nathanielshak/advancedprogramming
/Projects/hangman/hangman5.py
2,557
4.03125
4
import os def start_hangman(): print("Let's Start playing Hangman!") def start_hangman(): print("Let's Start playing Hangman!\n") man1 = """ ____ | | | | | _|_ | |_____ | | |_________| """ man2 = """ ____ | | | ...
1e916ffff1b29b8b06452f1457eb47dcfb366ce2
ds-ga-1007/assignment7
/lx557/Merge.py
2,587
3.765625
4
''' Created on 2016.11.13 @author: xulei ''' from assignment7 import Interval from exceptionClass import mergeException def sortInterval(interval1,interval2): intervals=[interval1,interval2] sortedInt= sorted(intervals, key=lambda x:(int(x.int_left[1:]),x.lower,x.upper,int(x.int_right[:-1]))) ...
5701fd0260648b50bfd33043a0dfa62ce76821fe
DiogoBerti/communicator
/socket_server.py
2,666
3.515625
4
#!/usr/bin/python # import sqlite3 import socket import threading class ThreadedServer(object): def __init__(self, host, port): self.host = host self.port = port self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADD...
859473d7d811b3d05cf89e47c2a13aeded0a2f40
akashgkrishnan/HackerRank_Solutions
/InterviewPrep/maxStackElemenet.py
841
3.9375
4
# Enter your code here. Read input from STDIN. Print output to STDOUT from collections import deque class Stack: def __init__(self): self.stack = deque() self.maxStack = deque() def push(self, value): self.stack.append(value) if self.maxStack: self.maxStack.append(m...
b08b5a5081e85d544856517741851966a416f5b5
preethamsridhar/advancedPython
/graphTheory2.py
7,628
3.796875
4
# -*- coding: utf-8 -*- """ Created on Wed May 1 19:10:05 2019 @author: preet """ class Graph(object): def __init__(self, graph_dict=None): if graph_dict == None: graph_dict = {} self.__graph_dict = graph_dict def vertices(self): return list(self.__graph_dict....
fc40d76f2a71562218df6a625104cca16ecc10d7
Rcmaveric/Reloading-Press-Monitor
/Testing_and Examples_Section/Gui_Examples/open_NewWindow_wbutton.py
240
3.5
4
import tkinter as tk def createNewWindow(): newWindow = tk.Toplevel(app) app = tk.Tk() buttonExample = tk.Button(app, text="Create new window", command=createNewWindow) buttonExample.pack() app.mainloop()
6381e05a845b62f3143be9db361309387855e515
HackneyChad/python-exercises
/4.2_control_structures_practice2.py
2,132
4.46875
4
# 4.2_control_structures_practice.py # Hackney, Chad # 4 Mar 19 print() print('## ========================================= ##') print() # file test: print('This will print if the file works...') # 1. prompt the user for a day of the week, print out whether the day is Monday # or not # look at Zach's example cod...
65c561ba65ba5fcccf9126f9a8b231029b6d8d91
Offliners/ZeroJugde-writeup
/基礎題庫/Contents/a044/a044.py
95
3.5
4
import sys for num in sys.stdin: num = int(num) print((num ** 3 + 5 * num + 6) // 6)
c5a7e9e35a03c7572398c08d4fe62aacd53330e5
GeoMassalas/PythonProjects
/MazeGenerator/disjointset.py
921
3.796875
4
class Node: def __init__(self, rank, value, parent=None): self.rank = rank self.parent = parent self.value = value def set_parent(self, parent): self.parent = parent class DisjointSet: def __init__(self, items): self.nodes = {} for i in items: ...
56e322ef2e8d586e9cd1bf5f4d61ca257d1386ac
pelinbalci/Intro_Deep_Learning
/Intro_Pytorch_Lecture/codes/5_nn_module.py
1,477
3.765625
4
from torch import nn class Network(nn.Module): def __init__(self): super().__init__() self.hidden = nn.Linear(784, 256) # Linear Transformation. self.output = nn.Linear(256,10) self.sigmoid = nn.Sigmoid() # After linear transformation we apply sigmoid. self.softmax = nn...
48dd77a38687543390b3d9fa545e101f8c1a13ce
anu-ka/coding-problems
/Python/reformat_string.py
1,530
3.9375
4
# https://leetcode.com/problems/reformat-the-string/ # Given alphanumeric string s. (Alphanumeric string is a string consisting of lowercase English letters and digits). # You have to find a permutation of the string where no letter is followed by another letter and no digit is followed by another digit. That is, no t...
b7260c92bd34b60481569b8de23af7725e7a9d71
borisboychev/SoftUni
/Python_Advanced_Softuni/Functions_Advanced_Lab/char_combinations.py
349
3.703125
4
def permutations(txt, index): if index >= len(txt): print("".join(txt)) return permutations(txt, index + 1) for i in range(index + 1, len(txt)): txt[index], txt[i] = txt[i], txt[index] permutations(txt, index + 1) txt[index], txt[i] = txt[i], txt[index] txt = list(...
90e537e7ea9a219b297b0b12080b54cf0d5bee07
DildeepBisla/DFESW3
/pynaative_tasks.py/Tasks_BUS_EXAMPLE_CLASSES.py
3,565
4.53125
5
####### CREATING CLASSES ######### # class Vehicle(): # def __init__(self, max_speed, mileage): # self.max_speed = max_speed # self.mileage = mileage # Vehicle_object_1 = Vehicle(250, 12000) # print (Vehicle_object_1.max_speed) ###### SUBCLASSES ###### # class ...
34fcc3d5824ee47be56da0fe14a9acf6d3c53a3d
rigo93acosta/cheatsheets
/Choropleth_maps.py
1,190
3.65625
4
import plotly.plotly as py import plotly.graph_objs as go from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot init_notebook_mode(connected=True)#This line to to pint in Jupyter Notebook the map data = dict(type='choropleth', locations=['AZ', 'CA', 'NY'], locationmode=...
2c1e06d3b5d55ab40541a19ce4b2a9dec6933794
Macielyoung/LeetCode
/66. Plus One/plus_one.py
501
3.53125
4
#-*- coding: UTF-8 -*- class Solution: def plusOne(self, digits): """ :type digits: List[int] :rtype: List[int] """ for i in range(len(digits)-1, -1, -1): if(digits[i] < 9): digits[i] += 1 return digits else: ...
6ca3358548169f322cc1474b70fa08ad4cc9cdee
Tashwri93/Python-Crash-Course-Activity
/exercise8.4.py
286
3.671875
4
def make_shirt(printed = "'obey!'", size = 'large'): print("The size of your shirt " + size.title() ) print("Printed on your shirt: " + printed.title()) make_shirt("'i love python'") make_shirt() make_shirt(size='medium') make_shirt(size ='small',printed= "'hello'")
3fbedca3f1c5e9f5e0050f5930c97ac4f10494d7
alansmathew/Algorithms-with-py
/lab programs/1.py
193
3.953125
4
print("Arithemitic operators") a=int(input("Input two numbers:")) b=int(input()) print('sum is',a+b,'\nDisfference is ', a-b, '\nProduct is ' ,a*b, '\nQuotient is ' ,a/b, '\nmodlus is ', a%b )
0c2fab621c943de9c61c85a9eab943cfc4015709
adonai-luque/CodewarsPython
/7 kyu/squareEveryDigit.py
81
3.53125
4
def square_digits(num): return int(''.join(str(int(n)**2) for n in str(num)))
5604e74244b247c5fbed3e7acafa991370748755
gabriellaec/desoft-analise-exercicios
/backup/user_285/ch47_2019_06_03_17_57_32_166905.py
445
3.9375
4
numero= int(input("Digite um numero")) dic={1:"Janeiro", 2:"Fevereiro", 3:"Março", 4:"Abril", 5:"Maio", 6:"Junho", 7:"Julho", 8:"Agosto", 9:"Setembro", 10:"Outubro", 11:"Novembro", 12:"Dezembro"} print(dic[numero]) listanum=[1,2,3,4,5,6,7,8,9,10,11,12] listanom=["Janeiro","Fevereiro","Março","Abril","Maio","Junho","J...
250f66c4ebc94485e668bdbb8ee3cb2e308b62b2
rebecafbraga/exercicio2
/exercicios2.py
245
3.859375
4
dias_semana = {1: 'domingo', 2: 'segunda', 3: 'terça', 4: 'quarta', 5: 'quinta', 6: 'sexta', 7: 'sabado'} numero = int(input('digite o numero:' )) if numero >=1 and numero <=7: print(dias_semana[numero]) else: print('digite novamente')
4d4e7d770ebde50dee6725db8d4e5b69d19d0a08
Octaviosf/MITx-PythonIntro
/mitx/Midterm/sumDigits.py
393
3.8125
4
def sumDigits(N): """ :param N: non-negative integer :return: sum of the digits of N """ # base case if N//10 == 0: return N # sum right-most digit to recursion of left-shifted N if N % 10 > 0: return N % 10 + sumDigits(N//10) if N % 10 == 0: return sumDigits(...
49f4510f31007ebe15cdb2755be4879b3d832ab0
jing1988a/python_fb
/amazon_leetcode/PalindromicSubstrings647.py
1,188
3.96875
4
# Given a string, your task is to count how many palindromic substrings in this string. # # The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters. # # Example 1: # Input: "abc" # Output: 3 # Explanation: Three palindromic strings: "a", "b", "...
cf8e0af9d6ae5484a0b60c732d1102f96c784187
vmsgiridhar/DSHackerRank
/Python_Prac/DS/Queue.py
406
3.875
4
# -*- coding: utf-8 -*- """ Created on Wed Jan 9 11:51:52 2019 @author: C5232886 """ class Queue: def __init__(self): self.data = [] def push(self, data): self.data.append(data) print(self.data) def pop(self): #FIFO if len(self.data) != 0: ...
08619ec2dd3848180c43a21083d4d3c54d5b42a7
AdamZhouSE/pythonHomework
/Code/CodeRecords/2624/52592/319639.py
579
3.625
4
import re import operator class Functiom: def diff(self, input): items = re.split('(\D)', input) nums = list(map(int, items[::2])) ops = list(map({'+':operator.add, '-':operator.sub, '*':operator.mul}.get, items[1::2])) def calc(low, high): if low == high: ...
0f631f03b3ec03bc76b8e4533ebaeb434f3d0f51
gaoruiqing123/proj12
/day007/two.py
294
3.53125
4
# 2.编写函数求三角形面积,输入参数为底边与高,输出面积(20分) import math def ssm(c,d): print("您输入的三角形面积是:", (c * d) / 2) a = int(input("请输入三角形的底边数字:")) b = int(input("请输入三角形的高数字:")) ssm(a , b)
353ed569b28a1ec0afb0bdd05a29953a9212d741
dotgourav/Competitive-Programming
/ATM.py
725
3.609375
4
__author__ = 'Gourav Chawla' """ Problem Code: HS08TEST Problem URL : http://www.codechef.com/problems/HS08TEST Compatability: Python 3.x """ x,y = input().split() # Splits the input into two strings. The space between strings acts as the delimiter # and assigns those strings to t...
cd2cd74a5ada837c6d7068a4b6c8631d9b519a49
Accerator/python
/Private/is a.py
2,325
4.375
4
''' is a 类之间的继承 例如:PC机 和 工作站 都继承计算机的共同属性 父类 基类(子类) ''' ''' 继承: Student,Employee,Doctor --->都属于类 相同代码 ----> 代码冗余,可读性不高 将相同代码提取 ----> Person类 Student,Employee,Doctor ---> 继承Person类 class Student(Person): pass 特点: 1.如果类中不定义__init__,调用父类 super class的__init__ ...
5ef4a92019886130fd1dcf42e3e1c22060e0c1cd
ksiomelo/cubix
/merge_scripts.py
1,634
3.84375
4
''' Created on Jul 5, 2012 @author: cassiomelo ''' import os def dir_list(dir_name, subdir, *args): '''Return a list of file names in directory 'dir_name' If 'subdir' is True, recursively access subdirectories under 'dir_name'. Additional arguments, if any, are file extensions to add to the list. E...
0c33b799e733b443750f9a16fa88d0b387831350
aniketmandalik/ProjectEuler
/Problem002.py
345
4.03125
4
from timeit import default_timer as timer def fibonacci_sum(n, d): """ Finds the sum of all fibonacci numbers less than n that are divisible by d """ x, y, sum = 1, 1, 0 while x + y < n: x, y = y, x + y if y % d == 0: sum += y return sum start = timer() print(fibonacci_sum(4000000, 2)) end = timer() pri...
a591b0dddda0466b314f186ddb5632ab519f8bc0
ballib/SC-T-111-PROG
/ehv/namskeid/namskeid_2/greater_value.py
155
3.96875
4
a = input("pleace enter a number") b = input("please enter a number") a_int = int(a) b_int = int(b) if a < b : print(b) elif a > b : print(a)
8ba24f6abbda1ccf99f016fd7a4e46f1a47a943c
michaelyorkpa/python-tstp
/inheritance.py
544
3.703125
4
class Shape(): def what_am_i(self): print("I am a shape") class Rectangle(Shape): pass def __init__(self,w,l): self.width=w self.length=l def calculate_perimeter(self): return 2*(self.width+self.length) class Square(Shape): def __init__(self,s1): self.s...
1ba4af77ef25fea9656e2e570c34bcec0408d9e7
robo360/leetcode
/Strings /atoi.py
1,619
3.78125
4
""" Implement atoi which converts a string to an integer. The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and inte...
090c06ea28c07c3adee6b2b8a3d7a1fcdec0ef82
rameshrameshrum/python-repository
/sum of n no.py
112
3.65625
4
n=int(input("enter the no:\n")) ''' x=n*(n+1)/2 print x ''' sum=0 for i in range (n+1): sum=sum+i print sum
65e353977b874f628c8f4f04618d9199e38371c6
jwross24/DS-Unit-3-Sprint-2-SQL-and-Databases
/module1-introduction-to-sql/sqlite_example.py
460
3.671875
4
import sqlite3 conn = sqlite3.connect('toy_data.db') curs = conn.cursor() query = 'CREATE TABLE toy (name varchar(30), size int);' curs.execute(query) curs.close() conn.commit() curs2 = conn.cursor() print(curs2.execute('SELECT * from toy;').fetchall()) insert_query = 'INSERT INTO toy (name, size) VALUES ("awesome",...
4255316e58587702b32267f36020ba6c749a227b
darienpmt/metis_prework
/python_intro/strings/mix_up.py
208
3.75
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Mar 2 13:00:54 2020 @author: darienpmt """ def mix_up(a, b): return b[:2] + a[2:] + ' ' + a[:2] + b[2:] print(mix_up('pezzy', 'firm'))
b95a88456e2b6e884bc168ae6b52e14b83f42474
sangwon02/python_study
/두수교롼함수(4번문제).py
153
3.625
4
a = int(input("첫번째 수를 입력하세요: ")) b = int(input("두번째 수를 입력하세요: ")) a, b = b,a #두수를 교환 print(a, b)
1f335fd45b4f73a78cbc683f5e50023f583e24ae
AlexClowes/advent_of_code
/2022/09/rope_physics.py
1,431
3.65625
4
from collections import namedtuple class Vector(namedtuple("Vector", ("x", "y"))): def __add__(self, other): return Vector(self.x + other.x, self.y + other.y) def __sub__(self, other): return Vector(self.x - other.x, self.y - other.y) def __abs__(self): return max(abs(self.x), ab...
5fdb9555e14e0de2dcd8db73f47fe0d11281e0d1
SecurityAnalysts/AlteMatrix
/altematrix/converter/hexadecimal.py
2,154
3.734375
4
def hexadecimal_to_binary(data): print("Hexadecimal value:",data) try: bnr = int(data,16) bnr = bin(bnr).replace('0b','') except ValueError: raise ValueError("Non-hexadecimal number entered!") print("Binary value:",bnr) def hexadecimal_to_binary_s(data): try: bnr = in...
a6acee48413dbe5a2b5451420d9b7352e4050c1c
dmitarint/algo_and_structures_python
/Lesson_5/2.py
1,189
3.578125
4
""" 2. Написать программу сложения и умножения двух шестнадцатеричных чисел. При этом каждое число представляется как массив, элементы которого это цифры числа. Например, пользователь ввёл A2 и C4F. Сохранить их как [‘A’, ‘2’] и [‘C’, ‘4’, ‘F’] соответственно. Сумма чисел из примера: [‘C’, ‘F’, ‘1’], произведение - [‘7...
8e77c0d5f3cb60ea3a2351dd9cf9e9ce66956bdc
zjunweihit/pyLab
/basic/data_structure.py
4,742
4.40625
4
# List, tuple, dictionary and set # list [] 是一种保存有序项集合的数据结构。 项目列表应该使用方括号扩起来. # start from 0 # tuple ()元组用于将多个对象组合在一起。可以将它们近似看作列表,但是没有列表类提供的许多功能。 # 元组的一个重要特征是,它们和字符串一样是 **不可变的 **,即你不能修改元组。 # dictionary {} 字典就像是一个地址簿,只要知道一个人的名字,你就可以找到他 / 她的地址或联系方式, # 即,我们将键 (名字)与 值 (详细信息)相关联。 # 注意, # 1. key is unquie # 2. key must...
a18f5d0430dd379539342deaf802a91dbffc002c
alans09/PythonAcademyExercises
/Lekcia4/cvicenie9-5-advanced.py
1,703
3.71875
4
# CEZAROVA SIFRA # vytvorte algoritmus, ktory simuluje cezarovu sifru a pouzije ju na sifrovanie # pre posun sa moze pouzit lubovolne dlhe cislo # Cézarova šifra je druh šifry, pri ktorej je každé písmeno správy posunuté o n pozícií ďalej v abecede, # pričom n môže byť 1 až m − 1, kde m je počet znakov prís...
1756f4e08d1062164e11b7df2ede3bdb75aa29b4
hghimanshu/Project-Euler
/problem-53.py
863
3.65625
4
""" There are exactly ten ways of selecting three from five, 12345: 123, 124, 125, 134, 135, 145, 234, 235, 245, and 345 In combinatorics, we use the notation, (53)=10 . In general, (nr)=n!r!(n−r)! , where r≤n, n!=n×(n−1)×...×3×2×1, and 0!=1 . It is not until n=23 , that a value exceeds one-million: (2310)=114406...
b6f99766c124f70bc28b37e34b1447f3bfc8256f
zerghua/leetcode-python
/N762_PrimeNumberofSetBitsinBinaryRepresentation.py
1,594
3.953125
4
# # Create by Hua on 5/16/22 # """ Given two integers left and right, return the count of numbers in the inclusive range [left, right] having a prime number of set bits in their binary representation. Recall that the number of set bits an integer has is the number of 1's present when written in binary. For example,...
586d44403708b51320e01e3dcba92dd1d0615835
Ashutos-h/python-L11
/5.py
699
4.09375
4
#Answer 5 #Import Error '''The ImportError is raised when an import statement has trouble successfully importing the specified module. Typically, such a problem is due to an invalid or incorrect path, which will raise a ModuleNotFoundError''' try: import gw_utility.Book except: print("cannot import file") #...
fc679c95fcec22975913d70b43878d96239612fb
Nelsont345/Radial-Invariance-soalr-magnetic-field
/other/Real data/dataplot1.py
562
3.6875
4
# -*- coding: utf-8 -*- """ Created on Sun Jan 21 19:45:45 2018 @author: nmt115 """ import numpy as np import pandas as pd from matplotlib import pyplot as plt datalist = pd.read_csv('2012.csv') def magnitude(X, Y, Z): return np.sqrt(X*X + Y*Y + Z*Z) datalist['Magnitude (nT)'] = magnitude(datalist['BX(nT)'...
5379488475dcf78a03bdeb1b042d7b4be6c782ec
theitalianscientist/covid-19
/benford.py
1,496
3.765625
4
import math # Code copied verbatim from: # https://towardsdatascience.com/frawd-detection-using-benfords-law-python-code-9db8db474cf8 # (it's an awesome site). # Benford's Law percentages for leading digits 1-9. BENFORD = [30.1, 17.6, 12.5, 9.7, 7.9, 6.7, 5.8, 5.1, 4.6] def count_first_digit(df, column): mask = d...
0123c7d60cdd0f6047eeae51e6873c79f3d975ed
Kako-0/AtividadePraticaOrdenacao
/src/algoritmosDeOrdenacao.py
12,840
3.984375
4
import math ''' Introdução: - Implementar algoritmo de ordenação que receba uma colecão - A coleção é uma lista de arestas - Para comparar o peso as arestas entre dois item da coleção basta usar a chave 'weight' (peso) Exemplos: - Modo convencional colecao[i] operador de comparacao colecao[j] colecao[i] < colecao[j] ...
6e3fd05bf8cb6432f5370b9fa94d57b4c974bd25
Jakezo/PythonStudy
/study5.py
161
3.5625
4
a = sum = 0 while a < 10: a +=1 if a%2 == 1: continue sum +=a print(sum) # 중요함.. 마지막에 10 더해짐 그래서 30임 중요!
7908d941f1a1b031e9bc139ff30deaa5764d5621
alex36540/drive-uploader
/src/drive_utils.py
1,880
3.625
4
from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive def drive_auth(): """ Authenticates Google Drive """ g_auth = GoogleAuth() g_auth.LocalWebserverAuth() return GoogleDrive(g_auth) def get_drive_dict(folder_id, drive): """ Returns a dictionary of how many file...
a69352af8f94efa74b0d8472a11c4e1dc2d7319e
gabriellaec/desoft-analise-exercicios
/backup/user_213/ch39_2019_03_29_13_54_02_597485.py
166
4.1875
4
pergunta=int(input('digite um numero: ') s=pergunta while pergunta!=0 pergunta=int(input('digite um numero: ') s+=pergunta print(s)
30f1d9632ac48d976227631238bc7cbd2a75c6f6
SBennett13/Codewars
/Python/ProductOfConsecutiveFibNumbers.py
1,960
4.3125
4
#!/usr/bin/env python3 """ Scott Bennett, scottbennett027@gmail.com Problem: The Fibonacci numbers are the numbers in the following integer sequence (Fn): 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, ... such as F(n) = F(n-1) + F(n-2) with F(0) = 0 and F(1) = 1. Given a number, say prod (for product), we sea...
43e8126ca50020fc4b301f6a620cc0b050a97321
goga-nakagawa/leetcode
/python/376_WiggleSsubsequence.py
1,935
4.1875
4
""" A sequence of numbers is called a wiggle sequence if the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with fewer than two elements is trivially a wiggle sequence. For example, [1,7,4,9,2,...
0fd68fa35c40826a7773e69cbfded56e2ef562e3
FawneLu/leetcode
/222/Solution.py
1,222
3.875
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def countNodes(self, root: TreeNode) -> int: if not root: return 0 def getheight(root): ...
12a750c4f246441181acd2a34a4d006867ff0eee
kunal768/hello-world
/Mutable String.py
214
3.796875
4
#this method is learnt to concantante a new character or string in the strings def mutable_string(string , position,character): l=list(string) l[position]=character string=''.join(l) return string
af9c380e2710b42e19fb9f3cde64663401ac3de5
udemonia/python-beyond-basics
/3-udemy-oop/4-the-3-pillars/0-encapsulation.py
1,002
4.0625
4
# we're taking in a value and setting it as a value in an instance class MyClass(object): #* SETTER VALUE - common OOP term def set_value(self, val): self.value = val #* GETTER VALUE - common OOP term def get_value(self): return self.value a = MyClass() b = MyClass() a.set_value(10...
08c4a920a200211d95f10640f290959d44af3cb3
ypycff/pythonClass
/PythonDev/Demos/05-DataStructures/WorkedExamples/readData.py
1,336
4.0625
4
# Keep a dictionary of goals scored for each player. # The key is the name of a player. # The value is a set of goals scored by that player. goals_dict = dict() # Process data for a player name and the list of goals for that player. def process_data(name, goals_string): # Split the goals-scored string into a list...
d7397afe280c479a86d3ec8f6cd2dcb45b0638b9
JosephLevinthal/Research-projects
/5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4162/codes/1675_2474.py
858
3.703125
4
q= int(input("insira o dia do mes entre(1-31): ")) ms= int(input("insira o mes entre(1-12): ")) a= int(input("insira o ano: ")) k=a%100 j=a/100 k1=(a-1)%100 j1=(a-1)/100 h= (q+((13*(ms+1))//5)+k+(k//4)+(j//4)+5*j)%7 hjf=(q+((13*((ms+12)+1))//5)+k1+(k1//4)+(j1//4)+5*j1)%7 h1=int(h) h2=int(hjf) if not(ms==1 or ms==2): i...
a9e396499bb78e0df45b602122a3571bcb1c42bf
realyuyangyang/Python3Michigan
/course_2_assessment_8/ac18_7_4.py
438
4.3125
4
# Given the same dictionary, medals, now sort by the medal count. Save the three countries with the highest medal count to # the list, top_three. medals = {'Japan': 41, 'Russia': 56, 'South Korea': 21, 'United States': 121, 'Germany': 42, 'China': 70} def medal_val(k): return medals[k] sorted_medals...
8c97b6cfcc88ca6a26c5897b1bb7cc5bafeaf393
mfalcirolli1/Python-Exercicios
/Aula 18 M 3.py
634
3.828125
4
# Listas (Parte 2) # Listas são mutáveis teste = [] galera = [] teste.append('Matheus') teste.append(23) galera.append(teste[:]) teste[0] = 'Joice' teste[1] = 23 galera.append(teste[:]) print(galera) pessoas = [['João', 19], ['Joaquim', 13], ['Ana', 33], ['Maria', 45]] for c in pessoas: print(c[0]) nomes = [] ...
8547f9604e6ac7aa4debf69801912af8a8aeeac0
dlingerfelt/DSC-510-Fall2019
/JALADI_DSC510/final/main.py
2,993
4.25
4
# File : main.py # Name : Pradeep Jaladi # Date : 02/18/2020 # Course : DSC-510 - Introduction to Programming # Assignment : # Create a header for your program just as you have in the past. # Create a Python Application which asks the user for their zip code or city. # Use the zip code or city nam...
737ead22c49c2fa10497161cb7c900e70690fafd
erysaputri/ErysaPutriVaraAfifa_I0320036_Andhika_Tugas5
/I0320036_Soal2_Tugas5.py
541
3.765625
4
#memasukkan data nama = input("Nama : ") nilai_angka = int(input("Nilai : ")) output = "Halo, " + nama + "!" + " Nilai Anda setelah dikonversi adalah" #konversi nilai if 85 <= nilai_angka <= 100: print(output,'A') elif 80 <= nilai_angka <= 84: print(output,'A-') elif 75 <= nilai_angka <= 79: print(output,'...
92209b55db083d85c37c92d303bc9fef2c8bdb30
CallmeTorre/Analisis_De_Algoritmos
/Practica 2/Fibonacci.py
1,076
4.375
4
# -*- coding: utf-8 -*- """ INSTITUTO POLITÉCNICO NACIONAL ESCUELA SUPERIOR DE CÓMPUTO Análisis de Algoritmos GRUPO: 3CV1 ALUMNOS: Reyes Fragoso Roberto Torreblanca Faces Jesús Alexis PROFESOR: Luna Benoso Benjamín FECHA: 5/Septiembre/2017 """ def recursive_fibonacci(n): """Funcion que genera la secuenc...
429e774c05bb7b5ec7eeb05946349a08ce88ba58
Sanyarozetka/Python_lessons
/hometask/hometask_04/searching_symbol_in_string.py
733
3.9375
4
""" Пользователь вводит, отдельно, строку `s` и один символ `ch`. Необходимо выполнить поиск в строке `s` всех символов `ch`. Для решения НУЖНО использовать только функцию `find()`(rfind()), операторы `if` и `for`(while). Старый, но рабочий код: 'for i in range(len(s)): b = s.find(ch, i) if b == i: p...
1286a71d15eb367d758f46ca25a866a566e7a91e
b1oki/99-Bottles-of-Beer
/bottles/bottles.py
858
3.625
4
#!python3 # coding: utf-8 import gettext def init_gettext() -> classmethod: es = gettext.translation('bottles', localedir='bottles/locales') es.install() _ = es.gettext return _ def get_bottle_word_ru(beer_num: int) -> str: if beer_num % 10 == 1 and beer_num != 11: word = _('бутылка') ...
993780ec79360be694f51e96b617436d469737cf
umangdubey/Pyhton_with_example
/keyword_arg.py
346
3.734375
4
def person(name,**data): print(name) print(data) #person("umang",20,"mumbai",255556) person(name="umang",age=20,city="mumbai",phone_no=255556) def per(name,**data): print(name) for i,j in data: print(i,j) #person("umang",20,"mumbai",255556) per(name="umang",age=20,city=...
6b6ee7052c115729769be319740813b0b4d73b00
ashwin4ever/Programming-Challenges
/Cracking the Coding Interview/ch16.1_number_swapper.py
345
4.0625
4
#16.1 Number swapper def swap(a , b): b = a + b a = b - a b = b - a print('a: ' , a , 'b: ' , b) def swapBits(a , b): a = a ^ b b = a ^ b a = a ^ b print('a: ' , a , 'b: ' , b) a , b = 3 , 4 print('a: ' , a , 'b: ' , b) swap(...
a9de7fc26dc9d4e0a0e3eecfa820f0eca4e3db14
MarceloDL-A/Python
/14-Statistics_with_Python/Mean,_Median,_and_Mode/Median_NumPy.py
1,345
4.09375
4
"""MEDIAN Median NumPy Finding the median of a dataset becomes increasingly time-consuming as the size of your dataset increases imagine finding the median of an unsorted dataset with 10,000 observations. The NumPy .median() function can do the work of sorting, then finding the median for you. In the example below, w...
87360e99df4feb701fafb5b9a9c433cb5ad3135d
FerCremonez/College-1st-semester-
/a12e3.py
249
4.1875
4
#exercício 3 a=[0]*5 for i in range(5): a[i] = [0] * 5 for j in range(5): a[i][j]=int(input()) print('Triangulo inferior esquerdo:') for i in range(1,5): for j in range(0,i): print(a[i][j],end='') print()
c275f6129cbe4b20eb4faea4633802f956f0e1e3
jeffwindsor/learn
/Coursera/Data Structures and Algorithms/C1 Algorithmic Toolbox/W4 - Divide-and-Conquer/inversions/iv.py
1,096
3.671875
4
# Uses python3 import sys def merge_sort_and_count(A): if len(A) == 1: return 0 m = int(len(a)/2) (lc, L) = merge_sort_and_count(A[:m]) (rc, R) = merge_sort_and_count(A[m:]) (ac, A) = merge_and_count(L,R) return lc+rc+ac, A def merge_and_count(A,B): C = [] count=i=j=0 la =...
bc1fcd310fc1f783e5fdcab5d715c3d66476d02f
Winniepoof/leetcode
/leetcode/permute46.py
467
3.671875
4
class Solution(object): def permute(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ self.res=[] def recursion(path,candy): if len(candy)==0: self.res.append(path) for i,item in enumerate(candy): ...
35403617bc8895e37a45c3b5a334ecfabed3d2e3
nnoyuwan/ATBSWP
/第4章 列表/1.列表数据类型.py
1,284
3.796875
4
# 4.1.1 用下标取得列表中的单个值 spam = ['cat', 'bat', 'rat', 'elephant'] print(spam[0]) spam1 = [['cat', 'bat'], [10, 20, 30, 40, 50]] print(spam1[0]) print(spam1[1][3]) # 多重下标,第一个下标表明使用哪个列表值,第二个下标表明该列表值中的值 # 4.1.2 负数下标 print(spam[-1]) print(spam[-3]) print('The ' + spam[-1] + ' is afraid of the ' + spam[-3] + '.') # 4.1.3 利用...
7b1dd3198682726210ab55bae98ea0e3965c7d18
aparnalikhitkar/Python
/simple_code/IfElse.py
453
4.15625
4
# -*- coding: utf-8 -*- """ Created on Wed Feb 17 22:52:24 2021 @author: aparn """ def product(x,y,z): if(x==7): temp = y*z elif(y==7): temp = z elif(z == 7): temp = -1 else: temp = x*y*z return temp a = int(input("Enter the 1st number ")) b = int(inpu...
f7c597c81f20749e26b306f83fbdf9308a6a3053
dlingerfelt/DSC510Summer2020
/TESORO_DSC510/Assignment 3 - Tiffany Tesoro.py
1,844
4.3125
4
#DSC 510 #Week 3 #Programming Assignment Week 3 #Author Tiffany Tesoro #06/21/2020 print() print() #USER GREETING MESSAGE print("Welcome to the Riverside Fiber Optic Cable Installation Calculator.") #RETRIEVAL OF USER AND COMPANY NAME name = input ("What is your name?\n") print() print("Nice to meet you " + name...
a87626e02ed4a2d2a63705d45d15796c8bf2ada3
RAVIRANJAN123456789/SENTIMENT-ANALYSIS
/RECOMBINATION OF TWEET AFTER PUNCTUATION REMOVAL.py
1,023
3.859375
4
# -*- coding: utf-8 -*- """ Created on Tue Nov 13 02:13:04 2018 @author: Ravi Ranjan """ # -*- coding: utf-8 -*- """ Created on Sun Nov 11 13:25:49 2018 @author: Ravi Ranjan """ import nltk from nltk.corpus import stopwords from nltk.tokenize import word_tokenize example_sent = "This is a sample ...
179c300096afb24135bc1d472679d14aa2a53ec0
bql20000/MLcoban
/Lesson_10/test_array_2D.py
137
3.546875
4
import numpy as np X = np.array([[1, 2],[3, 4]]) xi = X[1].reshape(1, -1) print(xi.shape) w = np.array([1, 2]) print(np.linalg.norm(w))
5e3c9d1b81f7d3fe059efc51010b18485043eacc
MINCARELLI13/GrandPy_Bot
/ChatBot/parser_question.py
4,521
3.984375
4
""" Parse a sentence into keywords by removing 'stopwords' and verbs """ import re class Parser: """ Parse a sentence into a list of words by removing stopwords and verbs """ @staticmethod def unicoding(word): """ Remove accentuation of letters in a 'word' ...
157c58d07f7e87493fdc29d1a11d2fe08ac2896b
bp2070/vr_software_renderer
/terrain.py
1,861
3.625
4
import Image from Geometry import * class Terrain: """ the terrain is composed of a grid of squares with all verticies at 0 height (initially). height can be adjusted via a heightmap passed in a bitmap, where pixels and verticies are mapped 1-to-1 and the height of each vertex is set based on the red ...
558c39a1ec92b8553923ca3fce20713bcc3a2a65
gqmelo/misc
/algorithms/chapter_01_arrays_and_strings/q04_palindrome_permutation.py
195
3.5625
4
import collections def is_palindrome_permutation(string): counter = collections.Counter(string) odd_counts = [v for v in counter.values() if v % 2 == 1] return len(odd_counts) <= 1
635f8350a17b84dd35f4fbccebc0bb15560a3269
mkharytonau/nx_todo
/nxtodo-lib/nxtodo/reminding/check_times.py
2,060
4.0625
4
from datetime import datetime from datetime import timedelta def check_deadline(deadline, now): """ This function checks if we missed deadline. """ if deadline and now > deadline: return deadline else: return None def check_range(from_datetime, to_datetime, now): """ This...
f89352da92a467c81349d2fea331e7ccfedbb217
kyandaks/python-tutorials
/controlflow.py
371
4.15625
4
age = int(input('How old are you?')) if age < 10: print('You are young!') elif age <25: print('You are a youth!') else: print('gundi okuze!!!') #operators > < => =< #comparison operators == != menu = input('do you need a menu? (y/n)') if menu == 'y': print('here is the menu and you get a free so...
e7ece740ac4ebd9397c72b9b3841249d9efe6755
appcubator/v1factory
/app_builder/manager.py
1,324
3.984375
4
def get_name(instance): """Either a dict or object, get name""" try: return instance.name except Exception: return instance['name'] class Manager: """ Manages a collection of objects """ def __init__(self, parent_class): self._parent_class = parent_class self._objects = [] def get_by...
6775e939eb981bbb69ba5514de93e5ec5db9443c
CodeAnGo/PyLive
/tests/security/AES.py
918
3.6875
4
import unittest import os from security import AES class AESTest(unittest.TestCase): def testCBCEncryption(self): print("Testing AES-CBC Encryption") inputText = "This is an example input string that should be encrypted, then decrypted!" encryptedText = AES.encryptBlockText(inputText) ...
030457e187f925c9474dd9f3150eb50a222174d6
Samrat0009/Python_REPO2
/#21 BinaryTrees_1/Printing_binary_trees.py
1,514
4.40625
4
# The Tree Format !! # note : most tree problems we will be using recursion !! class BinaryTreeNode: def __init__(self, data): self.data = data self.left = None self.right = None #def printTree(root): #very simple!! # if root is None: ...
3ca5b29a5bc6efe8d21a991cfa2a1e24aa69abbd
Beebruna/Python
/CursoemVideoPython/Desafio 5.py
213
4.15625
4
''' Faça um programa que lei um número inteiro e mostre na tela o seu sucessor e antecessor ''' n = int(input('Digite um número inteiro: ')) print(f'Número digitado: {n}\nAntecessor: {n-1}\nSucessor: {n+1}')
49979e2919077cf080fd8e8a9c5db9abbbd11991
ymichaelholding/Pandas
/python_connect_by_clause.py
2,481
3.578125
4
# -*- coding: utf-8 -*- """ Created on Thu Aug 19 14:49:12 2021 @author: Michael Yonas #find the hierarchy queries using recursive function in Python #try to achive the oracle connect by clause function select EMPLOYEE_ID,FIRST_NAME,MANAGER_ID from hr.employees start with MANAGER_ID =100 connect by prior employee_id =...
8ee544c39fa943370060cb6feae90fa19ed8adf0
thealphacoder9/mini-stuff-with-python
/translator.py
187
4.15625
4
dic = {"hello": "hola", "good": "bien", "how are you": "como esta"} x = input('Enter your input: ').lower() if x in dic.keys(): print(dic[x]) else: print('Match not found')
e7af266cf0e30a4f7c03c27ca3fd768dab04dfd4
jingjuanwang/Python_project
/vowel.py
140
3.5625
4
def vowels(s): k = 0 for i in ['a', 'e', 'i', 'o', 'u']: #print s.count(i) k = k + s.count(i) print 'number of vowels:', k return k
ce0d4a422857cb5a833d4accdad44dc8018954f4
Gaurav927/CSES-problem
/Introductory Problems/bit_strings.py
375
3.5625
4
mod = 1e9 + 7 def pow(n): # if n<=1: # return n+1 # if n%2: # x = pow((n-1)//2)%mod # return (2* x*x)%mod # x = pow(n//2)%mod # return (x*x)%mod ans = 1 for i in range(n): ans*= 2 ans = ans%mod return ans if __name__=='__main_...
f67257c7ffde4b5aa13e4e6e961f2a3a9daf65c8
shulanztf/python-cluster
/com/hhcf/fun/base-0.py
469
3.703125
4
#! /usr/bin/env python # -*- encoding: utf-8 -*- """ @version: 1.0 @author: zhaotf @file: base-0.py @time: 2017/8/9 0009 15:29 """ # # python 引用/对象 # L1 = [1, 2, 3] # L2 = L1 # print(L1) # print(L2) # print(L1 == L2) # L2[0] = 5 # print(L1) # print(L2) # print(L1[0]) # print(L1 == L2) # L1 = [88,99] # print(L1 == L2) ...
7fbb6b060879cf01407a5454e7fb8e260549bb81
wxke/LeetCode-python
/859 亲密字符串.py
755
3.5625
4
亲密字符串 class Solution: def buddyStrings(self, A, B): """ :type A: str :type B: str :rtype: bool """ if len(A) != len(B): return False if A ==B: q =set(A) for i in q: if A.count(i) >=2: ...
a08ee301cc131e8786faec4cd8e973d4a9fe1cc7
wyljpn/LeetCodeTest
/Greedy/53. Maximum Subarray.py
601
3.546875
4
class Solution: def maxSubArray(self, nums): result = float("-inf") count = 0 for num in nums: # 求自序和 count += num # 处理count > result的情况。包含count为负数的情况。 if count > result: result = count ...
e14883b8194c52f741ef75a18f209feecb228bca
devwill77/Python
/Ex007.py
274
3.890625
4
''' - DESAFIO 007 - Desenvolva um programa que leia as duas notas de um aluno, calcule e mostre a sua média. ''' n1 = float(input('Informe a primeira nota: ')) n2 = float(input('Informe a segunda nota: ')) media = (n1 + n2)/2 print('A média é igual a {}'.format(media))
b73ebe44b8dda828a8fa3943b2013709f1e6bc50
JiahangGu/leetcode
/Binary Search/src/20-7-22-offer-11.py
1,255
3.84375
4
#!/usr/bin/env python # encoding: utf-8 # @Time:2020/7/22 8:04 # @Author:JiahangGu from typing import List class Solution: def minArray(self, numbers: List[int]) -> int: ''' 这题的关键点在于区分前一段还是后一段的上升序列,根据当前范围的右端点可以确定是在左还是右, if nums[mid] < nums[right] 则答案一定是在mid的左边序列,right = mid elif nu...
65949b5c49045189065b2e7c6c490df9ed115121
aliahm/csf-Homework
/lab3.py
404
3.875
4
# Name: Ahmed Ali # Evergreen Login: Aliahm18 # Computer Science Foundations # Programming as a Way of Life # Lab 3 n = 5 series = 'fibonacci' if series == 'fibonacci': a = 0 b = 1 for i in range(n-1): fib = a + b (a,b) = (b,fib) print fib if series == 'sum': total = 0 a = 1 ...
7938a6476f6330159b3aabc90a81450547828f3e
somewacko/face-rec
/facerec/KNNClassifier.py
3,682
4.09375
4
''' KNNClassifier.py Class for performing k-nearest neighbor classification. ''' import numpy as np class KNNClassifier: def __init__(self, neighbors=5): ''' Constructor for KNNClassifier. Args (optional): neighbors (int): The number of neighbors to compare against. ...
753b966c5f9ea9cfb229275065f42548562f7f96
adnathanail/project_euler
/001-050/035 - Circular primes.py
440
3.59375
4
primes = [] for i in range(2,1000000): prime = True for prime in primes: if prime > i ** 0.5: break else: if i % prime == 0: prime = False break if prime: primes.append(i) print("Primes calculated") def is_circular(n): s = str(n) for i in range(len(s)): s = s[-1] +...
4cb0b9dd5a4787ca49d2f3df658cd3d17fb6915e
GRYadav1/recreational_repository
/leetcode/PracticeHack/CodingRound.py
2,260
3.84375
4
# Python3 program to print longest # palindromic subsequence # Returns LCS X and Y def lcs_(X, Y) : m = len(X) n = len(Y) L = [[0] * (n + 1)] * (m + 1) # Following steps build L[m+1][n+1] # in bottom up fashion. Note that # L[i][j] contains length of LCS of # ...