text stringlengths 37 1.41M |
|---|
#This program used to remove redundant words in a sentence.
s = input("Please input you text: ")
w = s.split(" ")
print (" ".join(sorted(list(set(w))))) |
import BinaryTree
root = BinaryTree.BinaryTree('root')
a = root.insertLeftChild('A')
b = root.insertRightChild('B')
c = a.insertLeftChild('3')
d = c.insertRightChild('D')
e = b.insertRightChild('E')
f = e.insertLeftChild('F')
root.inOrder()
a.preOrder()
print('\n')
root.preOrder() |
"""
title: data_structures
author: Zyden Walcher
date: 7/19/18 data_structures
"""
import random
def name_generator(first_list, last_list ):
"""generates random name
:param first_list: the list of strings of first names
:param last_list: the list of strings of last names
if __name__ == '__main__':
... |
import numpy as np
class Conv3x3:
# A Convolution layer using 3x3 filters.
def __init__(self, num_filters):
self.num_filters = num_filters
# filters is a 3d array with dimensions (num_filters, 3, 3)
# We divide by 9 to reduce the variance of our initial values
self.filters = np.random.randn(num_filters, 3,... |
#!/usr/bin/env python
"""
parse_species_data.py - script to display number of unique genera for (a)
given habitat(s)
Usage: parse_species_data.py [-m] [-v] <data_file>
One can run parse_species_data.py -h
for a list of command-line options.
Supplied data should be in the format of:
... |
#!/usr/local/bin/python
# Written by Duncan Forgan, 18th July 2012
# This code produces a Photon Wavelength/Frequency Calculator GUI
# We use the standard Tkinter toolkit which comes with pretty much all Python distributions
# We start by defining the GUI as a class (derived from the base class Frame), with methods
# ... |
import os
import math
def timedelta_to_seconds(delta):
'''Convert a timedelta to seconds with the microseconds as fraction
>>> from datetime import timedelta
>>> '%d' % timedelta_to_seconds(timedelta(days=1))
'86400'
>>> '%d' % timedelta_to_seconds(timedelta(seconds=1))
'1'
>>> '%.6f' % ti... |
"""
Name: 12_flatten
Author: Lio Hong
Date: 20180726
Goal:
Write a function to flatten a list. The list contains other lists, strings, or ints.
For example, [[1,'a',['cat'],2],[[[3]],'dog'],4,5] is flattened into
[1,'a','cat',2,3,'dog',4,5]
I.E. transfers all entries from nested lists to main li... |
"""
Name: letter_freq_counter
Date: 20181008
Author: Lio Hong
Purpose: Counts letter frequencies.
Comments:
I actually found code examples online but couldn't make sense of it.
I can check my results against online databases at least, but I still
have to code this to use on encrypted texts.
There's a lot of patterns:
... |
L = [3,9,5,3,5,3,9,5,9,13]
def largest_odd_times(L):
"""
Date: 20180725
Goal:
Assumes L is a non-empty list of ints
Returns the largest element of L that occurs an odd number
of times in L. If no such element exists, returns None
"""
'''
T... |
"""
Name: genPrimes
Date: 20181005
Author: Lio Hong
Purpose: A generator that returns primes numbers on successive calls to
its method
Comments: Store a list of primes that is used to find whether subsequent
numbers are primes.
//Generators are used for printing out unbounded sequences, or finding a specific
value in ... |
"""
Name: Mastermind00
Date: 20181003
Author: Lio Hong
Purpose: Recreate the game 'Mastermind' with Python. Inspired by EthosLab
who is doing this in Minecraft
Rules:
1. Player 2 generates a combination of coloured beads -> CPU randomly generates
a sequence
2. Player 1 makes a guess
3. [P2] Check for beads with same co... |
ch = input("enter a character")
if(ch=='A' or ch=='a'):
print(ch,"is a vowel")
else:
print(ch,"is aconstant")
|
# GUI 모듈(tkinter) import
import tkinter
# 가장 상위 레벨의 윈도우 창 생성
window = tkinter.Tk()
window.title("LEE A REUM") # 윈도우 창의 제목 설정
window.geometry("640x400+100+100") # ("너비x높이+x좌표+y좌표") 윈도우 창의 너비와 높이, 초기 화면의 위치 설정
window.resizable(False, False) # (상하, 좌우) 윈도우 창의 창 크기 조절 가능 여부 설정
label = tkinter.... |
# Resolve the problem!!
import string
import random
SYMBOLS = list('!"#$%&\'()*+,-./:;?@[]^_`{|}~')
LETTERS = list('abcdefghijklmnopqrstuvwxyz')
CAPITAL_LETTERS = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ')
NUMBERS = list('0123456789')
def generate_password():
# Start coding here
characters = SYMBOLS + LETTERS + CAP... |
def ears_cout(n):
if n == 0:
return 0
elif n % 2 == 0: #To count even bunnies
return ears_cout(n - 1) + 3
else: #To count odd bunnies
return ears_cout(n - 1) + 2
print("How many bunnies in a line?")
n = int ( input() )
m = ears_cout(n)
print("There are total... |
class Employee:
def __init__(self,first,last):
self.first = first
self.last = last
def get_data(self):
print(self.first + '' +self.last)
def Email(self):
email = self.first + '.' + self.last + '@company.com'
return email
# emp1 = Employee() # First instance of... |
import os
def divide(a, b):
assert b > 0
nmr=a//b
rem=a%b
visited={rem:0}
digit=[]
while(True):
rem *= 10
digit.append(rem//b)
rem = rem % b
if rem in visited:
location=visited[rem]
print "location is:"
print location
return (nmr, digit[:location], digit[location:])
else:
visited[rem] ... |
#you only have access to one node. the sol is to copy the data from next node
# and then delete the next node.
import os
global nodea
global nodeb
global nodec
global noded
class LinkedListNode:
def __init__(self, initData):
self.data = initData
self.next = None
self.previous = None
def getData(self):
re... |
lista = [2,4,3,1,7,6,9,8,5]
print('Lista :', (lista))
print("Minha lista em ordem numérica : ", sorted(lista)) |
print('Привет')
print('Напишите несколько чисел. Ваше первое число?')
a = int(input())
print('Напишите второе число')
b = int(input())
print('Напишите третье число')
c = int(input())
if (a*b = c):
print('Условие о равенстве произведении первых чисел третьему верно')
else:
print('Условие о равенстве пр... |
# store previous values of function f in a cache
# function takes a function as input
# function currying style
def memoize(f):
# create empty cache to store previously computed values of f(x)
cache = {}
#
def g(x):
print cache
if x not in cache:
print x,"not in cache"
# print "adding", f(... |
def summ(x):
if x == 1:
return 1
else:
return x + summ(x-1)
def sumSeries(n):
if n <= 0:
return 0
else:
return n + sumSeries(n-2)
def main():
print "returning sum of all integers from 1,2,3...10"
print summ(10)
print "returning sum of all integers from 24,22,20,18,16...0"
print sumSe... |
"""
https://leetcode.com/problems/find-all-duplicates-in-an-array/
Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements that appear twice in this array.
Could you do it without extra space and in O(n) runtime?
"""
class Solution(object... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
row=[]
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"... |
import keyboard
import time
time.sleep(2) # to give some time for interpreter to execute
for i in range(10): # here we are using loop for how many time we need to run our script
keyboard.write("hy \n") # write() function take the text as input
keyboard.press_and_release("enter") # here ... |
from turtle import *
import tkinter
import sys
class Node:
def __init__(self,item):
self.item = item
self.next = None
class Queue:
def __init__(self):
self.head = None
self.tail = None
def is_empty(self):
return self.head == None
def enqueue(self, item):
if self.is_empty():
self.head = self.tai... |
# 增加单个元素
# list1=[1,2,3]
# list1.append(4)
# print(list1)
# 指定位置添加
# list1=[1,2,3]
# list1.insert(3,4)
# print(list1)
# 列表一次性添加多个元素
# list1 = [1,2,3,4]
# list1.extend([5,6,7,8,9,10])
# print(list1)
#取值
# list1 = [1,2,3,4,5,6,7,8,9,10]
# print(list1[0:4])
# 修改
# list1 = [1,2,3,4,5,6,7,8,9,10]
# list1[-1]=11
# print(... |
def get_fibonacci_n(n):
return fibonacci_n_helper(n)
def fibonacci_n_helper(n, i=1, a=0, b=1):
return a if n <= i else fibonacci_n_helper(n, i + 1, b, a + b)
# if n <= i:
# print(a)
# return a
# print(a, end=" ")
# return fibonacci_n_helper(n, i + 1, b, a + b)
n1 = int(input("En... |
"""
*
**
***
****
*****
"""
a1 = int(input("Enter a number: "))
for i in range(a1):
print(" " * (a1 - i - 1), end="")
print("*" * (i + 1))
|
l1 = []
for i in range(10):
l1.append(int(input(f"Enter {i+1} value: ")))
max_value = max(l1)
for i in range(max_value, 0, -1):
for value in l1:
if value >= i:
print("*\t", end="")
else:
print("\t", end="")
print() |
from day13_inheritance.item_inheritance.book import Book
from day13_inheritance.item_inheritance.dvd import Dvd
print("Enter 5 items you want to issue")
items = []
for i in range(5):
item_type = input("book or dvd (b/d): ")
item = Book() if 'b' == item_type else Dvd()
item.read()
items.append(item)
p... |
a1 = input("Enter a word:\n")
for i in range(1, len(a1) + 1):
print(a1[i:], a1[:i], sep="")
|
a1 = input("Enter a word:\n")
l = len(a1)
for i in range(l):
for i2 in range(l):
print(a1[(i + i2 + 1) % l], end="")
print()
|
def power(x, y):
if(y == 0): return 1
temp = power(x, int(y/2))
if (y%2==0): return temp*temp
else:
if(y>0): return x * temp * temp
else: return (temp * temp)/x
x = 2; y = 10
print('%.6f' %(power(x, y)))
|
from utils.base_estimator import BaseEstimator
import numpy as np
from sklearn.tree import DecisionTreeClassifier
class AdaBoost(BaseEstimator):
"""
An AdaBoost classifier is a meta-estimator that begins by fitting a
classifier on the original dataset and then fits additional copies of the
classifier ... |
from utils.base_estimator import BaseEstimator
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
np.random.seed(2046)
def euclidean_distance(x, y):
return np.sqrt(np.sum((x - y) ** 2))
class KMeans(BaseEstimator):
"""Partition a dataset into K clusters.
Finds clusters by repeatedl... |
"""
For a categorization task the user has to select a category from a set of options.
Tasks and responses are stored in a SQLite database.
"""
from typing import NamedTuple
from typing import List, Optional
import json
class CategorizationTask(NamedTuple):
task_id: int
description: str
metadata: str
... |
#STACK with Python List
class Stack_with_Plist:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def push(self, item):
self.items.appent(item)
def pop(self):
if self.is_empty():
return None
else:
... |
# Author: coneypo
# Blog: http://www.cnblogs.com/AdaminXie/
# Github: https://github.com/coneypo/Generate_handwritten_number
# 生成手写体数字 / Generate handwritten numbers from 1~9
import random
import os
from PIL import Image, ImageDraw, ImageFont
random.seed(3)
path_img = "data_pngs/"
# 在目录下生成用来存放数... |
import numpy as np
import time
from time import time
time0 = time()
'''numero de ecuaciones'''
n = int(input("Número de ecuaciones: "))
print("\n")
'''llenado de matriz'''
def LlenarM(M):
m = np.zeros((n,n+1))
for i in range(n):
for j in range(n+1):
m[i][j]=float(input(f"Valor element... |
#!/usr/bin/env python
from hwtools import *
print "Section 4: For Loops"
print "-----------------------------"
nums = input_nums()
# 1. What is the sum of all the numbers in nums?
print "1.", sum(nums)
# 2. Print every even number in nums
print "2."
for i in nums:
if not i%2:
print i
#CODE GOES HERE
#... |
#!/usr/bin/env python
"""
tron.py
The simple game of tron with two players. Press the space bar to start the game. Player 1 (red) is controlled with WSAD and player 2 (blue) is controlled with the arrow keys. Once the game is over, press space to reset and then again to restart. Escape quits the program.
"""
impo... |
#!/usr/bin/env python
"""
users.py
User Database (Advanced)
=========================================================
The nice thing about dictionaries (and objects) is you can
have a list or a dictionary of items that all have the same
properties. The result is something like a lookup table or
a database
For th... |
import pygame
from pygame import Rect, Surface
from layer import Layer
class ShadowLayer(Layer):
color = 0,0,0,150
ratio = 3.0 / 4.0
def draw_sprite(self, sprite, ratio=None):
if ratio is None:
ratio = self.ratio
# calculate the size of the shadow
w = sprite.rect.wid... |
import sqlite3
class ToDoItem:
dbpath = ""
tablename = "todoitems"
def __init__(self,**kwargs):
#use kwargs if your table name is constantly changing, kwargs lets you take in any column value pairs
self.pk = kwargs.get("pk")
self.title = kwargs.get("title")
self.descri... |
# a=50
# if a>50:
# print('yes')
# elif a<50:
# print("hemine")
# else:
# print('nadarimo')
r = int(input('num'))
if r%2==0:
print('{} is even' .format(r))
else:
print('{} is fard',r) |
string = input().split()
a = float(string[0])
b = float(string[1])
c = float(string[2])
lista = [a, b, c]
lista.sort(reverse=True)
a = lista[0]
b = lista[1]
c = lista[2]
if a >= (b + c):
print('NAO FORMA TRIANGULO')
if (a ** 2) == (b ** 2) + (c ** 2):
print('TRIANGULO RETANGULO')
if ((a ** 2)... |
x = int(input())
z = 0
while True:
z = int(input())
if z > x:
break
soma = x
c = 1
while z > soma:
soma = soma + x
c += 1
x += 1
print(c)
|
while True:
try:
c1 = c = 0
flag = True
s = input()
if s == '':
flag = True
elif s[0] == ')' or s[-1] == '(':
flag = False
c = s.count('(')
c1 = s.count(')')
if c == 0 and c1 == 0 and s == '':
print... |
# criar uma lista com range
l = list(range(1, 11))
# step 2
l1 = list(range(2, 11, 2))
# criar um lista vazia
lista = list()
lista1 = []
# copiar um lista
lnew = l.copy()
print(lnew)
|
'''
from collections import deque
>>> d=deque([1,2,3,4,5])
>>> d
deque([1, 2, 3, 4, 5])
>>> d.rotate(2)
>>> d
deque([4, 5, 1, 2, 3])
>>> d.rotate(-2)
>>> d
deque([1, 2, 3, 4, 5])
Or with list slices:
>>> li=[1,2,3,4,5]
>>> li[2:]+li[:2]
[3, 4, 5, 1, 2]
>>> li[-2:]+li[:-2]
[4, 5, 1, 2, 3]
Note tha... |
print()
dados = {'nome':'Pedro', 'idade': 25}
# Criando um elemento
dados['sexo'] = 'M'
# Removendo um elemento e o valor dele
#del dados['idade']
# imprimindo somente as chaves
print(dados.keys(), 'imprimindo somente as chaves\n')
# imprimindo somente os valores
print(dados.values(),'imprimindo some... |
i = 0
j = 1
for x in range(3):
print("I=%d J=%d" % (i, j))
j = j + 1
for x in range(9):
j = j - 3
j = j + 0.2
i = i + 0.2
for x in range(3):
if (i == 1):
print("I=%d J=%d" % (i, j))
else:
print("I=%.1f J=%.1f" % (i, j))
j = j + 1
... |
n = int(input())
res2 = ''
if n == 0:
print('0')
n = -1
else:
t1 = 0
t2 = 1
res2 = '0 1 '
i = 2
while i < n:
t3 = t1 + t2
res2 += str(t3) + ' '
t1 = t2
t2 = t3
i += 1
print(res2[:-1]) |
c = 0
soma = 0
for x in range(1,7,1):
a = float(input())
if a > 0:
c = c + 1
soma = soma + a
print('%d valores positivos' % c)
print('%.1f' % (soma/c)) |
n = int(input())
if n <= 800:
print('1')
if 800 < n <= 1400:
print('2')
if 1400 < n <= 2000:
print('3') |
x = float(input())
if (x > 0.00) and (x < 2000.00):
print('Isento')
elif(x >= 2000.01) and (x <= 3000.00):
resto = x - 2000
res = resto * 0.08
print("R$ %.2f" % res)
elif (x >= 3000.01) and (x <= 4500.00):
resto = x - 3000
res = (resto * 0.18) + (1000 * 0.08)
print("R$ %.2f" ... |
# coding=utf-8
import random
import time
print("2 tane 1-6 arasında rakam gir ve kaçıncı denemede geldiğini öğren")
birinci_rakam = int(input("Birinci Rakamı Giriniz: "))
ikinci_rakam = int(input("İkinci rakamı giriniz: "))
if birinci_rakam >=1 and birinci_rakam <=6 and ikinci_rakam >= 1 and ikinci_rakam<=6:
i... |
#文字列を反転し、後ろから探索してみる
def execute(S):
while "dreameraser" in S:
S = S.replace("dreameraser", "")
while "dreamerase" in S:
S = S.replace("dreamerase", "")
while "eraser" in S:
S = S.replace("dreamerase", "")
while "dreamerase" in S:
S = S.replace("dreamerase", "")
while... |
def create_list(max,incr):
i = 0
numbers = []
for i in range(0,max,incr):
print "At the top i is %d" %i
print "Numbers is now: ", numbers
numbers.append(i)
print "At the bottom i is %d." %i
for num in numbers:
print num
create_list(8,2)
|
## Towers of Hanoi game. Plan is later use this with
## Reinforcement Learning model to find optimal strategy
## Create Initial Game State
def game_setup():
state = [[1,2,3,4],[],[]]
return state
## Check to see if rod is empty
def is_empty(rod,state):
if len(state[rod]) == 0:
is_empty = True
... |
from flask import Flask
app = Flask(__name__)
a=2
b=3
@app.route("/")
def index():
return str(a+b)
@app.route("/sub")
def sub():
return str(a-b)
@app.route("/mul")
def mul():
return str(a*b)
@app.route("/power")
def power():
return str(a**b)
@app.route("/exp")
def exp():
return str(a*b+a**b)
#"He... |
class Pixel:
@classmethod
def is_in_tap(cls, b: int, g: int, r: int) -> bool:
"""
:return: 色がTapの中身のものであればTrueを返す.
:rtype: bool
"""
if b in range(128, 213) and g in range(128, 238) and r in range(128, 238):
return True
else:
return False... |
import math
def binary_search(list, item):
low = 0
high = len(list) - 1
while low <= high:
mid = (low + high) // 2
guess = list[mid]
if guess == item:
return mid
if guess > item:
high = mid - 1
else:
low = mid + 1
return None
my_list = [1, 3, 5, 7, 9]
print(binary... |
x=(1,2,3)
y=(4,5,6)
# length of tuple
print len(x)
#index based
print x[2]
#list of tuples
listOfTuples = [x,y]
print listOfTuples
#use in data analysis
(age,income) = "20,120000".split(',')
print age
print income |
import numpy as np
np.random.seed(0)
totals = {20:0,30:0,40:0,50:0,60:0,70:0} #total number of people in each age grp
purchases = {20:0,30:0,40:0,50:0,60:0,70:0} # total purchase done by each age group
totalpurchases = 0
for _ in range(100000):
ageDecade = np.random.choice([20,30,40,50,60,70])
totals[ageDecad... |
import sys
class minHeap():
def __init__(self, arr, n):
self.harr = arr
self.heapSize = n
i = (self.heapSize // 2) - 1
while i >= 0:
self.heapify(i)
i -= 1
def left(self, i):
return (i * 2) + 1
def right(self, i):
return (i *... |
# chess dictionary validator
# Fantasy game Inventory
stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12, 'map fragments': 3}
def display_inventory(inventory):
#Print contents and total number of items in inventory.
print('Inventory:')
item_total = 0
for k, v in inventory.item... |
numpeople = input("How many people are taking the journey? ")
nummiles = input("How many miles is your trip? ")
price = 3
if int(numpeople) < 5:
price = price
if int(nummiles) == 1:
price = price
elif int(nummiles) > 1:
price = ((price * 2) - 1)
elif int(numpeople) >= 5:
price ... |
# Create table updated
import MySQLdb
#======================== Connect to database ==================================
# Create an Object = connection to database
db = MySQLdb.connect(host="localhost", # your host, usually localhost
user="root", # your username
... |
import math
# the above code imports everything from python math
# you can print number by just putting them in a print statement
print(2)
print(3.1415)
print(-6)
# all types of numbers work and you have the basic math operators too!
print(3*4)
print(4/2)
# % is the remainder operator will give you the remainder or ... |
from PIL import Image, ImageDraw, ImageFont
from datetime import date
import pandas as pd
import numpy as np
import yagmail
import os
#Function to verify if the certificate exists in the search_path
def find_files(filename, search_path):
result = []
for root, dir, files in os.walk(search_path):
if fil... |
# Credit: http://www.python-course.eu/turing_machine.php
class Tape(object):
blank_symbol = " "
def __init__(self, input=""):
self.__tape = {}
for i,sym in enumerate(input):
self.__tape[i] = sym
def __str__(self): # BUG
s = ""
minUsedIndex = min(self.__tape.key... |
###########################
# a lambda in Python is just an anonymous function that has one or more arguments, but only one expression.
###########################
# Syntax:
# lambda arguments : expression
# Example
add_ten = lambda a : a + 10
print(type(add_ten))
# Prints <class 'function'>
print(add_ten(5))
# Prints... |
"""Задача 0
Написать программу, запрашивающую у пользователя строку с текстом и разделитель.
Необходимо вывести список слов с их длиной в начале слова, например, 5hello.
Для каждой из пользовательских функций написать функцию-тест.
"""
def inp():
usstr = input("String here: ")
r = input("Razdel: ")
usstr = usstr.sp... |
"""Задача 1
Дана целая матрица А(N,N). Составить программу подсчета среднего арифметического значения элементов матрицы.
"""
# input: [1, 2, 3], [1, 4, 5], [3, 8, 0]
# output: ((1+2+3)/3 + (1+4+5)/3 + (3+8+0)/3)3
def make_matrix():
from random import randrange
# Задаем матрицу через генератор
n = int(input("Enter n... |
"""Задача 4*
Дана квадратная матрица А(N,N). Составить программу подсчета количества отрицательных элементов,
расположенных выше главной диагонали.
"""
def make_matrix(n=3):
from random import randrange
# n = int(input("Enter n: "))
matrix = [[randrange(-100, 100) for i in range(n)] for j in range(n)]
d = [] # ... |
# Задача 5. На вход поступают две строки. Необходимо выяснить, является ли вторая строка подстрокой первой.
str1 = 'aaaaaaasdadasdsadsadasgsdfgfggsg'
str2 = 'aaa'
# 1
if str2 in str1:
print(1)
else:
print(0)
|
""" Дана строка ‘Hello!Anthony!Have!A!Good!Day!’. Создать список,
состоящий из отдельных слов[‘HELLO’, ‘ANTHONY’, ‘HAVE’, ‘A’, ‘GOOD’, ‘DAY’].
"""
mystr = "Hello!How!Are!you?!"
s = mystr.upper().split("!")
s.remove("")
print(s)
|
from urllib.request import Request
from urllib.request import urlopen
from urllib.error import HTTPError
from urllib.error import URLError
from bs4 import BeautifulSoup
def converToSoup(url):
'''
This function will parse the url to BeautifulSoup(BS)
'''
try:
urlRequest = Request(url,hea... |
from datetime import date
import Book
# Receipt class
#
# Class to generate the receipt
class Receipt:
books = []
def add_book(self, book: Book, due_date=date.today()):
self.books.append([book, due_date])
def remove_book(self, book: Book):
self.books.remove(book)
def generate_recei... |
from itertools import combinations
"""
Python
======
Your code will run inside a Python 2.7.13 sandbox. All tests will be run by calling the solution() function.
Standard libraries are supported except for bz2, crypt, fcntl, mmap, pwd, pyexpat, select, signal, termios, thread,
time, unicodedata, zipimport, zlib.
Inpu... |
#2.
"""
#4. Convert degree celsius to fahrenheit
#take input in degree celsius
input1 = int(input("Enter temperatue in ˚C:"))
print("temperature in fahrenheit is: "+str(input1*(9/5)+32))
"""
"""
#5. to check the palindrome
def isPalindrome(string):
str = string[::-1]
#check whether str and string are the same
if... |
#!/usr/bin/env python3
# An insecure password locker program.
import sys
import pyperclip
PASSWORDS = {'email': 'F7minlBDDuvMJuxESSKHFhTxFtjVB6',
'blog': 'VmALvQyKAxiVH5G8v01if1MLZF3sdt',
'luggage': '12345'}
if len(sys.argv) < 2:
print('Copy account password to system clipboard')
pr... |
import numpy as np
from scipy.optimize import fmin_cg
class NeuralNetwork_Classifier(object):
forwardProp = None
def __init__(self,hidden_layers = [2]):
self.hidden_layers_size = hidden_layers
print(self.hidden_layers_size)
def sigmoid(self,X):
"""
It returns the sigmoid ... |
# https://www.reddit.com/r/dailyprogrammer/comments/8bh8dh/20180411_challenge_356_intermediate_goldbachs/
def goldbach_weak_conjecture(*args):
for n in args:
if n % 2 == 0 or n < 6:
print("Illegal argument")
return -1
def find_primes(n):
l = []
... |
import unittest
import numpy as np
from LogisticRegression import LogisticRegressionClassifier
class Test(unittest.TestCase):
def test_sigmoid(self):
# Creating object of classifier for unit testing
lrs = LogisticRegressionClassifier()
print("test_sigmoid")
# Checking if values for... |
# 第二章 CSV文件
# comma-separated value 逗号分隔值
#=======读写CSV文件=========================================================
#
#----------------------------------------------------------------
# input_file = 'supplier_data.csv'
# output_file = 'output_1.csv'
# with open(input_file,'r',newline='') as filereader:
# with open(ou... |
class Punkt:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"POINT ({self.x} {self.y})"
def __int__(self):
return f"POINT ({self.x} {self.y})"
# -------------------------------------
a = Punkt(2,3)
print(a) # <__main__.Punkt object at 0x0000028... |
from copy import deepcopy
class Board:
"""Represents a chess board which keeps track of positions where a queen can be placed."""
def __init__(self, n, allowed=None):
"""Initialize board dimension and allowed positions."""
assert isinstance(n, int), "Size must be an integer"
assert n ... |
import numpy as np
import pandas as pd
#n = input("Enter an integer:")
#for i in range(n):
# print(n)
my_matrix = np.identity(5)
second_matrix = np.random.random(size(5,4))
print(my_matrix, second_matrix) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon May 4 18:16:54 2020
@author: luismanuelalvarez
"""
class Estudiante:
def __init__(self,nombre,edad=16):
self.nombre = nombre
self.edad = edad
def devuelve_datos(self):
if(self.edad > 18):
... |
import random
"""
Chapter 1.10
"""
print()
print()
print("self_check_1:")
# the answer is: ['c', 'a', 't', 'd', 'o', 'g', 'r', 'b', 'i']
wordlist = ['cat', 'dog', 'rabbit']
letterlist = []
for aword in wordlist:
for aletter in aword:
if aletter not in letterlist:
letterlist.append(aletter)... |
import re
import string
def count_me():
freq = {}
file_obj = open('count.txt', 'r')
word_content = file_obj.read().lower()
reg_exp = re.findall(r'\b[a-z]{3,15}\b', word_content)
for word in reg_exp:
count = freq.get(word, 0)
freq[word] = count + 1
freq_list = freq.keys()
for word in freq_list:
... |
import numpy as np
#Do not import any other libraries
"""
Write a function that takes a two dimensional array, and returns another two dimensional array where the columns of the array are
the Z scores of the columns in the original array. You should do question 2 before doing this question. For example, suppose
arr = a... |
import numpy as np
import pandas as pd
#Do not import any other libraries
"""
Write a function that takes a pandas dataframe, df as input. df is assumed to have the columns col_1 and col_2. df will have missing values (NaNs) in both columns.
The function should return the dataframe but with the missing values in col_1... |
#!/usr/bin/env python3
# Wankyu Choi (c) 2014
# For Creative Works of Knowledge Python Training
# for loop and iterators: custom iterator
def my_year_range(start, end, step=1):
"""
iterator should yield resulting value
"""
result = start
while result < end:
yield result
result += step
def my_year_range_w... |
#program to find the sum of contiguous subarray of numbers that has the largest sum
def maxSubArraySum(arr):
size = len(arr)
if size == 0:
return 0
max_so_far = float('-inf')
max_ending_here = 0
for i in range(0, size):
max_ending_here = max_ending_here + arr[i]
if (max_so_... |
"""All messages."""
class Messages:
"""Class message."""
def __init__(self):
"""Init."""
self.message = ""
def set_message(self, message):
"""Add."""
self.message = message
def get_message(self):
"""Get and clear the messages."""
msg = self.message
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.