blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
297b94ef7808b2ae2d11bca54d431f1be2120f72 | xxxfly/PythonStudy | /ProjectBaseTest1/算法与数据结构/03-排序/05-快速排序.py | 867 | 3.90625 | 4 | # coding:utf-8
def quickSort(orgList, start, last):
"""快速排序"""
if start >= last:
return
mid_vlaue = orgList[start]
low = start
high = last
while low < high:
# high 左移
while low < high and orgList[high] >= mid_vlaue:
high -= 1
orgList[low] = orgList[h... |
4508f1a2a2db060764a3ccf1fcf01a56704031aa | xxxfly/PythonStudy | /ProjectBaseTest1/算法与数据结构/03-排序/06-归并排序.py | 1,019 | 4.125 | 4 | #encoding:utf-8
def mergeSort(orgList):
"""递归排序"""
n=len(orgList)
if n<=1:
return orgList
middle=n//2
#left_li 采用归并排序后形成新的有序列表
left_li=mergeSort(orgList[:middle])
#right_li 采用归并排序后形成新的有序列表
right_li=mergeSort(orgList[middle:])
#将两个有序的子序列合并成一个整体
# merage(left_li,right_li)... |
ddc40fd831996a7626f7b6056fb5fd2d2959da5d | xxxfly/PythonStudy | /ProjectBaseTest1/Python基础/dataType.py | 405 | 3.6875 | 4 | # print(1024*768)
#字符型,'' ""
# print("i 'am' ok")
#转义 \
# print('i \'m \"ok\"')
#r'' 不转义
# print(r'i \\\\\m \\\\ \nok')
#'''...''' 多行内容
# print('''lin1
# ...lin2
# ...lin3
# ''')
# print(r'''im \nm
# ok
# ''')
# age=17
# if age>18:
# print('adult')
# else:
# print('teenager')
# a="abc"
# b=a
# a='xyz'
# p... |
80b49b99ca21b7925f3d002958aa9d0e6431a26a | xxxfly/PythonStudy | /ProjectBaseTest1/python核心编程/02-高级3-元类/07-调试.py | 533 | 3.859375 | 4 | # coding:utf-8
#pdb调试
#python3 -m pdb xxx.py
#l -->list显示当前的代码
#n -->next向下执行一行代码
#c -->continue继续执行程序
#b -->break 添加断点 b 行数
#clear --> 清除断点 clear 1 (第一个断点)
#s -->step 进入函数
#p --> print 打印一个变量的值 p result
#a --> 查看传入参数
#q --> 退出
#r --> return 快速执行函数的最后一行
def getAverage(a,b):
result=a+b
print('result=%d'%resul... |
ee098f39f6fe27a1ccff0ca8ad738c7f9d1d916d | xxxfly/PythonStudy | /ProjectBaseTest1/Python基础/03-高级特性highFeatures.py | 3,000 | 3.59375 | 4 | # -*- coding: utf-8 -*-
import os
from collections import Iterable
from collections import Iterator
L=['Michael','Sarah','Tracy','Bob','Jack']
r=[]
n=3
for i in range(n):
r.append(L[i])
print(r)
print(L[0:3])
print(L[:3])
print(range(3))
print(L[-2:])
print(L[-3:-1])
print(L[-1:])
print((0,1,2,3,4,5,6)[:3])
print... |
2d4a74ef569e29442435b75a80524dce7e1a9a9d | afcarl/swedish_chef | /chef_global/accelerate.py | 498 | 3.859375 | 4 | """
Module to provide a means to accelerate slow python code.
"""
import multiprocessing
def acc_map(func, items):
"""
Applies func to each item in items.
@param func: A function of the form f(item)
@param items: The list of items to apply func to
@return: void
"""
p = multiprocessing.Poo... |
cd05f442d554622b27630f7e47202889efff6f93 | SirGuiL/Python | /Mundo 3/Python_Exercicios/ex086.py | 331 | 4 | 4 | matriz = [
[[], [], []],
[[], [], []],
[[], [], []]
]
for r in range(0, 3):
for c in range(0, 3):
num = int(input(f'Digite o valor da coluna {c + 1} da linha {r + 1}: '))
matriz[r][c].append(num)
for r in range(0, 3):
for c in range(0, 3):
print(matriz[r][c], end=' ')
... |
bdb285b9f5b80f2fd9dac9f176575a5e3a13d278 | SirGuiL/Python | /Mundo 1/Python_Exercicios/ex024.py | 316 | 3.984375 | 4 | cidade = input('Digite o nome de uma cidade: ')
res = (cidade.split()[0].lower().find('santo'))
if(res != -1 and cidade.split()[0].lower() == 'santo'):
print("O nome da cidade começa com 'SANTO'.")
else:
print("O nome da cidade não começa com 'SANTO'.")
cidade = input('Digite o nome de uma cidade: ') |
118d67162a02cae06b471053b643773c91a26c26 | SirGuiL/Python | /Mundo 2/aula_12/aula_12.py | 307 | 3.875 | 4 | nome = input('Digite seu nome: ')
if (len(nome.strip()) == 0):
print('Digite um nome =(')
else:
if(len(nome.strip()) >= 10):
print('Você tem um nome grande.')
elif(len(nome.strip()) <= 4):
print('Você tem um nome pequeno.')
print('Tenha um ótimo dia, {}!'.format(nome))
|
4b5a82fdef8ba7af79277758ccdecba1126a5037 | SirGuiL/Python | /Mundo 1/aula_07/Exercícios/ex001.py | 681 | 4.09375 | 4 | nome = input('Digite seu nome: ')
# Utilizando 20 caracteres para a variavel nome
print('Prazer em conhecê-lo {:20}!'.format(nome))
# Utilizando 20 caracteres para a variavel nome e alinhando a direita
print('Prazer em conhecê-lo {:>20}!'.format(nome))
# Utilizando 20 caracteres para a variavel nome e alinhando a esq... |
712120fb30ec319a5ee65a43bb9e0cb6ed0ffc20 | SirGuiL/Python | /Mundo 2/Python_Exercicios/ex053.py | 278 | 4.0625 | 4 | phrase = input('Digite uma frase: ')
phrasejoin = ''.join(phrase.strip().split()).lower()
if phrasejoin == phrasejoin[::-1]:
print('{} é um palíndromo'.format(phrase.strip().capitalize()))
else:
print('{} não é um palíndromo'.format(phrase.strip().capitalize()))
|
cf809f23d5dd09ee5e2d7dc5c43ce963fb68a796 | SirGuiL/Python | /Mundo 2/Python_Exercicios/ex058.py | 493 | 4 | 4 | from random import randint
print('Adivinhe o número que estou pensando:\nDica: É um número de 0 a 10\nBoa sorte =)')
num = int(input(''))
count = 0
randomNum = randint(1, 10)
while num != randomNum:
if (num - randomNum < 3 and num - randomNum > -3):
print('Foi por muito pouco!')
else:
print('... |
b749ecda7fb8899047c715347e6bcc5ebb5dae28 | SirGuiL/Python | /Mundo 1/aula_04/Exercícios/data_formatada.py | 465 | 4 | 4 | dia = input('Digite o dia do seu nascimento: ')
mes = input('Digite o mês do seu nascimento: ')
ano = input('Digite o ano do seu nascimento: ')
print('Você nasceu no dia', dia, 'do', mes, 'de', ano, ', certo? (s para sim e n para não)')
confirm = input('')
if(confirm == 's'):
print('Você nasceu no dia', dia, '/'... |
1cc3b57ca48ddedf9187b459761e4c517146fe2a | SirGuiL/Python | /Mundo 3/Python_Exercicios/ex078.py | 490 | 3.953125 | 4 | lista = []
maior = menor = 0
for c in range(0, 5):
lista.append(int(input('Digite um número inteiro: ')))
if c == 0:
maior = menor = lista[c]
else:
if lista[c] > maior:
maior = lista[c]
if lista[c] < menor:
menor = lista[c]
print(f'O maior valor digita... |
334afd4599524aca8327c38bcf390da76d0ca0b2 | SirGuiL/Python | /Mundo 2/Python_Exercicios/ex059.py | 961 | 4.03125 | 4 | n1 = int(input('Digite um valor: '))
n2 = int(input('Digite outro valor: '))
menu = 0
print('[1] somar\n[2] multiplicar\n[3] maior\n[4] novos números\n[5] sair do programa\n')
while menu != 5:
menu = int(input('Escolha uma opção: '))
if (menu == 1):
print('A soma entre {} e {} é igual a {}'.format(n1,... |
c59c91add9c2dd28a5f6b1098113dd4d92548d23 | SirGuiL/Python | /Mundo 1/Python_Exercicios/ex025.py | 185 | 4.03125 | 4 | nome = input('Digite seu nome: ')
if(nome.lower().find('silva') != -1):
print('Seu nome tem Silva.')
else:
print('Seu nome não tem Silva.')
nome = input('Digite seu nome: ') |
1514e8aeef456d124a94cf6dfd75c29e9aee8b4b | SirGuiL/Python | /Mundo 2/aula_15/aula_15.py | 175 | 3.875 | 4 | # break and fstring
num = soma = 0
while True:
num = int(input('Digite um número: '))
if num == 999: break
soma += num
print(f'A soma dos valores vale {soma}')
|
8d9e21adba4b96f52c286581e1eaf0b51501f8dd | SirGuiL/Python | /Mundo 2/Python_Exercicios/ex060.py | 180 | 4.03125 | 4 | num = int(input('Digite um número: '))
n = num
count = num
while count != 1:
num *= count - 1
count -= 1
print('{} fatorial é igual a {}'.format(n, num))
a = input('') |
b5f97be3b57ffe3bd6c173e40604e2e3eb8fafc2 | SirGuiL/Python | /Mundo 3/Python_Exercicios/ex081.py | 965 | 3.90625 | 4 | lista = []
números = cinco = 0
opc = str
while True:
if opc == 'N':
break
num = int(input('Digite um número inteiro: '))
if num == 5:
cinco += 1
if num not in lista:
números += 1
lista.append(num)
while True:
opc = input('Deseja continuar? [S/N] ').upper()
... |
cca3891d0edf3d2a82eb6d715601677018a41ce2 | SirGuiL/Python | /Mundo 3/aula_19/aula_19.py | 1,048 | 4.03125 | 4 | # Variáveis composta (Dicionários)
# dados = dict()
dados = {
'nome': 'Guilherme',
'idade': 18
}
print(dados['nome']) # Retorna Guilherme
print(dados['idade']) # Retorna 18
dados['sexo'] = 'M' # Adiciona o elemento sexo e adiciona a informação M
print(dados['sexo']) # Retorna M
del dados['idade'] # Deleta ... |
b98a6140be3bcfd45582f98f2e832b8c509d2d49 | mikksillaste/aima-python | /ht13_Ex12_ListEnds_ListProperties.py | 244 | 3.828125 | 4 | a = [5, 10, 15, 20, 25]
b = [11, 15, 176, 555, 43]
# funktsioon mis teeb uue listi ainult esimesest ja viimasest arvust antud listis
def newList(list):
newlist = [list[0], list[-1]]
return newlist
print(newList(a))
print(newList(b)) |
2215b7f1de2216e1de2ccaa7f5522ca7b53268ac | mikksillaste/aima-python | /ht13_Ex28_MaxThree.py | 524 | 3.921875 | 4 | # kasutaja sisestab 3 numbrit
number1 = int(input("Sisesta esimene arv: "))
number2 = int(input("Sisesta teine arv: "))
number3 = int(input("Sisesta kolmas arv: "))
# funktsioon, mis tagastab kolmes sisestatud arvust suurima
def largest(number1, number2, number3):
biggest = 0
if number1 > biggest:
big... |
c238078f55464429915d9c9f7b8987336966c957 | hcs42/hcs-utils | /bin/Catless | 2,227 | 3.703125 | 4 | #!/usr/bin/python
# Prints the text from the standard input or the given files using `cat` or
# `less` depending on whether the text fits into the terminal
import optparse
import os.path
import subprocess
import sys
def parse_args():
usage = 'Usage: Catless [options] [FILENAME]...'
parser = optparse.OptionPa... |
50c8515e0b3dc1115ce9d7b3e9aeb1bd7f39672a | mourya1729/algoexport | /arrays algoexpert.py | 6,861 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Aug 23 12:37:02 2020
@author: mourya
"""
""" two sum"""
def twosum(a,num):
dic={}
for ele in a:
dic[ele]=None
print (dic)
for ele in a:
x=num-ele
if x!=ele and x in dic.keys():
return (ele,x)
return -1
#... |
f8b5da75967beb83ce248c744aedbdcef844481b | akash9579/python_snippets | /python_basic_stack_using_deque.py | 525 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 7 21:25:03 2021
@author: 91937
"""
# stack follow the last in first out
# example web brawsing application
# push,pop operation
"""
Write a function in python that can reverse a string using stack data structure.
"""
string = "we will play football"
... |
fa63e80619af8eaa57cf50ee582972453341d31e | akash9579/python_snippets | /substring.py | 301 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jan 10 09:56:02 2021
@author: 91937
"""
string = "akash"
sub = []
for i in range(len(string)):
for j in range (i,len(string)+1):
sub.append(string[i:j])
print(len(sub))
se=set(sub)
nsub=list(se)
print(len(nsub))
|
3185f97dd036042062b6b56ab0b57ba2adfcec9f | akash9579/python_snippets | /python_oops/property_setter_deleter.py | 1,301 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat May 23 19:28:18 2020
@author: akash
"""
class Employee:
def __init__(self, first, last):
self.first = first
self.last = last
@property # known as property decorator we can use that met... |
62159d8fc2552b4764870818ab5a6e1b3041cf90 | akash9579/python_snippets | /python_basic_tree.py | 722 | 3.890625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jan 8 18:11:17 2021
@author: 91937
"""
class treenode:
def __init__(self,data):
self.data=data
self.children=[]
self.parent=None
def add_children(self,child):
child.parent=self
self.children.append(ch... |
a75a23d202b58959853cd395cd403ddb2a937ef5 | pjcperpso/PythonPlayer | /PAT/PAT_乙级/1023_组个最小数.py | 701 | 3.890625 | 4 | """给定个数小于10的几个数
要求组成最小数 0不能做首位
如:00121123-------10011223
思路利用排序算法将数字从小到大排列
取出第一个为不为0的数和第一个互换
在调用list转换成str的方法
首位不能为0
"""
list = [0,1,2,3,5,6,1,1,1]
for x in range(0,len(list)):
temp = 0
for y in range(0,len(list)-x-1):
if list[y]>list[y+1]:
temp = list[y]
list[y] = list[y+1]
... |
f216a4c7e7782b56ce7bac081478e58cf136d491 | pjcperpso/PythonPlayer | /PAT/PAT_乙级/testnum.py | 333 | 3.9375 | 4 | """python字符串截取"""
list = ["hEllo","Hello","Helo","hello","hell"]
str_test = "Hellohhelloooohlhello"
num = 0
#print(list[0].upper())
#for x in list:
#if x.upper()=="HELLO":
#num = num+1;
#print(num)
for i in range(0,len(str_test)):
if str_test[i:i+5].lower() == "hello":
num = num + 1;
print(nu... |
92e77e768e1a412f4a67b09f4aa52ec2a5b893ad | 40586/Functions | /starter.py | 376 | 4 | 4 | #Kieran burnett
#Starter program
b_hours = int(input("Please enter the number of basic hours worked: "))
e_hours = int(input("Please enter the number of overtime hours worked: "))
pay = int(input("Please enter your pay per hour: "))
o_pay = pay + (pay / 2)
overtime = e_hours * o_pay
basic = b_hours * pay
... |
4207409a35d60c91076752e24083cf4e00ccc20e | deivid-01/manejo_archivos | /csv/csv_module/csv_read.py | 327 | 3.84375 | 4 | import csv
fields = []
rows = []
fileName="personas.csv"
with open(fileName,'r') as csv_file:
#Crear objeto reader
csv_reader= csv.reader(csv_file)
#Obtener encabezado
fields = next(csv_reader)
#Extrar cada una de las filas
for row in csv_reader:
rows.append(row)
print(fields)
print... |
d8ab5ec281b21f17f17008519ef108f37d918e16 | kimje0322/Algorithm | /기타/0226/Queue.py | 168 | 3.640625 | 4 | def enqueue(n):
global rear
if rear == len(queue)-1:
print('full')
else:
rear += 1
queue[rear] = n
queue = [0]*3
front = rear = -1
|
3d46c364b2fda038f09bb32781197ad0144ee312 | kimje0322/Algorithm | /문자열/1213 팰린드롬 만들기.py | 699 | 3.671875 | 4 | def check_palindrome(word):
cnt = 0
ans = [0]*len(word)
cnt_word = []
one_word = list(set(word))
one_word.sort()
for i in range(len(one_word)):
cnt_word.append(word.count(one_word[i]))
for c in range(len(cnt_word)):
if (cnt_word[c] % 2):
cnt += 1
ans[l... |
eec9859f53416b41e566f456284399272f7f5abb | kimje0322/Algorithm | /기타/가비아.py | 362 | 3.640625 | 4 | # import math
# def solution(n):
# cnt = countFive(n)
# return cnt
# def countFive(n):
# count = 0
# # print(math.floor(n/5))
# if math.floor(n/5) >= 5:
# count += math.floor(n/5)
# return countFive(math.floor(n/5))
# else:
# count += math.floor(n/5)
# return coun... |
d60e11d393a63a48c798da4f5f89b77a43b7af6a | kimje0322/Algorithm | /문자열/10809 알파벳 찾기.py | 187 | 3.5 | 4 | word = input()
check = [-1]*26
for w in range (len(word)):
if check[ord(word[w]) - 97] == -1:
check[ord(word[w]) - 97] = w
print(*check)
# ord(a) = 97 (0)
# ord(z) = 122 (25)
|
b3e7c0ea4503e50c1389a2dd07b77f2423003d8b | rkbarnwal/python-experiment1 | /liked-list.py | 841 | 3.671875 | 4 | class Node:
def __init__(self, data, next):
self.data = data
self.next = next
def getData(self):
return self.data
def setData(self, value):
self.data = value
def getNext(self):
return self.next
def setNext(self, newNext):
self.next = newNext
class... |
f059d95e2757aacf6853f1c697e94570eb11b0dc | k123456774/PythonCode | /score_B10309034.py | 152 | 3.75 | 4 | z=int(input("the hightest score"))
y=int(input("medium score"))
x=int(input("the lowest score"))
z=x*0.5
y=y*0.3
x=x*0.2
a=float(x+y+z)
print("a=%s"%a)
|
88e0893f2afce21f3eae1cf65e1cef3a833f09b2 | outcoldman/codeinterview003 | /2013/cracking/01-02.py | 426 | 4.15625 | 4 | # coding=utf8
# Write code to reverse a C-Style String. (C-String means that "abcd" is represented as five characters, including the null character.)
def reverse_string(str):
buffer = list(str)
length = len(buffer)
for i in xrange(length / 2):
t = buffer[i]
buffer[i] = str[length - i - 1]
... |
b5ad4a2c2126a96419f269d065c86e97eb295da3 | karthikeyansa/Data_Structures_python | /Tree/tree.py | 1,132 | 3.96875 | 4 | class Node(object):
def __init__(self,data):
self.data = data
self.left = None
self.right = None
''' def insert(self,data):
if self.data:
if data < self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
if data > self.data:
if self.right is None:
... |
c8a861aa57631a538f48389f522e2627b29c892e | MGelein/simulating-mistakes | /agent.py | 3,523 | 3.546875 | 4 | from random import choice, random, randint
from util import similar_looking_word, closest_word
class Agent:
def __init__(self, simulation, number):
self.simulation = simulation
self.canonical_text = simulation.text[:]
self.written_text = self.canonical_text[:]
self.remembered_t... |
9f0131996b87f8110b6bf1688a496e45ba59d228 | jxhd518/day1 | /day1/ifelse.py | 245 | 3.75 | 4 | age_of_oldboy = 48
guess = int(input(">>:"))
if guess > age_of_oldboy :
print("猜的太大了,往小里试试...")
elif guess < age_of_oldboy :
print("猜的太小了,往大里试试...")
else:
print("恭喜你,猜对了...") |
4e10ff8b70898ac729fa530a4364bd238e215ea3 | jwilke/cs373 | /examples/Test.py | 284 | 3.8125 | 4 | #!/usr/bin/env python
def my_max (x, y) :
if x < y :
return y
return x
def my_max (x, y, bf) :
if bf(x, y) :
return y
else :
return x
assert my_max(2, 3) == 3
assert my_max(2, 3, lambda x, y : y < x) == 2
print "Done."
|
2e891d87430890bacd0c35e202a85609f498f656 | Mrwang19960102/work | /model/machine_learning/sklearn/k_近邻.py | 756 | 3.59375 | 4 | # -*- coding: utf-8 -*-
# @File: | k_近邻.py
# @Date: | 2020/8/5 16:57
# @Author: | ThinkPad
# @Desc: |
import numpy as np
import pandas as pd
from pandas import DataFrame, Series
# k邻近算法模型
from sklearn.neighbors import KNeighborsClassifier
# 手动创建训练数据集
feature = np.array([[170, 65, 41], [1... |
28c74e11030275997ea19c2b3195a11645f540d7 | v4nh4n/practicepython.org | /ex25.py | 437 | 3.765625 | 4 | def guesser():
i = 0
m = 100
mid = 50
print("Guess some number btw 0-100")
condition=input("Is your guess"+str(mid)+"? exact/low/high")
while condition!="exact":
if condition=="low":
i = mid + 1
elif condition=="high":
m = mid - 1
mid = (i+m)//2
... |
faeeac5a13e7acc581496ff6ed3cde7b3c820fa3 | v4nh4n/practicepython.org | /ex11.py | 271 | 4.03125 | 4 | def prime_number(num):
if num==1 or num==2:
return True
for i in range(num):
if i>1 and num%i==0:
return False
return True
while True:
number = int(input("ENTER A NUMBER (CTRL+C TO EXIT) => "))
print(prime_number(number))
|
38b243be83f550104533a75da2cf8b1e250c7bd6 | v4nh4n/practicepython.org | /ex6.py | 178 | 3.828125 | 4 | a = input("ENTER A STRING: ")
x = int((len(a)/2))
print(x)
h1 = a[:x]
h2 = a[x+1:]
print(h1)
print(h2)
if h1==h2:
print("palindrome!")
else:
print('not a palindrome...')
|
44848bd2b67081257b43f36a02cdf198be762ea5 | anthonykid/HelloWorldWithButton | /hello.py | 452 | 3.75 | 4 | import tkinter as tk
root = tk.Tk()
canvas1 = tk.Canvas(root, width=300, height=300)
canvas1.pack()
def hello():
label1 = tk.Label(root, text="Hello I'm AnthonyKid", fg='green',
font=('helvetica', 12, 'bold'))
canvas1.create_window(150, 200, window=label1)
button1 = tk.... |
eec8c0278f1ab0c8a01c7a12c36205e7f9e03657 | awenhaowenchao/bee | /src/bee/db/psd/table.py | 1,215 | 3.515625 | 4 | class Table():
def name(self) -> str:
pass
def alias(self) -> str:
pass
def prefix(self) -> str:
pass
def to_table(table: object) -> "Table":
if isinstance(table, str):
return SimpleTable(table)
elif isinstance(table, Table):
return table
def new_table(n... |
029eed69f21e51fe196224a5fbf95c8c5983cd84 | bhamal7/Task3 | /9.py | 108 | 4.03125 | 4 | n = int(input("Enter the number:"))
dict1 = dict()
for i in range(1,n+1):
dict1[i] = i*2
print(dict1)
|
0f972ebd21136f1593ad9a7726b129534706936d | Mezz403/Project-Euler | /Python/059_XOR Decryption (Optimized)/main.py | 742 | 3.671875 | 4 | import brute_force
import encryption
import letter_frequency
import text_analyzer
def main(filename):
with open(filename) as text:
intText = list(map(int, text.read().split(',')))
chrText = list(map(chr, intText))
frequencies = text_analyzer.text_analyzer(filename)
print('\nCreatin... |
8554ac9b1cfd70eae40a5b2819014edb7b4580a7 | kukubimaa/Tugas-Kampus-- | /Tugas 4.py | 934 | 3.546875 | 4 | NAMA = raw_input("MASUKKAN NAMA ANDA :")
NIM = raw_input("MASUKKAN NIM ANDA :")
UTS = int(raw_input("MASUKKAN NILAI UTS ANDA :"))
UAS = int(raw_input("MASUKKAN NILAI UAS ANDA :"))
TUGAS = int(raw_input("MASUKAN NILAI TUGAS ANDA :"))
akhir = (UTS+UAS+TUGAS)/3
print"=================================="
print " NILA... |
03d8c1b147a21616b238c33644b0bd6a488ba1ee | hellokayas/Some-Programming-Samples | /bit_manip.py | 6,364 | 4.34375 | 4 | import math
import sys
# | is bitwise or
# & and ~ are bitwise and and not respectively.
# x << y = x * 2**y which is x has its bits shifted to right by y places(think like multiplying by power of 10)
# x>>y = x // 2**y left shift
# can test if two bits equal or not by xoring them(^).
# Can flip a bit by xo... |
02ff53a09789c33fef7e5deb5a13942183203a08 | hellokayas/Some-Programming-Samples | /quicksort-leftright.py | 460 | 3.78125 | 4 | def qsort(l,b,e):
if b>=e:
return
p = b
q = p+1
while (q<=e):
if (l[q] > l[b]):
q=q+1
else:
l[q],l[p+1] = l[p+1],l[q]
p = p+1
q= q+1
l[b],l[p] = l[p],l[b]
qsort(l,b,p-1)
qsort(l,p+1,e)
def quicksort(l):... |
97d71dead162e971e3f3000fc85846ca8e14cbe8 | hellokayas/Some-Programming-Samples | /Strings.py | 10,521 | 3.984375 | 4 | import math
import sys
import string
from itertools import groupby
#Given a string A. Return the string A after reversing the string word by word.
#"the sky is blue" --> "blue is sky the"
def revword(S):# join returns words joined by space. Strip removes irrelevant spaces from start and end of the str
retur... |
d835bfb12ca4573d9088694f592fdd7366dc830b | hellokayas/Some-Programming-Samples | /Kruskals.py | 645 | 3.625 | 4 | from DisjSet import DisjSet
# Graph vertices are number 0 .. N-1 and M is the number of edges
def readEdgeList():
line = input()
l = line.split()
N = int(l[0])
M = int(l[1])
G = [] # List of the form (wt,vertex1,vertex2)
for i in range(0,M):
line = input()
l = line.split()
ls = list(map(int,l))
G.append... |
7eb869c50b42c1dc264327091a01d2b8bf5650bd | alvaronem/Codewars-Python-practice | /Sum-by-factors.py | 773 | 3.65625 | 4 | def prime_factors(n):
i = 2
factors = []
if n < 0:
n *= -1
while i * i <= n:
if n % i:
i += 1
else:
n //= i
factors.append(i)
if n > 1:
factors.append(n)
return factors
def combine(arr1, arr2):
for a in arr1:
if not... |
3e4752456955b6e55f9063a8a5fc7d5a295a1489 | saitoshin45/AnimalTetris- | /tetris2.py | 2,310 | 3.6875 | 4 | #tetris2.py
#import the necessary drivers
import tkinter
import random
#variable declaration
mouseX = 0
mouseY = 0
mouseC = 0
cursorX = 0
cursorY = 0
#function for the mouse positions
def mouse_move(e):
global mouseX, mouseY
mouseX = e.x
mouseY = e.y
#function to get the mouse click
def... |
10bc69d936b58fb5ed927a8a30970b88b804aeb8 | ashutoshabhimanyuxyz/loltracker | /location.py | 275 | 3.5625 | 4 | import phonenumbers
from phonenumbers import carrier
from phonenumbers import geocoder
num = input("Enter your phone number:")
phone_number = phonenumbers.parse(num)
print(geocoder.description_for_number(phone_number,"en"))
print(carrier.name_for_number(phone_number,"en")) |
c9c178a50f1a0a35908b8c38b43e798f27c27f2c | MSO-star/SP_opdrachten | /4.py | 485 | 3.578125 | 4 | def palindroom_version2(woord):
letters_woord= list(woord)
pali= True
for i in letters_woord:
if i ==letters_woord[-1]:
letters_woord.pop(-1)
else:
pali= False
break
return pali
print(palindroom_version2("malayalam"))
def palindroom_version1(woord):
... |
517d7f68fcfa50417dc4cc8fd4902b41d706171e | LilGherkin/PythonPractice | /2FlowControl.py | 7,599 | 4.5625 | 5 | # Boolean values are values that equate to either True or False.
booleanexample1 = True
booleanexample2 = False
# Python has comparision operators that will output as True or False.
# == equal to. 42 == 42 outputs 2. 41 == 42 outputs false.
# != not equal to. 42 != 41 outputs true. 42 != 42 is false.
# < less than. 4... |
08a2ef01d9989af3a634dec93ccbd125000eda40 | m-kashani/Problem-Solving-in-Data-Structures-Algorithms-using-Python | /IntroductoryChapters/Bulb.py | 574 | 3.53125 | 4 | #!/usr/bin/env python
class Bulb(object):
def __init__(self): # Constructor
self.isOn = False # Instance Variable
def turnOn(self): # Instance Method
self.isOn = True
def turnOff(self): # Instance Method
self.isOn = False
... |
bdf32e67adb4716e6e2e5f7e122c6359832021a7 | m-kashani/Problem-Solving-in-Data-Structures-Algorithms-using-Python | /IntroductoryChapters/ForDemo.py | 710 | 3.96875 | 4 | #!/usr/bin/env python
text = "Hello, World!"
PI = 3.141592653589793
def main1():
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
totalsum = 0
for n in numbers:
totalsum += n
print "Sum is :: " , totalsum
def main2():
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
totalsum = 0
i ... |
c73a54771e27fb298a73d595b5d925514f68e6cc | prashantchanne12/Leetcode | /find the first k missing positive numbers.py | 1,383 | 4.125 | 4 | '''
Given an unsorted array containing numbers and a number ‘k’, find the first ‘k’ missing positive numbers in the array.
Example 1:
Input: [3, -1, 4, 5, 5], k=3
Output: [1, 2, 6]
Explanation: The smallest missing positive numbers are 1, 2 and 6.
Example 2:
Input: [2, 3, 4], k=3
Output: [1, 5, 6]
Explanation: The s... |
879cde7a247d8c82757190d715cca62bcad6d168 | prashantchanne12/Leetcode | /longest substring without repeat character.py | 1,100 | 4.09375 | 4 | '''
Share
Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: "pwwkew"
Outpu... |
5718a2011b7dcd969516e4c3f2b24b2cebfa713b | prashantchanne12/Leetcode | /reverse linked list.py | 1,355 | 4.3125 | 4 | '''
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
'''
# Solution 1
class Solution(object):
def reverseList(self, head):
prev = None
current = he... |
831977afd452ae4782e43ffef22f77c08dfafcbc | prashantchanne12/Leetcode | /Kth largets element.py | 976 | 4 | 4 | from heapq import *
'''
Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
Example 1:
Input: [3,2,1,5,6,4] and k = 2
Output: 5
Example 2:
Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4
'''
# Solution - 1
class Solution(obje... |
37d21dbd7a42294165351460e68d301d30416a5a | prashantchanne12/Leetcode | /trapping rainwater.py | 1,421 | 4.09375 | 4 | '''
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.
Example 1:
Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In ... |
d57e3c988f5311a9198d2d8bcd415c58ebb837d6 | prashantchanne12/Leetcode | /daily tempratures.py | 923 | 4.1875 | 4 | '''
Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer temperature. If there is no future day for which this is possible, keep answer[i] == 0 instead.
Example 1:
Input: temper... |
20801f067b8f3b6248285c98c759bf60ef833c5f | prashantchanne12/Leetcode | /backspace string compare - stack.py | 1,839 | 4.1875 | 4 | '''
Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character.
Note that after backspacing an empty text, the text will continue empty.
Example 1:
Input: S = "ab#c", T = "ad#c"
Output: true
Explanation: Both S and T become "ac".
Example 2:
Input: ... |
209882f118ac28481841a9577f2caba3b5ecdbf6 | prashantchanne12/Leetcode | /path with given sequence.py | 2,155 | 4 | 4 | '''
Given a binary tree and a number sequence, find if the sequence is present as a root-to-leaf path in the given tree.
'''
# Solution - 1
# sequence - 101 (in the form of integer)
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right =... |
e2aa15140104f1ea6013fdc5526e3dac39720a5a | prashantchanne12/Leetcode | /first duplicate.py | 504 | 3.921875 | 4 | '''
Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.
Example 1:
Input: [1,3,4,2,2]
Output: 2
Example 2:
Input: [3,1,3,4,2]
Output: 3
'''
class ... |
4cc773965da12e433077f96090bdeea04579534a | prashantchanne12/Leetcode | /pascal triangle II.py | 688 | 4.1875 | 4 | '''
Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
Example 1:
Input: rowIndex = 3
Output: [1,3,3,1]
Example 2:
Input: rowIndex = 0
Output: [1]
'''
class Solution(object):
de... |
68b5f431afb5a3422a1f90195e341c0bb348a8f4 | prashantchanne12/Leetcode | /balance a binary search tree.py | 1,405 | 4.09375 | 4 | '''
Given a binary search tree, return a balanced binary search tree with the same node values.
A binary search tree is balanced if and only if the depth of the two subtrees of every node never differ by more than 1.
If there is more than one answer, return any of them.
Example 1:
Input: root = [1,null,2,null,3,nul... |
5efbfb64f054e7cbcd77aa0f55599835c48b4d0d | prashantchanne12/Leetcode | /bitonic array maximum.py | 998 | 4.34375 | 4 | '''
Find the maximum value in a given Bitonic array. An array is considered bitonic if it is monotonically increasing and then monotonically decreasing. Monotonically increasing or decreasing means that for any index i in the array arr[i] != arr[i+1].
Example 1:
Input: [1, 3, 8, 12, 4, 2]
Output: 12
Explanation: The ... |
a66aab6ac79fbd01af1c0c3f4558ef3f75277d8d | prashantchanne12/Leetcode | /set mismatch.py | 859 | 4.0625 | 4 | '''
The set S originally contains numbers from 1 to n. But unfortunately, due to the data error, one of the numbers in the set got duplicated to another number in the set, which results in repetition of one number and loss of another number.
Given an array nums representing the data status of this set after the error.... |
c8ce6f1d1f34106357210c7361c2471bea783240 | prashantchanne12/Leetcode | /smallest missing positive number.py | 712 | 4.21875 | 4 | '''
Given an unsorted array containing numbers, find the smallest missing positive number in it.
Example 1:
Input: [-3, 1, 5, 4, 2]
Output: 3
Explanation: The smallest missing positive number is '3'
Example 2:
Input: [3, -2, 0, 1, 2]
Output: 4
Example 3:
Input: [3, 2, 5, 1]
Output: 4
'''
def find_missing_positive... |
5944bd2874c4a561cebcc44ab45cd8a725b0cc05 | prashantchanne12/Leetcode | /power of two.py | 344 | 3.953125 | 4 | '''
Given an integer, write a function to determine if it is a power of two.
Example 1:
Input: 1
Output: true
Explanation: 20 = 1
Example 2:
Input: 16
Output: true
Explanation: 24 = 16
Example 3:
Input: 218
Output: false
'''
class Solution(object):
def isPowerOfTwo(self, n):
return (n != 0) and ((n & ... |
f9cdd9e18578be52a8d31f9d525d5376520bc13f | prashantchanne12/Leetcode | /reconstruct sequence.py | 2,926 | 3.765625 | 4 | '''
Given a sequence originalSeq and an array of sequences, write a method to find if originalSeq can be uniquely reconstructed from the array of sequences.
Unique reconstruction means that we need to find if originalSeq is the only sequence such that all sequences in the array are subsequences of it.
Example 1:
Inp... |
cb3e496fd43b93383a978d3e0ec27b37b5a57008 | prashantchanne12/Leetcode | /partition list.py | 1,071 | 4 | 4 | '''
Given the head of a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
Example 1:
Input: head = [1,4,3,2,5,2], x = 3
Output: [1,2,2,4,3,5]
Example 2:
... |
4708114b3e8133dddc8e6dc9d758bfc7dc25e5c4 | prashantchanne12/Leetcode | /find shortest path-graph dfs.py | 488 | 3.78125 | 4 | graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
}
def find_shortest_path_dfs(source, destination, visited, graph, dist):
if source not in visited:
visited.add(source)
if source == destination:
print(dist)
for n in... |
1811fedf3317e61f5fa1f70b1669b47cae04716d | prashantchanne12/Leetcode | /validate binary search tree.py | 1,294 | 4.125 | 4 |
import math
'''
Given the root of a binary tree, determine if it is a valid binary search tree (BST).
A valid BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the l... |
0423ec8f68bdbea0933002ff792eaaf73b0026e5 | prashantchanne12/Leetcode | /merge intervals.py | 1,718 | 4.375 | 4 | '''
Given a list of intervals, merge all the overlapping intervals to produce a list that has only mutually exclusive intervals.
Example 1:
Intervals: [[1,4], [2,5], [7,9]]
Output: [[1,5], [7,9]]
Explanation: Since the first two intervals [1,4] and [2,5] overlap, we merged them into
one [1,5].
Example 2:
Input: in... |
8f2ce57a0f07d2f6087b2511b27d44546559d555 | prashantchanne12/Leetcode | /doubly linked list.py | 1,327 | 4 | 4 | class Node:
def __init__(self, data=None, next=None, prev=None):
self.data = data
self.next = next
self.prev = prev
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def insert_at_beg(self,data):
if self.head == None:
... |
30c022b03d26825d5edcce633de3b490123772eb | prashantchanne12/Leetcode | /valid pallindrome.py | 698 | 4.21875 | 4 | '''
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
Example 1:
Input: "A man, a plan, a canal: Panama"
Output: true
Example 2:
Input: "race a car"
Output: false
'''
import... |
d25b0c3eb45e06f100dab5ca4699e529a17d0db6 | prashantchanne12/Leetcode | /insert interval.py | 3,240 | 4.1875 | 4 | '''
Given a list of non-overlapping intervals sorted by their start time, insert a given interval at the correct position and merge all necessary intervals to produce a list that has only mutually exclusive intervals.
Example 1:
Input: Intervals=[[1,3], [5,7], [8,12]], New Interval=[4,6]
Output: [[1,3], [4,7], [8,12]... |
6aab48bb7e3c455f36278482dad88fa76915b4c4 | prashantchanne12/Leetcode | /single number bitwise.py | 347 | 4.0625 | 4 | '''
In a non-empty array of integers, every number appears twice except for one, find that single number.
Example 1:
Input: 1, 4, 2, 1, 3, 2, 3
Output: 4
Example 2:
Input: 7, 9, 7
Output: 9
'''
def find_single_number(arr):
res = 0
for num in arr:
res = res ^ num
return res
print(find_singl... |
8eab0b75982372250d35703ec9ae464e24498417 | prashantchanne12/Leetcode | /longest subarray with ones after replacemenet.py | 1,114 | 4.03125 | 4 | '''
Given an array containing 0s and 1s, if you are allowed to replace no more than ‘k’ 0s with 1s, find the length of the longest contiguous subarray having all 1s.
Example 1:
Input: Array=[0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1], k=2
Output: 6
Explanation: Replace the '0' at index 5 and 8 to have the longest contiguous su... |
713c22ad11eec595b3337a723d15c8ae336ea4bd | prashantchanne12/Leetcode | /count paths for sum.py | 1,458 | 3.78125 | 4 | '''
Given a binary tree and a number ‘S’, find all paths in the tree such that the sum of all the node values of each path equals ‘S’. Please note that the paths can start or end at any node but all paths must follow direction from parent to child (top to bottom).
'''
class TreeNode:
def __init__(self, val, left=... |
3726adcdf00bf55230f9320a44a4b4a25da5efde | prashantchanne12/Leetcode | /01 knapsack.py | 2,045 | 3.5 | 4 | # Solution 1 - Recursive
def knapsack(profits, weights, capacity, n):
# base case
if n == 0 or capacity == 0:
return 0
if weights[n-1] <= capacity:
return max(
profits[n-1] + knapsack(profits, weights,
capacity-weights[n-1], n-1),
... |
ab90f228d7ce78e24b1af10e31d8857a2ea8db63 | prashantchanne12/Leetcode | /intersection of two linked list.py | 2,693 | 3.9375 | 4 | '''
Given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null.
For example, the following two linked lists begin to intersect at node c1:
It is guaranteed that there are no cycles anywhere in the enti... |
3198e640494c234e8603277b2d4f33922f3528c3 | prashantchanne12/Leetcode | /conflicting appointments.py | 1,061 | 4.03125 | 4 | '''
Given an array of intervals representing ‘N’ appointments, find out if a person can attend all the appointments.
Example 1:
Appointments: [[1,4], [2,5], [7,9]]
Output: false
Explanation: Since [1,4] and [2,5] overlap, a person cannot attend both of these appointments.
Example 2:
Appointments: [[6,7], [2,4], [8,1... |
9b2706672b9ab33617c4f91645e99eb990ec9e25 | DmitryKop/firststeps | /Python/TicTacToe.py | 5,554 | 4.09375 | 4 | import random
board = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
player_1_name = ''
player_2_name = ''
def get_names():
global player_1_name
player_1_name = input("Player 1, enter your name: ")
global player_2_name
player_2_name = input("Player 2, now please enter your name: ")
def get_marker... |
bf5dfe5e82866019001867bb7136e266b549593a | Sonjongkook/Group4-Emergency-Vehicle-Dispatching-System-Project- | /project/vertex.py | 1,006 | 3.859375 | 4 | import sys
class Vertex:
# initialize member variables of the vertex
def __init__(self, node_value):
self.id = node_value
self.neighbor = {}
self.distance = float('inf')
self.visited = False
self.previous = None # predecessor which is essential for graph
... |
04774b08d79956c826dd25ece5d12f3aea56922b | sgpl/project_euler | /1_solution.py | 586 | 4.28125 | 4 | #!/usr/bin/python 2.7
# If we list all the natural numbers
# below 10 that are multiples of 3 or 5,
# we get 3, 5, 6 and 9.
# The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5
# below 1000.
counter = 0
terminating_condition = 1000
sum_of_multiples = 0
while counter < terminating_c... |
6f5846ece2ce5539be0a08087f7d369e2b9ada35 | alphaonezero/python | /while.py | 133 | 4.0625 | 4 | L=[]
while len(L)<3:
new_name = input("Please add a new name: ").strip()
L.append(new_name)
print("The list is now full.")
|
dfb36aeb80967cd2386adaba35b7c98ca8a47a21 | theForgerass/3DPointCloud | /Commonstruct/Point2D.py | 2,126 | 3.96875 | 4 | """
二维点
"""
import math
class Point2D:
__slots__ = ('_x', '_y')
def __init__(self, x=0.0, y=0.0):
"""
初始化点坐标
:param x: X坐标
:param y: Y坐标
"""
self._x = x
self._y = y
def __add__(self, other):
if isinstance(other, Point2D):
retur... |
56c8db8750b288b5483a7bc339e865d589a1d503 | walterschell/classcode | /dict_demo.py | 207 | 3.96875 | 4 | def main():
ages = {}
ages["Alice"] = 29
ages["Bob"] = 21
ages["Eve"] = 30
for name in ages.keys():
print '%s: %s' % (name, ages[name])
if __name__ == '__main__':
main()
|
fdc04a8ea2ec6264781dd8fa7a91dc2bab4f46f7 | iamsabhoho/PythonProgramming | /Q1-3/MasteringFunctions/Accumulation.py | 233 | 3.90625 | 4 | #Write the accumulated sum of a list.
#For example, if the input is [1, 2, 3, 4, 5],
#then the output should be [1, 3, 6, 10, 15].
p = 1
list = [1,2,3,4,5]
print(list[0])
for i in range(len(list)-1):
p += list[i]+1
print(p)
|
e3ca39e8ccdee4d39038a95701ce541f85f19ff8 | iamsabhoho/PythonProgramming | /Q1-3/myLib.py | 2,323 | 4.09375 | 4 | def readText(filepath):
"""
read and return a text in a file
:param filepath:
:return:
"""
f = open(filepath, 'r')
returnText = f.read()
f.close()
return returnText.split()
def findNextWord(word, text):
"""
find the words that appears in the text file
:param word: the ke... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.