blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
7a01608a5c8fb2414f8833eba007da11688ac094 | nrgolden16/python | /위장.py | 445 | 3.734375 | 4 | #프로그래머스 LEVEL2 코딩테스트 연습 "위장"
def solution(clothes):
clothes_type_lst=[]
for i,v in clothes:
clothes_type_lst.append(v)
clothes_type_set=set(clothes_type_lst)
clothes_cnt=[]
for j in clothes_type_set:
clothes_cnt.append(clothes_type_lst.count(j)+1)
def multi(lst):
tot... |
c3c4c7610c4755ca125ef868ad2ac55619264253 | myllenaalves/Algoritmos-e-estruturas-de-dados | /arvoreBinaria.py | 1,722 | 3.5 | 4 | class No:
def __init__(self, chave, valor, esq=None, dir=None,p=None):
self.chave = chave
self.valor = valor
self.esq = esq
self.dir = dir
self.p = p
class Arvore:
def __init__(self):
self.raiz = No(None,None)
self.tamanho = 0
def __len__(self):
... |
8a31423c2e6874fcbc5dbec1aead865545fc46ba | dcorns/PyAssignments | /Chap8/prog1.py | 235 | 3.671875 | 4 | fname = raw_input("Enter file name: ")
if len(fname) < 1 : fname = "mbox-short.txt"
fh = open(fname)
lst = list()
for line in fh:
ln = line.rstrip().split()
for item in ln:
if item not in lst: lst.append(item)
lst.sort()
print lst |
abb44a36ffbe6b15698fd084154f071867747a79 | Kio0/En.Words | /Основная_программа.py | 2,536 | 3.53125 | 4 | #основная программа
import functions
from tkinter import *
from tkinter import messagebox
def avtoriz():
global root
s=functions.auth(name.get(),password.get())
Str=name.get()
if s!='Вход выполнен':
messagebox.showinfo("Error", s)
else:
messagebox.showinfo("Вход выпо... |
86813c8baa2c14f0706c6d62be34f8d279dbbd8b | jacquarPL/Python-learn | /lab_5.1.11.8_anagram.py | 386 | 3.734375 | 4 | def str2list(strng):
txt = ""
for char in strng:
txt += char + " "
lst = txt.split()
return lst
#t1 = "arbuzy".lower()
#t2 = "burza".lower()
t1 = "Ranek".lower()
t2 = "Nerka".lower()
#print(str2list(t1))
l1 = sorted(str2list(t1))
l2 = sorted(str2list(t2))
if l1 == l2:
... |
e65c38d24933d00568fbdf9548be40721111fa72 | Mica210/python_michael | /Lessons/Lab6.py | 1,511 | 4.1875 | 4 | '''
Write a code that will show a menu:
1.Insert Number and ** it by 3.
2.insert 4 IPs to a list and print it.
3.Insert 4 Entries to dns_Dictionary and print it.
4.check if a string is polindrom
if the user wont choose 1-4, you will tell him to insert ony 1-4.
'''
from time import sleep
print("Starting the menu... \n"... |
f08ea0fd685b93761086b423039734612ba5199a | Gustavo-Lourenco/Python | /Exercícios/ex053.py | 627 | 3.703125 | 4 | print('\033[35m{:-^40}\033[m'.format(' Verificador de Palíndromo !!'))
f = str(input('Digite uma frase: ')).upper().split()
f = ''.join(f)
inverso = f[::-1]
counter = 0
print(inverso)
print('O inverso da {} é {}'.format(f, inverso))
#print('O inverso da {} é '.format(f), end='')
'''for c in range(0, len(f)):
prin... |
1769f1fbaa413ddb759670ce34fe1bf420ee055c | steve-thousand/advent_of_code_2017 | /11/solution2.py | 2,921 | 4.1875 | 4 | import math
class Movement:
def __init__(self, north, direction=0):
self.north = north
self.direction = direction
self.nextMovement = None
def pushNextMovement(self, nextMovement):
self.nextMovement = nextMovement
def hasNextMovement(self):
return self.nextMovement... |
76b27bf542341b2f517fb70a15968ce0f75b48fc | barbaracalderon/curso-de-python3-do-curso-em-video | /mundo_2/desafio057.py | 425 | 4.09375 | 4 | # Faça um programa que leia o sexo de uma pessoa mas só aceite
# os valores 'M' ou 'F'. Caso esteja errado, peça a digitação
# novamente até ter um valor correto.
sexo = str(input('Digite seu sexo [M/F]: ')).strip().upper()[0]
while sexo not in 'MF':
print('Opção inválida. Tente novamente.')
sexo = str(input('D... |
642fb691f58eb39b72d41346469e15758057ee7b | swimorsink/onecodingproblem | /src/remove-last-link-list.py | 1,596 | 3.640625 | 4 | #!/usr/bin/python2.7
import unittest
from test import test_support
class Node(object):
def __init__(self, value):
self.next = None
self.value = value
class LinkedList(object):
def __init__(self):
self.tail = None
self.head = None
def add(self, value):
node = Node(value)
if self.head =... |
dfb990d6e744374251ad446147986dea5f4fd34e | my0614/python | /key_event.py | 641 | 3.65625 | 4 |
import turtle
import random
t = turtle.Turtle()
sc = turtle.Screen()
def move():
x = random.randint(-300,300)
y = random.randint(-300,300)
t.up()
t.goto(x,y)
t.down()
def fill_circle():
move()
t.color(random.choice(['red', 'blue', 'black']))
s = random.randint(10, 50)
a = random.... |
f57b2eb9ca7834c2d783f7acf3026b817e63fd9b | MarRoar/Python-code | /00-sxt/03-reg/07-dmeo.py | 1,147 | 3.5625 | 4 | ''''''
import re
'''
三个大引号就是真实存在的数据,内存在解析的时候,会解析出东西的
'''
s = '''<div>
<p>岗位职责:</p>
<p>完成推荐算法、数据统计、接口、后台等服务器端相关工作</p>
<p><br></p>
<p>必备要求:</p>
<p>良好的自我驱动力和职业素养,工作积极主动、结果导向</p>
<p> <br></p>
<p>技术要求:</p>
<p>1、一年以上 Python 开发经验,掌握面向对象分析和设计,了解设计模式</p>
<p>2、掌握HTTP协议,熟悉MVC、MVVM等概念以及相关WEB开发框架</p>
<p>3、掌握关系数据库开发设... |
0d702791abc0c6e073b443845f572086130050c3 | BOTFerran/NN | /Tiny_NN/NeuralNetwork.py | 3,268 | 4.1875 | 4 | import numpy as np
import random
# We start implementing the sigmoid function and its derivative
def sigmoid(x):
return 1.0/(1+ np.exp(-x))
def sigmoid_derivative(x):
return x * (1.0 - x)
# Then let's go with the main class
class NeuralNetwork():
"""
We need to give our neural network an input data 'x' ... |
632a8de5d58cb5076a01e1f235ae3eca4a5b53f8 | daniel-reich/ubiquitous-fiesta | /u3kiw2gTY3S3ngJqo_7.py | 197 | 3.8125 | 4 |
def superheroes(heroes):
words_list=[]
for word in heroes:
if word[-3:]=="man" and word[-4]!="o":
words_list.append(word)
words_list.sort()
return words_list
|
c310ecb080e7e021727c843723168e95bc62b869 | Harshupatil/PythonPrograms- | /Armstrong.py | 626 | 4.21875 | 4 | #******************************************************************************
#Armstrong Number, is the number that is equal to sum of cube of it's degits.
#For example 0, 1, 153, 370, 371, 407 are armstrong numbers.
#*******************************************************************************/
def armstrong():
... |
d7c3e03303c0adbc46e5291d2372e74a2bb65813 | Soyoung-Yang/se | /Python/exercise0/ex1-3.py | 483 | 4.03125 | 4 | txt = """
안녕 나는 댕소야
너는 누구니?
나는 소댕이야
그렇구나
반가워
"""
print(txt[11]) # 문자열의 요소
print(len(txt)) # 문자열 길이
print("소댕" in txt) # True
print("sodang" in txt) # False
print("유댕" not in txt) # True
a = " Hello, Soyoung! "
print(a.upper())
print(a.lower())
print(a.strip())
print(a.replace("Hello", "Goodbye"))
print(a.split(","))
... |
5b13d9b2fc20faafb6d2ae695f2de7900a7ab635 | tsurendher/Innomatics_Intenship | /day_2/3_NestedLoop.py | 400 | 3.578125 | 4 | if __name__ == '__main__':
nisted_list=[]
marks_list=[]
for _ in range(int(input())):
name = input()
score = float(input())
marks_list.append(score)
nisted_list.append([name,score])
marks_list=sorted(set(marks_list))
nisted_list=sorted(nisted_list)
... |
076f78dc15575bb59c53cf039108ddd48c60acd3 | lcmust/git6500py | /python/python_runtime.py | 1,351 | 3.53125 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from time import time
def test():
t = time()
lista=[1,2,3,4,5,6,7,8,9,13,34,53,42,44]
listb=[2,4,6,9,23]
intersection=[]
for i in range (1000000):
for a in lista:
for b in listb:
if a == b:
intersection... |
0db3f351dc1094bb65e2a62c7a5d82a39e7df66c | aleenaadnan15/official-assignment | /fibonacci.py | 141 | 3.640625 | 4 | #Question num 38:
''' Get the Fibonacci series between 0 to 50 '''
x = 0
y = 1
while y < 50:
print(y)
x,y = y , x + y
|
27443d6926ac804260993a0c504d97aa935875b2 | jamircse/Complete-Python-3-Bootcamp | /Python-3/10.1 Tuple Example .py | 286 | 4.25 | 4 |
data1=(1,2,3,4)
data2=(20,30,40)
data3=data1+data2;
print(data3);
print("Maximum value of tuple ",max(data3));
print("Minimum value of tuple ",min(data3));
print("Lenth value of tuple ",len(data3));
print("3rd value of tuple ",data3[2]);
for i in data3:
print(i);
|
6b07ab41c2f55ef6969a4500204f294065031ceb | lvshuy/Computer-Simulation-Book | /ch03/approx_prob_outcome.py | 322 | 3.578125 | 4 | from random import randint
n = 1000000 # No. of times experiment is performed
ne = 0 # Count the occurrences of event
for i in range(n):
outcome = randint(1, 6)
if(outcome == 3): # Check for event of interest
ne += 1 # ne = ne + 1
print("Prob = ", round(ne / n, 4)) # = 0.16... |
af44c6e165bb3009d08288feabee8e34d5ccd8d8 | AgiliaErnis/intro-to-py | /basics/wordplay.py | 838 | 4.09375 | 4 | from basics import scrabble
for word in scrabble.wordlist:
if "oo" in word and "aa" in word:
print(word)
print("==============================")
for word in scrabble.wordlist:
if "q" in word and "u" not in word:
print(word)
print("==============================")
letters = "qwertyuiopasdfgh... |
1510ad4e1bc5172a7abae33117557f142e1a8bae | daniel-reich/ubiquitous-fiesta | /DG2HLRqxFXxbaEDX4_5.py | 118 | 3.671875 | 4 |
def return_only_integer(lst):
lst1 = []
for x in lst:
if type(x) == int:
lst1.append(x)
return lst1
|
afdd59e71f41d9de941d1aac64d29a614e242040 | YunJ1e/LearnPython | /MissingKnowledge.py | 5,472 | 3.671875 | 4 | """
Updated: 2020/07/12
Author: Yunjie Wang
"""
"""
This file includes some basic Python knowledge I miss when I first learn Python
1. Difference Between Continue and Break (Line 18)
2. Passing by Reference, and the return of the function (Line 38)
3. OOP (Line 81)
4. Draw the Dynamics (Line 137)
"""
"""
Difference Be... |
5712f3116ae0e48e779850a0dbfe61f5ad51e94b | Iso-luo/python-assignment | /practice/Ch4_interface design/turtle_基础.py | 356 | 3.625 | 4 | # -*- coding:UTF-8 -*-
# !/usr/bin/env python
import turtle
bob = turtle.Turtle() # create an object
print(bob)
bob.fd(100) # forward 100 pixels 画线
bob.lt(90) # left turn 90 degrees 箭头方向
bob.bk(100) # backward 100 pixels 画线
bob.rt(90) # right turn 90 pixels 箭头方向
# turtle.mainloop() # call m... |
0913f3e934cb073268da44bc837865acbdb2fd65 | philoxmyu/pro-python | /polymorphic_test.py | 853 | 4.125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 17-9-9 下午4:34
# @Author : philoxmyu
# @Contact : philoxmyu@gmail.com
'''
多态的概念其实不难理解,它是指对不同类型的变量进行相同的操作,它会根据对象(或类)类型的不同而表现出不同的行为。
有了继承,才有了多态,不同类的对象对同一消息会作出不同的相应
'''
class Animal(object):
def __init__(self, name):
self.name = name
def greet(se... |
e5ca079f8b95c88707b87d6a92269d87d33f2151 | dundunmao/lint_leet | /mycode/lintcode/Binary Search/38 Search a 2D Matrix II.py | 3,272 | 3.65625 | 4 | # -*- encoding: utf-8 -*-
# 写出一个高效的算法来搜索m×n矩阵中的值,返回这个值出现的次数。
#
# 这个矩阵具有以下特性:
#
# 每行中的整数从左到右是排序的。
# 每一列的整数从上到下是排序的。
# 在每一行或每一列中没有重复的整数。
# 您在真实的面试中是否遇到过这个题? Yes
# 样例
# 考虑下列矩阵:
#
# [
#
# [1, 3, 5, 7],
#
# [2, 4, 7, 8],
#
# [3, 5, 9, 10]
#
# ]
#
# 给出target = 3,返回 2
class Solution:
"""
@param matrix: An ... |
f018d611f88eb6c4785161e1d86eb307b3292788 | alhilario/python-stuff | /vac.py | 715 | 3.90625 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
def hotel_cost(nights):
return nights * 140
def plane_ride_cost(city):
if (city == "Charlotte"):
return 183
elif (city == "Tampa"):
return 220
elif (city == "Pittsburgh"):
return 222
elif (city == "Los Angeles"):
return... |
86f73eb1544abc472a2b52f423446ba24a1a7a7a | nrohankar29/Python | /parentheses_checker.py | 354 | 4 | 4 | def parentheses_checker(s):
stack = []
for char in s:
if char == '(' or char == '{' or char == '[':
stack.append(char)
if char == ')' or char == '}' or char == ']':
stack.pop()
if len(stack) == 0:
print('balanced')
else:
print('not balanced')
t = int(input())
for i in range(t):
s = input... |
2a2c448c5ce88835f2e367b5a2cf64c512587e97 | zhangmeiling0611/OOP | /opp_demo.py | 979 | 4.1875 | 4 | #!/user/bin/env python3
# -*- coding:utf-8 -*-
#定义一个类,类名为Student
class Student(object):
count = 0 #类属性,所有实例共享
def __init__(self,sno,name):
'''初始化方法,或者叫构造器,对属性进行初始化
'''
self.sno = sno #实例属性,属于每个对象,每个对象都有一份
self.name = name
Student.count += 1
def show(self):
... |
85bda477158b893bc7a0d979b2ad55f100198009 | satyam-seth-learnings/python_learning | /Geeky Shows/Core Python/2.Nested_While_Loop[37].py | 163 | 4.28125 | 4 | # Nested While Loop
i=1
while i<=2:
print("Outer Loop",i)
i+=1
j=1
while j<=3:
print("Inner Loop",j)
j+=1
print("Rest Of The Code") |
d94a060aadd68e93c463788ca257b3a5fe5cd50c | eugenechernykh/coursera_python | /week6_sort_by_count.py | 822 | 3.96875 | 4 | '''
Дан список из N (N≤2*10⁵) элементов, которые принимают целые значения от 0 до 100 (100 включая).
Отсортируйте этот список в порядке неубывания элементов. Выведите полученный список.
Решение оформите в виде функции CountSort(A), которая модифицирует передаваемый ей список.
Использовать встроенные функции сортировки ... |
e8dde7e51fda91a03e5c648d42f1a74c8b239fa3 | hellge83/AI_alg_python | /les02/les02_06.py | 937 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
6. В программе генерируется случайное целое число от 0 до 100.
Пользователь должен его отгадать не более чем за 10 попыток.
После каждой неудачной попытки должно сообщаться, больше или меньше
введенное пользователем число, чем то, что загадано.
Если за 10 попыток число не отгадано, вывес... |
0c2fdc8e4109a124c9ee30fda6e1dd7575d960be | MReeds/Interview-Prep | /Comprehension.py | 753 | 4.4375 | 4 | """ Comprehensions in Python provide us with a short and concise way
to construct new sequences (such as lists, set, dictionary etc.)
using sequences which have been already defined"""
# Create a new list of squared numbers from the original list
original_list = [1,2,3,4,5,6,7,8,9]
squared = [num*num for ... |
e2475054d336406594c21a096c31f4475d330bef | marlonprudente/DataMining | /Exemplos/coletaAPIs/streamingTwitter/processaExemplo1/exemploSimples1.py | 732 | 3.765625 | 4 |
import simplejson as json
# Arquivo com Tweets
tweets_file = open('tweet.txt', "r")
#le a linha do arquivo
tweet_json = tweets_file.readline()
#imprime a linha lida
#print tweet_json
#remove espacos em branco
strippedJson = tweet_json.strip()
#converte uma string json em um objeto python
tweet = json.loads(s... |
5d9311824e0ae00f2142a4adb575b1bf4fc4c572 | aalorro/python-projects | /for-loop.py | 347 | 4.53125 | 5 | #!/usr/bin/python3
# Python program that counts the number of characters in a given string
print("This python program counts the number of characters in a string\n")
string = input("Enter a string: ")
count = 0
for letter in string:
count += 1
print("You typed: " + string)
print("The number of characters in the... |
b56db6e18070f7cb05d86042b4c8e1e69c62cec7 | Amicond/AdaptivePython | /2.88.py | 68 | 3.5 | 4 | s=input()
print(s.upper() if 97<=ord(s)<=122 and s.islower() else s) |
b96855e07178f698664cf7455fd192271e804fb3 | abanuelo/Intro-To-Code | /Week 3/introductions_revisited.py | 850 | 4.09375 | 4 | #give me your age
age = 1000000
#give me your name
name = "MY NAME GOES HERE"
#Do a name check with basic if else
if name == "MY NAME GOES HERE":
print("You still have not changed your name")
else:
print("Nice to meet you!")
#Do a more complex age check
if age < 10:
print("An elementary student taking my class... |
2e6ac79f018c1482906d17d205a17cebda87900e | ModeConfusion/Programming-With-Python-For-DevOps-Engineers-Course | /Lesson-2-Python-Basics/Labs/arithmatic-operators/add.py | 77 | 3.625 | 4 | x = 5
y = 10
def addition(x: int, y: int):
print(x + y)
addition(10, 5) |
e94f898b777968c443069db7d36f4c31d7cf5403 | yifang0-0/BADgoose | /8/day3 class.py | 843 | 4.21875 | 4 | class Test:
def __init__(self, foo):
self.__foo = foo
def __bar(self):
print(self.__foo)
print('__bar')
class Test2:
def __init__(self,foo):
# 定义初始化函数的时候一定要加双下划线,因为构造函数不应该被其他类访问
self.foo = foo
def bar(self):
print(self.foo)
prin... |
dc23925be427219894ac1f34a99e4a114d701e4f | AkiraKane/Python | /examples/Web Browser/c_lexicalAnalyzer.py | 1,131 | 3.546875 | 4 | # Crafting Input
# Define a variable called webpage that holds a string that causes our lexical
# analyzer to produce the exact output below
# LexToken(WORD,'This',1,0)
# LexToken(WORD,'is',1,5)
# LexToken(LANGLE,'<',2,11)
# LexToken(WORD,'b',2,12)
# LexToken(RANGLE,'>',2,13)
# LexToken(WORD,'webpage!',2,14)
webpag... |
40a04c20fd73ed82701252050566bb54f72e7088 | rishavb123/MontyHallSimulation | /game.py | 1,049 | 3.828125 | 4 | import sys
import numpy as np
# Problem Setup
num_doors = int(sys.argv[1]) if len(sys.argv) > 1 else 3
prize_door = np.random.choice(num_doors)
# Choice
choice = input(f"Choose a door number between 0 and {num_doors - 1}: ")
while not choice.isdigit() or int(choice) < 0 or int(choice) >= num_doors:
choice = input... |
e565d461c7d914ecdfb0c51eca31f5ef6d86803b | victorrrp/Python-Intermediario | /aula37_curso.py | 1,128 | 4.03125 | 4 | '''
Count - Itertools
*Função que gera um contador que retorna um iterador
O python já tem um contador próprio, basta colocar
duas linhas de código: from itertools import count
'''
from itertools import count
contador = count()
#iterador (pode-se colocar quantos quiser, pois é um iterador)
print(next(... |
962eb10ecb2310e5538845bb7db28f0eaf7dbb54 | gistable/gistable | /all-gists/9009867/snippet.py | 267 | 3.75 | 4 | def is_palindrome(x):
x = str(x)
return x == x[::-1]
def find_palindromes(m, n):
for i in xrange(m, n):
for j in xrange(i, n):
x = i * j
if is_palindrome(x):
yield x
print max(find_palindromes(100, 1000))
|
9c4d06f31a7790cb41799c2a28dcc91071cb4cbe | AK-1121/code_extraction | /python/python_11536.py | 194 | 3.828125 | 4 | # how to replace punctuation in a string python?
import string
replace_punctuation = string.maketrans(string.punctuation, ' '*len(string.punctuation))
text = text.translate(replace_punctuation)
|
a1eea68dcc1ee821df9ed1e6e4a10ae6c0dc73fd | prekshaa/Computer-Security | /cryptBreak/cryptBreak.py | 1,928 | 3.546875 | 4 | #####
#Homework Number: 1
#Name: Prekshaa Veeraragavan
#ECN login: pveerar
#Due Date: January 28, 2021
#####
#!/usr/bin/env python 3.7)
import sys
from BitVector import *
def cryptBreak(ciphertextFile, key_bv):
PassPhrase = "Hopes and dreams of a million years"
BLOCKSIZE = 16
numbytes = BLOCKSIZE // 8
... |
1f972608888ce67d2903e33fdaab87531ac4945c | GretaP/DayTracker | /DatabaseCreation.py | 1,525 | 3.640625 | 4 | #database creation file
import psycopg2
import dbsettings
#Creates initial database using connection to postgress server
def createdatabase():
#create connection with postgress 'server'. note: under connect must include database=postgress
conn = psycopg2.connect(user=dbsettings.user, host= dbsettings... |
4693e2ec1e09bcb8f8d5cd4c28de2723c02822ff | DavidBitner/Aprendizado-Python | /Curso/ExMundo1/Ex002Nascimento.py | 231 | 3.828125 | 4 | dia = input('Qual o dia do seu aniversário?')
mes = input('Qual o mês do seu aniversãrio?')
ano = input('Em que ano você nasceu?')
print(dia, '/', mes, '/', ano)
print('Você nasceu no dia', dia, 'mês', mes, 'no ano de', ano)
|
9bdc82cdfd9854bffc47e2461dcc4226804028ba | greenbeen/IntroToPython | /Students/KHart/Session01/break_me.py | 454 | 3.625 | 4 | def name_error():
print a
# a has not been defined yet
def type_error():
"abc" / 2
# trying to perform operation inappropriate for type
def syntax_error():
#While 1 < 2:
print "error"
#capitalized while when it should be lower case
def attribute_error():
b = "string"
b.fa... |
18dae5cb6c627cb426faa6cd67e88eddf8e5e79a | rkhullar/python-problems | /problems/max_profit.py | 806 | 3.625 | 4 | """
Given the history of prices for a stock, find the optimal time to buy and sell one share.
scratch pads
https://repl.it/repls/MiniatureRosybrownCommands
https://repl.it/repls/FunnyAromaticParticle
"""
from typing import List, Dict
def solution(data: List) -> Dict:
min_idx, max_idx, buy_idx, sell_idx = 0, 0, ... |
b3fdaad2bde9c56a471f5f0b522317d11dff620c | VictorSalazar10/prueba | /sexto.py | 402 | 3.609375 | 4 | import time
hora=time.strftime("%H:%M:%S")
x=(hora.split(':'))
print(int x(0))
# def decorador(funcion):
# def cambio():
# if int(x[0])>=10 and int(x[0])<=16:
# funcion()
# else:
# print('No se mueve la mano pq no es el horario correcto')
# return cambio
#
# @decorador
#... |
c614fa03d1ea01c4f51b205428785d79736e94e4 | Jafet6/Jafet6.github.io | /computer-science/exercises/37_4/exercise5.py | 507 | 4.09375 | 4 | def binary_search(array, value):
low_index = 0
high_index = len(array)
while low_index < high_index:
middle_index = (low_index + high_index) // 2
if array[middle_index] == value:
return middle_index
elif array[middle_index] < value:
low_index = middle_index ... |
cc7813394ca74c9b894b9c78aa4d1560fee61ca6 | kevinelong/PM_2015_SUMMER | /StudentWork/DarWright/Python/Archive/tweet_bot.py | 1,181 | 3.5625 | 4 | import tweepy
from Tools.get_weather import Weather
# setting up tweedy api with keys and fun things.
consumer_key = 'U8cqX60tkVaElYwi2tSF6juU3'
consumer_secret = '5PvyrWArTnLRnEwvnrMXLAZW8MWlsnrXEOWy1lJEqNi7IGBM7A'
access_token = '3253921376-59a5Q52Qm6FMDorvvHDSttQtp6vRYennGGhIPga'
access_token_secret = 'NSprt2x9pa... |
ce9143b13822e0fe93921cdabe89de24c94e7373 | niki4/leetcode_py3 | /medium/061_rotate_list.py | 2,601 | 4 | 4 | """
Given the head of a linked list, rotate the list to the right by k places.
Example:
Input: head = [1,2,3,4,5], k = 2
Output: [4,5,1,2,3]
"""
from collections import deque
from tools.linked_list import make_linked_list_from_iterable, traverse
# Definition for singly-linked list.
class ListNode:
def _... |
ae3b2a1394d51e16949b1b05042555616b4f7087 | kheaney21/Final-Project | /Driver.py | 1,944 | 3.953125 | 4 | import sys
from voter import voter
class election:
'Driver for a simple questionnaire'
def __init__(self):
#list of voters
self.electorate = []
#ballot for q1
self.b0 = []
#ballot for q2
self.b1 = []
#ballot for q3
self.b2 = []
def poll():
'Prompt user for new votes or to tally'
input = ("... |
2cb4b59e2a433118e87572851ec8205f0cdfb266 | Esen9248/Python-Academy | /Examples/January/19.01.18/05.py | 289 | 3.8125 | 4 | res = input('Do you want to procced? (Y,N) ').upper()
class ContinueCommandError(Exception):
pass
def f():
if res == 'Y':
print('Yes')
elif res == 'N':
print('No')
else:
raise ContinueCommandError(res)
try:
f()
except ContinueCommandError as e:
print('Unknown command: ', e) |
ccec675354711732b7ef25e967f28380dc895522 | nikopoulospet/pythonScripts | /start.py | 1,380 | 3.765625 | 4 | #!/usr/bin/python
import random
class Nodes:
def __init__(self):
self.location = (-1,-1)
self.searched = False
self.neighbors = []
def create(self, location, neighbors):
self.location = location
self.neighbors = neighbors
def assign_neigbors(self, size):
... |
28f4689957253f7aca2f1da44320fd8f7ef15197 | mariotalavera/ai_jetson_nano | /primer/pythonArraysTwo.py | 1,081 | 4.09375 | 4 | gradeArray=[]
numGrades=int(input("How many grades do you have? "))
print("")
for i in range(0,numGrades,1):
grade=float(input("Input the grade: "))
gradeArray.append(grade)
print("")
for i in range(0,numGrades,1):
print("Your ",i+1," grade is ", gradeArray[i])
print("")
print("That's it boys; thank you for pl... |
d9d01be95165115cf4c8f2eeeef3438f02485ae8 | rjcmarkelz/python_the_hard_way | /exercises/ex13.py | 272 | 3.59375 | 4 | from sys import argv
script, first, second, third = argv
age = float(raw_input("How old are you in years?"))
print "The script is called:", script
print "Your first variable is:", first
print "Your second variable is:", second
print "Your age in years is:\t", age
|
702e2a5de9a35852cf52c4d7f17fbba346e35feb | z3r0sw0rd/COMP2041 | /test09/sort_words.py | 200 | 3.65625 | 4 | #!/usr/bin/python3
import sys
import re
for line in sys.stdin:
line = line.strip()
words = re.split(r'\s+', line)
for word in sorted(words):
print(word + " ", end = '')
print()
|
168c8fe840a84bbc71181f15e397b5a87f99a5da | AmyBrowneDesigns/CC_RPS_FLASK_WEEKEND_HOMEWORK | /tests/game_test.py | 482 | 3.5 | 4 | import unittest
from app.models.game import Game
from app.models.player import Player
class TestGame(unittest.TestCase):
def setUp(self):
self.player1 = Player('Amy', "rock")
self.player2 = Player('Bob', 'scissors')
self.banana = Player("matt", "paper")
self.game = Game("Amy", "... |
25667927a66b41e6115c94013e78737e08cfa673 | rheard/ProjectEuler | /p082.py | 2,197 | 3.84375 | 4 | """
The minimal path sum in the 5 by 5 matrix below, by starting in any cell in the left column
and finishing in any cell in the right column, and only moving up, down, and right,
is indicated in red and bold; the sum is equal to 994.
( 131 673'234'103'18'
'201'96''342'965 150
630 803 746 422 1... |
a83f1ceaa3eb082117a883c4f815f435b68b0659 | Jay168/ECS-project | /prog6.py | 86 | 3.578125 | 4 | celsius=float(input("Please provide temperature in degree celsius\n"))
print(celsius) |
56413d8f9c524b32745d3d917a9d1ceb026d8774 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/hamming/af7b69640e274d6d8a746f5ec4603bfe.py | 200 | 3.734375 | 4 | def hamming(s1, s2):
hamming_distance = 0
for i, j in zip(s1+' '*(len(s2)-len(s1)), s2+' '*(len(s1)-len(s2))):
if i != j:
hamming_distance += 1
return hamming_distance
|
dea6624c859356ed196474cbb7f746f5d5b44dd8 | DayGitH/Python-Challenges | /DailyProgrammer/DP20120808C.py | 1,199 | 4.1875 | 4 | """
[8/8/2012] Challenge #86 [difficult] (2-SAT)
https://www.reddit.com/r/dailyprogrammer/comments/xx970/882012_challenge_86_difficult_2sat/
Boolean Satisfiability problems are problems where we wish to find solutions to boolean equations such as
(x_1 or not x_3) and (x_2 or x_3) and (x_1 or not x_2) = true
Thes... |
d278d292850f2e9d4ae304f49290ddd4d6dd81aa | varununayak/refactoring | /04_inline_variable.py | 764 | 4.0625 | 4 | # Inline Variable
class Order:
def __init__(self, base_price: float) -> None:
self.base_price = base_price
def expensive_base(order: Order) -> bool:
base_price = order.base_price
return base_price > 1000
"""
Sometimes the name of a variable that is declared before an expression doesn't really ... |
0248933df015df076df258515cc6a3d1eae11f6e | filfilt/pythonRepository | /Part014 Identity and Membership.py | 389 | 3.84375 | 4 | #Identity & Membership
# Identity: Is and Is not
'''
lst1 = []
lst2 = []
lst3 = lst1
print(lst1 is lst2) # False b/s they are in diff place
print(lst1==lst1) # True b/s they are empty
print(lst3==lst1) # True they have the same value
print(lst3 is lst1) # True they are in the same place
'''
#Membership
fruits = ['ban... |
3b1270caca775ddf7c91cefe1ca65f61a7d91930 | PaulIsenberg/Election_Analysis | /PyPoll_Challenge.py | 3,911 | 3.765625 | 4 | # Add our Dependencies
import csv
import os
# Assign a variable for the file to load and the path.
file_to_load = os.path.join("Resources/election_results.csv")
# Assign a variable to save the file to a path.
file_to_save = os.path.join("analysis", "election_analysis.txt")
# 1. Initialize a total vote counter.
total_vo... |
7473ea8c60e70f9205af8334e0215e527b4532c2 | KKosukeee/CodingQuestions | /LeetCode/48_rotate_image.py | 1,247 | 3.96875 | 4 | """
Solution for 48. Rotate Image
https://leetcode.com/problems/rotate-image/
"""
class Solution:
"""
Runtime: 40 ms, faster than 74.53% of Python3 online submissions for Rotate Image.
Memory Usage: 13.4 MB, less than 5.35% of Python3 online submissions for Rotate Image.
"""
def rotate(self, matri... |
b006f3f99e33f2c2fb7f7c3f5405863030225382 | yesid23/python_class | /cajero automatico1.py | 1,775 | 4.03125 | 4 | #cajero automatico
print("cajero automatico")
atras = ("y")
intentos = 3
saldo = 1.000.000
while intentos >= 0:
clave = int(input("digite su clave:"))
if clave == (1234):
print("clave correcto ")
while atras not in ("n", "no", "N", "No"):
print("====menu===/n1-saldo/n2-retiro/n3-cambiarclave/n4-salir/n=... |
a10a232f8856b5ac5cebef4f56ede22de8a935a6 | crazywiden/Leetcode_daily_submit | /Widen/LC694_Number_of_Distinct_Islands.py | 2,554 | 3.796875 | 4 |
"""
LC694 -- number of distinct islands
Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.
Count the number of distinct islands. An island is considered t... |
3a57b14deaec52ccfb1d95dc4f6c04422193c58a | michelleweii/Leetcode | /05_图dfs与bfs/1_回溯算法/3_子集问题/78-子集.py | 1,163 | 3.734375 | 4 | """
middle 2022-01-14 回溯法-子集问题(无重复元素)
子集问题,树枝上的所有节点都要(遍历整棵树)。解集不能包含重复的子集start_index+1。
输入: nums = [1,2,3] 输出: [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
"""
class Solution(object):
def __init__(self):
self.res = []
self.path = []
def subsets(self, nums):
if not nums:... |
8fa3f522e409767302a5d80352ad8b88eae80a01 | MDolinski/SamplePythonProjects | /NoughtsAndCrosses.py | 3,096 | 3.84375 | 4 | from random import randint
class Board(object):
def __init__(self, size):
assert isinstance(size, int)
self.size = size
self.positions = [["-"] * self.size for i in range(self.size)]
def __repr__(self):
board_string = '\n'.join(['|'.join(self.positions[i]) for i in r... |
ac5705b3e4b760541a22ce49a67029ce07a3ee97 | Cainuriel/Training-Python- | /ficheros permanentes.py | 2,302 | 3.9375 | 4 | import pickle
class persona():
def __init__(self, nombre, genero, edad):
self.nombre = nombre
self.genero = genero
self.edad = edad
print("Se ha creado a una persona. Se llama: ", self.nombre)
# metodo que crea una cadena de texto con la informacion de un objeto:
def __str__(self):
return "{}... |
77fc096dcb75724e6a902f5a920de8bf219482e8 | jrgosalia/Python | /problem3_gameOfLuckySeven.py | 2,377 | 4 | 4 | """
Program : problem3_gameOfLuckySeven.py
Author : Jigar R. Gosalia
Verion : 1.0
Course : CSC-520 (Homework 1)
Prof. : Srinivasan Mandyam
Game of lucky sevens
--------------------
1. Player enters bet.
2. Player presses enter to roll the dices.
3. If the dots count equal to 7 then player wins $4.
4. If the dots... |
0d73fbe0cca9b55c913355f241c1b94c6be114f4 | sdmunozsierra/barebones-python-module | /App/main_app.py | 574 | 3.53125 | 4 | """Example file containing the main executable for an app."""
from logging import DEBUG
from Logger import logging_config
# Create a Logger for main_app
MAIN_LOG = logging_config.get_simple_logger("main_logger", DEBUG)
# Main program
def __main__():
MAIN_LOG.info("Running Main Program inside main_app.py")
MA... |
0b8e9818a762cfb359f0481032b16a5c66f7104f | this-josh/advent_of_code_2020 | /code/day_6.py | 1,073 | 3.53125 | 4 | with open("./inputs/day_6.txt", "r") as f:
input_data = f.readlines()
input_data = [line.strip() for line in input_data]
input_data.append("") # don't miss the last line
def common_values(people):
from functools import reduce
return list(reduce(lambda i, j: i & j, (set(x) for x in people)))
def part_... |
680213be0bca440bd3f7172671b3e28046b89791 | 3123958139/20180920hwjj | /AutoSendBW163Email/src/test5.py | 734 | 3.515625 | 4 | def ___get_currency_price(list_currency=['BTC', 'EOS', 'ETH', 'XRP', 'BCH', 'LTC']):
import urllib.request
cur_price_dict = {}
headers = {'User-Agent':'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0'}
for cur in list_currency:... |
a431f11214294f51248b4e16204fb9e78090df25 | MrMace/PythonProjects | /gradient_bar.py | 1,210 | 3.96875 | 4 | #Matt Mace
#BDAT610/week3
#gradient_bar
import graphics as g #import for graphics library
#creates screen
winWidth = 400 #window width
winHeight = 300 #window Height
win = g.GraphWin("Gradient Bar", winWidth,winHeight)
win.setBackground('red')#verifiy background is not seen under gradient
#vars
numBars = 1... |
6606d91ce412e3596642d99784712cfd198c9c29 | SUJEONG999/Python_Practice | /day3/whileLab4.py | 548 | 3.96875 | 4 | while True:
Month = int(input("월을 입력하시오(숫자만):"))
if 1 <= Month <= 12:
if Month == 12 or Month == 1 or Month == 2:
print (Month, "월은 겨울",sep="")
elif Month == 3 or Month == 4 or Month == 5:
print(Month, "월은 봄",sep="")
elif Month == 6 or Month == 7 or Month == 8:... |
e54523ce4dca08e0a889e4ee6eacfd40cbb340b2 | FarzanAkhtar/Intro-to-Webd | /Week 1 Practice Problems/4.py | 455 | 4.03125 | 4 | #Commas in number
def addcommas(a):
for element in a:
b=insertCommas(element)
print(b)
def insertCommas(a):
a=a[::-1]
b=[]
for i in range(len(a)):
b.insert(0,a[i])
if (i+1)%3 == 0:
b.insert(0,",")
if b[0] == ",":
b.pop(0)
return ("".join(b))... |
e941cdb40f5852c9a01038c5e0db7bae7545883d | Zhouenze/learnPython | /code/ch15t17c1.py | 5,269 | 3.5 | 4 | # -*- coding: utf-8 -*- #中文注释需要
X = 99
L = []
def func():
L.append(5) #虽然改变了但不是赋值语句,L仍是全局变量不是本地变量
print L #全局版本
# L = 1 #解注释会和上面冲突:有赋值语句的话L在整个本地命名空间都是本地变量,和上面的全局变量用法冲突
# print X #解注释会和下面冲突:X由下面已确定是本地变量,还没产生就引用。这里无法引用到全局版本
X = 98 #X是本地变量与外界不冲突
print... |
24dec35d32ce75986c9a36ff009c51db13c6a4a1 | aswinsajikumar/Python-Programs | /Permutation & Combination of a Number.py | 272 | 3.578125 | 4 | def fact(x):
f=1
for i in range(x,1,-1):
f=f*i
return f
n=int(input('Enter n:'))
r=int(input('Enter r:'))
d=n-r
nf=fact(n)
rf=fact(r)
df=fact(d)
ans=nf/(rf*df)
print ('Combination(nCr)=',ans)
ans1=ans*rf
print ('Permutation(nPr)=',ans1)
|
c25f298bdd9bef1eefa7f22dd6b0f34cba101d8f | llgeek/leetcode | /105_ConstructBinaryTreeFromPreorderAndInorderTraversal/solution1.py | 794 | 3.734375 | 4 | """
speed up by preprocessing the indexes in preorder
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
... |
dcc5d11886fb68b3a0654dc0677873721c920c0a | doitfool/leetcode | /Pascal's Triangle II.py | 1,074 | 4.0625 | 4 | """
@Project: leetcode
@file: Pascal's Triangle II.py
@author: AC
@time: 2016/5/10
@Description: Given an index k, return the kth row of the Pascal's triangle.
For example, given k = 3,
Return [1,3,3,1].
Note:
Could you optimize your algorithm to use only O(k) extra space?
[1]
[1, 1]
[1... |
eb74ccb8365739de446fb029f9bfa682dcc73abb | Rogerd97/mintic_class_examples | /P47/08-06-2021/lambda_function.py | 948 | 4.09375 | 4 | # reference
# MLA, 8.ª edición (Modern Language Assoc.)
# Romano, Fabrizio, et al. Python: Journey From Novice to Expert. Packt Publishing, 2016.
# APA, 7.ª edición (American Psychological Assoc.)
# Romano, F., Phillips, D., & Hattem, R. van. (2016). Python: Journey From Novice to Expert. Packt Publishing.
# example... |
5d963aea7e1a1ee053da10aad935e0bcb4aa5d6e | jhonathanmpg/clase-26 | /src/ale/utils.py | 1,439 | 3.984375 | 4 | import math
# Escribir una funcion que basado en el radio:
# calcule la sup de un circulo
# calcule la circunferencia
# calcule la sup de una esfera
# calcule el vol de una esfera
def calcularCircunferencia(radio):
"""
calcularCircunferencia() -> float
radio -- radio is in float
"""
circunfer... |
88b1d5ec121975017041e29630caf808aad6b8c5 | mohcinemadkour/ML_Programs | /ML_Basics/Logistic_Regression_GD.py | 2,421 | 3.6875 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 10 12:17:26 2018
@author: Das
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
class Logistic_Regression:
def fit(self, X, Y, theta, alpha, num_iter):
train = Train()
self.theta, J = train.gradient_des... |
aeb031cdfac9891a5639191202472b30d5efb451 | github-six06/project-1 | /第十一章/11-1/test_cities.py | 284 | 3.640625 | 4 | import unittest
from city_functions import city_country_name
class CitysTestCase(unittest.TestCase):
def test_city_country_name(self):
"""deal with message such as Santiago Chile"""
name=city_country_name('santiago', 'chile')
self.assertEqual(name,'Santiago Chile')
unittest.main()
|
ece32db09d98f717a02176a42f4e2977a2c1afd6 | 13thZygrite/AdventOfCode2017 | /day8.py | 1,438 | 3.6875 | 4 | #!/usr/bin/env python
with open("input_day8") as f:
input = f.readlines()
input = [x.strip() for x in input]
split = [line.split(" ") for line in input]
registers = {}
for instruction in split:
registers[instruction[0]] = 0
max_value = 0
# Part 1 and 2
for instruction in split:
cond... |
f52b0674a57c0c8f06c48ff17ff2ada908d49def | aalicav/Exercicios_Python | /ex048.py | 187 | 3.71875 | 4 | acm1 = 0
acm2 = 0
for c in range(0,500):
if c % 2 != 0 and c % 3 == 0:
acm1 += 1
acm2 += c
print('A soma dos {} numeros é {}'.format(acm1,acm2))
|
d09e0fa34338ce7773b55187e4e523b02cb90cd0 | bhavesh622/Sem6 | /Machine Learning/graddescentfunc.py | 2,610 | 3.65625 | 4 | import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
def cost_func(theta, X, y):
m = len(X)
pred = X.dot(theta)
cost = (1/m) * np.sum(np.square(pred - y))
return cost**(1/2)
def gradie... |
74d005d858b3c38555037ad546bee1228270a168 | rjmarzec/Google-CSSI---Coursera | /Algorithmic Toolbox/week3_greedy_algorithms/6_maximum_number_of_prizes/different_summands.py | 508 | 3.6875 | 4 | # python3
import sys
'''
2
'''
def optimal_summands(n):
summands = []
remaining_n = n
current_num = 1
while current_num <= remaining_n:
summands.append(current_num)
remaining_n -= current_num
current_num += 1
summands[len(summands) - 1] += remaining_n
return summand... |
dd83d7f6a74007ad3807019d8432dcbd69a5615d | EcoJuliet/Python-Projects | /Py files/CARTEIRA DE MOTORISTA.py | 585 | 3.9375 | 4 | # CALCULAR A IDADE DA PESSOA E VER SE ELA PODE TIRAR A CARTEIRA DE MOTORISTA
from datetime import datetime
print ('-----------------------')
print ('DEPARTAMENTO DE TRÂNSITO')
print ('-----------------------')
now = datetime.now()
print ('Nós estamos em', now.year)
ano_nasci = int(input('Insira seu ano de nascimento ... |
d075184f0c3dc3b14a2cc659e4bc9dc52a70500c | Frank-tree/my_tool | /set_pic_opacity.py | 403 | 3.5 | 4 | from PIL import ImageEnhance
def reduce_opacity(wm_pic, opacity):
"""Returns an image with reduced opacity."""
assert opacity >= 0 and opacity <= 1
if wm_pic.mode != 'RGBA':
wm_pic = wm_pic.convert('RGBA')
else:
wm_pic = wm_pic.copy()
alpha = wm_pic.split()[3]
alpha = ImageEnha... |
66c1c24a5f4a85f4f544084fcee7d0e78b0eaca2 | chaitanyamean/python-algo-problems | /Array/specialarrayProductsum.py | 288 | 3.84375 | 4 | '''Given a special non-empty array of integers, find the product of sum
'''
def productArray(arr, multiplier = 1):
sum = 0
for i in arr:
if type(i) is list:
sum += productArray(i, multiplier + 1)
else:
sum += i
return sum * multiplier
|
fd13ab68137e412b701b71be99312b9a1afa3a9d | lizetheP/PensamientoC | /programas/LabLiz/8_strings/examenStrings2.py | 410 | 3.828125 | 4 | def cuenta_caracter_espacios(cadena, letra):
cont = 0
for i in range(len(cadena)):
if cadena[i].lower() == letra.lower() or cadena[i] == ' ':
cont = cont + 1
return cont
def main():
cadena = str(input("Introduce una cadena: "))
letra = str(input("Introduce la letra : "))
re... |
54d8ac27ee48ab33fb4c4c0b64009003bf633bb2 | uciharis/Udemy-dletorey | /Python Programming Masterclass/Python/FlowControl/ranges.py | 1,428 | 4.34375 | 4 | # # exercise 60 iterating over a range
# for i in range(1, 20): # this will go from 1 to 19 as the last number in the range is not included
# print("i is now {}".format(i))
# # coding exercise 8 For Loop
# # Write a program to print out all the numbers from 0 to 9.
# for i in range(0, 10):
# print(i)
# #Exerc... |
9a6583d6beb85a2e98c589f5fd63e25163036ef8 | Sudeep-sudo/myrepo | /mypython/expense-tracker.py | 1,377 | 3.71875 | 4 | import sqlite3 as sql
import datetime as dt
from tabulate import tabulate
con = sql.connect("exp.db"); #connected to a database
cursor = con.cursor();
tab= '''CREATE TABLE IF NOT EXISTS tracker(
Spent_on TEXT NOT null,
Amount INTEGER NOT null,
Comment... |
8869656e93a6d8d9cbc99a32165c9eb5b1f6a53c | Rashmin528/BST-Algorithm | /bst_insertion.py | 898 | 4 | 4 | class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def insert(root, node):
if root is None:
root = node
else:
if root.data > node.data:
if root.left is None:
root.left = node
else:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.