text stringlengths 37 1.41M |
|---|
pyramid = int(input("Number of floors = "))
for i in range(pyramid):
for j in range(i+1):
result = (" "*(pyramid-(j+1))+"*"*(1+(2*i)))
print(result)
|
class Calculator:
# name = 'Good calculator'
# price = '18'
# 类似构造器的一个东西,初始化参数,不同的是,不需要提前定义变量
def __init__(self, name, price):
self.name = name
self.price = price
def add(self, x, y):
print(self.name)
result = x + y
print(result)
def minus(self, x, y):
... |
import copy
a = [1, 2, 3]
b = a
print(id(a) == id(b))
# 两个id一毛一样,所以是同一块内存,改变一个,另一个也会改变
a[0] = 11
print(a, b)
# copy 两个id并不一样,所以是两块内存,互相不影响
c = copy.copy(a)
print(id(a) == id(c))
c[0] = 22
print(a, c)
# 特殊情况,copy.copy(),list嵌套的话,内层list仍然是同一块内存,这种叫浅copy
d = [1, 2, [3, 4]]
e = copy.copy(d)
print(id(d[2]) == id(e[2])) # ... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import time
start = time.time() # 시작 시간 저장
a = 1
for i in range(100):
a += 1
# 작업 코드
print("time :", time.time() - start) # 결과는 '초' 단위 입니다.
# In[2]:
my_list = ['a', 'b', 'c', 'd']
for i in my_list:
print("값 : ", i)
# In[3]:
my_list = ['a','b','c','d']
... |
'''
Created on Sep 22, 2015
@author: ljiang
Design an algorithm and write code to remove the duplicate characters in a string without using any additional buffer. NOTE: One or two additional variables are fine. An extra copy of the array is not.
FOLLOW UP
Write the test cases for this method.
'''
#Cannot do it in py... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 21 16:13:02 2017
@author: leo
Try to infer properties of reference based on given matches (from manual training or exact match on a given field). In particular: guess words that SHOULD be present in a given column. You can then restrict the referenc... |
# Exercise 1.
# Print out the contents of this file (basic_python_8.py)
# Hint: you can open and print this file just like any other!
# Exercise 2. Open a few imdb review txt files (like 1000 will do) and find the 10 longest words.
# Exercise 3. Open all the imdb review files, build a database representing all the ... |
import openpyxl
def get_excel(file_name,sheet):
#打开Excel
wb=openpyxl.load_workbook(file_name)
#访问sheet页
sheet=wb[sheet]
#包含最小的行索引从1开始
minRow = sheet.min_row
print("最小行索引是:",minRow)
maxRow = sheet.max_row
print("最大行索引是",maxRow)
minColumn=she... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 23 13:08:11 2020
@author: nabilz
"""
end = False
while (end == False):
#USER INPUT
input_phrase_str = input("Enter phrase to piglatinate: ")
lower_phrase_str = input_phrase_str.lower()
VOWELS = "aeiou"
#LOGIC
... |
def maximum(x, y):
if x > y:
return x
elif x == y:
return 'Numbers equals'
else:
return y
print(maximum(3, 3)) |
number = 23
guess = int(input('Number :'))
if guess == number:
print('congratulations')
elif guess < number:
print('little')
else:
print('bigger')
print('end')
|
#Recording player name:
print("ARE YOU A SEAGULL? The official quiz")
print("----------------")
print("if you identify with some of these situations, Science says you could be a seagull!!!!!")
print("Enter player name: ")
player_name = input()
#Question lists
print("Please answer the questions with A, B or... |
"""
Overview
-------
At any point in time we need to store two key pieces of information about each
node.
1. The nodes' probability distribution over the set of the labels.
2. The node's adajacency list.
To do this, we generate two types of tuples.
1. Tuples that contain label information of the form (k, (l, p))
2.... |
time = int(input("Enter the number of times u want:"))
for i in range(0,time):
print "Hello"
|
from multiprocessing import Process, Queue, Pipe
import time, random
def produce(q):
count = 0
while True:
time.sleep(random.random() * 3)
if q.full() is False:
val = count * count
print('produce product: ', val)
q.put(val)
count += 1
def consume(q):... |
import json
# 1. 对简单对象的转换
class A:
def __init__(self, name, age):
self.name = name
self.age = age
def a_2_json(obj):
return {
'name': obj.name,
'age': obj.age
}
a = A('jack', 18)
json_str = json.dumps(a, default=a_2_json)
print(json_str)
# 2. 复杂对象的转换
class Customer:
d... |
a=[[0,1,2,0],
[3,4,5,2],
[1,3,1,5]]
len1=len(a)
list1=[]
for i in range(len1):
if 0 in a[i]:
for j in range(len(a[i])):
if a[i][j]==0:
list1.append((i,j))
'''
for idx, ele in list1:
for i in range(len(a[idx])):
a[idx][i]=0
a[i][ele]=0
'''
print(list1)
pri... |
l1=[1,2,3,4,5,3,2,1,5]
def finDuplicate(l1):
l2=[]
for x in l1:
if x not in l2:
l2.append(x)
#l2=[x for x in l1 if l1.count(x)>1 and x not in l2]
return l2
finDuplicate(l1)
|
a=3
b=[1,2,1,3]
def flightMovie(fTime,Mtime):
sum1=set()
for idx, ele in enumerate(Mtime):
travel=fTime-ele
if travel in Mtime:
return True
sum1.add(ele)
print(sum1)
return False
flightMovie(a, b)
|
tup1 = (1, 2, 3, 4)
print(tup1)
print(len(tup1))
# concatenating tuples
tup2 = (5, 6, 7)
print(tup1+tup2)
print(len(tup1+tup2))
# nesting of tuples
tup3 = (tup1, tup2)
print(tup3)
print(len(tup3))
# deleting tuple
del tup3
# print(tup3)
# slicing in tuples
print("tup1[1:] = ", tup1[1:])
print("t... |
#!/usr/bin/python3
"""Function to add two integers
"""
def add_integer(a, b=98):
"""Function to add two integers
Arguments:
a {int} -- Integer to be added
Keyword Arguments:
b {int} -- Integer to be added (default: {98})
Raises:
TypeError: a must be an integer
Ty... |
#!/usr/bin/python3
"""Write a function that creates an Object from a “JSON file”:
"""
import json
def load_from_json_file(filename):
"""Write a function that creates an Object from a “JSON file”
Args:
filename ([type]): [description]
Returns:
[json file]: [description]
"""
with ... |
#!/usr/bin/python3
""" class that inherits from rectangle
Returns:
printing format.
"""
Rectangle = __import__('9-rectangle').Rectangle
class Square(Rectangle):
""" class that inherits rectangle
Arguments:
Rectangle {[int]} -- the size
"""
def __init__(self, size):
"""isntance ... |
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
def plot_density_distribution(x, saveto=None, logscale=False, dataname=""):
"""Plots a density distribution for visualizing how values are spread out"""
fig, ax = plt.subplots(figsize=(6, 4))
sns.set_style('whitegrid')
sns.kdeplot... |
#!/usr/bin/env python
# a system takes transaction information
# return top K most traded company
# return a company's currentPrice, currentProfit
# return top K profit company
# return top K most frequently changed company
# return top K highest in history company and its top price
# use double linked list to mainta... |
#!/usr/bin/env python
class ListNode(object):
def __init__(self, player, sensor, rank):
self.player = player
self.sensor = sensor
self.rank = rank
self.prev = None
self.next = None
class DoubleLinkedList(object):
def __init__(self):
self.head = ListNode(0, 0, 0)... |
print("ingrese valor de a")
a = int(input())
print("ingresate el valor de: " , a)
print("ingrese valor de b")
b = int(input())
print("ingresaste el valor de: " , b)
s = a + b
print("mira, tu resultado de a = ", a, "+ " "b = ", b, "es: ", s) |
def run():
# for i in range(100): #imprime solo los pares.
# if i%2 != 0:
# continue
# print(i,'', end='')
for i in range(100):
print(i)
if i == 27:
break
if __name__ == '__main__':
run() |
numeroPacientes = int(input("Ingresa el número de pacientes: "))
contador = 1
cantidadAlertaAzul = 0
cantidadAlertaAmarilla = 0
cantidadAaf = 0
cantidadNoAaf = 0
cantidadSeguimiento = 0
sumaTamaño = 0
while contador <= numeroPacientes:
composicion = input("Escoge una opcion digitando su codigo: ")
ecogenicidad ... |
class HangmanGame:
def __init__(self):
self.should_start = True
while (self.should_start):
self.missed_letters = []
self.guessed_letters = []
self.secret_word = raw_input("Please enter the secret word: \n\t")
self.player_word = "_" * len(s... |
#### Dropdown list
from selenium import webdriver
from selenium.webdriver.support.ui import Select
driver = webdriver.Chrome(executable_path='D:\\Day Shift\\Zpyth\\Pseln\\External Libraries\\chromedriver_win32\\chromedriver.exe')
driver.get('https://fs2.formsite.com/meherpavan/form2/index.html?1537702596407')
###... |
# Movie Recommendation based on overview of movie
# Content based Recommender System
import os
os.chdir("D:\\CQ\\Python\\datasets")
import pandas as pd
movie_data = pd.read_csv("movies_metadata.csv",low_memory = False)
movie_data.shape
movie_data.columns
movie_data.overview
from sklearn.feature_extraction.text im... |
"""
Given an int n, return True if it is within 10 of 100 or 200. Note: abs(num) computes the absolute value of a number.
near_hundred(93) True
near_hundred(90) True
near_hundred(89) False
"""
def near_hundred(n):
return abs(n-100)<=10 or abs(n-200)<=10
print near_hundred(93)
print near_hundred(90)
print nea... |
import math
import random
from sys import stdin, stdout
#Asking for input
stdout.write("COIN CHANGE PROBLEM\n")
stdout.write("Enter the change and the amount of coins: \n")
change, numCoins = map(int, stdin.readline().split())
denominations = list()
stdout.write("Enter the denominations:\n")
for i in range(numCoins):
... |
"""Class for generating Monopoly-style cards given text and svg inputs."""
import svgwrite
import textwrap
class ChanceCard:
"""Represents a Monopoly chance or community card."""
def __init__(
self,
name="adv_to_go",
mr_monopoly_img_file="",
card_text="Advance to go, do ... |
# binary search
def binary_search(a_list, item):
""" Binary search
returns an index of item in a_list (first index is 0)
returns None if item is not in a_list
"""
low = 0
high = len(a_list)- 1
while low <= high:
mid = (low + high) // 2
guess = a_list[mid]
if guess =... |
#Ввод данных
V1=int(input("Введите скорость первого автомобиля:"))
V2=int(input("Введите скорость второго автомобиля:"))
s1=int(input("Введите какое расстояние будет между ними:"))
#Решение
S=(s1+V1/2-V2/2)
#Вывод данных при соблюдении условия
if V1<V2:
print("Ошибка условия")
else:
print("Расстояние:... |
import numpy as np
stackSize= int(input("Enter the size of Stack:-"))
stack = np.array([])
print("Stack operation keywords")
print("'push' 'pop' 'isEmpty' 'isFull' 'peek' 'count' 'change' 'display'")
print("To exit program just type 'exit'")
def push():
global stack
if isFull():
print("Stack is overflo... |
print("hi planet earth")
for i in range (100)
if (i%2 == 0):
print(i)
|
import shutil
nessora = input('Ну что, обошлось? (y/n): ')
if nessora == 'y':
f = open('nessora', 'r+') # opening file + create if not exists
counter = f.read() # here we read the file
if counter == '': # if file is empty
counter = 1
else:
counter = int(counter) + 1 # plus 1 to ... |
# returns hex value of a string with its length encoded
# in the beginning
from pyint import encode
def hexify(payload):
"""
>> hexify('hello, world')
>> Ox68656c6c6f2c20776f726c64a
"""
delimited_payload = payload + '\n'
if len(payload) == 0:
return '0x0'
payload_length =... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 16 14:45:38 2020
РАШН ЭДИШН
@author: mbtor
"""
import math
def binary_search(lst):
low = 0
high = len(lst) - 1
print("Ну, погнали")
while low <= high:
mid = int((low + high) / 2)
choice = input(" %d Это число, верно... |
import math
print(math.sqrt(10))
no1 = input("enter no 1:")
no1= float(no1)
no2=input("enter no 2:")
no2=float(no2)
print("addition number is:", no1+no2)
print("multiplication number is", no1*no2) |
print('-----------------------------------------')
print('Hello World')
print('-----------------------------------------')
user_message = 'Please Enter Your Name:'
name = input(user_message)
greeting = 'Welcome to Python ' + name
print(greeting)
|
#!/usr/bin/python3
import json
def main():
with open("challenge.json", "r") as data:
datastring = data.read()
datadecoded = json.loads(datastring)
# Name
print(datadecoded[3]["name"])
# Eye color
print(datadecoded[3]["eyeColor"])
# Favorite fruit
print(datadecoded[3]["favor... |
"""
PRACTICE Test 3.
This problem provides practice at:
*** READING FROM THE CONSOLE ***
Authors: David Mutchler, Valerie Galluzzi, Mark Hays, Amanda Stouder,
their colleagues and Yuankai Wang. October 2016.
""" # DONE: 1. PUT YOUR NAME IN THE ABOVE LINE.
##############################################... |
import random
import re
import stix2generator.exceptions
import stix2generator.utils
class ValueConstraintOperators:
"""
A mixin/base-class for the constraint classes, which contains some
convenience constants et al for operators.
"""
# Legal operators
EQ, NE, GT, GE, LT, LE = OPERATORS = ra... |
# Reverse string
def FirstReverse(str):
return ''.join(reversed(str))
# Factorial
# example: num = 4 => answer = 4*3*2*1
def FirstFactorial(num):
if num <= 1:
return 1
return num * FirstFactorial(num-1)
# find the longest word in a sentence
def LongestWord(sen):
# code goes here
symbols = ['!', '?'... |
#You can also change 'choosen' list for more words in this game
import random
def menu():
print('H A N G M A N')
action = input('Type "play" to play the game, "exit" to quit:')
if action == 'play':
game()
elif action == 'exit':
pass
def game():
print()
choosen = li... |
#!/bin/env python3
# Solution for "Rot12"
# https://www.codewars.com/kata/530e15517bc88ac656000716
# simple letter substitution cipher that replaces a letter
# with the letter 13 afer it in the alphabet.
import sys
# The function for the kata
def rot13(message):
result = ""
for i in range(len(message)):
... |
#!/bin/env python
# https://www.codewars.com/kata/556deca17c58da83c00002db/
# "This was a lot simplier after I figured it out."
def tribonacci(signature, n):
if n == 0:
return []
for _ in range(3,n): # offset for the original 3
signature.append(sum(signature[-3:]))
return signature[:n]
... |
import re
def binary(t):
"""String must be a binary number."""
return re.match(r'[01]', t)
def binary_even(t):
"""String must be a binary number and be even."""
return re.match(r'^[01]+0$', t)
def hex(t):
return re.match(r'[A-F0-9]+$', t)
def word(t):
return re.match(r'[a-zA-Z0-9-]*[^\d]... |
import sqlite3
import os
dname = 'test.db'
if os.path.exists(dname):
os.remove(dname)
conn = sqlite3.connect(dname)
c = conn.cursor()
c.execute('''CREATE TABLE database
(d1 text,d2 int, d3 real)''')
c.execute("INSERT INTO database VALUES ('data1',10,3.14)")
conn.commit()
c.execute("SELECT * FROM database")
... |
"""
@author: Linh Vo
@purpose: This program composes and displays a summary of the purchase data from the past week for a coffee shop then provides answers for questions regarding peak for each day of the week.
"""
import datetime
import orderlog
ORDERS = orderlog.orderlst
ORDERS.pop(0) # Remove column header of ord... |
from typing import Tuple
import numpy as np
def particle_elastic_collision(
ux1: float,
uy1: float,
ux2: float,
uy2: float,
m1: float,
m2: float
) -> Tuple[float, float, float, float]:
"""2D elastic collision of two particles.
The model assumes the particle... |
import unittest
from account import Account
class TestAccount(unittest.TestCase):
def tearDown(self):
Account.account_list = []
def setUp(self):
self.new_account = Account("Twitter","Derek","Thrifty")
def test_init(self):
self.assertEqual(self.new_account.details,"Twitter")
... |
def sum():
sum = 0
for n in range(1, 101):
sum = sum + n
return sum
print(sum()) |
class LinkedList:
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
def toString(self):
return str(self.data)
def __init__(self):
self.__size = 0
self.__head = None
s... |
vegetables=["ONION","CHILLI","POTATO","BRINJAL","OKRA"]
print(vegetables[0])
print(vegetables[1:3])
vegetables[3]="TOMATO"
print(vegetables)
cordinates=("223265.00, 5236656.23", "2236546.00,5565332.00","225879.69,55.123658.08")
print(cordinates[1])
my_data={"Name": "AJMAL USMAN","AGE":"32","MARRIED":"YES","No.of KIDS":... |
# -*- coding: utf-8 -*-
#一个5位数,判断它是不是回文数。
#while 循环
x = input("请输入一个五位数")
while 1:
if x[0] == x[4] and x[1] == x[3]:
print("这是一个回文数")
break
else:
print("这不是一个回文数")
break
print(x)
# for 循环
x = input("请输入一个五位数")
t = 0
for i in range(int(len(x)/2)):
if x[i] != x[-i-1]:
... |
## basic questions
## read the input to list
#a = list(map(int, input().rstrip().split())) ## rstrip removes white spaces
#b = list(map(int, input().rstrip().split()))
### basic operation
#format(2, '.6f')
#round(2.33333, 6)
## strings
#course = 'Python'
#print(course[:])
#print(course[-1])
#print(course[1... |
def Bubble_sort(tab):
k = len(tab)
j = 0
while True:
uporzadkowana = True
for i in range(j, k - 1):
if tab[i] > tab[i + 1]:
uporzadkowana = False
tab[i], tab[i + 1] = tab[i + 1], tab[i]
for i in range(k - 2, j - 1, -1):
if tab[... |
class Mensagens():
@staticmethod
def roundInicio(self, round):
roundString = "===================================== - Round {} - =====================================\n".format(round)
print(roundString.center(150))
@staticmethod
def vidaMessage(self, pokemon1, pokemon2):
... |
"""
Conta espaços e vogais. Dado uma string com uma frase informada pelo usuário (incluindo espaços em branco), conte
quantos espaços em branco existem na frase.
quantas vezes aparecem as vogais a, e, i, o, u.
"""
import exercises as cabecalho
cabecalho.cabecalho("conta espaços e vogais")
def conta_frase(fr... |
import sqlite3
from veiculos import Pessoa, Veiculo
import template as template
from time import sleep
def cadastrar_no_banco():
"""
Essa função é responsável pelo cadastro no banco de dados, o usuário
pode escolher cadastrar uma pessoa ou um veículo.
"""
template.cabecalho("Cadastro")
te... |
from os import system, name
palavra = ""
chances = 0
opcao = 0
letras_usadas = []
def carregar_config():
global palavra
global chances
linhas_arquivo = []
with open("C:\Python_Entra21\Entra21_Python\Forca.cfg") as f:
for linha in f:
linhas_arquivo.append(linha.strip())
palavra... |
from os import system, name
def jogar():
palavra = "abelha"
chances = 5
letras_usadas = []
while True:
tentativa_palavra = ""
# for windows
if name == 'nt':
system('cls')
# for mac and linux(here, os.name is 'posix')
else:
system(... |
from Pessoas import Pessoa, NovaPessoa
import sqlite3
passageiros = []
teste = True
conn = sqlite3.connect("C:\Entra21_Python\Aulas\Exercicios\Aula4\Veiculos.db")
class Veiculo():
global passageiros
global menu
def __init__(self, fabricante, qtd_rodas, combustivel, qtd_lugares, cor ):
self.fabric... |
"""here the pattern is
*
**
***
****
***
**
* """
n=int(input())
n1=(n+1)/2
n2=n//2
i=1
while i<=n1:
j=1
while j<=i:
print('*',end='')
j=j+1
print()
i=i+1
i=1
p=n2
while i<=n2:
j=1
while j<=p:
print('*',end='')
j=j+1
p=p-1
print()... |
def printTable(start,end,step):
while start<=end:
cel=int((start-32)*(5/9))
print(start,'\t',cel)
start=start+step
s = int(input())
e = int(input())
step = int(input())
printTable(s,e,step)
|
import heapq
def dijkstra ( mygraph , source):
dist = dict()
prev = dict()
explored = set()
unexplored = [(0 , source)]
dist[source] = 0
while unexplored :
v_dist , v = heapq.heappop(unexplored)
if v in explored:
continue
explored.add(v)
... |
parrot= "Norwegian Blue"
letter = input("Enter a character: ")
if letter in parrot:
print(f"{letter} is in {parrot}")
else:
print("{} is not in {}".format(letter, parrot)) #Showed 2 ways to format on lines 5 and 7 |
import sys
def getint():
while True:
try:
x = input("First number: ")
y = input("Second number: ")
return int(x) / int(y)
except ZeroDivisionError:
print("Can't divide by zero\n")
except TypeError:
print("Enter integer... |
# import tkinter
#
# mainWindow = tkinter.Tk()
#
# mainWindow.title("Hello World")
# mainWindow.geometry('640x480')
#
# label = tkinter.Label(mainWindow, text='Hello World')
# label.grid(row=0, column=0)
# # label.config(anchor='w')
#
# leftFrame = tkinter.Frame(mainWindow)
# leftFrame.grid(row=1, column=1)... |
# x = 8 = 5 # results in an error obviously
# y = x / 0 # 0 division error
def factorial(n):
# n! can also be defined as n * (n - 1)
if n == 1:
return 1
return n * factorial(n - 1)
try:
print(factorial(1000))
except RecursionError:
print("This program can't calculate fa... |
class Tag(object):
def __init__(self, name, contents):
self.start_tag = '<{}>'.format(name)
self.end_tag = '</{}>'.format(name)
self.contents = contents
def __str__(self):
return f"{self.start_tag}{self.contents}{self.end_tag}"
def display(self):
print(s... |
# import sqlite3
# import pytz
#
#
# db = sqlite3.connect("accounts.sqlite", detect_types=sqlite3.PARSE_DECLTYPES)
#
# for row in db.execute("SELECT * FROM history"):
# utc_time = row[0]
# local_time = pytz.utc.localize(utc_time).astimezone()
# print(f"{utc_time}\t{local_time}")
# db.close()
import sqlite3... |
splitstring = 'This string has been' \
'split over' \
'several lines'
print(splitstring)
tabbedstring = '1\t2\t3\t4\t'
print(tabbedstring)
print('The pet shop owner said "No, no \'e\'s uh... he\'s resting".')
print("The pet shop owner said \"No, no 'e's uh... he's resting\".")
pr... |
def sum_multiple(target, value):
result = 0
for i in range(1, target):
if (i % value == 0):
result += i
return result
final = sum_multiple(1000, 3) + sum_multiple(1000, 5) - sum_multiple(1000, 15)
print(final) |
import math
def binary_array_to_number(arr):
arr.reverse()
print(arr)
a=0
index=0
for i in range(0, arr.count(1)):
num=arr.index(1,index)
print(num)
a+=math.pow(2, num)
index=num+1
return(int(a))
|
import pandas as pd
from random import randrange
import itertools
import os
class passwordgenerator:
def __init__(self, list, complexity, numbers, uppercase):
self.list = list
self.complexity = complexity # Complexity levels: 1 -> Only add numbers | 2 -> Numbers + one special character ... |
def main():
new_string = ''
string = input()
for letter in string:
if ord(letter) >= 65 and ord(letter) < 91:
new_string += chr((ord(letter) + 4 - 65) % 26 + 65)
elif ord(letter) >= 97 and ord(letter) < 123:
new_string += chr((ord(letter) + 4 - 97) % 26 + 97)
... |
def rot90(board_size, pos_1d, k):
"""
Function rotate board
:param board_size: size of board
:param pos_1D: position in board
:param k: 1: rotate 90
2: rotate 180
3: rotate 270
"""
pos_2d = (pos_1d // board_size, pos_1d % board_size)
... |
"""
Python's Instance, Class and Static Methods
"""
import math
class Myclass:
def __init__(self):
pass
def method(self): # it can freely access attributes and other methods
return 'instance method called', self
@classmethod
def classmethod(cls): # it cannot modify object in... |
"""
Sorting algorithms in python
You can use sorting to solve a wide range of problems:
-searching
-selection
-duplicates
-distrubiton
"""
from random import randint
from timeit import repeat
# build-in sorting algorithm
# array = [8, 2, 6, 4, 2]
# print(sorted(array))
# time complexity
def run_sorting_algorithm(alg... |
def sci_num(x):
#SCIENTIFIC NOTATION sci_num()
# Use str.format() on a number with ""{:e}" as str to format the number in scientific notation.
# To only include a certain number of digits after the decimal point, use "{:.Ne}", where N is the desired number of digits.
# scientific_notation = "{:.2e}".... |
"""
creditparser.py
Parses Santander UK credit card reports and produces a list with the transactions.
Copyright (C) 2016 by Arménio Pinto
Please the the file /LICENSE for the license details.
"""
import argparse
import re
from decimal import Decimal
# [start_date][end_date][card]
FIRST_LINE_PATTERN = re.compile(r... |
import os, inspect
import pandas as pd
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
from sklearn.model_selection import train_test_split
def get_dataset():
path = os.path.dirname(os.path.abspath(__file__)) # inspect.stack()[0][1] #os.path.dirname(os.path.realpath(__file__))
file_path = path... |
from pip._vendor.distlib.compat import raw_input
class movierater_input:
def choose_algorithm(self):
algoritms = {1: "KNN", 2: "ANN", 3: "PCA.py"}
print("--------------------------")
print("Welcome to the movie rater, where you can see into future and see upcoming movies imdb ratings!")
... |
import random
adventurelist = ["get eggs, chocolate, honey, and mango sauce from TJoe's",
"watch a single episode/lecture of a data science course",
"organize and wipe down desk",
"neat stuff"]
print("""
Type 'help' for a list of prompts!""")
def adventurepicker():
... |
import random
import sys
from math import floor
from generation import generate_random_solutions
from sorting import stochastic_sort
def breed(parents, mutation_crossover_ratio, mutation_replacement_ratio):
"""
Apply variation operators to all parents and generate the same
number of children.
:param ... |
import itertools
primes = set()
non_primes = set([1])
def is_prime(p):
if p in primes:
return True
elif p in non_primes:
return False
for i in range(2,p):
if p%i==0:
non_primes.add(p)
return False
primes.add(p)
return True
none_circ... |
def findName(bot, ds, nam):
for d in ds:
if("name" in d):
if(d["name"] == nam):
return d
return None
def startPoll(bot, msg):
args = msg["text"].split(",")
if(len(args) > 2):
poll = {"name":args[1].lower(), "voted":{}}
i = 2
while(... |
'''
Proving the Monty Hall Problem with Python.
Assumptions for Monty Hall problem (based on https://en.wikipedia.org/wiki/Monty_Hall_problem):
1) The host must always open a door that was not picked by the contestant
2) The host must always open a door to reveal a got and never the car
3) The host must always offer t... |
"""
Employee factory class.
Creates objects, populated from database table employee.
"""
from database import db
from models.employee import employee, basic_employee, ext_employee
class EmployeeFactory():
"""
Employee factory class.
Exposes three methods to populate employee objects with different amount... |
class UnionFind:
def __init__(self, data):
self.data = data
self.ranks = [0 for n in data]
def find(self, a):
while self.data[a] != -1:
a = self.data[a]
return a
def union(self, a, b):
sentinel_a, sentinel_b = self.find(a), self.find(b)
if self.... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import png
from math import pi, sin, cos, acos, atan, sqrt
def normalize_LatLon(lat, lon):
if lat < -pi/2 or lat > pi/2:
lat = (lat + pi)%(2*pi) - pi
if lat < -pi/2:
lat = - pi - lat
lon += pi
if lat > pi/2:
... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
from math import ceil, sqrt
def es_primo(numero_ori):
i = 2
numero = ceil(sqrt(numero_ori)) + 1
while i < numero:
if numero_ori % i == 0:
return False
i += 1
return True
numero = int(raw_input("Este programa busca el número pr... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
def is_palindrom(num):
num = str(num)
for i in range(len(num)/2):
if not num[i] == num[-i - 1]:
return False
return True
sum_palindrom_numbers = 0
for i in range(1000000):
if is_palindrom(i) and is_palindrom(bin(i)[2:]):
sum_p... |
def base(n, b):
if n != 0:
base(n/5,b)
print n%5, |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.