blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
1cfe9365f1ff2acde27bc54b09949f1132577819
ShowingDREAM/DataClassificationScript
/test_解压指定路径下的zip.py
377
3.71875
4
import os import zipfile def unzip_file(zip_src, dst_dir): r = zipfile.is_zipfile(zip_src) if r: fz = zipfile.ZipFile(zip_src, 'r') for file in fz.namelist(): fz.extract(file, dst_dir) else: print('This is not zip') unzip_file(a,b)// #zip_src:zipļȫ· #dst_d...
9f1073553733a94bc7326e07459ca0811eb98d9e
syurskyi/Algorithms_and_Data_Structure
/_algorithms_challenges/leetcode/LeetCode/437 Path Sum III.py
2,552
3.640625
4
#!/usr/bin/python3 """ You are given a binary tree in which each node contains an integer value. Find the number of paths that sum to a given value. The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes). The tree has no more than 1,00...
fe550073e2d99af768e06f6119ae16c3b7a70aae
terrantsh/Python--
/first/hello.py
658
3.953125
4
#-*- coding = utf-8 -*- #@Time : 2020/4/15 21:47 #@Author : Shanhe.Tan #@File : hello.py #@Software : PyCharm #my first python program print("hello world") #comment ''' comment a = 10 print("This is :", a) ''' ''' #format output age = 18 print("My age is %d \r\n" %age) age += 1 print("My age i...
4b79aa98fa5ba33043623e90ca7a9e505604a047
Runi-VN/PythonElective
/Week 7/ClassExercises/Regex.py
1,211
3.625
4
import re myStr = "Peter Hansen was meeting up with Jacob Fransen for a quick lunch, but first he had to go by Peter Beier to pick up some chokolate for his wife. Meanwhile Pastor Peter Jensen was going to church to give his sermon for the same 3 people in his parish. Those were Peter Kold and Henrik Halberg plus a th...
25e21a0b72ecb3d1b21f760f58d71e802dab5b7e
fslaurafs/Projetos-Python
/Curso em Vídeo/exercicios/Ex020 - Sorteando uma Ordem na Lista/ex20.py
328
3.796875
4
# SORTEANDO UMA ORDEM NA LISTA from random import shuffle a1 = str(input('Informe o nome do aluno: ')) a2 = str(input('Informe o nome do aluno: ')) a3 = str(input('Informe o nome do aluno: ')) a4 = str(input('Informe o nome do aluno: ')) l = [a1, a2, a3, a4] shuffle(l) print('A ordem de apresentação é: ',...
714b0803450961f4c56482424f9389d075d83f1b
AndrewPau/interview
/parentPostOrder.py
859
3.890625
4
""" Given a tree of height h constructed with integers [1...(2^h)-1] in postorder traversal, find the integers who are direct parents of each value in q, or -1 if the value is the root's. """ def answer(h, q): retVal = [] for converter in q: currHeight = h prev = -1 start = 1 end...
93b263e1f927cdecf82039f730fd6ec64ea7080c
diegomunhoz/python
/topico_3/exercicioMediaAritmetica.py
934
3.546875
4
# ********************************************************************************************* # ****** Programação II - 2º Ciclo Jogos Digitais ****** # ****** Programa: Faça um programa que que solicite ao usuário, para que digite 4 ****** # ****** notas e ...
6bd1eed135e4467e44a849d1dd99cd867074159e
naveenprao/algorithm
/searching_sorting/inversions.py
1,226
3.640625
4
import random def inversion(alist): inversions = [0] def _inversion(first, last): mid = (first + last) / 2 if first < last: _inversion(first, mid) _inversion(mid+1, last) i, j, k = first, mid+1, 0 temp = [None] * (last-first+1) while i <= mid an...
d2881c7e6fdf3e37595cf002a500766d7d5f3014
RaphaelCouronne/TravellingSalesmanProblem
/src/new/naive/permutations.py
927
4
4
# def Liste_Permutees(n): # """ retourne les permutations""" # verbose = False # if verbose: # print("--> entre dans permut n={0}".format(n)) # if n == 2: # if verbose: # print("<-- sortie de permut n={0}, p={1}".format(n, [[0]])) # return [[0]] # else: # ...
c3d7f00ce0b3f7cb5c9236bc06d19c6bc7ec3cfd
AlexanderPrincipe/Conceptos_Python
/pregunta2.py
161
3.9375
4
numero1 = int(input('Ingrese un numero')) numero2 = int(input('Ingrese otro numero')) print(numero1 + numero2) print(numero1 - numero2) print(numero1 * numero2)
2ff94008e05718d6f37653204813ace8a0918075
Marstaable/Repo_warsztaty
/week6/Fibo.py
531
3.640625
4
class Fib: def __init__(self,n): self.a = 0 self.b = 1 self.max = n # iter - zwraca obiekt iterowalny? # next - stopIteration? def __iter__(self): return self def __next__(self): while self.a <= self.max: t = self.a self.a = self.b ...
67576ac974a9b5d2377fe7bbcd4e22da3fb2e07a
skinnyporkbun/cs114
/Todolist.py
1,148
4.375
4
#Lists to use for if statements to check. As well as list to record data reminder = [] yeslist = ["Yes", "YES", "yes", "Y", "y"] nolist = ["No", "NO", "no", "N", "n"] #Intro to program, asks what users wants to be reminded of print("Hello! What would you like to be reminded of today?") #defines function for the progr...
2e826afc6a2511ab51613d63649e6e5e6ef55f8e
swbuild1988/leetcode
/0097. 交错字符串/main.py
966
3.640625
4
class Solution(object): def isInterleave(self, s1, s2, s3): """ :type s1: str :type s2: str :type s3: str :rtype: bool """ n1 = len(s1) n2 = len(s2) if n1+n2 != len(s3): return False dp = [[False for _ in range(n2+1)] for ...
1b71c51491af4a7e4c0e8b43c8508251fb3319f8
piksa13/ChallengingTasks4beginners
/ChallengingTask_level_3/unicode.py
233
3.953125
4
# -*- coding: utf-8 -*- #s = input() #exec("s") exec("print('Hello Word')") unicodeString = u"hello world!" print(unicodeString) #unicodeString1 = u(input()) #print(unicodeString1) #s = input() #u = unicode( s ,"utf-8") #print(u)
0068ed2345c46cc157ef42a317e424c5bdf10644
Liang-WenYan/Python-Crash-Course
/Chapter9_2.py
681
3.546875
4
class Restaurant(): def __init__(self, restaurant_name, cuisine_type): self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type def describe_restaurant(self): print( "\nThe restaurant named " + self.restaurant_name.title() + " is serves " + self.cuisine_type.t...
1b0cb66a89bb49f8520e3fa03a9c316219d74ad7
Aanand98/Python---CodeKata
/amstrongrange.py
553
3.546875
4
def amstrong(n): number = n list = [] while number != 0: num = number % 10 num = num ** 3 list.append(num) number = int(number/10) number = sum(list) if number == n: return 1 else: return 0 value = 0 list_values = input() list_values = list_values....
05d397ee05ba9bfff9846e552d151e728bf5ede7
yyangyncn/core_programming
/core_programming/chapter7/demo.py
142
3.78125
4
import operator dict2 = {'name': 'earth', 'port': 80} dict3 = {1: 'earth', 'port': 80} for eachKey in sorted(dict2): print(eachKey)
bcb300a6483153b335212ed468f2119829da010b
yungxinyang/Python200803
/day1-4.py
187
3.609375
4
# -*- coding: utf-8 -*- """ Created on Mon Aug 3 13:49:32 2020 @author: user """ score=input('score') score=int(score) if score>=60: print('pass') else: print('fail')
6ba0f0525bfd39ac66a8cd32d2dd66c2997d5311
balaorcl/hello-streamlit
/caching.py
1,470
3.96875
4
import streamlit as st import pandas as pd import numpy as np import plotly_express as px """ Caching In our simple app. We read the pandas dataframe again and again whenever a value changes. While it works for the small data we have, it will not work for big data or when we have to do a lot of processing on the data...
42ec6bacc76d6918ed316efd0021cd1ad20b5c5d
vicchu/leetcode-101
/03 Hashing/Practice/08_election_winner.py
734
3.796875
4
# Print the name of candidate that received Max votes. If there is tie, print lexicographically smaller name. Function to return the name of candidate that received maximum votes. def winner(self, arr, n): if n == 1: return [arr[0], 1] # return the name of the winning candidate and the votes he reciev...
8bee85923ada9a3903f819dfe679312f02a5f903
TryNeo/practica-python
/ejerccios/ejerccio-84.py
1,784
3.828125
4
#!/usr/bin/python3 """ Un almacén de ventas de productos por catálogos dispone de n vendedores asignados mensualmente de forma aleatoria a 4 regiones.ventascatalogo El gerente de ventas mensualmente registra los montos de las ventas por cada vendedor para luego determinar el total de ventas en dólares por región. ...
cda9d85befe1a90979f3faee5dfad73a8254b16f
gyang274/leetcode
/src/1400-1499/1418.display.orders.in.restaurant.py
1,046
3.578125
4
from typing import List from collections import defaultdict class Solution: def displayTable(self, orders: List[List[str]]) -> List[List[str]]: foods = sorted(set(x[2] for x in orders)) fdict = {f: i for i, f in enumerate(foods)} tdict = defaultdict(lambda: [0] * len(foods)) for x in orders: td...
30907fc27c9de894e816d79ea4fca396f2f1e8d2
thermoptics7/EDX
/mystery.py
682
4.71875
5
#Write a for loop that finds the factorial of mysteryValue and prints it. A #factorial of x is the multiplication of every number from 1 to x. For #example, the factorial of 5 = 5 * 4 * 3 * 2 * 1 = 120. import sys mysteryValue = int(sys.argv[1]) print("~ testing with mysteryValue = {} ~".format(mysteryValue)) #Don't ...
7bd52e23d15f2bddb07edc77ac7e3223c3aecaf1
ShuhaoZQGG/CodeWars_Solutions
/6 kyu/Playing_with_Digits.py
608
3.71875
4
def dig_pow(n, p): # your code # n = x*p # n (a,b,c,d) for example 9476 (9,6,7,4) # Is there an integer k such as : (a ^ p + b ^ (p+1) + c ^(p+2) + d ^ (p+3) + ...) = n * k # first find every digit (a,b,c,d) of n x = 0 n = str(n) digits = [int(digit) for digit in n] for count, ele in...
1c0c6257d3b5c3da3cd139d50385745f7a2eb447
HenriqueNO/Python-cursoemvideo
/Desafios/Desafio_028.py
559
3.9375
4
perg = int(input('Vou pensar em um numero de 0 a 5, tente advinhar!\n Em qual número eu pensei?')) from random import randint from time import sleep print('PROCESSANDO...') sleep(2) num = randint(0, 5) if num == perg: print('=-='*8, ' PARABÉNS!!! ','=-='*8) print(' O número escolhido era {}!'.format(num)...
aecf108367728cfd7fbad42415cc055ffa35c90c
Valim10/Uri
/2650.py
286
3.515625
4
qtd,alt= raw_input().split() qtd = int(qtd) print "aaa" while qtd > 0: titan = raw_input() titan_v = titan.split() name_titan = titan.strip(titan_v[len(titan_v)-1]) ttitan = titan_v[len(titan_v)-1] if int(ttitan) > int(alt): print name_titan qtd= qtd-1
50d42082097cb47a2e8e3d2e2dab855b8378c4e6
gabriellaec/desoft-analise-exercicios
/backup/user_396/ch42_2019_09_11_13_25_34_530022.py
154
3.59375
4
def quantos_uns(x): s = 0 numero = str(x) for i in numero: if i == '1': s += 1 else: s += 0 return s
af43d8b01c29c3b8554c32319371491306f9fb34
balocik/Simple-Python-Games
/TwoDies.py
430
3.9375
4
#--------------------------- # 01/10/2017 # created by Wojciech Kuczer #--------------------------- import random numer = 1 while numer == 1: die1 = random.randint(1, 6) die2 = random.randrange(6) + 1 print("\nDie 1: " + str(die1)) print("\nDie 2: " + str(die2)) print() print("Result is...
befb370ba8184c5040031f2a9af27a1578a0c7e5
Isaacg94/password-locker
/password_test.py
3,719
3.671875
4
import unittest import pyperclip from passwords import User, Credentials class TestUser(unittest.TestCase): """ Test class that tests the User class. """ def setUp(self): """ Method that will run before each test. """ self.new_user = User("Isaac", "Gichuru", "123456") ...
e5a1b1f34c477f8e7833b7d68ba12001dab44d00
augustedupin123/python_practice
/p81_1st_nonrepeating.py
513
4.125
4
#Write a program to find the first non repeating character in a given string '''def string_nonrepeat(str1): str2 = '' for i in range(len(str1)): if (str1[i] not in str1[:i] and str1[i] not in str1[i+1:]): print (str1[i]) string_nonrepeat('abcaaxbxxklm') Above code is printing all unique...
485a773738b891aba77ba87f3bf6ec8222f6b1e2
shim1998/Competitive-Programming
/ds/postorder.py
830
4.28125
4
class Node: def __init__(self, value): self.left = None self.right = None self.data = value """ In this traversal method, the root node is visited last. First we traverse the left subtree, then the right subtree and finally the root node. POSTORDER - (left, right, root) """ def postorder...
f458aa0ed4dfec2ebf374cc1fa4eb9015311a48f
jlesca/python-strings
/slicing-strings.py
719
4.09375
4
# CORTAR NUESTRAS STRINGS # Python nos permite cortar nuestras strings de manera que podamos tomar las posiciones de los caracteres que deseemos. # Para eso debemos indicar entre [corchetes] las posiciones de inicio y fin, separados por : (dos puntos). name = "Koche" # Creo la variable con su valor Koche. print(name[2...
d489f34bc2e0467f3a07c9127c22d81af9a00ea1
MaxGolden/5590_Python_Deep_Learning_Lab
/Lab1/Hongkun_Jin_Lab1/Source/lab1_1.py
1,140
4.15625
4
""" Lab 1 - 1 Write a program that computes the net amount of a bank account based a transaction log from console input. The transaction log format is shown as following: Suppose the following input is supplied to the program: Deposit 300 Deposit 250 Withdraw 100 Deposit 50 Then the output should be ...
e7518a4ddcbcab69b1798508af47256f5cb44a32
aleonardh/ALS
/LABO2/Ej1/main.py
647
3.671875
4
import statistics class Uno: def __init__(self, sec): self.sec = sec def media(self): res = 0 for x in self.sec: res += x return res / len(self.sec) def mayor(self): return max(self.sec) def menor(self): return min(self.sec) def desvia...
88577f90bb6db55a97346db8dbf25625310d076f
brucette/Programming-stuff
/Private_Critter.py
636
3.875
4
# demonstrates private attributes and methods class Critter(object): def __init__(self, name, mood): print("A new critter has been born!") self.name = name # public attribute self.__mood = mood # private attribute def talk(self): print("\nI'm", self.name) pr...
25f625841b64603efeccfbda5a29a9b36262b1af
thehadiaman/DecimalToBinaryConvertionAlgorithm
/binaryConverter.py
393
3.96875
4
def toBinary(num): binaryNumber = [] b = 0 while num != 0: a = num % 2 num = int(num/2) binaryNumber.insert(b, a) b += 1 binaryNumber.reverse() binaryNum: str = '' for a in binaryNumber: a = str(a) binaryNum += a return binaryNum decimal...
437464f279867f51ae8f100cc5938961a9efa38e
MadhukaraBS/python-challenge
/PyPoll/main.py
1,783
3.5
4
import sys import csv # Initialize all variables used below. Not needed for Python # but is it a good practice? cand_vote_count = {} total_votes = 0 # open data file and output file with open("election_data.csv", 'r', encoding="utf8") as infile, \ open("election_results.txt", 'w', newline=None) as outfile: ...
226fb3f9f55a7336f62ecc0c9380a6a2b76d510a
bj1570saber/muke_Python_July
/cha_6_7_flow_control_N_loop/7_13_dir_name.py
799
4.03125
4
import sys,c7 print('~'*20) print(dir(sys)) # dir() retrieves variables list from parameter module. print('~'*20) print("\nc7.py: "+ str(dir(c7))) # How to use __name__ if __name__ =='__main__':#!!!!!! print('This is an app.'+ __name__) # This line will not print, if another .py file import this module. else...
e083bb157974214f7829c2ee370d6aecb923f54e
sjmcmullan/N-Queens-Problem
/HCS/HCS.py
5,715
4.15625
4
import random import time import sys # This will create a completely random board as a start point. def GenerateInitialBoard(gameSize): board = [] # Each queen will be at a random column. However, they will be placed on unique rows. for i in range(0, gameSize): board.append(random.randint(0, gameS...
43850cbfb8750f651d120647fe2f0f3c9dfddc60
liucheng2912/py
/100例/12.py
606
3.953125
4
""" 判断101-200之间有多少个素数,并输出所有素数 思路: 1、素数定义 只有1和自身能整除的数, 1是素数 2也是素数 3也是素数 5也是素数 7也是素数 11也是素数 2、判断素数 既不是奇数也不是偶数的数 n==1 or n==2 or n==3: print(n) n%2!=0 and n%3!=0 print(n) 缺点: 素数判断方法有问题 应该是用素数除以1到素数本身-1的范围,能除尽就不是素数 """ for i in range(101,201): count=0 for j in range(2,i): if i % j ==0: c...
9da3218e8cde2ea817ee33ca9938e3dce3bb5f23
xukangjune/Leetcode
/solved/107. 二叉树的层次遍历 II.py
1,416
3.875
4
# Definition for a binary tree node. """ 本题和102题一个套路,只不过结果要反向输出,第一种是使用头递归加上BFS的方法,每一层都先向下递归,后加入返回数组中,这样可以实现逆序输出。还有 一个即直接逆序输出102题的结果。 """ class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def levelOrderBottom(self, root): """ ...
5be91bb082deeec454798b0c989dfbdf18495db3
kintanuki/50-ejercicios
/ejercicio 5.py
232
4.09375
4
print("Este programa se realizo con el fin de seperar un decimal y su entero") num=float(input("ingresa un número decimal:")) print(f"la parte entera de tu decimal es: {int(num)} , y la parte decimal es:{num%int(num)}")
899c35f83ba3cf4f0b6fdb863be38246d39e1429
SohanJadhav/python_assignments
/Assignment2/Assignment2_8.py
242
3.765625
4
def DisplayPattern(no): for i in range(1, no+1,1): for f in range(1,i+1): print(f, end=" ") print("") def main(): no=int(input("Enter Number")) DisplayPattern(no) if __name__=="__main__": main()
5b7e3ba691ce64d3f29f73487b93fe3de0a2fecf
Sigald/code
/LPTHW/ex6.py
921
4.4375
4
# sets a value to a variable types_of_people = 10 # sets a formated string to x, targeting the variable above x = f"There are {types_of_people} types of people" # sets a sting to a variable binary = "binary" do_not = "don't" # sets a formated string to x, targeting the variables above y = f"Those who know {binary} and...
7d938fee321c7907b63b5937518675d5c23f2905
shreyamandolia/movies_database
/all_together.py
1,391
3.734375
4
# database,exeptional handling,module,tinkter # creating database import sqlite3 connection = sqlite3.connect('movies.db') print("Database opened successfully") TABLE_NAME ="movies_table" MOVIES_ID = "movies_id" MOVIES_NAME = "movies_name" MOVIES_DURATION = "movies_duration" MOVIES_RATING = "movies_rating" MOVIES_GEN...
4225b371181047968f90143a97553222edd9239d
UnimaidElectrical/PythonForBeginners
/Random_code_store/Dictionaries/Dictionaries_3.py
7,830
4.65625
5
##############:::::::::::::::::::::::##############**********################ ###:::: ###:::: ###:::: Dictionaries Revisited: ###:::: ###:::: ###:::: ######...
d546c8ff7e56f2ef8c37a187f4fc6f690f008687
mkhoin/pycodinglec
/예제및유제(190608)/Level 2/[예제2-8]삼각형넓이.py
242
3.921875
4
# 출력: 삼각형의 넓이(s) # 입력: 삼각형의 밑변(b)과 높이(h) print("삼각형의 넓이 구하기") b = float(input("밑변: ")) h = float(input("높이: ")) s = str((b*h)/2) print("삼각형의 넓이는 "+s+"입니다.")
4a63b1ab3df2f0ecf313eae0e3c80f90f517965e
XUANXUANXU/1-1803
/09-day/26章作业题/3.账户密码.py
209
3.859375
4
user_name = "小可爱" password = 000000 acc = input("请输入用户名") pwd = int(input("请输入密码")) if acc == user_name and pwd == password: print("登陆成功") else: print("登录失败")
e5800e6690d28a2f72b8d0d20f397a67f7360a3d
MrHamdulay/csc3-capstone
/examples/data/Assignment_4/nwtdou001/ndom.py
644
3.625
4
import math def decimal_to_ndom(num): pow = int(math.log(num,6)) sen = '' while pow>=0: dig = 6**pow mul = num//dig sen += str(mul) num -= mul*dig pow -= 1 return int(sen) def ndom_to_decimal(num): num = str(num) dec = 0 length = len(...
7f9604eb83115df0f6502a7f0360018cf036efcf
GauthamAjayKannan/GUVI-1
/hunter22.py
162
3.609375
4
list1 = list(map(int,input().split(" "))) product = 1 list2 = [] for i in list1: product = product * i for i in list1: list2.append((product//i)) print(*list2)
a0f25b59aae3d6c7a8c429430bea0b97e5b03c6a
Yoda-BZH/http-cache-analyzer
/http_cache_analyzer/result.py
1,096
3.703125
4
class result(): rtype = None text = "" recommendation = None def __init__(self, rtype, text, recommendation = None, score = 0): self.rtype = rtype self.text = text self.recommendation = recommendation self.score = score def show_entry(self): prefix = "[??] " if self.rtype == "ok": ...
7f0c84ed3c317575839326bbbe33de4e62d885ad
makhtardiouf/Pyvibes
/classes.py
1,619
3.953125
4
''' Demo for Classes, simulating pseudo stock market operations ''' # import math import random import datetime class Stock: availDate = datetime.date.today() # Conctructor of the object def __init__(self): self.type = "BTC" self.shares = [] def add(self, x): self.shares.appe...
1cdfe3c1def12781d7d233e7d348d2fe0c9c4923
Tenksomm/passwordgenerator
/passwortgenerator.py
1,831
4.03125
4
import random import string import time letters = string.ascii_letters + string.punctuation + string.digits counter = 0 x = int(input("Wie lang soll das Passwort sein?\n")) f = open("generatedpasswords.txt", "a") print("Vorgang wird bearbeitet") time.sleep(2) hello = str() if x <= 5: print("\nWenn du ein sicheres ...
f595e4dbb9a8267b869e1bb1b7d61e764ed4b7fc
shrish1294/Simple-Genetic-Algorithm
/check_better_prediction.py
4,194
3.53125
4
import numpy as np import random from copy import deepcopy import matplotlib.pyplot as plt def initialize(N): Map = np.zeros((N,N)) for i in range( 0 , N): for j in range(0 , i): Map[i][j] = random.randint(0,6) Map[j][i] = Map[i][j] return Map def Print(N , Map): ...
6f5f159ba13f6b9524e11753b3564f69200b638a
chicochico/exercism
/python/tournament/tournament.py
1,874
3.546875
4
class Team(): def __init__(self, name): self.name = name self.wins = 0 self.draws = 0 self.losses = 0 @property def points(self): return self.wins * 3 + self.draws @property def matches_played(self): return self.wins + self.draws + self.losses d...
95498423ea5003defb23428b8ca3393fc45610c5
chaoticfractal/Python_Code
/Factorial.py
390
4.25
4
""" A simple function to calculate the factorial of a integer """ #This first version just uses a simple while loop def factorial(n): num = 1 while n >= 1: num = num * n n -= 1 return num print factorial(10) #This version uses recursion def recfac(n): if n == 1 or n == 0: ...
1218eb2a6ac77aecfdef4846500dc1623c58c418
FefAzvdo/Python-Training
/Exercicios/Aula 10/033.py
738
4.25
4
# Condição de existência de um triângulo # Para construir um triângulo não podemos utilizar qualquer medida, tem que seguir a condição de existência: # Para construir um triângulo é necessário que a medida de qualquer um dos lados seja menor que a soma das medidas dos outros dois e maior que o valor absoluto da difere...
4fe2512ebbfa9c8a163c47f1039620f230cf103c
reyllama/leetcode
/Python/#1312.py
1,271
4.1875
4
""" 1312. Minimum Insertion Steps to Make a String Palindrome Given a string s. In one step you can insert any character at any index of the string. Return the minimum number of steps to make s palindrome. A Palindrome String is one that reads the same backward as well as forward. """ class Solution(object): de...
92b6f4a93b261b084eba4474fe50da0441814079
ananyo141/Python3
/hours_to_min.py
214
3.671875
4
#WAP to convert hours to minutes def convert_to_min(in_hours): '''(num)-->num Return the numbers of minutes in in_hours >>>convert_to_min(9) 540 >>>convert_to_min(20) 1200 ''' return in_hours *60
a6b6465cdcb2050608ed97700d48b00f166ae95b
priyamore/lc-problems
/data-structures/containsDuplicate.py
981
4
4
''' Problem Statement - Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct. Example 1: Input: nums = [1,2,3,1] Output: true Example 2: Input: nums = [1,2,3,4] Output: false ''' #Solution 1 - using dict class Solution: def co...
6ab737b3d96d233193b40a4b88f841ae8c6e45e1
Lee-3-8/CodingTest-Study
/level2/수식_최대화/규빈.py
1,174
3.6875
4
import re def solution(expression): nums = re.findall(r"\d+", expression) operand = re.findall(r"\D", expression) order = list(set(operand)) S = operation(nums, operand, order) # 길이가 1일때 예외처리 lenOrder = len(order) for i in range(lenOrder): order[0], order[i] = order[i], order[0] ...
8538c0d9f3ee52a5b82687212e3a22c07e7693c2
Khaitsev/PYTHON_lessons
/Tasks/Les1/Task_6.Les_1.py
966
4.1875
4
print('Задание 6. Спортсмен занимается ежедневными пробежками. В первый день его результат составил a километров. ' '\nКаждый день спортсмен увеличивал результат на 10 % относительно предыдущего. Требуется определить номер дня, ' '\nна который общий результат спортсмена составить не менее b километров. Прог...
85be807eb7966a209bb6fca9258d56c9790e002f
Erivks/aprendendo-python
/Coursera/coh-piah/v.1.0/média_palavras.py
1,440
4.09375
4
import re text = "Navegadores antigos tinham uma frase gloriosa: ""Navegar é preciso; viver não é preciso"".Quero para mim o espírito [d]esta frase,transformada a forma para a casar como eu sou:Viver não é necessário; o que é necessário é criar.Não conto gozar a minha vida; nem em gozá-la penso.Só quero torná-la grand...
3a0db4f1bc9e21948b7f1d220f342213a00ad7c8
Brian-Mascitello/Random-Projects
/Python Projects/CodingBat code practice/Warmup-1/not_string.py
915
4.15625
4
# -*- coding: utf-8 -*- """ Author: Brian Mascitello Date: 1/4/2016 School: Arizona State University Websites: http://codingbat.com/prob/p189441 Info: Given a string, return a new string where "not " has been added to the front. However, if the string already begins with "not", return the ...
51750a44076159c024434f971490e881b2a68300
keyPan-GitHub/MyPythonCode
/day3/匿名函数与内置函数(二).py
4,362
3.765625
4
# 匿名函数 lambda def f1(): return 123 f2 = lambda: 123 r1 = f1() print(r1) r2 = f2() print(r2) def f3(a1, a2): return a1 + a2 f4 = lambda a1, a2: a1 + a2 r3 = f3(1, 2) print(r3) r4 = f4(3, 4) print(r4) # 内置函数 # 绝对值 i = abs(-123) print(i) # all 循环参数,如果每个元素都为真,那么all的返回值为真 # r = all([True,True,False]) # ...
8ea311da0faa58257a9146335dd6d69c8783357f
atillman4/python
/Act11_2_Task2_TEAM256.py
1,036
3.671875
4
# HW 8.1 Python Individual #File: HW8_1_Task1_functions_Tillmaaa.py #Date: 28 Oct 2018 #By: Alex Tillman # Justin Kohler # Ryan Steffen # David McCoy #Section: 021 #Team 256 # #Electronic Signature # Alex Tillman # # # #This electronic signature above indiccates the script #submitted for eval...
3a1b95fab4dc990a22cde0d4265ef32e6e416434
ajhe/myAutoTestFrame
/test_page/get_time.py
431
3.5
4
# coding=utf-8 import time class GetTime(object): """ 获取当前时间的类 """ def get_system_time(self): print (time.time()) #time.time()获取从1970年到现在的时间间隔,单位为秒 print (time.localtime()) #当前时间 new_time = time.strftime('%Y%m%d%H%M%S', time.localtime()) print ne...
8e6b2c43f74470173be1707d559d5b005c5ceb42
EndIFbiu/python-study
/04-循环/18-for...else之break-continue.py
282
3.8125
4
str = "success" for i in str: if i == 'e': break print(i, end="") else: print("循环正常结束执行的代码") print() str = "success" for i in str: if i == 'e': continue print(i, end="") else: print("循环正常结束执行的代码")
44e72f6dd732f2131721a40b42644dbc6cb38e2f
sandeepkumar8713/pythonapps
/21_firstFolder/27_backspace_string_compare.py
1,407
3.875
4
# https://leetcode.com/problems/backspace-string-compare/ # Question : Given two strings S and T, return if they are equal when both are typed into empty text # editors. # means a backspace character. # # Example : Input: S = "ab#c", T = "ad#c" # Output: true # Explanation: Both S and T become "ac". # # Question Type :...
e9690d2a403089791a99554a158b0f1938a8942f
sadieBoBadie/Dec2020Python
/Week1/Day5/for_loop_review.py
691
3.78125
4
# for i in range(0, 10, 1): # print(i) # print("*"*15) # fruits = ["apples", "mangoes", "durians", "kiwis"] # for i in range(len(fruits)): # print(fruits[i]) # print("*"*15) # for fruit in fruits: # print(fruit) # print("*"*15) class User: def __init__(self, first, last): self.first_name...
918b41a08941b780d41b5a36b9d0b6b1ea7778a8
swanyriver/leetcode
/twocombinationssum.py
636
3.5
4
from itertools import combinations class Solution(object): def combinationSum2(self, candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ cadidates = sorted(set(candidates)) answer = [] ...
2d1e60940250b4f98a9ebc2e09b1988864b410e2
ntire/AdventOfCode2020
/day6-py/questions/yes_counter.py
732
3.765625
4
def count_unique_answers_of_anyone(all_answers): unique_answers = set() for answer in all_answers: for item in answer: unique_answers.add(item) return len(unique_answers) def count_unique_answers_of_everyone(answer_group): # initialize counter = dict() for letter in range(2...
1c49706b04d70f7d4a83c06adc98208f37e49fac
kolisachint/Learn-Python-the-Hard-Way
/Exercises/ex44a.py
272
3.78125
4
#!/usr/local/bin/python3 # _*_ coding: utf-8 _*_ # Basic Object- Oriented # Implicit Inheritance class Parent(object): def implicit(self): print("PARENT implicit()") class Child(Parent): pass dad = Parent() son = Child() dad.implicit() son.implicit()
e62c6f4f23819d1f46557d0764e97f34a35a8148
davidyip50/WallBreakers
/unionFind/surrounded_regions.py
4,109
3.65625
4
from collections import defaultdict class Solution(object): def find(self,parent,node): if(parent[node] == -1): return node else: return self.find(parent,parent[node]) def solve(self, board): """ :type board: List[List[str]] :rtype: None D...
70f30538b8b1617772426a7c8cdd599064d3df56
jxxl1203/leetcode
/155/solution.py
715
3.828125
4
import sys class MinStack(object): def __init__(self): self.stack = [] self.min_num = sys.maxint def push(self, x): self.stack.append(x) if x < self.min_num: self.min_num = x def pop(self): """ :rtype: None """ a = self.stack[-1]...
7eca1a74a679dc99965c9b979f6f68e749c92e2f
rsersh/fantastic-bombastic
/names.py
1,616
3.921875
4
NAMES = ['arnold schwarzenegger', 'alec baldwin', 'bob belderbos', 'julian sequeira', 'sandra bullock', 'keanu reeves', 'julbob pybites', 'bob belderbos', 'julian sequeira', 'al pacino', 'brad pitt', 'matt damon', 'brad pitt'] def dedup_and_title_case_names(names): """Should return a lis...
d71f530885ef33c9215b58db47accc4c2c8bf533
viniciusmartins1/python-exercises
/ex024.py
117
3.6875
4
cidade = str(input('Em que cidade você nasceu? ')).rstrip().lstrip().upper().split() print('SANTO' in cidade[0])
0c34f5d365621377d9eca5f2f805185c46a67ed2
murali-kotakonda/PythonProgs
/PythonBasics1/basics/functions/Functions.py
2,288
4.09375
4
# code :- reused in diff places of ur project #solution: write code once and reuse any no of times ==> FUNTIONS # EX: #syntax # create a funtion with no input and no output def sayHi(): print("hi") print("hello") print("welcome to python function") # call the function sayHi() sayHi() x=30 # global # crea...
053c422043f773bf3f85fec35ab1c2922a5205c4
caiocezarccas/Curso-Python
/ex29.py
919
4.09375
4
velocidade = float(input('Digite a velocidade que você estava: ')) if (velocidade >= 81): print('''Você ultrapassou o limite de velocidade! Você será MULTADO e a multa é 7,00R$ por Km/h ultrapassado.''') valor_km = 7.00 multa = (velocidade - 80)* valor_km acréscimo = 400 valor_total = multa...
d68f24ac5fbdbb899f041ce1062679d7b950ccc2
Cazeck/PracticeProjects
/7. Real Estate Webscraper/7a. Webscraping With Beautiful Soup/scrapper.py
524
3.671875
4
import requests from bs4 import BeautifulSoup # Request information from Website r = requests.get("http://www.pyclass.com/example.html", headers={'User-agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:61.0) Gecko/20100101 Firefox/61.0'}) # Pull data from request (HTML) c = r.content soup = BeautifulSoup(c, "html....
a06107dde88defc27c9792b148546d3ad020dbb2
c0rekt/WorldPopulation
/c0rekt_WorldPopulationData2019.py
5,494
4.03125
4
data = [] continentData = {} rank, country, y2018, y2019, share, popChange, percentChange, continent = 0,1,2,3,4,5,6,7 #open file file = open('WorldPopulationData2019.txt', 'r') with file as f: #skipping first 2 rows next(f) next(f) #reading from 3rd row onwards for line in f: ...
84565ff0c6a6c0138e55c42030493bd9fb06fa8d
doolypark/discordWeatherBot
/main.py
3,167
3.5
4
import json import requests from pprint import pprint import discord from discord.ext import commands # creates discord client and stores it in "client" # this is our bot bot = commands.Bot(command_prefix='!') @bot.event async def on_ready(): print('Powering up {0.user}... ONLINE'.format(bot)) @bot.event asyn...
664b3c40c2fb472aa66a78656d1db7716ab80f74
RRoundTable/CPPS
/week7/Longest_Increasing_Subsequence.py
2,120
4
4
''' link: https://leetcode.com/problems/longest-increasing-subsequence/ Given an unsorted array of integers, find the length of longest increasing subsequence. Example: Input: [10,9,2,5,3,7,101,18] Output: 4 Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4. Note: There may ...
23a43d4e2666a982259cba9d832fbe98f5450590
mayaragualberto/URIOnlineJudge
/Python/1008.py
113
3.53125
4
NF=int(input()) HT=int(input()) VH=float(input()) print("NUMBER =",NF) print("SALARY = U$ {:.2f}".format(HT*VH))
a736a10ce55daf03fd690fb07ec3faa961473eb8
mohammad-areeb/Python-programmes
/Multiplication Tables.py
304
3.984375
4
i=1 e=int(input("enter the number whose table you want to find:")) d=0 n=int(input("enter till what number you want to find the table")) while (i<n) : print("{} into {}".format(e,i)) d=e*i print(d) i=i+1 for i in [5, 0]: print(i+1) y=input("enter yes to end the progam")
9f14cebb4e4e71387a81f862edd3dfc392b959da
MyodsOnline/diver.vlz-python_basis
/Lesson_4/task_4.py
1,031
3.796875
4
"""урок 4 задание 4 Представлен список чисел. Определить элементы списка, не имеющие повторений. Сформировать итоговый массив чисел, соответствующих требованию. Элементы вывести в порядке их следования в исходном списке. Для выполнения задания обязательно использовать генератор. Пример исходного списка: [2, 2, 2, 7, 23...
2fdbadd9a18a9aa6de165511cbf7c7283d3a6d85
soultreemk2/coursera-python-for-everybody-assignment-code
/1. Programming For Everybody/assignment3.1.py
653
4.375
4
# 3.1 Write a program to prompt the user for hours and rate per hour using input to compute gross pay. # Pay the hourly rate for the hours up to 40 and 1.5 times the hourly rate for all hours worked above 40 hours. # Use 45 hours and a rate of 10.50 per hour to test the program (the pay should be 498.75). # You shou...
17b327a16069959e065ca4b73169cf233130a281
JasonTLM/multiprocess
/more_thread/class_thread.py
753
3.578125
4
# coding=utf-8 import threading import time class MyThread(threading.Thread): def run(self): for i in range(5): time.sleep(1) msg = "I'm " + self.name + ' @ ' + str(i) print(msg) class TestThread(threading.Thread): def run(self): for i in range(5): ...
f0e1e6e12b11eefebb9a7f83a42949678417220c
KishoreMayank/CodingChallenges
/Interview Cake/Binary Search Trees/ValidBST.py
370
4.28125
4
''' Valid BST: Validate if a Binary Tree is a BST ''' def bst(root, mini = -float('inf'), maxi = float('inf')): if not root: return True if root.value < mini or root.value > maxi: # check if the node is out of bounds return False return (bst(root.left, mini, root.value - 1) and bst(root...
c82610e12060246cc3a51b13e46618706d2ec0ec
colo6299/super-octo-enigma
/HW8/rotate_array.py
383
3.78125
4
def rotate_right(array, delta): """ O(n*k%n) runtime where k is the number of steps to rotate O(1) memory """ for _ in range(delta%len(array)): last_item = array[-1] for index in range(len(array)-1, -1, -1): if index > 0: array[index] = array[index-...
2ec1a66995899e39a9a0bc3f77c0f53ca850b280
iCyris/NPEC
/Exp1/user_app.py
3,464
4.03125
4
""" Login System (with sqlite3) Author: Cyris """ import sqlite3 import os.path import getpass from argparse import ArgumentParser DATABASE = 'user.sql' def connect_db(): """ Connect to database """ cd = sqlite3.connect(DATABASE) cd.row_factory = sqlite3.Row # It supports mapping access by...
997e2c9e7b37917bfccd63016ebd83518459c6d8
MekImEne/LearnPython3_FromScratch-
/Learn Python 3 from scratch to become a developer/basicsyntax/lists_methods.py
626
4.15625
4
""" Built-in methods to help manipulating a list """ cars = [ "BMW" , "Honda" , "Audi"] length = len(cars) print(length) # la longueur de la liste cars.append('Benz') print(cars) # insérer un objet à la fin cars.insert(1, 'Jeep') print(cars) # insérer un objet à la position 1 x = cars.index('Honda') print(x) y = c...
d9ecba6fcd20cdc1b6d4df72ab43e5a7ae92e218
ishaqibrahimbot/algorithms-python
/Merge Sort.py
1,652
4.375
4
""" This file implements the merge sort algorithm. Merge Sort: Given an array A of length n, sort all its elements in ascending order. Brainstorm: - Function starts by breaking array into 2 parts and calling merge on each part. - Base case is when length of array is either 0 or 1, in that case just returns the elemen...
e676d9243b14def2ad0eaaa6d9d8a86ea6ecf91c
nnik1/asd
/set_methods.py
2,191
3.78125
4
ss=set([1,2,3,4,5]) print(ss) # {1, 2, 3, 4, 5} type(ss) # add ss.add(9) print(ss) # {1, 2, 3, 4, 5, 9} ss=set([1,2,3,4,5]) ss2=ss print(ss2) # difference ss1 = set([1, 2, 3, 4, 5]) ss2 = set([4,5,6,7,8]) print(ss1,ss2) #({1, 2, 3, 4, 5}, {4, 5, 6, 7, 8}) ss3 = ss1.difference(ss2) #({1, 2, 3, 4, ...
378b7183903b8e91da2c4f744d030acca9d1b0de
mjr390/python-challenge
/PyPoll/main.py
2,587
3.84375
4
# import needed packages import csv import os # create a variable of where the file is located, change for different files csvpath = os.path.join('..', 'PyPoll', 'election_data_2.csv') #set counters to 0 and create empty lists totalVotes = 0 candidates = [] voteCount = [] percentVotes =[] #open the file reading each...
68b0d810956c8f381e3aee6fa11a7aca24ff9dec
ravencruz/python-start
/weather.py
374
4.15625
4
temperature = 50 forecast = "rain" raining = True if temperature > 80: print("It's too hot!") print('Stay inside!') elif temperature < 60: print("It's too cold!") print('Stay inside') else: print('Enjoy the outdoors!') # print("Is raining ? " + raining) if not raining: print("Go outside is no...
b178a6f1e54b3fb18d5403677a9ab9d7a7c09832
changediyasunny/Challenges
/leetcode_2018/253_meeting_rooms_count.py
2,137
4
4
""" 253. Meeting Rooms II Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), find the minimum number of conference rooms required. Example 1: Input: [[0, 30],[5, 10],[15, 20]] Output: 2 Example 2: Input: [[7,10],[2,4]] Output: 1 Time Complexity: O(NlogN). T...
84e6da02bbac0736ff73aa7c2325a5dde4d5d364
baluneboy/biomedken
/pims/kinematics/rotation.py
1,203
4.03125
4
#!/usr/bin/env python import math import numpy as np def rotation_matrix(roll, pitch, yaw, invert=0): """convert roll, pitch, yaw into a 3x3 float32 rotation matrix, inverting if requested examples: --------- [ x' [ x y' = rotationMatrix(...) * y z' ] ...
eaf6d9b5ef8befe5776dbf3bc4b46a200abe23f0
sujeevraja/utility-scripts
/csv_to_json.py
2,009
3.640625
4
#!/usr/bin/env python3 """ Script to convert CSV files to JSON. """ import argparse import collections import csv import json import logging import os log = logging.getLogger(__name__) Config = collections.namedtuple('Config', [ 'file' ]) class ScriptException(Exception): """Custom exception class with ...
c43eb756b156732d0d84c9488bc99dde62db90e6
smmvalan/Python-Learning
/initial_file/addition.py
126
3.625
4
val1=float(input("Enter the first number:")) val2=float(input("Enter the second nmumber:")) sum=val1+val2 print(sum) id(sum)