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
271a1acd635adb0a0cdc6093d00a0320d6a010ab
pxliang/Leetcode
/String/670_Maximum_Swap.py
1,084
3.640625
4
class Solution: def maximumSwap(self, num: int) -> int: string = str(num) current = 0 pre = current for t, sub in enumerate(string[:-1]): if int(string[t + 1]) > int(sub): current = t break max_num = int(string[current]) m...
4485520094907f764f6899b3ebacd87ca9d26207
zimolzak/Raspberry-Pi-newbie
/fake_meter.py
892
3.828125
4
#!/usr/bin/env python """Mimic a one-dimensional bar graph. Control an arbitrary number of LEDs. Make them light up or turn off, one at a time, starting at one end of the list. Randomly decide whether to go up or down. """ import RPi.GPIO as GPIO from time import sleep from random import randint pins = [5, 22, 27, ...
b07250ab7c114d7209f12f4762d148c779fdbc53
unssfit/python-programming-work-
/Gui_Calculator.py
3,609
3.84375
4
from tkinter import * from functools import partial # clculator # https://www.youtube.com/watch?v=_1tTS638xUQ root = Tk() root.title('First Program') frame = Frame(root) frame.pack(side=TOP) num_input = Entry(frame,border=10,width=25,insertwidth=1,font=30) num_input.pack(side=TOP) def Calculator(num): if num == ...
268d24cae8949edbc347065c1a85415f9374aa2b
jordanbsandoval/python3_al-descubierto
/capituloDos/diccionarios/acceso-insercion-borrados/modificar-element-diccionario.py
205
4.09375
4
#!/usr/bin/python3 """ Modificando el valor de un elemento del diccionario, atraves de la clave """ dicc = {'edad': 28, 'nombre':"jordan", 'peso':"67.2"} print(dicc) dicc['nombre'] = "Ronaldo" print(dicc)
6f61ee306cee7191ec69789b404dadbd703f74cf
bopopescu/PycharmProjects
/Class_topic/16.py
232
3.5625
4
class ParentA: def __init__(self,a,b): self.a = a self.b = b def setInfo(self): return complex(self.a) * int(self.b) class Child: pass obj = ParentA('10','50') temp = obj.setInfo() print(temp)
a197c94f5eb02413bae678fc826efea002544f02
Aaronphilip2003/Python_Aaron
/Palin_number.py
179
3.9375
4
num=int(input("Enter a number:")) temp=num rev=0 r=0 while num>0: r=num%10 rev=rev*10+r num//=10 if rev==temp: print("Palin") else: print("NOT")
5779779497fdd911f8781f48e89126e76382e22f
johnmorgan123/python_projects
/WebScraping/BookScraping.py
905
3.53125
4
#getting the title of every book with a 3 star rating import requests import bs4 base_url = 'https://books.toscrape.com/catalogue/page-{}.html' page_number = 13 res = requests.get(base_url.format(page_number)) soup = bs4.BeautifulSoup(res.text, 'lxml') products = soup.select(".product_pod") example = products[0] #...
077ca8dfb25e031accbf863ad806ea46a6a28061
Yannyezixin/python-study-trip
/stack-qa/string/re_split_str.py
260
3.609375
4
#coding: utf-8 import re s = 'words, names, yes, sex, book.' gbk = '中文, name, 名字.' print re.split('\W+', s) print re.split('\W+', gbk) print re.split('\W+', s, 2) print re.split('\W+', s, 3) print re.split('(\W+)', s) print re.split('(\W+)', gbk)
4a66e9497721b61820cb8187192308fa60794b9f
codacy-badger/pythonApps
/dayOfWeek.py
448
3.828125
4
import re #regular expression import calendar import datetime def processDate(userInput): userInput = re.sub(r"/"," ",userInput) userInput = re.sub(r"-"," ",userInput) return userInput def findDay(date): born = datetime.datetime.strptime(date, '%d %m %Y').weekday() return (calendar.day_name[...
6f3d57523a6f0a7048654f86c444162af7a17188
weizhuowang/Racecar
/libMPPlot.py
4,571
3.59375
4
import matplotlib import multiprocessing import time import random import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation import math def main(): #Create a queue to share data between process q = multiprocessing.Queue() #Create and start the simulation process simu...
4b5997f55fe73a6494750c5a1503dd888e49a91a
erikamaylim/Python-CursoemVideo
/ex084.py
1,040
3.765625
4
"""Faça um programa que leia nome e peso de várias pessoas, guardando tudo em uma lista. No final, mostre: A) Quantas pessoas foram cadastradas. B) Uma listagem com as pessoas mais pesadas. C) Uma listagem com as pessoas mais leves.""" galera = [] dados = [] peso = [] resp = 'S' while resp in 'Ss': dados.append(st...
33420e9e12d2ace81f7646eda0e52cb4ad4af996
yenner123/BigDataAnalyticsCourse
/Proyecto/utils.py
1,557
3.578125
4
import math def removeSymbols(word): word = word.replace("==", " ") word = word.replace("(", " ") word = word.replace(")", " ") word = word.replace(".", " ") word = word.replace(",", " ") word = word.replace(" =", " ") word = word.replace("\n", " ") word = word.replace("\r...
43b979cb23e92fc98e92a26e589c29fa93111563
bernardosequeir/CTFSolutions
/project_euler/Problem20/p20.py
184
3.734375
4
from math import factorial def factorial_digit_sum(number): return sum([int(i) for i in str(factorial(number))]) if __name__ == "__main__": print(factorial_digit_sum(100))
57261c7c2900d65b32ec7316edf015b7703727bf
siddharthadtt1/Leet
/HiredInTech/09-simplify_fraction.py
440
4.0625
4
def simplify_fraction(numerator, denominator, result): # Write your code here # result[0] = ... # result[1] = ... x, y = max(numerator, denominator), min(numerator, denominator) # finding the greated common divisor, which will be x after the while loop while y != 0: x, y = y, x % y re...
65064e3c33410e3ec527b89d28872e6562491af1
anjana-analyst/Programming-Tutorials
/Competitive Programming/DAY-25/password.py
875
4.0625
4
def password(p): sym=['$','#','@','%'] val=True if len(p)<6: print("Length should be atleast 6") if len(p)>20: print("Length is more than 20") if not any(char.isdigit() for char in p): print("It should have atleast one number") val=False if not any(...
7cc8f356b89182c0e32637864e9c51e03946a04a
shadmanhiya/Python-Projects-
/tuples.py
747
3.984375
4
""" Write a program to read through the mbox-short.txt and figure out the distribution by hour of the day for each of the messages. You can pull the hour out from the 'From ' line by finding the time and then splitting the string a second time using a colon. From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 On...
5be927cbe41c2b02cd2e659620873d41547dd4ab
Gitlittlerubbish/SNS
/exe5_2.py
229
4.15625
4
#! usr/bin/python3 def fact(num): if num == 1 or num == 0: return 1 return fact(num-1) + fact(num-2) def main(): num = 20 print("Factorial of 20 is ", fact(num)) if __name__ == "__main__": main()
2e4058b42f48378529dde75c77a89db7110cf6f4
erinnlebaron3/python
/PipenvManaging/PolymorphBuildHtml.py
2,130
4.28125
4
# going to build out a HTML class so you can think of this as a tool that can render HTML on the page # build multiple subclasses that allow you to render custom versions of that HTML. # going to be a common convention that you see whenever you're using very complex system # going to create what is called a abstract ...
5a3bca5570f26f93134815941c1bfda9833b8d7d
piyavishvkarma09/dictionery
/w3_eg.py
453
3.828125
4
# #Add a new item to the original dictionary # car = { # "brand": "Ford", # "model": "Mustang", # "year": 1964 # } # x = car.keys() # print(x) #before the change # car["color"] = "white" # print(x) #after the change # a=0 # while a<10: # # print(a) # a+=1 # print(a) # # print(a) a=[{"a":1,"data":"...
a34cb02704752606582ca48169365c39c72869a9
renderance/tic-tac-toe-python
/tictactoe.py
5,586
3.53125
4
import os # A little googling yielded this to clear interpereter window: def cls(): os.system('cls' if os.name=='nt' else 'clear') # The game consists of tiles changing values. class tile: def __init__(self): self.state = ' ' def set_state(self,player): if play...
49588239d6e6261abe74b97b3e9646b90845dcf2
melvanliu123/StudentCard.py
/Date.py
608
4.03125
4
class Date(): def __init__(self, month,day,year): self.__month = month self.__day = day self.__year = year def setMonth(self, newMonth): self.__month=newMonth def setDay(self, newDay): self.__day=newDay def setYear(self, newYear): ...
ccbd3e032b6436918eb220807e453c10359ceb84
cladren123/study
/AlgorithmStudy/백준/6 유니온파인드/1922 네트워크 연결(크루스칼).py
700
3.765625
4
import sys input = sys.stdin.readline def find(x) : if x == parent[x] : return x else : rootx = find(parent[x]) parent[x] = rootx return parent[x] def union(x,y) : rootx = find(x) rooty = find(y) # 이 부분이 중요 if rootx != rooty : parent[rooty] = rootx ...
1dc7de84d546dd61aeebaf31d2e89dd359154ff2
westlicht/euler
/006/euler.py
278
3.671875
4
#!/usr/bin/python def sumsquares(max): num = 0 for i in range(1,max+1,1): num += i * i return num def squaresum(max): num = 0 for i in range(1,max+1,1): num += i return num * num max = 100 a = sumsquares(max) b = squaresum(max) print "%d - %d = %d" % (b, a, b -a)
ca5e3fee45038cbc63be07f5472a4cced3c2d339
githubeiro/Estudos-Python
/curso-em-video/curso-de-python-3/mundo-1-fundamentos/ex008-conversor-de-medidas.py
284
4.03125
4
# Escreva um programa que leia um valor em metros e o exiba convertido em centímetros e milímetros. medida = float(input('Infome um valor em metros: ')) cm = medida * 100 mm = medida * 1000 print(f'{medida}m equivale a {cm:.0f}cm') print(f'{medida}m equivale a {mm:.0f}mm')
4c9ea53d8bcf0376ccc4258828145c018404fc3a
jxhe/sparse-text-prototype
/scripts/compress_glove.py
1,507
3.75
4
import argparse import numpy as np def parse_embedding(embed_path): """Parse embedding text file into a dictionary of word and embedding tensors. The first line can have vocabulary size and dimension. The following lines should contain word and embedding separated by spaces. Example: 2 5 ...
1a9c3bbb7b8796e9b4393da8bd06c51437872f7a
ai-kmu/etc
/algorithm/2022/0719_199_Binary_Tree_Right_Side_View/jaeseok.py
1,086
3.71875
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def rightSideView(self, root: Optional[TreeNode]) -> List[int]: def sol(node, depth): if...
5a2e32b494ab7d029ff790f16076bcba9487ed10
TatyanaV/Finding-Mutations-in-DNA-and-Proteins-Bioinformatics-VI-
/6_Shortest_NonShared_Substring.py
2,761
4.125
4
''' Shortest Non-Shared Substring Problem: Find the shortest substring of one string that does not appear in another string. Input: Strings Text1 and Text2. Output: The shortest substring of Text1 that does not appear in Text2. CODE CHALLENGE: Solve the Shortest Non-Shared Substring Problem. (Multiple solut...
6794e31ec482e5c1e0193566e9937cfd8a4ac6b1
delfick/timepiece
/timepiece/helpers.py
741
3.65625
4
class memoized_property(object): """Decorator to make a descriptor that memoizes it's value""" def __init__(self, func): self.func = func self.name = func.__name__ self.cache_name = "_{0}".format(self.name) def __get__(self, instance=None, owner=None): if instance is None: ...
057258f6f8ec245ea98d6ccc1b0c4124494d3376
krunaljain/Data-Mining-top-influencers-in-a-social-network
/adjacencyMatrix.py
1,192
3.671875
4
# Adjacency matrix for the graph def create_adj_matrix(adjacency_list): max_length = 0 for node, neighbors in adjacency_list.items(): if node > max_length: max_length = node temp_max = max(neighbors) if temp_max > max_length: max_length = temp_max # initializ...
59f1ef08f8c86e9d443140c547ab007931505300
Jhumbl/A-Multilayer-Network-Understanding-of-Foursquare-Checkins
/network_functions.py
6,725
3.546875
4
''' NETWORK ANALYSIS COURSEWORK 2 FUNCTIONS ======================================== Author: Jack Humble Email: jack.humble@kcl.ac.uk Date: 01/04/2019 This document contains functions creating the networks for the project as well as the functions needed for the recommender system. ''' import pandas as pd import nump...
838ed45152864302cd35a611483bfecce3f9dbf4
tuankhaitran/Pythonpractices
/UnitTest/test_circle.py
685
3.859375
4
import unittest from circles import circle_area from math import pi class TestCircleArea(unittest.TestCase): # Test function def test_area(self): #Test when radius > 0 self.assertAlmostEqual(circle_area(1),pi) self.assertAlmostEqual(circle_area(0),0) self.assertAlmostEqual(circle_...
8318b83447b807eb82a5995a1859443fe98b77fa
chixujohnny/Leetcode
/Leetcode2019/58. 最后一个单词的长度.py
284
3.9375
4
# coding: utf-8 class Solution(object): def lengthOfLastWord(self, s): if len(s.replace(' ','')) == 0: return 0 s = s.strip().split(' ') return len(s[-1]) s = Solution() print s.lengthOfLastWord(' ') print s.lengthOfLastWord('hello world')
59a607099cab1ebce548777a49f0edace6ea11c6
Gummy-stack/Teaching-Python-on-stepik
/metiz_3.4-3.7.py
6,028
3.78125
4
""" 3.4. Список гостей: если бы вы могли пригласить кого угодно (из живых или умерших) на обед, то кого бы вы пригласили? Создайте список, включающий минимум трех людей, которых вам хотелось бы пригласить на обед. Затем используйте этот список для вывода пригласительного сообщения каждому участнику. """ guests = ['numb...
4e5131694561766df044283af92a3dff4adee528
DiegoSantosWS/estudos-python
/estudo-6/tuplas.py
2,221
4.09375
4
print("Tupla com parênteses") linguagens = ("Assembly", "Cobol", "C", "C++") print(linguagens) # para saltar uma linha no resultado, deixando mais fácil sua leitura # posso usar print() ou "\n" (quebra de linha) print("\nTupla sem parênteses") linguagens = "Python", "Java", "Go", "C#" print(linguagens) print("\nAcess...
00565d6f6597df1fb7cbd6f3f92678bb8753bf87
AlbertoParravicini/nlp-ulb
/assignment-1/code/perplexity.py
3,788
3.578125
4
import pandas as pd import numpy as np import re import timeit import string from language_model import preprocess_string def perplexity(string, language_model, log=True, vocabulary=list(string.ascii_lowercase[:26] + "_")): """ Computes the perplexity of a given string, for the specified language model. ...
a589d62705ba2f1e9aa51c3fa46c6176ebb273a6
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/bob/defc5c0f3d5f4c029a61737f7424d144.py
537
3.921875
4
# Implementation of Bob, a lackadaisical teenager def contains_alpha(str): """check if str contains any alphabet characters""" for x in str: if x.isalpha(): return True return False def hey(str): """Say str to bob. Bob responds (lackadaisically)!""" str = str.strip() if ...
9d1252ad15b454e333eda7af2dafa89c543ea135
zhangbo1888/timeTransverter
/timeTransverter.py
2,439
3.578125
4
from tkinter import * from time import * ''' 1、这个程序实现时间戳和日期格式的相互转换。 2、使用grid方法按照表格方式对组件位置进行安排 3、通过Button按钮进行转换和刷新操作。 4、通过Entry来获取用户输入。 ''' root = Tk() root.title('时间戳转换') root.resizable(0,0)#禁止拉伸 会变丑 # 对变量进行创建,和数据初始化 Label1 = Label(root, text='时间戳:').grid(row=0, column=0) Label2 = Label(root, text='日期:').grid(row=1, c...
993b5b868445d3049f15dc875f0b26db0aec85ad
DigiDuncan/AdventOfCode2020
/advent/advent.py
770
3.796875
4
from advent import days from advent.lib.utils import tryInt def main(): day = tryInt(input("Day? ")) part = tryInt(input("Part? ")) if not isinstance(day, int): print(f"{day} is not an integer.") return if not isinstance(part, int): print(f"{part} is not an integer.") ...
12499347984ced85f73ce2258db7bde81568490e
joe-salih/SelectionMenu
/Selection Menu Design v1.py
20,629
3.671875
4
#Imports import tkinter as tk from tkinter import * from tkinter import ttk from tkinter.ttk import * import tkinter.font as font def Space(): space =tk.Label(bg=bgSetting, text="\n") space.pack() #Global Variables fontSize = "Large" buttonSize = "Small" fontColour = "Black" bgColour = "Grey" ...
519753c34a57c9a96e65b429b28cce6f77a103c0
Dython-sky/AID1908
/study/1905/month01/code/Stage1/day08/exercise08.py
205
3.609375
4
""" 统计一个函数的执行次数 """ count = 0 def fun01(): global count count += 1 fun01() fun01() fun01() fun01() fun01() fun01() fun01() print("函数调用了{}次".format(count))
87aff466ed1f153d59c64f66725ef11e5c86d93d
shrddr/hyperskill
/Tic-Tac-Toe with AI/tictactoe.py
8,160
3.53125
4
import random def negate(char): return 'X' if char == 'O' else 'O' class Board: size = 3 def __init__(self, text=None, data=None): if text: self.data = [] if len(text) != self.size * self.size: raise ValueError for c in text: i...
cc9abcc56f86e00e0d6747a90cd93ecedd556a9e
roshankprasad/PythonScratchs
/scratch_27.py
1,127
3.96875
4
#hackerrank seating Arrangment question testcases = int(input()) for _ in range(0,testcases): seatNum = int(input()) divby3 = int(seatNum / 3) modby3 = (seatNum % 3) seatBerth = '' if modby3 > 0: compartment = divby3 + 1 else: compartment = divby3; oppositeCompartment = 0...
549d583f5e7959c381efaca191eafb7f7e11b3a2
KoderDojo/hackerrank
/python/challenges/algorithms/algo-reducestring.py
1,221
4.09375
4
""" Steve has a string, , consisting of lowercase English alphabetic letters. In one operation, he can delete any pair of adjacent letters with same value. For example, string "aabcc" would become either "aab" or "bcc" after operation. Steve wants to reduce as much as possible. To do this, he will repeat the above o...
1fe84444ac10a6a11944304adfaa4b498b3460f5
gresendiz/Python
/cubo.py
166
3.84375
4
#Funciones #Escibir el cubo de un numero def cubo(x): y= x * x * x return y a = int(input("Ingresa el valor: ")) b = cubo(a) print("el cubo es: ", b)
268a0ca3c7b728254fb027309d5dba3f7b396e29
ebsud89/leetcode_python
/python/list/Remove Duplicates from Sorted Array.py
356
3.5625
4
from typing import List class Solution: def removeDuplicates(self, nums: List[int]) -> int: idx = 1 for i in range(0, len(nums)): if i != 0 and nums[i - 1] != nums[i]: nums[idx] = nums[i] idx += 1 return idx s = Solution() nums = [1,1,2] print(s...
5e7b663cb61a3a1616ebc5dd78682204d13cb8a9
jjspetz/digitalcrafts
/py-exercises1/CtoF.py
179
4.46875
4
''' Python3 program that converts user inputed value in Celsius to Fahrenheit ''' temp = input("Temperature in C? ") temp = float(temp) * 9 / 5 + 32 print("{} F".format(temp))
193741fc10c6c6e36c662471a7985f23984a7851
pranay0124/cspp1
/cspp1-practice/M3/sum_1_end1.py
91
3.90625
4
n = int(input("Enter the value ")) sum = 0 for i in range(1,n+1,1): sum = sum+i print(sum)
bd076f0c97ce42e0c4c09a4ff32c7135de4ca313
Graham84/LearningPython
/Chapter 3 - Iterating and Making Decisions/simplefor1.py
323
4.3125
4
for number in [0, 1, 2, 3, 4]: print(number) for number in range(5): print(number) print list(range(10)) # one value: from 0 to value (excluded) print list(range(3, 8)) # two values: from start to stop (excluded) print list(range(-10, 10, 4)) # three values: steps is added(4)...
1e68e86f0b2b35377ab6173a9eb140dfa48e80d3
DamonReyes/Python_Classes-
/Python_Class/PRACTICE_PY/practice_D_S.py
2,646
3.6875
4
def practice_1(): nomb = input('cual es tu nombre?: ') nume = int(input('escribe el numero de reps: ')) print(f' {nomb} tiene {len(nomb)} letras') math1 = 2+3/2.5**2 print(math1) def practice_7(): horas = int(input('numero de horas trabajadas?: ')) coste = horas * 1000 pag...
fac39f56d8519489e825715a070e1c6890e10993
twy3009/sparta
/python/datetime_test.py
796
3.5625
4
import datetime def GetWeekNumberLastDate(year, weekNumber): yearFirstDate = datetime.datetime(year, 1, 1) currentDate = yearFirstDate + datetime.timedelta(weeks=weekNumber - 1) targetDate = currentDate - datetime.timedelta(days=currentDate.isoweekday() % 7 - 7) results = targetDate.strftime('%Y%m%d')...
50a9db4cdd0d9bc05ece204e273f77d158e53b5d
tpt5cu/python-tutorial
/language/python_27/operators_/asteriks.py
601
4.28125
4
#https://treyhunner.com/2018/10/asterisks-in-python-what-they-are-and-how-to-use-them/ """Also see the functions/parameters/kwargs_py notes""" def copy_dictionary(): """The ** operator can be used inside of a dict() construction to copy one dict into the new dict""" animals = { # Using this ** opera...
3d106b73baeb06e3bdeeb4ca1e3bc8a71d7b54e4
MichalGk94/Python
/MG5/rekurencja.py
462
3.9375
4
def factorial(n): wynik = 1 if n == 0 or n == 1: return wynik else: for i in range(1, n+1): wynik *= i return wynik def fibonacci(n): wynik = 0 liczba = 0 if n <= 2: return 1 elif n == 3: return 2 else: f1 = 1 f2 = 2 ...
a8e566888e8897be8544d1ae7fecf58be54e57ad
selbovi/python_exercises
/week3/vkladComplex.py
252
3.59375
4
a = int(input()) b = int(input()) c = int(input()) d = int(input()) total = b while d > 0: total = (b * 100 + c) + (a / 100) * (b * 100 + c) b = int(total // 100) c = int(total % 100) d -= 1 print(int(total // 100), int(total % 100))
08b4a7f3f12677e15afddd2d4cad952ecb3c88d0
daedalus/math
/fermat_factor.py
574
4.1875
4
#!/usr/bin/env python # Author Dario Clavijo 2020 # Example taken from https://en.wikipedia.org/wiki/Fermat%27s_factorization_method # GPLv3 import gmpy2 def fermat(n): a = gmpy2.isqrt(n) if a ** 2 == n: return a, a b2 = (a ** 2) - n step = 0 while not gmpy2.is_square(b2): a += 1 ...
f13082bd64d29c89fd481228db0b84cdc003591c
rasmusnuko/4sem
/ML/exercise/exercise_6/exercise6-3.py
1,028
3.984375
4
circles = [(1,3), (1,8), (1,9), (4,6), (5,7), (6,8), (7,6)] squares = [(5,4), (6,1), (6,3), (7,2), (7,4), (8,2), (8,3)] ks = [4,7,10] triangle = (6,6) def dist(p,q): # Manhattan dist return abs(p[0]-q[0])+abs(p[1]-q[1]) # Different k's for k-nearest neighbour for k in ks: list = [None] * k # Find dist...
d550bc52e83b8c8d3c36e6cc7ab9fdd56434db65
AayushRajput98/PythonML
/Practice/Tut1/Program4.py
187
4.3125
4
x=int(input("Enter the number")) while not x%2==0: print("Enter a number that is divisible by 2") x=int(input("Enter again")) print("You have finally entered the correct number")
7fbea669880a538a8c0c12c0a9119ebca3b2e6e3
amccarthy9904/foobar
/LeetCode/Medium/FindPeakElement.py
1,134
3.796875
4
# https://leetcode.com/problems/find-peak-element/ # 162. Find Peak Element # Medium # A peak element is an element that is strictly greater than its neighbors. # Given an integer array nums, find a peak element, and return its index. # If the array contains multiple peaks, return the index to any of the peaks. # You m...
29fdf7b3afa5bbae446008ec948e367952367703
OSP123/Python_exercises
/Assignment_2.py
1,009
4.15625
4
''' Printing a modular letter: Program has two variables, a letter string and a list with tuples inside. The print statements print the letterString. The strings within the tuples in the list replace the %s parts of the letterString. ''' letterString = 'Dear %s,\n\nI would like you to vote for %s\nbecause I think he ...
b583922c366c6e6b39567c1d0f7046bc446b3d07
adityaveldi/simplepythonprograms
/venv/functions.py
269
4.03125
4
# Now let us see how to use functions in python #we have to use def keyword for defining functions def add(x,y): a=x b=y c=a+b print('the sum is',c) x=int(input('enter first value for addition')) y=int(input('enter second value for addition')) add(x,y)
c2d30c76377cf3f3eabe69acf73425686e47070c
anniasebold/prog1-ufms
/if else/lanche.py
268
3.5
4
cod, qtd = input().split() cod = int(cod) qtd = int(qtd) if cod == 1: total = qtd * 4.00 elif cod == 2: total = qtd * 4.50 elif cod == 3: total = qtd * 5.00 elif cod == 4: total = qtd * 2.00 elif cod == 5: total = qtd * 1.50 print(f"Total: R$ {total:.2f}")
1e4a671bfd2b73a01e77db96b193dcabfac8c453
RubenPants/RobotSimulator2D
/population_inspection.py
1,007
3.5
4
""" inspect.py Inspect a population of choice. """ import argparse from collections import Counter from population.population import Population def count_genome_sizes(population): c = Counter() for g in population.population.values(): c[g.size()] += 1 return c if __name__ == '__main__': pa...
f5d1efa3aa9f480d7ff820ad04190935b66a0b14
Zylophone/Programming-for-Sport
/firecode.io/03-number_of_leaves.py
2,734
3.6875
4
class BinaryTree: def __init__(self, data, left_child=None, right_child=None): self.data= data self.left_child= left_child self.right_child= right_child def number_of_leaves(self,root): count_soFar = 0 node_stack = [] node_stack.append(root) whil...
0a4894f687a22fdc186de0cc0031b409e734c55d
Demitroy/Euler_Python
/euler_9.py
287
3.515625
4
# Find pythagorean triple where a + b + c = 1000 import time t1 = time.time() for a in range(1,500): for b in range(a,1000): if((a**2 + b**2)**(1/2))%1 == 0 and a+b+(a**2 + b**2)**(1/2) == 1000: print(a*b*(a**2+b**2)**(1/2)) print(time.time() - t1)
8636e96cc7c98ba30f884ba335480db9b71a0097
vyshuks/june-leetcoding-challenge
/search_in_binary_tree.py
725
3.90625
4
""" Given the root node of a binary search tree (BST) and a value. You need to find the node in the BST that the node's value equals the given value. Return the subtree rooted with that node. If such node doesn't exist, you should return NULL. For example, Given the tree: 4 / \ 2 7 / \ ...
ee43a379c19dbed25d6fb60c29243bd4c0857c02
cristiancmello/python-learning
/5-data-structures/5.3-tuples-sequences/script-1.py
682
4.28125
4
# Tuples and Sequences # TIPOS DE DADOS SEQUENCIAIS => list, tuple, range # Há um outro tipo sequencial => TUPLA tupla = 2, 5, 'hello' # ou (2, 5, 'hello') print(tupla) # (2, 5, 'hello') # Suportam Nested Tuples tupla = 1, 2, ('hello', 'world') print(tupla) # (1, 2, ('hello', 'world')) # IMPORTANTE! # TUPLAS ...
0402db8f23be68c3f26cf65ea4317fbf2fe231ad
msaei/coding
/LeetCode/Top Interview Questions/Math/Roman to Integer.py
659
3.75
4
#Roman to Integer #https://leetcode.com/explore/interview/card/top-interview-questions-easy/102/math/878/ class Solution: def romanToInt(self, s: str) -> int: vals = { "I":1, "V":5, "X":10, "L":50, "C":100, "D":500, "M":1000 \ , "IV":4, "IX":9, "XL":40, "XC":90, "CD":400, "CM":900 } ...
582fe920cc4dd459ec3f9b102f3f91dc5fd3960f
xpansong/learn-python
/列表/列表元素的排序.py
750
4.25
4
print('--------使用列表对象sort()进行排序,不生成新的列表,原列表直接运算,不需要重新赋值----------') lst=[10,90,398,34,21,77,68] print(lst,id(lst)) #调用列表对象sort(),对列表进行升序排序 lst.sort() print(lst,id(lst)) #通过指定关键字参数,对列表进行降序排序 lst.sort(reverse=True) print(lst,id(lst)) print('-------使用内置函数sorted()进行排序,生成新的列表,因此新列表需要重新赋值----------') lst=[10,90,398,34,21...
668d41c7030aacefd33ba83887146a75bf0361f7
27Saidou/cours_python
/EntityTp.py
338
3.875
4
def guest(): invites = ["Ramatoulaye ", "Ismatou", "Kadiatou", "Musk","Agier"] nom=input("Votre nom") if nom.capitalize() in invites: print("Bonjour Monsieur/Madame",nom) print("Bienvenue") else: print("Désole Monsieur/Madame{},Vous ne faites pas parti de la listes.".format(nom))...
9f7ee87ddc71893b4ff2307cf4944cc278c2d865
luo-simon/British-Informatics-Olympiad-Solutions
/Python/2018/2a.py
733
3.90625
4
n, word = input('> ').split() n = int(n) alphabet = [letter for letter in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'] def create_cipher(): cipher = [] index = 0 while len(alphabet) > 0: index += n-1 index = index % len(alphabet) # equivalent to i %= len(alphabet) cipher.append(alphabet[index]) ...
86c9c0021aabf848f6163aab7786e53ddb8f4c2a
czs108/LeetCode-Solutions
/Medium/43. Multiply Strings/solution (1).py
2,139
3.875
4
# 43. Multiply Strings # Runtime: 248 ms, faster than 11.81% of Python3 online submissions for Multiply Strings. # Memory Usage: 14.5 MB, less than 8.02% of Python3 online submissions for Multiply Strings. from itertools import zip_longest class Solution: def multiply(self, num1: str, num2: str) -> str: ...
e5e75a1c2cb0c7f4ce2975a6dfbb5c95c838618d
ahmadraad97/py
/numpy4.py
2,654
3.796875
4
from numpy import * # ممكن حساب الارقام التي ليست صفر a=random.randint(0,10,(3,3)) b=count_nonzero(a) print(a) # [[2 4 2] # [6 3 7] # [3 2 2]] print(b) # 9 # او تحديد عدد الارقام اكبر او اصغر من كذا a=random.randint(0,10,(3,3)) b=count_nonzero(a>5) c=count_nonzero(a<5) print(a) # [[0 4 1] # [4 9 4]...
170bb1b92f4fc47d6b4c26bd3730a26a6df17e1b
Subtracting/mp3player
/mp3db.py
1,123
3.546875
4
import sqlite3 def create_connection(db_file): conn = None conn = sqlite3.connect(db_file) return conn def insert_row(conn, timestamp, location, table): sql = f'INSERT INTO {table} (timestamp, location) values (?,?)' params = (timestamp, location) cur = conn.cursor() cur.execute(sql, par...
05ea4a76df73255cf316f6234b22084879070f6f
Nikunj-Gupta/Python
/practice/Level2/printdigit.py
114
3.5625
4
n = input("Enter a number: ") a = [] while(n>0): a.append(n%10) n = n/10 a.reverse() for i in a: print i
c8c90435d586999c357d3c77fcef016b934691eb
CaoZhens/ML_Learning
/study/4_PythonFoundation/distrubutionGenerate/DistributionWithRandom.py
2,362
4.09375
4
# coding:utf-8 ''' Created on Sep 30, 2017 @author: CaoZhen @desc: Distribution Generation 1. Uniform Distribution 2. Standard Normal Distribution 3. Gaussian Distribution @reference: 4.1.intro.py Section 6 ''' import numpy as np import matplotlib matplotlib.use('TkAgg') import matplotlib.pypl...
76648a0a63eccae1453622d4deb523aa4adfba86
sakshigarg22/python-projects
/error.py
309
3.78125
4
##rule 1 ##try: ## pass ##except: ## pass try: int('ddsd') except: print('error handled') while 1: try: i = int(input()) print(i) break except ValueError : print('not valid integer...try again') except EOF: print('please enter something')
6dc9ec45a1fef9a2465f1edcc1423248fae92fa3
wunnox/python_grundlagen
/U4_7_Menge.py
517
3.859375
4
#!/usr/bin/python3 ################################################################### # # Uebung: # Erstellen Sie folgendes Tupel: # a=('Petra','Hans','Fred','Hans','Ursula','Robert','Petra','Ursula','Hans') # Geben Sie die obigen Namen auf dem Bildschirm so aus, dass jeder # Name nur einmal erscheint. # #############...
519bed5582a275737e55c43ed81fe27652e1c533
abinashnayak1996/Function
/function9.py
148
3.609375
4
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] square = list(map(lambda x: x ** 2, nums)) print(square) cube = list(map(lambda x: x ** 3, nums)) print(cube)
4ff60f782c7d8f43f4a52ef187b7603bcd1ce5ea
edumaximo2007/python_remembe
/DESAFIO063.py
551
3.65625
4
import emoji print('=-=' * 10) print('''\033[7m DESAFIO 063 \033[m''') print('=-=' * 10) print(emoji.emojize(''':bulb: \033[1mEscreva um programa que leia um\033[m\033[1;35m número\033[m\033[1;32m n \033[m \033[1minteiro qualquer e mostre na tela os\033[m\033[1;32m n \033[m\033[1mprimeiros elementos de...
4e650257693dc3c2d683ea638a09e6c81fad9f18
juliecoleman/word-count
/wordcount.py
359
3.875
4
def count_words_in_file(filename): lines = open(filename) word_counts = {} for line in lines: words = line.split(" ") print(words) for word in words: word_counts[word] = word_counts.get(word, 0) + 1 return word_counts print(count_words_in_file("test.txt")) p...
43817943b0f55ae1c5ee5ea1a8ca454c749e3fde
brusetse/chaos
/py/hello.py
81
3.5
4
msg = "Hello world" print(msg) # 输入 # name = input() # print("I am " + name)
84b9605b9859f64085e738573f66569ba62f1cfe
michaelmcnees/server_side_languages
/lectures/helloworld/python.py
180
3.796875
4
import sys name = raw_input("What is your name?") f = open("myfile.txt", "w") # f.write("here is my text"+name) # f.close() # f.open("myfile.txt", "r") print(f.read()) f.close()
8a95f9363d8cfce24cc5be4fbae6af5467416a7f
SigmaQuan/BOOK-CODE-Learning.Python.The.Hard.Way
/lesson_49.py
8,423
4.375
4
""" Exercise 49: Making Sentences What we should be able to get from our little game lexicon scanner is a list that looks like this: # >>> from ex48 import lexicon # >>> lexicon.scan("go north") # [('verb', 'go'), ('direction', 'north')] # >>> lexicon.scan("kill the princess") # [('verb', 'kill'), ('stop', 'the'), ('...
4a5ab04f21bbf2ec2bcc5869a4490ecdbdd82c24
sun9121/CodeUp
/Python_basic100/59.py
719
3.78125
4
# 입력 된 정수를 비트단위로 참/거짓을 바꾼 후 정수로 출력해보자. # 비트단위(bitwise)연산자 ~ 를 붙이면 된다.(~ : tilde, 틸드라고 읽는다.) # ** 비트단위(bitwise) 연산자는, # ~(bitwise not), &(bitwise and), |(bitwise or), ^(bitwise xor), # <<(bitwise left shift), >>(bitwise right shift) # 가 있다. # 예를 들어 1이 입력되었을 때 저장되는 1을 32비트 2진수로 표현하면 # 00000000 00000000 00000000...
bcffc88f3cee0f80b84daedb5799477bed2b2f0b
sk-vojik/Intro-Python-I
/src/hello.py
410
3.796875
4
# Print "Hello, world!" to your terminal print("hello world") # class Animal: # # define attributes, assign initial values # def __init__(self, sound, leg_count=4): # self.leg_count = leg_count # self.sound = sound # def set_let_count(self, leg_count): # self.leg_count = leg_count # def make_sou...
2fa2f965f2ebb9c9a5ceef55c855cac6b18a2542
dhimanmonika/PythonCode
/Lambda,Map,Filter,Reduce/reduce.py
449
3.8125
4
""" The function reduce(func, seq) continually applies the function func() to the sequence seq. It returns a single value. """ from functools import reduce l=[1,2,6,3,4,9,7,23,66] print("original list ",l) # find the maximum number from the list max=reduce(lambda x,y:x if (x>y) else y,l) print("the max value from t...
cc33a3c72ebe849cec7d049de3e6d5526c8c1eff
DibPuelma/mlnd_capstone
/data_cleaner.py
3,827
3.5625
4
import requests as req import pandas as pd # https://twitter.com/RodrigoWagnerB/status/410907897019629568 API_HOST = 'https://api.rutify.cl/rut/' # get the address, commune and sex for each RUT in the database def get_data(rut): r = req.get(API_HOST + str(rut)) data = r.json() if 'servel' in data: ...
b55ff227de82e263b26d2fd838ce7cb2421560f0
tcandzq/LeetCode
/Math/IntegerBreak.py
1,753
3.5
4
# -*- coding: utf-8 -*- # @File : IntegerBreak.py # @Date : 2020-02-09 # @Author : tc """ 题号 343 整数拆分 给定一个正整数 n,将其拆分为至少两个正整数的和,并使这些整数的乘积最大化。 返回你可以获得的最大乘积。 示例 1: 输入: 2 输出: 1 解释: 2 = 1 + 1, 1 × 1 = 1。 示例 2: 输入: 10 输出: 36 解释: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36。 说明: 你可以假设 n 不小于 2 且不大于 58。 解法1:参考:https://leetcode-cn....
f57dff4d02a96ac4d4e28e7c6daee2329366fe07
stasvorosh/pythonintask
/INBa/2014/MorenkoAA/MorenkoAA_5_14.py
1,931
4.34375
4
# Задача 5, Вариант 14 # Напишите программу, которая бы при запуске случайным образом отображала название одной из двадцати башен Московского кремля. # Моренко А.А. # 16.03.2016 import random print('Программа случайным образом отображает название одной из двадцати названий башен Кремля') feat = random.randint(1,20)...
155c9422a450d5fd2e7de8e113244513c49b375f
olaruandreea/KattisProblems
/aah.py
233
3.734375
4
s1 = raw_input() s2 = raw_input() count_a1 = 0 count_a2 = 0 for each in s1: if each == "a": count_a1 += 1 for each in s2: if each == "a": count_a2 += 1 if count_a1 < count_a2: print "no" elif count_a1 >= count_a2: print "go"
1b95ba5d4e07b4298ff4a16202e0882031dd9465
erinrep/aoc
/2022/12/puzzle.py
1,954
3.828125
4
print("Day 12: Hill Climbing Algorithm") def valid_neighbor(elevations, curr, i, j): if i >= len(elevations) or i < 0: return False if j >= len(elevations[0]) or j < 0: return False next = elevations[i][j] if next == "E": next = "z" if next <= curr or ord(curr) + 1 == ord(next): return True ...
ba0cc4720686e2bd6d864db7eafd817437881987
sunanqi/algorithms
/quick_sort_random_pivot.py
1,612
4.125
4
""" - Problem: sort an array - Algorithm: 1. Select a pivot. If random_pivot == True, a random number is selected as pivot, otherwise the first number is pivot 2. swap numbers in the array until left part is all <= pivot and right part is all > pivot 3. recurse to sort the left part and right part - tim...
483e06bbb710bfb7a6c3495eb55c98f3ad4b08b6
tsutsuku/leetcode
/Trie/Word_Search_II.py
1,904
3.71875
4
#Question No.212 Word Search II class Solution: def findWords(self, board, words): """ :type board: List[List[str]] :type words: List[str] :rtype: List[str] """ root = Trie() for i in range(len(board)): for j in range(len(board[i])) class Trie: ...
3ad621858e6219a7f9d16bc89ce77ba6baee90b2
Ambitioner-c/Flower
/python/branch.py
961
3.984375
4
import turtle as t def draw_tree1(branch): # 条件满足先画右边 if branch > 10: # 绘制最开始的树干 t.fd(branch) # 然后右转30,第一个右分支 t.right(30) # 继续画右边的,走不动了往左边转60和下面一样用到了递归 draw_tree1(branch / 1.5) # 然后左转60 进入向左绘制 t.left(60) # 继续画左边的,走不动了右转30回到最后一步的之前那个节点 ...
b192adb8ab518f80293805134841f8cdc2b2e187
an-lam/python-class
/oo-examples/car1maincopy.py
1,033
3.84375
4
# car1main.py from car1 import Car toyota = Car("Toyota", 2005) print(toyota.make) print(toyota.year) print(toyota) toyota.year = 2017 honda = Car("Honda", 2010) print("Cars: {}: {}, {}: {}".format(toyota.make, toyota.year, honda.make, honda.year)) print("Cars: {0.make}: {0.year}, {1.make}, {1.year}".f...
8120ecd337b137ee0c7a6f4d0a8c194ae6fcd0c0
maleficus1234/School
/COMP452TME3/Game2/Tiles/Tile.py
1,641
3.515625
4
import pygame # Map for storage of tile sprites tileTextures = {} # Base class for tiles class Tile(object): # Create a tile using the given texture, with the given pathfinding cost. # -1 cost indicates inaccessibility def __init__(self, textureFile, cost): # Load the sprite if it hasn't alre...
ca9111c91a3af84b2f7b6ef3541bfd2a29b98368
kaloyandenev/Python-learning
/Odd Occurrences.py
329
3.515625
4
data_list = input().split() data_dict = {} data_list = [element.lower() for element in data_list] for element in data_list: if element in data_dict: data_dict[element] += 1 else: data_dict[element] = 1 for element in data_dict.items(): if element[1] % 2 != 0: print(f"{element[0]}", e...
271dd4f431070c14320b04b1794dbd8f88272ae9
cernst122/dev
/PythonReview/script.py
1,815
4.03125
4
# sales_tax=.095 # item_list={"water": 1.00, "milk": 1.50, "apple": .75} # def calc_tax(price): # return price*sales_tax # # def calculate_final_price(item_value): # return calc_tax(item_value)+item_value # # def calculate_final_price_by_name(item_name): # return calculate_final_price(item_list[item_name]) ...
1b3ad1f75c681cfd3781d7a3d20b587bc1545272
dquan101/MLE2020
/tarea_14_01_2020/menu.py
166
3.625
4
def menu(options): print("Bienvenido al menu!") print("\n".join(list(options.keys()))) return list(options.values())[int(input("Elija su opcion:")) - 1]
0ebba6345fbea934d42dca93b933d831bc0755fc
neilpa/euler
/Python/040.py
713
3.84375
4
#!/usr/bin/env python """ Problem 40 28 March 2003 An irrational decimal fraction is created by concatenating the positive integers: 0.123456789101112131415161718192021... It can be seen that the 12th digit of the fractional part is 1. If d_n represents the nth digit of the fractional part, find the value ...
fe29b3faa1353a37fa37f6a7eae041085d11c7d6
Aasthaengg/IBMdataset
/Python_codes/p02261/s555222998.py
1,096
3.5625
4
from copy import deepcopy def bubble_sort(lst): size=len(lst) for i in xrange(size): for j in reversed(range(i+1,size)): if lst[j].num<lst[j-1].num: tmp=lst[j] lst[j]=lst[j-1] lst[j-1]=tmp def selection_sort(lst): size=len(lst) for i i...