text stringlengths 37 1.41M |
|---|
##############################################
#Original Author: Tony Sanchez Sep 2018
#last edited by: Tony Sanchez
#last edit Date: 10-16-2018
#Description:
# This file will plot data
#
#Dependancies:
# Python3.7
# Matplotlib
#
#
##Goals#
# open file for reading
# read data
# format data from string t... |
from unittest import TestCase
import os
from objects.movie import Movie
class TestMovie(TestCase):
def tearDown(self) -> None:
if hasattr(self, "movies"):
print(f"Cleaning up after {self.movies}")
[i.delete() for i in self.movies]
else:
print(f'Cleaning up: {se... |
import fenics as fe
import numpy as np
import matplotlib.pyplot as plt
# Create mesh and define function space----------
# defines a uniform finite element mesh over the unit square
# cells in 2D are triangles with straight sides.
# 8 x 8 divides square into 8 x 8 rectangles, each divided into 2 triangles (=128 ... |
import random
class Card:
def __init__(self, value, suit, suits=["hearts", "spades", "diamonds", "clubs"]):
self.value = value
self.suit = suit
self.suits = suits
def short_card(self):
ret_str = ""
if self.value == 14 or self.value == 1:
ret_str += "A"
... |
'''
https://www.geeksforgeeks.org/snake-ladder-problem-2/
Given a snake and ladder board, find the minimum number of dice throws required to reach the destination or last cell from source or 1st cell.
The idea is to consider the given snake and ladder board as a directed graph with number of vertices equal to the n... |
# created by saif gati
print("Welcome to the BMI calculator by Saif Gati")
Name = input("Please enter your name >> ")
weight = float(input(f"Please {Name.upper()} enter your weight in kg >> "))
height = float(input(f"Please {Name.upper()} enter your height in cm >> "))
BMI = float((weight / (height * height)) * 10... |
""" Project 3D data onto a 2D subspace """
import numpy as np
def concatenate_vectors(*vectors):
"""
Concatenate vectors into a matrix
"""
return np.column_stack((vectors))
def projection_matrix(*vectors):
"""
Determine the projection distance_matrix P = B @ np.linalg.inv(B.T @ B) ... |
# palindromocomplexo.py
# Programa que testa uma palavra, frase ou expressao
# eh um palindromo: se a inversao de seus caracteres
# gera a mesma palavra, frase ou expressao
# Por: Pedro Muniz, Joao Vieira, Brenda Souza
def main ():
print ("Cheque se uma palavra/termo/frase é a mesma coisa ao contrário!")
palav... |
def riffle_once(L):
"""
Performs a single riffle shuffle on a list
Takes a list as a parameter
Returns a shuffled list
"""
import random
# Initialise the two halves of the list and final list
halfList1 = L[:int(len(L)/2)]
halfList2 = L[int(len(L)/2):]
finalList = []
# lo... |
class Board():
def __init__(self, board):
self.board = [[tile for tile in row] for row in board]
self.size = len(self.board)
@classmethod
def empty_board(cls, size):
board = [[0 for col in range(size)] for row in range(size)]
return cls(board)
def __repr__(self... |
square = lambda num: num**2
print(square(23))
even = lambda num1: num1%2 == 0
print(even(45))
first_char = lambda s: s[0]
print(first_char('abhilash'))
reverse_string = lambda s1: s1[::-1]
print(reverse_string('abhilash')) |
#!/usr/bin/env python
# used for processing payroll
class PayrollSystem:
def calculate_payroll(self, employees):
print('Calculating Payroll')
print('===================')
for employee in employees:
print(f'Payroll for: {employee.id} -> {employee.name}')
print(f'-> Check amount: {employee.calculat... |
#!/usr/bin/env python
# Imports
import sqlite3
from sqlite3 import Error
# Classes
# Methods
# Used to connect to an sqlite DB, denoted by 'path' of DB
def create_connection(path):
connection = None
try:
connection = sqlite3.connect(path)
print("Connection to SQLite DB Success!")
except Error a... |
def random_list(size):
import random
array = []
for i in range(size):
array.append(random.randint(1, size))
return array
def insertion_sort_partition(array, inc, gap):
for i in range(gap + inc, len(array), gap):
start = array[i]
j = i
while j > 0 and arr... |
from itertools import permutations
options = list(map(str, input().strip().split()))
for pair in sorted(permutations(options[0], int(options[1]))):
print("".join(pair)) |
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'getTotalX' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
# 1. INTEGER_ARRAY a
# 2. INTEGER_ARRAY b
#
def lcm(x, y):
return int(round(x*y / math.gcd(x,y)))
... |
#!/usr/bin/python3
import sys
from random import randrange
from math import inf
import copy
BLANK = '-'
WHITE_STONE = u'\u25cf'
BLACK_STONE = u'\u25cb'
'''
Cell object for each cell in the board
Attributes:
- num: cell number
- val: value in the cell (stone or blank)
- position: tuple of x,y position of cell on ... |
# mode: run
# ticket: 593
# tag: property, decorator
class Prop(object):
"""
>>> p = Prop()
>>> p.prop
GETTING 'None'
>>> p.prop = 1
SETTING '1' (previously: 'None')
>>> p.prop
GETTING '1'
1
>>> p.prop = 2
SETTING '2' (previously: '1')
>>> p.prop
GETTING '2'
2
... |
#!/usr/bin/python
import datetime
from sunrise import sun
def daytime(s):
sunup = s.sunrise(when=datetime.datetime.now())
sundown = s.sunset(when=datetime.datetime.now())
tmp=datetime.datetime.now()
# print tmp.hour
# print tmp.minute
# print tmp.second
now = datetime.time(tmp.hour,tmp.minute,tmp.secon... |
fname = input("Enter file name: ")
try:
fh = open(fname)
except:
print("File name does not exist!")
quit()
lst = list()
for line in fh:
line = line.rstrip()
temp = line.split()
for i in temp:
if i not in lst:
lst.append(i)
lst.sort()
print(lst)
|
from bs4 import BeautifulSoup #导入库
import lxml
#创建模拟HTML代码的字符串
from scrapy.utils import response
html_doc="""
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their name were
<a hre... |
i = 1
j = 1
for i in range(20):
print("\n")
for j in range(i):
print("*",end="") |
from collections import Counter
lst=[1,2,3,4,5,1,2,4,4,4,5]
cnt=Counter(lst)
print(cnt)
print(cnt[1])
print(list(cnt.elements()))
print(cnt.get(7))
print(cnt.most_common(3))
# help(cnt)
|
def get_directions():
with open('day3_input.txt') as f:
data = f.read()
return data
def log_visit(houses, visited_house):
try:
houses[tuple(visited_house)] += 1
except KeyError: # First visit to this house
houses[tuple(visited_house)] = 1
return houses
def p1():
hou... |
array=[]
t=int(input())
for i in range(t):
array.append(int(input()))
print((sorted(array))[1]) |
def main():
print(fizzbuzz(3))
print(fizzbuzz(5))
print(fizzbuzz(15))
print(fizzbuzz(4))
print(fizzbuzz(10))
def fizzbuzz(numero):
if numero % 3 == 0 and numero % 5 != 0:
return "Fizz"
if numero % 3 != 0 and numero % 5 == 0:
return "Buzz"
if numero % 3 == 0 a... |
colors=("blue","yellow","red")
shapes=("square","triangle","circle")
list=colors+shapes
print(list)
#change wenne nathi dewal tama touple wala store krnne
#ex:- coordinates of paris
#shapes[0]="green"
#there is no insert function in touple
print(shapes[0:2]) |
# coding: utf-8
# Using Breast Cancer DataSet from sklearn
# In[5]:
## import all the necessary packages##
import numpy as np
import pandas as pd
import sklearn
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_spl... |
"""Consistent logging of messages across the scripts
"""
__all__ = ['log', 'LoggingWrapper']
__version__ = '0.1'
__author__ = "Steven Smith"
from time import time, asctime, strftime
def log(message):
"""Displays a logging message to the screen without wrapping a code block
as LoggingWrapper does.
:para... |
year = int(input("Enter Year :"))
if (year%400==0):
print("Leap Year")
elif (year%100==0):
print("not Leap Year")
elif (year%4 ==0):
print("Leap Year")
else:
print("Not Leap Year")
|
# open a file
# f = open("Test_file.txt","w")
# getting some info from file
# print('name = ',f.name)
# print('name = ',f.mode)
# f.write("My name is Sagor.")
# f.close()
# f = open("Test_file.txt","a")
# f.write(" My age is 22.")
# f = open("Test_file.txt","r+")
# info = f.read()
# print(info)
# # f.write(" My age ... |
# def centared_average(some_list):
# sum = 0
# count = 0
# temp_list = some_list.sort()
# for i in range(1,len(some_list)-1):
# sum = sum+some_list[i]
# count = count+1
# return sum/count
# some_list = [1,2,3,4,5,6,7]
# print(centared_average(some_list))
import copy as cp
s = [10, 2... |
import os
from keras.datasets import mnist # subroutines for fetching the MNIST dataset
from keras.models import Model # basic class for specifying and training a neural network
from keras.layers import Input, Dense # the two types of neural network layer we will be using
from keras.utils import np_utils # utilities fo... |
def can_close(opener, closer):
if closer == ')':
return opener == '('
if closer == '}':
return opener == '{'
if closer == ']':
return opener == '['
return False
def checker(array):
queue = list()
opens = ['(','{','[']
for word in array:
print (queue)
... |
#!/usr/bin/env python3
from collections import Counter
import itertools
class SeatMap:
"""Seat map class."""
def __init__(self, data):
"""Init."""
self.data = data
self.width = len(data[0]) - 1
self.length = len(data) - 1
def render(self, data=None):
"""Render dat... |
answer = 6
print("Your guess? ", end="")
guess = int(input())
if answer == guess:
print("Bingo!")
else:
print("Boo...") |
#Python Challenge 29 Guess My Word App
import random
print("Welcome to the Guess My Word App")
game_dict = {
"sports" : ['basketball', 'baseball', 'soccer', 'football', 'tennis', 'curling'],
"colors" : ['orange', 'yellow', 'purple', 'aquamarine', 'violet', 'gold'],
"fruits" : ['apple', 'banana', 'watermelon', 'pe... |
#Python Challenge 15 Average Calculator App
print("Welcome to the Grade Point Average Calculator App")
name = input("What is your name: ").title().strip()
grades = []
number = int(input("How many grades would you like to enter: "))
for num in range(1, number + 1):
num = int(input("Enter grade: "))
grades.append(n... |
# Python Challenge 32 Python Calculator App
def first_number():
number_1 = float(input("\nEnter a number: "))
return number_1
def second_number():
number_2 = float(input("Enter a number: "))
return number_2
def operation(number_1, number_2):
oper = int(input("Enter an operations (1.addition, 2.subtr... |
#Python Challenge 27 Even Odd Number Sorter App
print("Welcome to the Even Odd Number Sorter App")
running = True
while running:
number = input("\nEnter in a string of numbers separated by a comma (,) : ").replace(' ','').split(',')
even = []
odd = []
print("\n---- Result Summary ----")
for num in number:
... |
from tkinter import *
from tkinter.font import Font
from PIL import ImageTk, Image
import numpy as np
def updateBox(background, cell, dpTable):
## This function is responsible for chaning the colour of the boxes when we are back tracking for the solution
## Declaring some variables
j,i = cell
box_size... |
#Tomas James Fernadez
#24.09.14
#Assignment_Spot_Check: Question 1
pool_width= int(input('Please input the width of the pool:'))
pool_length= int(input('Please input the length of the pool:'))
pool_depth= int(input('Please input the depth of the pool:'))
main_section_volume= pool_width *pool_length *pool_depth
c... |
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the minimumSwaps function below.
def minimumSwaps(arr):
swaps = 0
used = [False] * len(arr)
for i in range(n):
print("** i is ", i, " ***")
if not used[i]:
used[i] = True
j = arr[i]... |
# The football.csv file contains the results from the English Premier League.
# The columns labeled ‘Goals’ and ‘Goals Allowed’ contain the total number of
# goals scored for and against each team in that season (so Arsenal scored 79
# goals against opponents, and had 36 goals scored against them). Write a
# program... |
#!/usr/bin/env python3
# using Postgresql
import psycopg2
# query_1 stores most popular three articles of all time
query_1 = """select articles.title, count(*) as num from logs, articles where
log.status='200 OK' and articles.slug = subdtr(log.path,10) group by
articles.title order by num desc limit 3;"""
# query_2... |
'''
Sampling Approach
'''
import numpy as np
from pandas import qcut, read_csv
from tqdm import tqdm
class RandomSampling:
def __init__(self, k):
'''
Select negative sample on random
Args:
- k (int) : negative sample ratio
'''
self.k = 1 if ... |
# If we list all the natural numbers below that are multiples of or , we get and . The sum of these multiples is .
# Find the sum of all the multiples of or below .
t = int(input().strip())
for a0 in range(t):
n = int(input().strip())
n=n-1 #because multiples below n
#finding no. of multiples of 3 ... |
maxFloor = 0
def house_of_cards(num):
global maxFloor
if maxFloor < num:
maxFloor = num
totalCard = 0
if num == 0:
return "No house"
if num == 1:
totalCard += 8
return totalCard
if maxFloor > num:
totalCard += 5
totalCard = totalCard + 8 + house... |
def same_necklace (a, b):
"""
Sees if string a and b are just the same. Then splices through string a to
see if any combination matches string b. Otherwise it returns false
"""
if a == b:
return True
for i in range (1, len(a)):
if a[i:] + a[0:i] == b: return True
re... |
from random import randint
from art import logo
EASY_LEVEL_TURNS = 10
HARD_LEVEL_TURNS = 5
#Function to check user's guess against actual answer.
def check_answer(guess, answer, turns):
"""checks answer against guess. Returns the number of turns remaining."""
if guess > answer:
print("Too high.")
return t... |
#!/usr/bin/python
# -=- encoding: utf-8 -=-
"""Convert a Tunisian monuments list to structured format."""
import re
import sys
import argparse
scope_re = re.compile(r"""
^\s!\s # Starts with whitespace and a !
scope=\"row\" #
\s\|\s # Whitespace, pipe, whitespace
(?P<id>\d*) # dig... |
#my solution
import random
a = random.sample(range(1,100),10)
b = random.sample(range(1,100), 10)
print("list_a is ", a)
print("list_b is ", b)
unique_a = []
unique_b = []
for elementa in a:
if elementa in unique_a:
pass
else:
unique_a.append(elementa)
print ("unique_a l... |
#Exercise 18
# "Cows and Bulls" game
#Logic:
# 1. Randomly generate a 4-d number lst1 = [a,b,c,d]
# 2. User input lst2 = [w,x,y,z]
# 3. e.g. if lst1[1] in lst2: it's a bull
# a. If lst1[1] = lst2[1], it's not a bull, it’s a cow
# 4. Track how many by a counter
import random
randnum = random.sample(... |
i = int(input("Какое количество товаров вы хотите занести в базу данных?"))
n = 1
myList = []
while n <= i:
product = (n, {'название': input("Введите название "), 'цена': input("Введите цену "), 'количество': input('Введите количество '), 'единица измерения': input("Введите единицу измерения ")})
myList.append(... |
#coding=utf-8
import re
# s = "they're my friends, where's your friends'sdfjwer"
# print s.title()
# pattern = re.compile(r"'[a-zA-Z]+")
# match = pattern.findall(s.title())
# print match[0].lower()
s = "你好"
s2 = "我吗"
s3 = "你好"
mySet = set()
mySet.add(s.strip().decode("utf-8"))
mySet.add(s2.strip().decode("utf-8"))
... |
#!/usr/bin/env python
# Ahsen Uppal
#
# CS 6421 - Simple Python based echo print server.
# Echos its received input.
#
import socket, sys
import traceback
BUFFER_SIZE = 1024
def process(conn):
greeting = "Welcome, you are connected to a Python-based print server.\n"
conn.sendall(greeting.encode('UTF-8'))
... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import sys, unicodedata, math, collections
from sets import Set
##------------------------------------------------------------------------------
##-------------------------- READING FROM FILE SOURCE --------------------------
##-----------------------------------------------... |
"""Convergence plots.
"""
from typing import List, Optional
import matplotlib.pyplot as plt
import opytimizer.utils.exception as e
def plot(
*args,
labels: Optional[List[str]] = None,
title: Optional[str] = "",
subtitle: Optional[str] = "",
xlabel: Optional[str] = "iteration",
ylabel: Optio... |
import numpy as np
import opytimizer.visualization.surface as s
def f(x, y):
return x**2 + y**2
# Defines both `x` and `y` arrays
x = y = np.linspace(-10, 10, 100)
# Creates a meshgrid from both `x` and `y`
x, y = np.meshgrid(x, y)
# Calculates f(x, y)
z = f(x, y)
# Creates final array for further plotting
... |
"""Random-based mathematical generators.
"""
from typing import Optional
import numpy as np
def generate_binary_random_number(size: Optional[int] = 1) -> np.ndarray:
"""Generates a binary random number or array based on an uniform distribution.
Args:
size: Size of array.
Returns:
(np.n... |
# Input: A string Pattern
# Output: The reverse of Pattern
def Reverse(Pattern):
rev_p = ""
for n in Pattern:
rev_p = n + rev_p
return rev_p
input_s = "AAAACCCGGT"
result = Reverse(input_s)
print(result)
|
'''
Name :oddnum.py
Date :04/12/2017
Author :srinath.subbaraman
Question:Write a program that examines three variablesx, y, and z and prints the largest odd number among them.
If none of them are odd, it should print a message to that effect?
'''
num1 = raw_input("Enter the Number 1 : ")
num2 = raw_input("Enter th... |
'''
Name :forbidden_letters.py
Date :04/12/2017
Author :srinath.subbaraman
Question:Write a function named avoids that takes a word and a string of forbidden letters, and that returns True if
the word doesnt use any of the forbidden letters.?
'''
def avoids(str1,n):
for i in n:
if i in str1:
return 0
... |
'''
Name :even.py
Date :04/12/2017
Author :srinath.subbaraman
Question::Implement a function that satisfies the specification. Use a try-except block.
def findAnEven(l):
"""Assumes l is a list of integers
Returns the first even number in l
Raises ValueError if l does not contain an even number"""?
'''
def f_even(l... |
# Assignment 5
# 010123102 Computer Programming Fundamental
#
# Assignment 5.4
# In this exercise, there are two lists.
# NAMES = ['Alice', 'Bob', 'Cathy', 'Dan', 'Ed', 'Frank', 'Gary', 'Helen', 'Irene', 'Jack', 'Kelly', 'Larry']
# AGES = [20, 21, 18, 18, 19, 20, 20, 19, 19, 19, 22, 19]
# These lists match up, so Alice... |
import time
start = time.time()
list = []
for i in range(10000):
list.append(10000-i)
sort = []
def sort(list): # selection sort
for i in range (len(list)):
min = list[i]
ind = i
for j in range (i+1, len(list)):
if (list[j] < min):
min = list[j]
ind = j
t = list[i]
list... |
# Assignment 4
# 010123102 Computer Programming Fundamental
#
# Assignment 4.11
# The number 6 is a truly great number. Given two int values, a and b, return True if either one is 6. Or if their sum or difference is 6.
# Note: the function abs(num) computes the absolute value of a number.
#
# Phattharanat Khunakornopha... |
# Assignment 3
# 010123102 Computer Programming Fundamental
#
# Assignment 3.11
# Difference between largest and smallest number
#
# Phattharanat Khunakornophat
# ID 5901012610091
# SEP 2 2016
# Due Date SEP. 6 2016
list_number = [] # Array name list_number
x = int(input('Enter how many element in Array: '))
def in... |
# Assignment 4
# 010123102 Computer Programming Fundamental
#
# Assignment 4.7
# Given three ints, a b c, return True if one of b or c is "close"
# (differing from a by at most 1), while the other is "far", differing from both other values by 2 or more.
# Note: abs(num) computes the absolute value of a number.
#
# Phat... |
# Assignment 4
# 010123102 Computer Programming Fundamental
#
# Assignment 4.4
# Given 3 int values, a b c, return their sum.
# However, if one of the values is the same as another of the values, it does not count towards the sum.
#
# Phattharanat Khunakornophat
# ID 5901012610091
# SEP 10 2016
# Due Date SEP. 14 2016
... |
# Assignment 3
# 010123102 Computer Programming Fundamental
#
# Assignment 3.10
# Return the "centered" average of an array of ints,
# which we'll say is the mean average of the values, except ignoring the largest and smallest values in the array.
# If there are multiple copies of the smallest value, ignore just one co... |
# Assignment 5
# 010123102 Computer Programming Fundamental
#
# Assignment 5.4
# In this exercise, there are two lists.
# NAMES = ['Alice', 'Bob', 'Cathy', 'Dan', 'Ed', 'Frank', 'Gary', 'Helen', 'Irene', 'Jack', 'Kelly', 'Larry']
# AGES = [20, 21, 18, 18, 19, 20, 20, 19, 19, 19, 22, 19]
# These lists match up, so Alice... |
from collections import Counter
def main():
input = open("input", "r")
instruction_list = input.read().splitlines()
partOne(instruction_list)
partTwo(instruction_list)
#Brute force...change every instruction...see if we loop.
def partTwo(instruction_list):
accumulator = 0
i = 0
modIn... |
def main():
input = open("input","r")
content_list = input.read().splitlines()
partOne(content_list)
partTwo(content_list)
def partTwo(content_list):
totalValidPasswords = 0
length = len(content_list)
for i in range(length):
#Get Min Range
min = parseRange(content_list[i],0... |
def get_positive_number () :
number = -1
while number < 0 or number == 0 :
try :
number = float(input(": "))
if number < 0 or number == 0 :
print ("Vous ne pouvez pas entrer un nombre négatif ou égal à 0.")
except :
print ("Nombre ... |
#Claire Yegian
#11/30/17
#warmup15.py - doubles list of numbers
def double(numbers):
numbers2 = []
for item in numbers:
item = item*2
numbers2.append(item)
return(numbers2)
print(double([3,4,6]))
|
#格式化操作format
name='keyou'
print('我叫{}!'.format(name))
print(f'{name}')
#序列类型支持的操作(列表/字典/元组)
zodiac_animal = "猴鸡狗猪鼠牛虎龙蛇马羊"
#1 支持索引取值
print(zodiac_animal[3])
#2 切片操作
print(zodiac_animal[1:-3])
#3 成员关系操作(in 或者 not in)
print("猴" in zodiac_animal)
#4 连接操作(+)
new_zodiac = zodiac_animal+"猫"
print(new_zodiac)
#5 重复操作符(*)
... |
#使用python内置的doctest来测试
def mul(a,b):
"""
>>>mul(10,2)
21
>>>mul('y',2)
yy
"""
return a * b
def add(a,b):
"""
>>>add(-1,-2)
-3
"""
return a + b
#测试乘法
|
#
# def read_file_line(file_name,mode= 'r',encoding='utf-8'):
# """
#
# :param file_name:
# :param mode:
# :param encoding:
# :return:
# """
# src_file = open(file_name,mode=mode,encoding=encoding)
# data_list = src_file.readlines()
# file_len = len(data_list)-1
# for key,value i... |
import numpy as np
from matplotlib import pyplot as plt
def phi(x: str):
return (1 - np.exp(-x)) / (1 + np.exp(-x))
def phi_d(x):
return (1 - phi(x) ** 2) / 2
class LearningRule:
error_array = []
debug = False # debug option
def fit_batch(self, W, X, T, eta, n_epoch):
pass
def ... |
import numpy as np
import scipy.stats
from math import isclose
def mean_confidence_interval(data, confidence=0.95):
"""
Compute the mean and confidence interval of the the input data array-like.
:param data: (array-like)
:param confidence: probability of the mean to lie in the interval
:return: (t... |
class BST:
def __init__(self, data, left=None, right=None):
if isinstance(data, list):
self.data = data[0]
del data[0]
self.insert_list(data)
else:
self.data = data
self.left = left
self.right = right
def insert_list(self, ls):
... |
"""
Custom Python3 module to simulate certain functions of physics to a limited degree
Efficiency improvements could probably be made
"""
import random
import math
def collide(p1, p2):
""" Calculates the speed, angle, vel, etc. of two objects if they collide (overlap)"""
#diff in x,y
dx = p1.x - p2.x
... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
def _odd_iter():
n = 1
while True:
n = n+2
yield n
def _not_divisable(n):
return lambda x: x%n >0
def primes():
yield 2
it = _odd_iter() #初始序列
while True:
n = next(it) #返回序列第一个数
yield n
it = filter(_not_divi... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import itertools
##count 无限迭代器,打印自然数
natuals = itertools.count(1)
print('\n---------------华丽的分割线--------------\n')
##cycle 无限迭代器,循环打印ABC
cd = itertools.cycle('ABC')
## repeat 有限迭代器, 重复打印AB这整个字符串
ns = itertools.repeat('AB', 3)
for n in ns:
print(n)
print('\n-------... |
import numpy as np
class Board:
'''
class handling state of the board
'''
def __init__(self, state=None):
if state == None:
self.state = np.zeros([2,3,3])
else:
self.state = np.array(state)
self.player = 0 # current player's turn
def copy(self):
'''
make copy of the board
... |
'''
PS#2
Q1 Data augumentation for the CNN for CIFAR-10 dataset
'''
import keras
from keras.datasets import cifar10
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Conv2D, MaxPooling2D
import pandas
batch_size = 256
num_classes = 1... |
#!/usr/bin/env python
# encoding: utf-8
import unittest
from scripts.class_dojo import Dojo
class TestClassDojo(unittest.TestCase):
def __init__(self):
'''
testing create_room functionality
'''
# test1: test if new room is appended to list (well done in the example)
# tes... |
# В первый день спортсмен пробежал x километров,
# а затем он каждый день увеличивал пробег на 10% от предыдущего значения
# По данному числу y определите номер дня,
# на который пробег спортсмена составитне менее y километров.
a = int(input())
b = int(input())
i = 1
sum = a
while sum <= b:
sum = sum * 1.1
i = ... |
#!/usr/bin/python
# Grab my external IP address
# parts of this was borrowed from
# http://johnklann.com/python-how-to-get-external-ip-address/
import urllib
import re
from socket import gethostbyaddr
URL="http://ipchicken.com"
request = urllib.urlopen(URL).read()
ip = re.findall(r'[0-9]+(?:\.[0-9]+){3}', request)
... |
#!/usr/bin/python
# simple script to XOR encrypt / decrypt text with a key
import argparse
import sys
from itertools import izip, cycle
def main():
parser = argparse.ArgumentParser(description='xor or unxor text', usage='%(prog)s -i inputfile -k key -o outputfile')
parser.add_argument('--encrypt', '-e', action='st... |
print ("Nhap so thu nhat")
number1 = input()
number1 = float(number1)
print ("Nhap so thu hai")
number2 = input()
number2 = float(number2)
if number1>number2:
bigger = number1
smaller = number2
elif number1<number2:
bigger = number2
smaller = number1
else:
equal = True
if equal == True:
print ("Hai so bang nhau"... |
def quicksort(arr):
less = []
pivotList = []
more = []
if len(arr) <= 1:
return arr
else:
pivot = arr[0]
for i in arr:
if i < pivot:
less.append(i)
elif i > pivot:
more.append(i)
else:
pivotL... |
def return_dupli(a_list):
#create an empty list to hold the duplicates
dup = []
#crate an empty set
a_set = set()
#use a for-loop to step hrough each item in the list
for item in a_list:
#get the length of the set
length_one = len(a_set)
#add an item from the list into set
... |
#!/usr/bin/python3
"""A class that inherits from a list"""
class MyList(list):
"""inherits another list's class
Args:
list: the class to be printed
"""
def print_sorted(self):
print(sorted(self))
|
#!/usr/bin/python3
def new_in_list(my_list, idx, element):
if my_list:
if (idx < 0 or idx >= len(my_list)):
return my_list
my_list2 = my_list[:]
my_list2[idx] = element
return my_list2
|
#!/usr/bin/python3
i = 'a'
for i in range(ord('a'), ord('z') + 1):
if (not (chr(i) == 'e' or chr(i) == 'q')):
print("{}".format(chr(i)), end='')
|
# * Feature importance functions have been gathered from;
# https://machinelearningmastery.com/calculate-feature-importance-with-python/
from sklearn.linear_model import LinearRegression
from sklearn.tree import DecisionTreeRegressor, DecisionTreeClassifier
from sklearn.ensemble import RandomForestRegressor, Random... |
from os import system
from time import sleep
system('clear')
print("Hey, I'm here to help you choose!!\n"
"Where you are...")
sleep(3)
gasoline = float(input('What is the price of gasoline? '))
alcohol = float(input('And the price of alcohol? '))
system('clear')
if alcohol <= (gasoline * 0.7):
print('You have... |
from Chip import Chip
from Deck import Deck
from Hand import Hand
playing = True
def show_card(player, dealer):
print('player {}'.format(player))
print('dealer {}\n\n'.format(dealer))
def take_bet(chip):
while True:
try:
chip.bet = int(input('how many chips would you like to bet? ')... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.