blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
93b6d02581e0918c0326a124aad57984886b4441 | git123hub121/Python-Practicalcase | /机器人简单对话.py | 139 | 3.84375 | 4 | while(True):
question = input()
answer = question.replace('吗', '呢')
answer = answer.replace('?', '!')
print(answer) |
0b211cf3e93e2029909fc55d5f7adda8cb101377 | salonishah01/Assignments-CVG-2020- | /Histogram_Equalisation.py | 1,624 | 3.703125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
##Histogram Equalization is a computer image processing technique used to improve contrast in images.
##It accomplishes this by effectively spreading out the most frequent intensity values,
##i.e. stretching out the intensity range of the image.
# In[2]:
#Import r... |
a0e0c793ad84b69d9ecf248cc3a6d275f72558b6 | jaloz/hours | /hours | 1,841 | 3.765625 | 4 | #!/usr/bin/env python
from datetime import date, time, datetime
import json
from functools import singledispatch
@singledispatch
def to_serializable(val):
"""Used by default."""
return str(val)
@to_serializable.register(datetime)
def ts_datetime(val):
"""Used if *val* is an instance of datetime."""
... |
92ddeabedc5e59c669e97e48ea69a01258b2d625 | ActionableQueryExplain/AutoAction | /utils/_fit.py | 825 | 3.515625 | 4 | import numpy as np
def fit(data, fit_attributes, agg_attribute, model):
"""
Fit a model on the given table.
Args:
data: Dataframe
Input table.
fit_attributes: List
A set of attributes in original schema to fit the model.
agg_attribute: String
Th... |
b357fbe39b52e497e7cb9519d65d24d835cea4f3 | Guilherme-Galli77/Curso-Python-Mundo-3 | /Exercicios/Ex074 - Maior e menor valores em Tupla.py | 711 | 4.15625 | 4 | #Exercício Python 074: Crie um programa que vai gerar cinco números aleatórios e colocar em uma tupla.
# Depois disso, mostre a listagem de números gerados e também indique o menor e o maior valor que estão na tupla.
from random import randint
Tupla = (randint(0, 10), randint(0, 10), randint(0, 10), randint(0, 10), ran... |
b55e10cd5cf97cb4e859c3462c015b855a21d533 | fimh/dsa-py | /sorting/sort_helper.py | 797 | 4.1875 | 4 | class SortHelper:
@staticmethod
def is_array_sorted(arr, ascending=True):
"""
Check whether the given array is sorted or not.
:param arr: List[int], array to be checked
:param ascending: Bool, ascending order or descending order
:return: True, the given array is sorted; ... |
9e1b7355fba644ea3bbbd0f3edbb4a1e03a8b43f | Msubboti/PythonExt3 | /Lesson_03/Homework/PyTest/test_one.py | 2,446 | 3.671875 | 4 | from Lesson_3_for_Test import Testing
def test_small_number():
dictionary = Testing(245)
banknotes = list(dictionary.keys())
expected = 0
for index in banknotes:
expected += index * dictionary[index]
assert (expected == 245)
def test_big_namber():
dictionary = Testing(87... |
c311450a3cab7ffa7397a082cae3f42a194232ef | akimi-yano/algorithm-practice | /lc/review2_1091.ShortestPathInBinaryMatrix.py | 1,718 | 3.828125 | 4 | # 1091. Shortest Path in Binary Matrix
# Medium
# 2754
# 132
# Add to List
# Share
# Given an n x n binary matrix grid, return the length of the shortest clear path in the matrix. If there is no clear path, return -1.
# A clear path in a binary matrix is a path from the top-left cell (i.e., (0, 0)) to the bottom-r... |
2ed04815ebab88905e38dba9568c3698ffd10b69 | Akshay-Chandelkar/PythonTraining2019 | /Ex15_StringConcat.py | 277 | 4.0625 | 4 |
def StringConcat(S1):
if len(S1) >= 5:
return S1[:2] + S1[-2:]
else:
return S1
if __name__ == '__main__':
S1 = input("Enter a string with 5 or more characters :: ")
res = StringConcat(S1)
print("The new string is {}".format(res)) |
48c93f28ba0b35d27f1717d51e8881942f8cfb99 | Yeeun-Lee/coding-test-study | /DynamicProgramming/Programmers/level3_하노이탑.py | 301 | 3.875 | 4 | def solution(n):
def hanoi(n, f, t, sub):
if n == 1:
answer.append([f, t])
return
hanoi(n-1, f, sub, t)
answer.append([f, t])
hanoi(n-1, sub, t, f)
answer = []
hanoi(n, 1, 3, 2)
return answer
n = int(input())
print(solution(n))
|
af8923d14716cf267797a8e5b1acfc8008bb530f | cloudmesh-community/sp19-222-99 | /prime/prime/prime.py | 241 | 3.90625 | 4 | def prime(x):
if x >= 2:
for i in range(2, x):
if(x % i) == 0:
print(x,"is prime\n")
break
else:
print(x,"is not prime")
else:
print("error")
return
|
bbfadecb70f94bf80ba6f6b8617d07e08ff0e22c | schappidi0526/IntroToPython | /0_Numpymodule.py | 522 | 3.671875 | 4 | """Numpy is faster than regular python functions as it stores values CONTINOUSLY where as
python stores values randomly"""
#without Numpy
import time
sum=0
starttime=time.time()
for i in range(10000000):
sum=sum+i
print (sum)
endtime=time.time()
time=endtime-starttime
print (time)
#using numpy
... |
372cfcc394feeaddffe9481dc88c9455af373797 | hyybuaa/AlgorithmTutorial | /FindPath.py | 1,070 | 3.640625 | 4 | from copy import deepcopy
class TreeNode():
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution():
def findPath(self, root, exceptNumber):
if root == None:
return None
result = []
path = []
result = self.dfs(... |
217df1618bfa007d6db78f48e0c9d13d03128144 | elbarbero/Ejercicio_Variados_Python | /metodos.py | 4,103 | 4.0625 | 4 | """Modulo con varios métodos generales"""
def validateName(name, minC, maxC):
"""Método que validate el nombre se usuario
* name -> nombre a validar
* minC -> mínimos caracteres permitidos
* maxC -> máximos caracteres permitidos
* return True o False
"""
try:
if len(name) >= minC:
if len(name) <= maxC... |
4a99fa89b9fb360e44adf5ab44552dfa7f983a40 | vhsw/Advent-of-Code | /2017/Day 07/recursive_circus.py | 2,540 | 3.59375 | 4 | """Day 7: Recursive Circus"""
import re
from collections import Counter, defaultdict
from dataclasses import dataclass
from typing import DefaultDict, Optional
@dataclass
class Node:
"""Graph node"""
weight: int = 0
children: tuple[str, ...] = ()
parent: Optional[str] = None
Graph = dict[str, Node]... |
6b40041cb4bf75820191e0b597778f5a09914ce5 | ChangxingJiang/LeetCode | /LCCI_程序员面试金典/面试17.22/面试17.22_Python_2.py | 1,710 | 3.59375 | 4 | from typing import List
class Solution:
def __init__(self):
self.ans = []
def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[str]:
if endWord not in wordList:
return []
all_words = [beginWord] + wordList
graph = {word: set() for word... |
c447cd87db1f4ae14398f52a02a8fd98975dbe60 | HSJung93/-Python-algorithm_interview | /56~57.trie_palindrome_pairs.py | 3,262 | 4.03125 | 4 | from collections import defaultdict
from typing import List
class Node:
def __init__(self):
self.word = False
# Node가 값으로 있는 dict
self.children = defaultdict(Node)
class Trie:
def __init__(self):
self.root = Node()
def insert(self, word: str) -> None:
node = self.root
for char in word:
... |
3d94ffd055a08360fbd31da52bb1e6c84f688b75 | Levizar/CodeWar | /python/5 kyu/Numbers that are a power of their sum of digits.py | 565 | 3.578125 | 4 | def power_sumDigTerm(n):
valid_number = []
for number in range(2, 100):
for exponant in range(2, 100):
candidate = number**exponant
if sum([int(d) for d in str(candidate)]) == number:
valid_number.append(candidate)
valid_number = sorted(valid_number)
retu... |
11cccbc7bba1b4980f17bfba324ef96b2f0c4922 | shrirangmhalgi/Python-Bootcamp | /8. Boolean Statements/bouncer.py | 227 | 4 | 4 | age = int(input("Enter your current age...\n"))
if age >= 18 and age < 21:
print("You need to wear a wristband...")
elif age >= 21:
print("You get a normal entry...")
else:
print("No entry inside the club...")
|
2cd1b47c72ec11ab333da382264429a18519bffe | Anon-B/QGIS-plugin | /QGIS Plugin/code_python/check_empty.py | 193 | 3.953125 | 4 | a = ''
b = ' '
if a.strip() =='' :
print('empty')
else:
print('not empty')
if b.strip() == '':
print('empty')
else:
print('not empty')
|
e07a33de6d57dbfc851261ebdb98743c48c5f6ea | elainy-liandro/mundo1e2-python-cursoemvideo | /Desafio44.py | 921 | 3.6875 | 4 | print('{:=^40}'.format('LOJAS THOP'))
preco = float(input('Preços das compras?R$ '))
print('''FORMAS DE PAGAMENTO
[1] à vista dinheiro/cheque
[2] à vista cartão
[3] 2x no cartão
[4] 3x ou mais no cartão''')
opcao = int(input('Escolha uma das opções acima para pagamento: '))
if opcao == 1:
total = preco - (preco * 10 ... |
f68cab178bcb2d8188cbb3993fd67d0fa75ae6c3 | NyshanMadara/WebDevelopment | /Informatics/цикл for/j.py | 466 | 3.796875 | 4 | # Сумма ста
# Вычислите сумму данных 100 натуральных чисел.
#
# Входные данные
# Вводятся 100 чисел, сумму которых необходимо посчитать.
#
# Выходные данные
# Программа должна вывести единственное число - полученную сумму.
c=100
s=0
for i in range(c):
s+= int(input())
print(s)
|
ed99fa7a7cbc7b4d49636a91eccc0951578b65ce | leo-mcarvalho/Python_Exercicios | /Curso_Em_Video/ex001 - Entrada e saída de dados.py | 193 | 3.84375 | 4 | nome = input('Qual é o seu nome?')
idade = input('Qual a sua idade?')
peso = input('Quanto você pesa?')
print('Seu nome é', nome, 'você está com', idade, 'anos', 'e pesa', peso, 'quilos')
|
cf2869e64e7608be0e5417d26ef2c85f6eabd9af | sgomeza13/ST0245-008 | /Taller 6/8.py | 2,976 | 4.0625 | 4 | def Omerge(unaLista):
print("Dividir ",unaLista)
if len(unaLista)>1:
mitad = len(unaLista)//2
mitadIzquierda = unaLista[:mitad]
mitadDerecha = unaLista[mitad:]
## LLamada recursiva para cada lista
Omerge(mitadIzquierda)
Omerge(mitadDerecha)
i,j,k... |
072e4bb7ccc4aa3c275a6d674ef41c17bd0786f0 | nasopida/tic-tac-toe | /tic-tac-toe.py | 1,604 | 3.671875 | 4 | from tkinter import *
def win():
#only one row
if list[0]["text"]==list[1]["text"]==list[2]["text"]!=" ":
return 1
if list[3]["text"]==list[4]["text"]==list[5]["text"]!=" ":
return 1
if list[6]["text"]==list[7]["text"]==list[8]["text"]!=" ":
return... |
326d51983943703b41f651af266c4a663a48b35b | hhhhhhhhhh16564/pythonLearn | /05/04sorted.py | 698 | 4.09375 | 4 | #排序算法
L = [2, 3, 8, 1, -8, 5]
print([sorted(L)])
#sorted()函数也是一个高阶函数,它还可以接收一个key函数来实现自定义的排序,例如按绝对值大小排序:
print(sorted(L, key=abs))
#字符串排序,默认是ascii比较
names = ['bob', 'about', 'Zoo', 'Credit']
print(sorted(names))
#忽略大小写
#要传一个方法的类
print(sorted(names, key=str.lower))
#要是进行反向排序的话,传入第三个参数 reverse
print(sorted(names, key=... |
bc7421fab7d3d46786e44d6ddc475251569526da | VladislavAtanasov/HackBG-Programming101 | /Week9/1-Money-In-The-Bank/sql_manager.py | 2,034 | 3.515625 | 4 | import sqlite3
from Client import Client
import os
class Db:
def __init__(self, dataname):
self.conn = sqlite3.connect(dataname)
self.cursor = self.conn.cursor()
def create_clients_table(self, sql):
with open(sql, "r") as f:
self.cursor.executescript(f.read())
... |
64d8d273a3ac7606d2d92b01da5495f57fb12fa4 | arnavsadhu/Wipro-python-pjp-2020 | /TM01/Flow Control Statements/10.py | 157 | 3.890625 | 4 | v=int(input('Enter the number'))
R=0
v1=v
while(v>0):
Rem=v%10
R=(R*10)+Rem
v//=10
if(v1==R):
print('Pallindrome')
else:
print('not a pallindrome') |
dcf6dac17aac70124597f28b64df58eecf7bdade | pramitsawant/interview_prep_python | /connected_black_shapes.py | 781 | 3.578125 | 4 | '''
Given N * M field of O's and X's, where O=white, X=black
Return the number of black shapes. A black shape consists of one or more adjacent X's (diagonals not included)
'''
def count_black(matrix):
l, m = len(matrix), len(matrix[0])
count = 0
for i in range(l):
for j in range(m):
if... |
b4788fe720c1deb3d0d0a0871216506f0db03d1d | Jeevankv/LearnPython | /PrG4.py | 1,785 | 4.34375 | 4 | #List and list function-- Mutable
sports = ["cricket","football","Basketball"]
print(sports)
sports.sort()
print(sports)
sports.reverse()
print(sports)
print(len(sports))
numbers=[10,20,30,40,50]
print(numbers[1:4:2])
print(numbers[::-1])
numbers.append(60)
print(numbers)
print(type(numbers))
sports.exten... |
0beeb04e9ceb0753962404a83b5735a06623041b | eecs110/winter2019 | /course-files/lectures/lecture_06/07_find_largest_number.py | 158 | 3.515625 | 4 | numbers = [65, 1800, 12, 20, 19163, 5000, 260, 0, 40, 953, 775, 67, 33]
# Challenge: write a program that finds the biggest number
# in the numbers list above |
649ef9075ee81dd8b107a97161bc38b1dde472f6 | rohitsinha54/Learning-Python | /algorithms/binarysearch.py | 588 | 3.96875 | 4 | #!/usr/bin/env python
"""binarysearch.py: Program to implement binary search"""
__author__ = 'Rohit Sinha'
def binary_search(alist, item):
if len(alist) == 0:
return False
else:
mid = len(alist)/2
if alist[mid] == item:
return True
else:
if alist[mid] ... |
7e9891842698a1be36ad9cb9c242e5c6c867b7e4 | connorjcj/PesslMailer | /irrigator_manager.py | 3,682 | 3.5625 | 4 | '''Function that reads weather data and makes irrigation reccomendations'''
import matplotlib.pyplot as plt
# can also use html hex eg #eeefff
BLUE = "b"
GREEN = "g"
RED = "r"
CYAN = "c"
MAGENTA = "m"
YELLOW = "y"
BLACK = "k"
WHITE = "w"
colours = ["b", "g", "r", "c", "m", "y", "k", "w"]
# Create random data with n... |
45e47a44fe7ad59c92b2a72c841a866404fd1968 | PBPatil/python_intermediate_project | /q03_create_3d_array/build.py | 222 | 3.6875 | 4 | # Default Imports
import numpy as np
import random
# Enter solution here
def create_3d_array():
a = np.zeros((3,3,3))
N = a.size
reshaped_3d_array = np.arange(0,N).reshape((3,3,3))
return reshaped_3d_array
|
9b55f10342373ef4438c08c0d93dd28a4ff267cc | yosef8234/test | /pfadsai/02-array-sequences/questions/array-pair-sum.py | 1,704 | 4.09375 | 4 | # -*- coding: utf-8 -*-
# Array Pair Sum
# Problem
# Given an integer array, output all the unique pairs that sum up to a specific value k.
# So the input:
# pair_sum([1,3,2,2],4)
# would return 2 pairs:
# (1,3)
# (2,2)
# NOTE: FOR TESTING PURPOSES< CHANGE YOUR FUNCTION SO IT OUTPUTS THE NUMBER OF PAIRS
# Solution
... |
47c9eef20ab7cfa46b6d5247b3cc0c23f309cc2b | notthumann/nguyentrangan-fundametals-c4e22 | /session4/c3.py | 184 | 3.53125 | 4 | pokemon = {
'name':'pikachu'
}
text = input("Enter new item: ")
pair = text.split(",")
key, value = pair
#key = pair[0]
#value = pair [1]
pokemon[key] = value
print(pokemon) |
acd34f3bc5880f8e0494cc00ddf310a332b6553a | jack-x/HackerEarthCode | /M_BalancedParenthesis.py | 794 | 3.515625 | 4 |
def main():
N=int(input())
parenthesis=input().split(' ')
stack=[]
count=0
MirrorCount=0
balancedCount=[]
balancedCount.append(0)
for x in parenthesis:
xx = int(x)
if xx > 0 :
stack.append(xx)
count+=1
MirrorCount=0
elif xx < 0:
if(len(stack)>0):
y = stack.pop()
... |
7f9737253f6450643dc441ff1c142dd745530fe5 | Sahithipalla/pythonscripts | /list.py | 345 | 3.90625 | 4 | alpha=[1,2,3,4,5,6]
alpha[0]
alpha[0:-1]
alpha[3:-2]
var=['a','b','c','d','e']
var[-1:-3]
new_list=alpha+var
print(new_list)
var.append('sai')
alpha[0]='orange'
print(alpha)
var.append('x')
alpha.append("x")
print(alpha)
var.copy(alpha)
#print(var)
alpha.remove('orange')
print(alpha)
alpha.pop()
alpha
var.extend(alpha)... |
c0c9aa4cfed330d773a29725fdb00243fe4bee5a | B-Griffinn/hacker_rank | /get_runner_p.py | 1,203 | 4.0625 | 4 | '''
Given the participants' score sheet for your University Sports Day, you are required to find the runner-up score. You are given scores. Store them in a list and find the score of the runner-up.
Input Format
The first line contains . The second line contains an array of integers each separated by a space.
Con... |
3344b762759327e7094be8506eb28b7bf2451fff | vishnoiashish/face_recognition | /tree_traversal.py | 2,110 | 4.1875 | 4 | class Tree(object):
def __init__(self):
self.left = None
self.right = None
self.data = None
root = Tree()
root.data = "root"
root.left = Tree()
root.left.data = "left"
root.right = Tree()
root.right.data = "right"
#inorder , pre oder, post order traversal
#tree -node, left, right
class b... |
857883f4d762fa4aad2e416205a542491608c170 | kgrozis/python_cookbook | /app/07__functions/07__02-Writing-Functions-that-Only-Accept-kwargs.py | 609 | 3.609375 | 4 | # PROBLEM: Want a function to only accept certain args by keywords
# SOLUTION: Put keyword args after a * arg or a single unnamed *
# keyword specify greater clarity for optional args
# keyword args enforce code clarity
def recv(maxsize, *, block=False):
'Receives a message'
pass
# builtin help func
pri... |
3af1fcd12662f473c0d8aa480dc6477018567099 | FrankCasanova/Python | /Tipos estructurados De Secuencias/5.3-232.py | 405 | 4.03125 | 4 | # En una cadena llamada texto disponemos de un texto formado por varias frases.
# Escribe un programa que determine y demuestre el número de palabras de cada frase.
frase = 'Esto es una frase más o menos corta. Y esto es otra frase, normalita, no tiene nada especial.'
sepFrase = frase.split('.')
sepFrase.pop()
pala... |
d3e0d225ad6910196cea5cb5351655b3cd780288 | Robbie-K/Python | /Python Programs/Exercises/ex8.py | 988 | 4.03125 | 4 | """ Robert Karg
Exercise 8 """
import sys
def countLettersInString(string):
""" Function for counting letters in a given string and printing the results """
letterCount = {} # empty dictionary
# creates new keys if they don't exist, adds to them if they do
for char in string:
# c... |
efbf1f244b078ef58f2b4295a0257d38456c552f | Future-Aperture/Python | /exercícios_python/exercicios_theo/Exercicios 16-30/ex030.py | 236 | 3.953125 | 4 | # par ou impar
print('')
numero = int(input('Me diga um número inteiro qualquer e eu digo se é par ou impar: '))
if numero % 2 == 0:
print(f'O número {numero} é PAR')
else:
print(f'O número {numero} é ÍMPAR')
|
278b31508df93eeeb1627c038d7452d923c00d3f | anilkumar0470/git_practice | /Terralogic_FRESH/exception_handling/exception_proper.py | 154 | 3.578125 | 4 | while True:
try:
n = int(raw_input("enter the value"))
print "value",n
break
except :
print "enter proper output"
|
f7ef3bebd76fa080f45593fa4ed828c2ea2c4e62 | emir-naiz/first_git_lesson | /Courses/1 month/2 week/day 10/Задача №1 элемент С вставить на позицию К.py | 183 | 3.828125 | 4 | # Необходимо вставить в список на позицию K элемент C
number_list = [1,20,30,40,2,3]
k = 3
c = 4
number_list.insert(k,c)
print(number_list)
|
1833cec67b5cfb92a629a26677474a4e0bf74bd6 | saisai/coding-challenges | /python/daily_interview_pro/202004/07.py | 1,130 | 3.90625 | 4 | """
Distribute Bonuses
This problem was recently asked by Twitter:
You are the manager of a number of employees who all sit in a row. The CEO would like to give bonuses to all of your employees, but since the company did not perform so well this year the CEO would like to keep the bonuses to a minimum.
The rules of ... |
bf7e49150dcd3924c9405bf12c5506f96fd72391 | jtowler/adventofcode19 | /src/advent20/day13.py | 1,114 | 3.5625 | 4 | from typing import List
import numpy
def get_earliest(time: int, bus: int) -> int:
return filter(lambda x: x >= time, range(0, bus + time, bus)).__next__()
def part1(info: List[str]) -> int:
departure = int(info[0])
buses = [int(i) for i in info[1].split(',') if i != 'x']
bus_times = {bus: get_earli... |
81da2f1fced9d8119adaba181c50f027af3b9789 | William-An/SMSAssignmentSystem | /DataStoreIntoDB.py | 594 | 3.640625 | 4 | import sqlite3
database=sqlite3.connect("StudentsDatabase.db")
try:
database.execute('''CREATE TABLE Students118(name text,class text,number int)''')
except sqlite3.OperationalError as err:
print("Table already exists, "+str(err))
tempdatafile=open("database.txt",encoding="utf-8")
datatemp=[i for i in te... |
fddc62f44f3fd1a99e1d4a2d080a907d97996efb | Everfighting/leetcode-problemset-solutions | /subsets.py | 454 | 3.828125 | 4 | #给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
#说明:解集不能包含重复的子集。
#示例:
#输入: nums = [1,2,3]
#输出:
#[
# [3],
# [1],
# [2],
# [1,2,3],
# [1,3],
# [2,3],
# [1,2],
# []
#]
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
res = [[]]
for i in nums:
res += [li+[i] for li in ... |
3e8d072ac1442a13cbde3d7eb860ed763401336e | TheWaWaR/leetcode | /python/medium/16-3sum-closest.py | 1,285 | 3.734375 | 4 | #!/usr/bin/env python
#coding: utf-8
class Solution(object):
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
nums = sorted(nums)
min_sum = nums[0] + nums[1] + nums[2]
min_abs = abs(min_sum - targe... |
206a37bea0a1409ee8bdfd773b76ae0dc1642602 | Mmeli-B/BasicAlgorithms | /BasicAlgorithms/recursion.py | 438 | 3.84375 | 4 | def sum_array(array):
sum = 0
if len(array) < 1: return sum
else:
sum += array.pop(0)
return sum_array(array)
def fibonacci(n):
if n <= 1: return n
else: return fibonacci(n - 1) + fibonacci(n - 2)
def factorial(n):
if n <= 1: return n
else: return n * factorial(n - 1)
de... |
88be52a16a712edaef97b7e8428eb47875cd167d | Thomas-James-Rose/python-katas | /longest-palindrome/longest_palindrome/longest_palindrome.py | 825 | 3.90625 | 4 | import string
import functools
def get(input_string):
if(input_string == ""):
print(f"Input String: \"\"")
print("Length: 0")
return
print(f"Input String: {input_string}")
substrings = []
for i in range(0, len(input_string)):
remaining_string = input_string[i + 1 : len(input_string)]
for... |
20edfac3a1ab48241b642be698068be0b8b8bead | chacalo510/PythonBasics | /variables.py | 684 | 4.21875 | 4 | # -*- coding: utf-8 -*-
#
# Esto es un comentario mágico
# Esto es un Here-doc
"""
Esto es el heredoc
"""
mensaje = '''
Esto también es un comentario o heredoc
Esto es otra línea
'''
# Cadenas de carácteres (strings)
nombre = "Jean"
apellido = 'Soto' # Esta es la forma preferida
nombre_completo = nombre + ' ' + ... |
96deafb05f62c2ab4998d3795075bd30bd22ce27 | johnnybieniek/boilerplate-sea-level-predictor | /boilerplate-sea-level-predictor/sea_level_predictor.py | 996 | 3.703125 | 4 | import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import linregress
import numpy as np
def draw_plot():
# Read data from file
df = pd.read_csv('epa-sea-level.csv')
# Create scatter plot
plt.scatter(x='Year',y='CSIRO Adjusted Sea Level', data=df)
# Create first line of best fit
... |
6a84fe7b534c47c3d6f18e505a65f571a42ad8a8 | benjaminhr/python-practice-projects | /grave22.py | 498 | 4.03125 | 4 | numbers = []
def loop(top_limit):
i = 0
while i < top_limit:
print "At the top i is %d" % i
numbers.append(i)
i += + increment
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
print "The numbers: "
for num in numbers:
print num
print "... |
c5643f5c2c14c498b9f192f75df7cd9b7749e394 | chuzcjoe/Leetcode | /542. 01 Matrix.py | 1,371 | 3.546875 | 4 | class Solution:
def updateMatrix(self, matrix: List[List[int]]) -> List[List[int]]:
row = len(matrix)
col = len(matrix[0])
dis = [[0 for i in range(col)] for j in range(row)]
def bfs(i,j):
step = 0
visited = set()
... |
d6d99d9624e1cba2476c4191b139f5af2b802b9f | ShivamPrakash2000/Verify-Email-GUI-Python | /database.py | 2,497 | 4 | 4 | import sqlite3
from sqlite3 import Error
class DB_Users():
"""
Class For CRUD(Create, Read, Update and delete) in Database
"""
def __init__(self):
try:
self.db = sqlite3.connect("users.db")
self.cursuser = self.db.cursor()
except Error as e:
... |
55274f4837aedae665919c4e586c43d064a43278 | mixterjim/Learn | /Python/Algorithm/reduce.py | 268 | 3.5 | 4 | from functools import reduce
l = [0,1,2,3,4,5,6,7,8,9]
def f(a, b):
return a * 10 + b
print(reduce (f,l))
def fake_reduce(function,list):
outcome = list[0]
for x in list[1:]:
outcome = function(outcome,x)
return outcome
print(fake_reduce(f,l))
|
c009358c66fa4c9738bb3eeff564ccdf505855a3 | leetcode-notes/UniversityAssignments | /Programming in Python/Laboratorul 2/problem_11.py | 372 | 3.640625 | 4 | def compute_transposed_lists(*lists):
return [tuple(lists[line][column] if column < len(lists[line]) else None
for line in range(len(lists))) for column in range(max([len(sequence) for sequence in lists]))]
def main():
print(compute_transposed_lists([1, 2, 3], [4, 5, 6, 7], ["a", "b", ... |
ba2d710489e59feebbb00d5333a55f3624955ba6 | arunselvanr/Toy-problems | /Testing and stuff.py | 1,199 | 4 | 4 | class complex(object):
def __init__(self, a,b):
self.real = float(a)
self.complex = float(b)
def complex_sum(x1, x2):
sum = complex(0.0,0.0)
sum.real = float(x1.real) + float(x2.real)
sum.complex = float(x1.complex) + float(x2.complex)
return(sum)
def complex_prod(x1,x2):
prod=... |
b7c22367592cfaf1dd73d2659d9aeeff5bb0e17b | Ishanbhatia98/linkedinlearningcourses | /python_xml_json_and_the_web/resources/03_requests/reqerrs_start.py | 461 | 3.515625 | 4 | # using the requests library to access internet data
import requests
def main():
# Use requests to issue a standard HTTP GET request
url = "http://httpbin.org/status/404"
result = requests.get(url)
printResults(result)
def printResults(resData):
print("Result code: {0}".format(resData.statu... |
eb0db50a273c4bee3bc814fd68c1d65c61be196b | cankutergen/hackerrank | /The_Power_Sum.py | 389 | 3.640625 | 4 | def powerSum(X, N):
memo = {}
return dp(X, N, 1, memo)
def dp(X, N, num, memo):
if (X, num) in memo:
return memo[(X, num)]
value = X - num**N
if value < 0:
return 0
elif value == 0:
memo[(X, num)] = 1
return 1
else:
memo[(X, num)] = dp(X, N, num + ... |
04249e71cc2b8eaaad02e6ad74d2a85d3f874fdc | daniel-reich/turbo-robot | /xFQrHSHYAzw9hYECy_2.py | 1,415 | 4 | 4 | """
Someone is typing on the sticky keyboard. Occasionally a key gets stuck and
more than intended number of characters of a particular letter is being added
into the string. The function input contains `original` and `typed` strings.
Determine if the `typed` string has been made from the `original`. Return
`True` i... |
1cb3b5383b2bddc3cbfee18ea5a981d55f487542 | MariaTrindade/CursoPython | /01_Entrada e Saída/02_Print_Input.py | 553 | 3.890625 | 4 | """
Print >>> Mostrar dado
Input >>> Obter um dado do usário
"""
# nome = 'leonardo alvES'.title().strip().split()
# print('Muito prazer, {}'.format(nome))
# print(f'Muito prazer, {nome[1]}')
# Com split: Gerando índice
# 0 1
# L e o n a r d o a l v e s
# 0 1 2 3 4 5 6 7 8 9 10 11 12 13 Py... |
3d779dd0c77f9c46b3c885ad7658fb12b486c150 | RobinTPotter/camjam_pygame_car | /robot_module.py | 5,663 | 3.578125 | 4 | """initializes RPi.GPIO, assuming installed, sets the pins for motor controls for
the CamJam EduKit3
"""
import RPi.GPIO as GPIO # Import the GPIO Library
print ('set up GPIO pins')
# Set variables for the GPIO motor pins
pinMotorAForwards = 10
pinMotorABackwards = 9
pinMotorBForwards = 8
pinMotorBBackwards = 7
pri... |
68bdd105625120ceef0fbe4aff89c16608ec5f21 | more2503/DiscordBotTest | /filemanagement.py | 794 | 3.578125 | 4 | filename = "test.txt"
def readFile():
file = open(filename, "r")
content = file.read()
file.close()
content = content.splitlines()
return [l.split(',') for l in ','.join(content).split(';')]
def writeFile(c):
file = open(filename, "w")
file.write(c)
file.close()
return True
def... |
e98975c11de863d75fcfc9e2eb13ae33aa222742 | Saengsorn-Wongpriew/6230403955-oop-labs | /saengsorn-6230403955-lab8/ex2.py | 1,226 | 3.859375 | 4 | class Vehicle:
def __init__(self, name, speed, mileage):
self.name = name
self.__speed = speed
self.mileage = mileage
def set_speed(self, new_speed):
self.__speed = new_speed
def get_speed(self):
return self.__speed
class Car(Vehicle):
def __init... |
35244fb44f960bc963c78f5a90692843c30f144d | AnnaNastenko/python_tortures | /done_homework/2) Базовые структуры данных/zoo.py | 1,718 | 3.65625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# есть список животных в зоопарке
zoo = ['lion', 'kangaroo', 'elephant', 'monkey', ]
# посадите медведя (bear) между львом и кенгуру
# и выведите список на консоль
# TODO здесь ваш код
zoo.insert(1, 'bear')
print(zoo)
# добавьте птиц из списка birds в последние клетки ... |
89d88189132b10c2a7601701dbcedf657f32f21e | HLNN/leetcode | /src/1915-check-if-one-string-swap-can-make-strings-equal/check-if-one-string-swap-can-make-strings-equal.py | 1,394 | 4.15625 | 4 | # You are given two strings s1 and s2 of equal length. A string swap is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices.
#
# Return true if it is possible to make both strings equal by performing at most one string swap on exactly one of the str... |
db1fdffbdf76967359cc26c7ab30922c7f5cee07 | anshumanairy/Codechef | /sum or difference.py | 195 | 3.765625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
def diff():
N1=int(input(""))
N2=int(input(""))
if(N1>N2):
print(N1-N2)
else:
print(N1+N2)
diff()
# In[ ]:
|
b67510734665ba597645d0c394fbc13216218043 | SapirAlmog/employee-management-system | /tests.py | 1,247 | 3.625 | 4 | try:
df = pd.read_csv('/Users/sapir/Documents/python/final project- employee attandance log/emplist.csv', index_col=0)
ask_to_enter_emp = input("Do You want to create a new employee? y/n")
if ask_to_enter_emp == "y":
ask_manually = input("Do you want to type it? y/n")
ask_csv = input("Do you... |
0053fc43125a0c17594d78ff0747dffa6fff5596 | jslx2/whatup | /user_profile.py | 1,081 | 4.21875 | 4 | #using arbitrary keyword arguments
"""
you can write functions that accept
as many key-value pairs as the calling statement provides
"""
"""
the definition of build_profile() expects a first and last name, and then it allows
the user to pass in as many name-value pairs as they want.
doulble asterisks(**user... |
ca271923cc4be0e5d044992795bc80f9583de54c | dshaffe2/homework | /PyPoll/pypollhw.py | 2,518 | 3.84375 | 4 | import csv
filename = "C:/Users/dshaf/Documents/School/election_data.csv"
totalvotes = 0
candidates = []
candidate1count = 0
candidate2count = 0
candidate3count = 0
candidate4count = 0
cand1_per = 0
cand2_per = 0
cand3_per = 0
cand4_per = 0
counts = []
with open(filename, 'r') as file:
data = csv.reader(file)
... |
a596f69141c367644fc4c694897a62da0c6c674e | Mayuri0612/Improtant-Algorithms-For-Interviews | /StringsAndArrays/1.py | 802 | 3.890625 | 4 | #Reverse a string without affecting special characters
def revFunc(string):
#small = [chr(x) for x in range(ord('a'), ord('z')+1)]
#capital = [chr(x) for x in range(ord('A'), ord('Z')+1)]
ls = list(string)
l = 0
r = len(ls)-1
print(ls[l])
print(ls[r])
while(l < r):
if( ((ls[l] ... |
0a7740014a4774a5f2afc6bae826a0b1b925ae67 | ELind77/Candidate_Classifier | /candidate_classifier/string_processing.py | 13,139 | 3.515625 | 4 | #!/usr/bin/env python2
"""
Idea behind the structure:
A StringTransformer is a generalized way to perform an ordered
series of transformations on a string. There are a number of
pre-built transformations already included and arbitrary
callables can be added to the pipeline.
There are three primary kinds of transfor... |
608bb18c272897afc7ba7c8d6c68b2264ca140af | Senple/ChatBot_lesson | /HELLO.py | 534 | 3.75 | 4 | """
言葉を覚えるプログラム、"こんにちは"だったら、馬鹿っていう
"""
a = input("言葉を教えてね")
word_list=[]
def reply_func(input_word):
if input_word not in word_list:
word_list.append(input_word)
if a == "こんにちは":
reply_message = "馬鹿!"
else:
reply_message = input_word + "だね!" +" "+ "知らなかった、ありがとう"
... |
678223c231944823e8191507cdac54766dae6c72 | ChesterNut999/Python_Lab_04_Test_Py_Seguranca_Informacao | /Aula_3/01_PasswordGenerator.py | 295 | 3.703125 | 4 | import random, string
tamanho = int(input('Digite o tamanho de senha: '))
chars = string.ascii_letters + string.digits + 'ç!@#$%&*()-=+,.:_/?'
rnd = random.SystemRandom() #os.urandom (gera números aleatórios a partir de fontes do SO
print(''.join(rnd.choice(chars) for i in range(tamanho))) |
f2dec8dc8b585416626bc3618e990ec94ff62ebb | codeslug/python_newbie | /MyTestProject/piglatin.py | 1,634 | 3.9375 | 4 | '''
Created on Dec 19, 2013
@author: codeslug
This document converts a single word to "pig latin."
Rules of pig latin:
1. The first letter of a word is taken, added to the end of the word, followed by "ay." dog == ogday
2. If the first letter of the word is a vowel, it is not removed, but "ay" is still ad... |
64efd846f1a0aed5a676f986c5a01f905204bed6 | blueOkiris/EmbeddedLinuxClass | /hw03/etch-a-sketch/domain/game.py | 2,922 | 3.609375 | 4 | import typing
import data.drawable as drawable
# Basically a static class that is used to update the actual 'game'
class Game:
def __init__(self, startPos):
self._reset = True
self._startPos = startPos
self._cursorPos = (0, 0)
self._directionPressed = [ False, False, False, False ]
... |
9a8c13080dcf6bac93811a874668de79d5ccd251 | geeeh/boot-camp | /person/person.py | 736 | 3.890625 | 4 | class Person(object):
"""class to model an object person"""
def __init__(self, person_name, person_number):
if type(self) == Person:
raise NotImplementedError("object cannot be instantiated directly")
self.name = person_name
self.person_number = person_number
class Staff(P... |
887559f5a029e3d268d899b75c3e71006c29bce3 | IoanCristianRadu/python-cheatsheet | /7. While loops.py | 149 | 4 | 4 | x = 0
while x < 3:
print("Count is {0}".format(x))
x += 1
num = 10
while True:
num += 10
if num == 30:
break
print(num)
|
fcb0022f56095fdc15601ebbd2d0282d3e8189a4 | ElvinOuyang/reuters-w2v-practice | /text_clean.py | 3,258 | 3.625 | 4 | import numpy as np
import pandas as pd
import re
import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
from collections import Counter
def load_response(dataframe, col_name):
"""
Function to load survey response from a pandas ... |
d7eb690700efc936d0adbbf7d18d15826ad9f66c | LeonardoSaid/uri-py-solutions | /submissions/1004.py | 64 | 3.5 | 4 | x = int(input())
y = int(input())
print("PROD = %d" % (x*y)) |
df6ba8b1de51fa16f19eae043f456492c8426258 | PiKaChu-R/code-learn | /program/sort_search/selectSort.py | 733 | 3.578125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
@File : selectSort.py
@Time : 2019/06/22 15:45:26
@Author : R.
@Version : 1.0
@Contact : 827710637@qq.com
@Desc : 选择排序
'''
'''
'''
# here put the import lib
def selectSort(seq):
assert (type(seq) == type(['']))
... |
e597643c9dc06b4692318f028a8a3cc9f3382258 | RandyField/learn-note-randy | /python-note/json/test.py | 748 | 3.890625 | 4 | #!/usr/bin/python3
import json
# Python 字典类型转换为 JSON 对象
data = {
'no' : 1,
'name' : '百度',
'url' : 'http://www.baidu.cn'
}
#转换为json字符串
json_str = json.dumps(data)
print ("Python 原始数据:", repr(data))
print ("JSON 对象:", json_str)
# 将 JSON 对象转换为 Python 字典
data2 = json.loads(json_str)
print ("data2['name']: ... |
92eac02ed1c90865b6fecbb4da352e34a4724232 | lebrice/FunAIExperiments | /sudoku/sudoku.py | 10,396 | 3.90625 | 4 | """
Fabrice Normandin - fabrice.normandin@gmail.com
Algorithm to solve sudokus.
For fun, while on the plane from Istanbul to Berlin
(finished while on the way to Montreal from London)
"""
from time import time
from typing import *
from queue import PriorityQueue
import multiprocessing as mp
SudokuGrid = List[List... |
fd3e7bea79ecc8d2a52d0b32b5c5d349107aabf2 | AdamAndrei/algorithms-and-programming-course | /lab 3/Menu.py | 8,070 | 3.671875 | 4 | def all_tests():
test_get_all_subsequences()
test_get_subsequence_with_length()
test_is_ascending()
test_get_ascending_subsequences()
test_find_max_length()
test_two_base()
test_bits()
test_has_same_amount_of_1()
test_get_subsequences_with_numbers_with_same_amount_of_1()
"""
Descri... |
89697624553ac3e361aacdb28814577a62b4bc20 | SandraAlcaraz/FundamentosProgramacion | /EjemploPrintconFormato3.py | 221 | 4.0625 | 4 | #Conversión de numero entero a Hexadecimal y Octal
numero=int(input("Dame el número a convertir "))
print("El número %d en Hexadecimal es %#4x"%(numero,numero))
print("El número %d en Octal es %#4o"%(numero,numero))
|
e2221b2035b15aaa8e97836b7e902c5ea136b73f | dkweisel/Python-Projects | /tic_tac_toe.py | 3,237 | 3.625 | 4 |
import itertools ##player_choice = itertools.cycle([1,2])
#Tic Tac Toe Game by sentdex on YT
## Winning Parameters
def win(current_game):
def all_same(l):
if l.count(l[0]) == len(l) and l[0] != 0:
return True
else:
return False
#horizontal winning
for row in game:... |
20eda0244abc3b9e47322361ffc4b70c87b8bae1 | lucasvini92/cursos | /introducao_a_ciencia_da_computacao_com_python/segundos.py | 305 | 3.609375 | 4 | valor = int(input("Por favor, entre com o número de segundos que deseja converter: "))
dias = valor//86400
horas = (valor%86400)//3600
rest_horas = (valor%86400)%3600
minutos = rest_horas//60
segundos = rest_horas%60
print(dias,"dias,",horas,"horas,",minutos,"minutos e",segundos,"segundos.")
|
03bdd88e1cce142c27249c0e80ad1f3a8c167a71 | grettelduran/taller4 | /taller/model/modelo.py | 522 | 3.53125 | 4 | class Operador():
def __init__(self, id, nombre):
self.id = id
self.nombre = nombre
self.sub_estacion = None
class SubEstacion():
def __init__(self, id, nombre):
self.id = id
self.nombre = nombre
self.ciudades = []
def addCiudad(self, ciudad):
self.ciu... |
7d66e7a515d1bfc3abbfa80038ea64c83a7670c3 | nourey/AI720_hw1 | /1_homework.py | 563 | 4.1875 | 4 | # Creating lists
first_list, second_list=[],[]
for i in range(10):
if i%2 != 0 :
# first list should contain odd values
first_list.append(i)
else:
# so the second list contains even values
second_list.append(i)
# merging lists
merged_list=first_list+ second_list
# mul... |
ddcaecb990f67746a10dd0a8d943acc682ac162f | Kinfe9870/Mad-libs | /Mad libs.py | 370 | 3.703125 | 4 | adjective = input("Enter an adjective: ")
bird = input("Enter a type of bird: ")
room = input("Enter the room number: ")
print("It was a " + adjective + " windy day in November." \
"I was in room " + room + " looking out " \
... |
d44642bbb95dd448b14b68a55e5aa67b29115232 | vrinda41198/GAA | /Knapsack.py | 8,772 | 3.890625 | 4 | import random
import operator
gen_no = 0 # Number of generations created
def random_chrom(args: dict, total_weight: float, n: int) -> list:
"""
Random chromosome generation
:param args: Info regarding weight and value of each item
:param total_weight: Total weight capacity of knapsack
:param n: ... |
38c9bca9f107f02af9cda2412bf215f088f39a8a | JoyceHsieh/CGU-IST341 | /Week1/hw1pr3.py | 26,902 | 3.96875 | 4 | #CodingBat.com
#Warmup-1>sleep_in
def sleep_in(weekday, vacation):
'''
The parameter weekday is True if it is a weekday,
and the parameter vacation is True if we are on vacation.
We sleep in if it is not a weekday or we're on vacation.
Return True if we sleep in.
'''
if not weekday or va... |
645d32b3600cf00f4b5697a40f7655cbaa4b5a6d | fantasylsc/LeetCode | /Algorithm/Python/150/0132_Palindrome_Partitioning_II.py | 963 | 3.78125 | 4 | '''
Given a string s, partition s such that every substring of the partition is a palindrome.
Return the minimum cuts needed for a palindrome partitioning of s.
Example:
Input: "aab"
Output: 1
Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut.
'''
class Solution:
... |
6653128c30ad6029bc34d03818b959249bdd21fb | Cjkkkk/data_mining_homework | /hw3/kmeans/kmeans.py | 1,575 | 3.9375 | 4 | import numpy as np
def kmeans(x, k):
'''
KMEANS K-Means clustering algorithm
Input: x - data point features, n-by-p maxtirx.
k - the number of clusters
OUTPUT: idx - cluster label
ctrs - cluster centers, K-by-p matrix.
iter_ctrs - cluster cen... |
a676ec6dbf8496b51e8a96c59e8dbdea8f3a8192 | oisinhenry/CA117-2018 | /lab10.2/count_102.py | 102 | 3.53125 | 4 | def count_letters(string):
if len(string) == 0:
return 0
return 1 + count_letters(string[:-1])
|
f5b27cba966abe2af02f6d68ada88ea91d9ae711 | makowiecka/Hangman | /game_level.py | 1,379 | 3.671875 | 4 | from chance import Chance
from game_level.abstract_level import AbstractLevel
class GameLevel:
__levels = (
{'name':'Easy', 'chances': 21},
{'name': 'Normal', 'chances': 12},
{'name': 'Hard', 'chances': 6},
{'name': 'Super Hard', 'chances': 3}
)
def __init__(self, chances)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.