text stringlengths 37 1.41M |
|---|
# !/usr/bin/python
# -*- coding: utf-8 -*-
def myLog(x, b):
'''
x: a positive integer
b: a positive integer; b >= 2
returns: log_b(x), or, the logarithm of x relative to a base b.
'''
# Your Code Here
assert type(x) is int
assert type(b) is int and b >= 2
p = 0
while True:
... |
from random import randint
# Generate a 4 digit number pass
def credit_pass():
password = ""
while len(password) < 4:
password += str(randint(0,9))
return password
# Generate a card number
def card_number():
card = [4]
while len(card) != 16:
card.append(randint(0,9))
if l... |
from turtle import *
for i in range(3):
color('red')
forward(100)
left(120)
for i in range(4):
color('blue')
forward(100)
left(90)
for i in range(5):
color('brown')
forward(100)
left(72)
for i in range(6):
color('yellow')
forward(100)
left(60)
for i in range(7):
c... |
# age = 10
# if age < 18:
# print('baby')
# age = 10
# is_baby = age < 10
# print(is_baby)
# num = 101
# is_odd = num % 2 == 1
# print(is_odd)
# text = 'xin chao'
# text_is_not_empty = len(text) > 10
# print(text_is_not_empty)
# from math import *
# num = int(input('nhap so:'))
# print(abs(num))
# num = int(i... |
class DependentOperand:
"""
Class that stores data regarding the dependent operand
"""
__dependent_criterion: str
__relational_operator: str # Can be <, >, <=, >=, ==, ~=
__dependent_criterion_value: str
def __init__(self):
self.__dependent_criterion = ''
self.__relational... |
import datetime
def days_diff(date1, date2):
d1 = datetime.datetime(date1[0], date1[1], date1[2])
d2 = datetime.datetime(date2[0], date2[1], date2[2])
return abs((d2 - d1).days)
|
# https://py.checkio.org/mission/brackets/
def brackets_checkio(expression):
brackets = {'{': '}', '(': ')', '[': ']', }
chars_set = {'{', '}', '(', ')', '[', ']', }
chars = list(filter(lambda x: x in chars_set, expression))
stack = []
# if no brackets, it's good
if len(chars) == 0:
r... |
#inheritance
#is a relationship
#Car is a vehicle
#Truck is a vehicle
class Vehicle():
def __init__(self,name):
self.vehicle_name = name
def name(self):
print(self.vehicle_name)
class Car(Vehicle):
def drive(self):
print(self.vehicle_name," is drive")
class Truck(... |
#Multiple inheritance
#is a relationship
#Car is a vehicle
#Truck is a vehicle
class Vehicle():
def __init__(self,name):
self.vehicle_name = name
def cname(self):
print(self.vehicle_name)
class Driver():
def __init__(self,name):
self.driver_name = name
def dna... |
#Object Oriented Programming(oop)
#Object
'''
i = 10
str = "codinglaugh"
list = [1,2,3,4,5,6]
list.append(6)
str.__len__()
'''
class Vehicle:
pass
car = Vehicle()
car.name = "Toyota"
car.Wheel = 4
car.driver = "Solimoddin"
print(car.name,car.driver)
truck = Vehicle()
truck.name = "Tata"
tr... |
from .abstract_view import AbstractView
import pygame
class GameOverView(AbstractView):
""" Display the Game over view. Inherits from "AbstractView"
"""
def __init__(self, window, maze_result, maze):
""" initialize private attribute maze result
Args:
maze_result (bool): if pl... |
""" collects countries available for get query """
import xml.etree.ElementTree as ET
import pickle
import requests
def get_result(day, month, year):
""" returns dict of country names/country id based on api """
if int(day) < 10:
day = "0{}".format(day)
if int(month) < 10:
month = "0{}".fo... |
limit = 10
result = list(map(lambda x: 2 ** x, range(limit)))
print("total terms:",limit)
for i in range(limit):
print("power",i,"is",result[i])
|
import numpy as np
arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
print(arr[1, 1:4])
print(arr[0:2, 2])
print(arr[0:2, 1:4])
# [7 8 9]
# [3 8]
# [[2 3 4]
# [7 8 9]]
|
n = int(raw_input())
now = 1
fact = []
for i in range(1, 45):
now *= i
fact.append(now)
while n > 0:
n -= 1
a = int(raw_input())
print(fact[a - 1])
|
n = int(raw_input())
if n < 2: print("WRONG ANSWER")
elif n > 3: print("RUNTIME ERROR")
else : print("ACCEPTED") |
def triangular(n):
x = long(n ** 0.5)
if x * x == n:
return True
return False
while 1:
n = input()
if n == 0:
break
if triangular(8 * n + 1):
print 'YES'
else:
print 'NO' |
def ok(a):
a = a.split(' ')
b = ''
for i in a:
b += i
return b
a = raw_input()
b = raw_input()
if a == b:
print("Accepted")
elif ok(a) == ok(b):
print("Presentation Error")
else:
print("Wrong Answer") |
suma = 0.00
for i in range(12):
a = float(input())
suma += a
suma /= 12.00
print ("$" + str(suma))
|
count = 0
sum = 0
print ("Before",count,sum)
for value in [9,41,12,3,74,15]:
count = count + 1
sum = sum + value
print (count, sum, value)
print ("After", count, sum, sum/count)
|
# -*- coding: utf-8 -*-
"""
Created on Wed May 31 14:15:40 2017
@author: yuwang
This is the Python code for parsing the data table in xls or xlsx extension.
"""
import os
import xlrd
import xlwt
import math
import datetime
""" ---------Core-------- """
def isyear(A):
if type(A) is float:
P = math.modf(... |
# Items that exist in each room and the functions you can use to interact with them
#TODO Define items in each room
room0items = ['leaflet']
room1items = ['fish']
room2items = []
room3items = []
room4items = []
room5items = []
room6items = []
room7items = ['lantern']
room8items = []
room9items = []
room10items = []
ro... |
"""
A number, a, is a power of b if it is divisible by b and a/b is a power of b.
Write a function called is_power that takes parameters a and b
and returns True if a is a power of b.
Note: you will have to think about the base case.
"""
#code faux, la récursive ne fonctionne pas
def isPower(a,b):
if a%b == 0:
... |
#compte le nombre de fois qu'une lettre apparait dans 1 string
from list import has_duplicates
def checkString(s):
listLetters={}
for c in s:
if c not in listLetters:
listLetters[c]=1
else:
listLetters[c] +=1
retur... |
#project-1
import random
a=random.randint(1,3)
def win(comp,human):
if comp=='s' and human=='w':
print("Oops-comp wins")
elif comp=='s' and human=='g':
print("Yeah-you win")
elif comp=='s' and human=='s':
print("Tie")
if comp=='w 'and human=='s':
print... |
# PROJECT-3
print("\n****WELCOME TO CHAT-BAZAR****\n")
print("PLEASE SELECT YOUR ORDER: ")
print("PANEER: 250/PLATE")
print("CHICKEN: 500/PLATE")
print("PANEER-TIKKA: 300/PLATE")
print("BHOJAN-THAL: 200/PLATE")
print("MANCHURIAN: 150/PLATE")
print("CHOWMEIN: 50/PLATE")
print("After Ordering The Food Please Ent... |
#PROJECT-2
import random
n = random.randint(1, 100)
print(n)
numberSn = None
guess=0
while (numberSn != n):
numberSn = int(input("Enter A Number: "))
guess+=1
if (numberSn == n):
print("Awesome! Right Answer")
else:
if (numberSn > n):
print("Oops! Enter a Smaller... |
#!/usr/bin/env python3
import sys
import os
import hashlib
def check_hash(filepath: str, obj: list) -> None:
"""This method checks if hashes match.
:param filepath: File location path
:param obj: Argument list
obj[0] - filename
obj[1] - hash_method
obj[2] - hash_string
:return... |
var input = print("Give me one number")
var usernum = parseInt(userinput, 10)
sum = sum + usenum
print("User number is: "+ usernum +")
|
# 'Data Science from Scratch' Chapter 1 exampl
# Create list of users
userNames = ["Hero", "Dunn", "Sue", "Chi", "Thor", "Clive", "Hicks", "Devin", "Kate", "Klein"]
users = []
for ind, name in enumerate( userNames ):
users.append( {"id": ind, "name": name})
# Helper function to get id
get_id = lambda userlist... |
from collections import OrderedDict
import os
import pandas as pd
def get_book_content():
csv_path = os.path.dirname(os.path.realpath(__file__)) + '/test_example.csv'
print('Test CSV File :: ', csv_path)
df = pd.read_csv(csv_path, header=None).rename(
columns={0: 'chapter', 1: 'sentence', 2: 'text... |
# --- Day 7: Handy Haversacks ---
from urllib.request import urlopen
data = urlopen('https://raw.githubusercontent.com/MarynaLongnickel/AdventOfCode2020/main/Day7/day7.txt').read().decode().split('\n')[:-1]
dic = {}
dic2 = {}
for d in data:
d = d.split(' bags contain ')
k = d[0]
v = d[1].replace('s, ', '... |
def prime_number(n):
"""
this function takes in a number then generates
all the prime numbers in the range of that number
and append to a list which is the output
"""
primes = []
if n<2:
return False
else:
for prime in range(2, n):
for b in range(2, prime):
if (prime % b == 0):
... |
class Room(object):
def __init__(self, name, description):
self.name = name
self.description = description
self.paths = {}
def go(self, direction):
return self.paths.get(directions, None)
def add_paths(self, paths):
self.paths.update(paths)
hogsmeade = Room("Hogsme... |
from readint import readinput
def gcd(x, y):
""" input: 2 integers x and y with x >= y >= 0
output: greatest common divisor of x and y """
if (y == 0):
return x
return gcd(y, x % y)
def main():
x = readinput("x")
y = readinput("y")
if y > x:
x, y = y, x
ans = gcd(x, y... |
# python-3
def inputmatrix_values(row, col):
print ("Enter matrix values row by row - space separated")
r = 1
matrix = []
while r <= row:
row_in = input("row %d: " % r)
rowvals = row_in.split(" ")
try:
rowvals = [int(val) for val in rowvals]
except ValueError... |
# multiplication of 2 binary numbers using grade school technique
from binary_addition import binary_sum
def binary_number_input(msg):
while True:
x = input(msg)
found = True
for i in x:
if i != '0' and i != '1':
found = False
print ("Bad binary ... |
def readinput(k):
bstr = raw_input("Enter a binary string %s: " % k)
return bstr
def bitsum(a, b, carry):
""" assumes a, b and carry are single bits
returns result = (sum of bits, carry) """
result = (0, 0)
c = a + b
if c == 1 and carry == 0:
result = 1, 0
elif c == 1 and carr... |
n=int(input("ENTER THE NUMBER"))
sum=0
for i in range(n,0,-1):
sum=sum+i
print(sum)
|
english=float(input("enter english marks"))
tamil=float(input("enter tamil marks"))
science=float(input("enter science marks"))
maths=float(input("enter maths marks"))
socialscience=float(input("enter social science marks"))
x=int("5")
total=english+tamil+science+maths+socialscience
print(f"english-{english}")
... |
name=str(input("PLEASE ENTER TOUR USERNAME:"))
password=int(input("PLEASE ENTER YOUR PASSWORD:"))
user=str("balamurugan")
pswd=int("9876543210")
if (user and pswd)==(name and password):
print("WELLCOME SIR")
else:
print("Please Enter Correct Username and Password")
|
for i in range(5):
for j in range(5):
if (j==0) or (i==4):
print("*",end=" ")
else:
print(" ",end=" ")
print()
|
'''
def [function_name]([parameters]):
[function_definition]
def add(x, y):
"""
Returns x + y.
:param x: int.
:param y: int.
:return: int sum of x and y.
"""
return x + y
'''
def f(x):
return x * 2
def f():
return 1 + 1
result = f()
print(result)
def f(x, y, z):
return x ... |
x = 10
while x > 0:
print('{}'.format(x))
x -= 1
print("Happy New Year!")
i = 1
while i <= 5:
if i == 3:
i += 1
continue
print(i)
i += 1
while input('y or n?') != 'n':
for i in range(1, 6):
print(i)
|
my_dict1 = dict()
print(my_dict1)
my_dict2 = {}
print(my_dict2)
fruits = {"Apple": "Red",
"Banana": "Yellow"
}
print(fruits)
facts = dict()
# add a value
facts["code"] = "fun"
facts["Bill"] = "Gates"
facts["founded"] = 1776
# lookup a key
print(facts["founded"])
print(facts)
bill = dict({"Bill ... |
def find(a,b):
s=a+b
p=a*b
r=a/b
return s,p,r
a=int(input("Enter First No. : "))
b=int(input("Enter Second No. : "))
s,p,r=find(a,b)
print("Sum is : ",s)
print("product is : ",p)
print("remainder is : ",r)
|
import random
low=25
point =5
for i in range (1,5):
Number=low + random.randrange(0,point);
print(Number,end=":")
point-=1;
print()
|
# In the name of Allah, Most Gracious, Most Merciful
# /
#
#
#
#
# ??
n = input()
scores = {}
records = {}
for i in range(n):
name, score = raw_input().split()
score = int(score)
if name not in scores:
scores[name] = 0
records[name] = []
scores[name] += score
records[name].append((scores[name], i))
hi... |
def staircase(n):
first, second = 1,1
for index in range(n):
first, second = second, first + second
return first
# Test Cases
print(staircase(4))
# 5
print(staircase(5))
# 8 |
# a-97
# z-122
import string as s
alphabet = s.ascii_letters[:26] # to get only letters with lowercase
def char2bits(s=''):
return bin(ord(s))[2:].zfill(8)
#rint(char2bits('d'))
def bits2char(b=None):
return chr(int(b, 2))
#print(bits2char(char2bits('d')))
def encrypt_vernam(message, key, decode=False... |
"""
An if statement activates if the condition is true:
"""
a = 1
b = 2
c = 3
if a == b:
print("This Is False") # Wont be written
if b < c:
print("This is True) # Will be written
|
print("Exercise 11: ");
list1 = [1, 2, 3, 4, 5];
l1 = len(list1);
list2 = [6, 7, 8, 9, 10];
l2 = len(list2);
def recursion(list, i):
if i == 0:
return (list[i]);
else:
return (list[i] * recursion(list, i-1));
print("\nTesting two arrays for recursively getting the products of their elements");
... |
print("Exercise 3: ");
print("\na. float(123) = ", float(123) );
print("This turns 123 into a float type and then prints it out.");
print("\nb. float('123') = ", float('123') );
print("This turns the input of '123' into a float and prints the actual value of 123 without the apostrophies");
print("\nc. float(... |
class Player:
def __init__(self):
self.display = 'A'
self.num_water_buckets = 0
self.row = 0
self.col = 0
def set_row(self, row):
self.row = row
def set_col(self, col):
self.col = col
def add_bucket(self):
self.num_water_buckets +=1
... |
from abc import ABC, abstractmethod
from typing import TypeVar, List, Iterator
# Define some generic types
T = TypeVar("T")
K = TypeVar("K")
class AbstractStore(ABC):
@abstractmethod
def __len__(self) -> int:
pass
@staticmethod
def add(self, value: T) -> K:
"""Returns key"""
... |
import sys
list1=sys.argv[1].split(",")
def add_last (a):
a.append ( a[len(a)-1] )
return a
add_last (list1)
print list1
|
from typing import List
class Question:
def __init__(self, text: str, answer: str, *args, **kwargs):
self.text = text
self.answer = answer
def display(self) -> None:
raise NotImplementedError('Method "display" must be implemented on Question class')
class TrueFalse(Question):... |
class Coche(object):
"""Abstraccion de los objetos coche."""
def __init__(self, gasolina):
self.gasolina = gasolina
print("Tenemos " + str(gasolina) + " litros")
def arrancar(self):
if self.gasolina > 0:
print ("Arranca coche!")
else:
print ("No arran... |
class Persona(object):
def __init__(self, name): #__init__ FUNCIÓN DE INICIALIZACIÓN, DONDE SE INTRODUCEN LOS OBJETOS DONDE QUE SERÁN NECESARIOS PARA CORRER EL PROGRAMA
self.name = name
def saluda(self):
print("Hola " + self.name)
def despidete(self):
print("Adios " + self.name)
p=Persona("Ana")... |
uno=1
dos=2
tres=3
print(uno<dos<tres) #Esta comparación encadenada significa que las comparaciones (uno<dos) y (dos<tres) son realizadas al mismo tiempo
es_mayor=tres!=dos
print(es_mayor) |
import random
class Baraja():
def __init__(self):
trajes=["♤", "♡", "♧", "♢"]
rangos=["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"]
#Baraja de 52 cartas disponibles
self.barajas=[]
#Ciclo for para cada traje en trajes
for traje in trajes:
#cic... |
#La diagonal invertida es utilizada para "escapar" comillas simples y dobles; por ejemplo: 'it's me'
#Imprime el siguiente texto utilizando una cadena: the name of this ice-cream is "sweet'n'tasty"
dont_worry="Don't worry about aphostrophes"
print(dont_worry)
print("\"sweet\" is an ice-cream")
print('text')
msg="Th... |
import unittest
import src.generate_world as generate_world
from src import cell_types
from src.cell import Cell
class TestGenerateWorld(unittest.TestCase):
def test_generate_world_size_too_small(self):
"""
Tests that a board is not created for a board that is too small
"""
self.as... |
"""
..module:: read_yaml
:synopsis: Open a provided file path and load the yaml-formatted contents
into a dictionary.
"""
import os
import yaml
#--------------------
def read_yaml(path, output=True):
""" Open a provided file path and load the yaml-formatted contents
into a dictionary. Return an erro... |
import logging
def new_logger(filename, lvl=logging.DEBUG):
"""
This module establishes Python logging to a new user-provided log file at
a specified message level. By operating on the root logger, parent modules
can set up a new log file and allow child modules to simply use 'logging'
commands. ... |
'''
Simulate housing data, then run EM algorithm
'''
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
import scipy.optimize as opt
import scipy.integrate as sci_integrate
from scipy.stats import norm, expon
#############################
##### Generate the Data #####
#########################... |
# 要するにもっとも長くしりとりが続く順番を求めよ
words = [
'Brazil', 'Croatia', 'Mexico',
'Cameroon', 'Spain', 'Netherlands',
'Chile', 'Australia', 'Colombia',
'Greece', 'Cort d\'Ivoire', 'Japan',
'Uruguay', 'Costa Rica', 'England',
'Italy', 'Switzerland', 'Equador',
'France', 'Honduras', 'Argentina',
'Bosnia... |
BOY = 'B'
GIRL = 'G'
n = 30
memo = {}
def add(current: list) -> int:
counts = len(current)
# 30 人並んだら終了
if counts >= n:
return 1
# 前回並んだ人
last = current[-1] if counts > 0 else 'N'
# メモがあればそこから応答
if (last, counts) in memo:
return memo[(last, counts)]
# 男女を繋げる
cn... |
# 10 以上の数字で、2,8,10 進数表記で回文になるものを捜す。
def is_palindrome(v):
bin_str = bin(v)[2:]
oct_str = oct(v)[2:]
dig_str = str(v)
return bin_str == bin_str[::-1] and \
oct_str == oct_str[::-1] and \
dig_str == dig_str[::-1]
if __name__ == "__main__":
tmp = 11
while not is_palindrome(tmp):
... |
from Tkinter import *
root = Tk()
wid = 800
hei = 800
w = Canvas(root, scrollregion=(0,0,wid,hei), bg="white", width=wid, height=hei)
w.pack()
def drawDragon(n):
turns = []
for i in range(n):
newturns = []
newturns.append(1)
last = 1
for turn in turns:
newturns.append(turn)
last *= -1
... |
import random
import os
class hangman:
def __init__(self, words, file_path=None):
self.target_word = ""
self.lifes = 6
self.lifes_lost = 0
self.render_word = ""
self.chars_entered = []
self.games_lost = 0
self.games_won = 0
self.wrong_answers = 0
... |
"Expt 5: Implement Bit plane slicing as explained. Include all 8 plane outputs."
def bitplane(img, plane):
"Returns the specified bitplane of the image"
assert 0 <= plane <= 7
planeImg = img.point(lambda i: i & 2**plane or (255 if plane < 6 else 0))
return planeImg
def allBitplanes(img):
"Returns ... |
import numpy as np, random, operator, matplotlib.pyplot as plt
from math import sqrt
class City:
def __init__(self, id, x, y):
self.pos = (x,y)
self.ID = id
def distance(self, city):
xDis = abs(self.pos[0] - city.x)
yDis = abs(self.pos[1] - city.y)
distance = np.sqrt((xD... |
"""The module read the file contents.
Usage:
fileread.py [filename ...]
Description:
In the absence of input file, reading comes from the standard input.
Display the contents of the files produced on standard output.
"""
import signal
import sys
import const
def sigint_handler(error, stack):
"""Han... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"... |
#환영 인사말
print("동전합산 서비스에 오심을 환영합니다.")
print("가지고 계신 동전의 개수를 입력해주세요.")
#보유 동전 개수를 키보드에서 입력 받음
coin500= int(input("500원짜리는?"))
coin100= int(input("100원짜리는?"))
coin50= int(input("50원짜리는?"))
coin10= int(input("10원짜리는?"))
#보유 동전의 총액을 계산
total= coin500 *500 +coin100 * 100 + \
coin50 *50 + coin10 *10
#보유 동전의 총액을 실행... |
#ctto-----RockEt🚀
name=input("Enter your name\n")
reg_num=input("Enter your reg_num\n")
years_of_studies=input("What's your course duration?\n")
print("Dear "+name+" you have "+years_of_studies+" years to complete your studies in our institude\n") |
#!/usr/bin/env python
# heap.py
# max/min-heap data structure
class Node:
def __init__(self, payload):
self.payload = payload
self.parent = None
self.left = None
self.right = None
class Heap:
INIT_SIZE = 100
def __init__(self):
self.array = [0 for i in xrange(INIT_S... |
from random import randint
def Solve(A, B):
''' Linear system solving for AX=B. Returns vector X '''
N=len(B)
X=[0]*N
def a(i, j, n):
if n==N: return A[i][j]
return a(i,j,n+1)*a(n,n,n+1)-a(i,n,n+1)*a(n,j,n+1)
def b(i, n):
if n==N: return B[i]
return a(n,n,n+1)*... |
from collections import deque
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def averageOfLevels(self, root: TreeNode) -> List[float]:
queue = deque()
if root is not ... |
import pygame
import os
WIDTH, HEIGHT = 900, 500
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("First Game!")
WHITE = (255, 255, 255)
FPS = 60 # Standard
vel = 5 #Velocity to be used when left key is pressed, to move spaceship left
SPACESHIP_WIDTH, SPACESHIP_HEIGHT = 55, 40
YELLOW_SP... |
def main():
print("Money invested")
money = int(input())
print("Annual rate (0-1)")
ar = float(input())
print("Enter years into the future")
years = int(input())
newmoney = 0
for i in range(years):
newmoney = money*(1+ar)
money = newmoney
print("Your new money is:",fl... |
class AccountError(Exception):{}
class BalanceError(Exception):{}
class BankAccount:
def __init__(self, acct_num):
self.__acct_num = acct_num
self.__int_bal = 0
@property
def acct_num(self):
return self.__acct_num
@acct_num.setter
def acct_num(self, new_acct_n... |
#Bubble sort of numeric data without using 3rd variable
#Try it online https://code.sololearn.com/c6uI3ZlD5Nj4
instr=list("57335527388546344")
print("Input Str",instr)
c=0
while c<len(instr)-1:
n=0
while n<len(instr)-1:
#print(instr[n],instr[n+1])
if int(instr[n])>int(instr[n+1]):
instr[n]=int(instr[n])+int(... |
#PRINTS A TREE/LIST OF SUBCLASSES OF A GIVEN CLASS
def printSubclassTree(thisclass,nest=0):
if nest > 1:
print(" |" * (nest - 1), end="")
if nest > 0:
print(" +--", end="")
print(thisclass.__name__)
for subclass in thisclass.__subclasses__():
printSubclassTree(subclass,nest + 1)
printSubclassTree(BaseE... |
# coding: utf-8
class MaxPriority:
def __init__(self):
self.nums = []
def out(self):
print self.nums
def Max(self):
if len(self.nums) == 0:
return 'empty queue'
return self.nums[0]
def __HeapArrange(self, i, size):
li = 2 * i + 1
ri = 2 * ... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
before = ListNode(-1)
before.next = head
fa... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import scipy.ndimage as im
import scipy.misc as sm
import numpy as np
import PIL
from MyKMeans import MyKMeans
class ColorQuantizer:
"""Quantizer for color reduction in images. Use MyKMeans class that you implemented.
Parameters
----------
n_colors : i... |
import pygame
import time
import random
#Szymon Czaplak
def bullet_create(n,x,y):
if n == 1:
bullet_position_y.append(y)
bullet_position_x.append(x)
if n >= 2:
bullet_position_y.append(y)
bullet_position_x.append(x)
bullet_position_y.append(y)
bullet_position_x.... |
# input()
def get_input():
matrix = list()
# main loop for input()
while True:
# getting string from input
i = input()
# end if empty string
if not i: break
# save input string and its len()
matrix.append(list(map(int, i.split())))
# return matrix
return matrix
# main function
def main(matrix):
... |
#!/usr/bin/env python
__author__ = "Rio"
def compress_str(string):
''' Compress string where duplicated characters become number.
>> compress_str('a')
>> a
>> compress_str('abc')
>> a1b1c1
>> compress_str('aabb')
>> a2b2
'''
if not string:
return None
if len(string)... |
#!/usr/bin/env python
__author__ = 'Rio'
from LinkedList import *
def remove_dups_dict(lst):
'''
Remove duplicates from a linked list.
Use dictionary to check duplicates.
Time Complexity: O(n), where n means the number of linked list.
Space Complexity: O(n), additional storage is requested.
... |
##############################################################################################################
#
# Python implementation of the Delaunay triangulation algorithm
# as described in http://paulbourke.net/papers/triangulate/
#
# developed by PanosRCng, https://github.com/PanosRCng
#
#
# --> module usage
# ... |
from d2lzh_pytorch import linear_reg, data_process, rnn,plot
import time
import torch
import torch.nn as nn
import numpy as np
import math
def train_ch3(net, train_iter, test_iter, loss, num_epochs, batch_size,
params=None, lr=None, optimizer=None):
"""
The training function of chapter3, it is a... |
# coding=utf-8
import torch
"""
这一节介绍了线性回归的基本概念和神经网络图
"""
x = torch.ones(100)
y = torch.ones(100)
z = torch.zeros(100)
# 两个向量相加一种方法是用循环逐元素相加,这种做法繁琐且速度极慢
for i in range(100):
z = x[i]+y[i]
# 另一种做法是直接做向量加法,这种做法速度快很多,所以在计算的时候最好将计算向量化
z = x+y
# 多运用广播机制可以简化代码的编写(见2.2)
a = torch.ones(10)
b = 2
print(a+b)
print('————... |
# coding=utf-8
# 用这个来导入PyTorch包
import torch
"""
这一节介绍了tensor基础的操作
"""
# 默认数据格式是float32
x = torch.ones(2, 4)
y = torch.zeros(2, 4)
# tensor加法1
z = x+y
# tensor加法2
z = x.add(y)
# tensor加法3,注意pytorch中函数后缀是下划线的均代表此操作是原地操作
z = x.add_(y)
print(z)
print('————————————')
# 可以获得tensor的索引,冒号和matlab一样用于得到一个范围值
y = x[0, :]
# ... |
#!/usr/bin/python
def printMax(x,y):
'''Print the maximum of the two integers.
The tow input must be integers.'''
if x>y:
print x
else:
print y
print printMax.__doc__
printMax(3,5)
help(printMax)
|
"""Main flow."""
from brain_games.cli import welcome_user
import prompt
def flow(game):
name = welcome_user()
print(game.PHRASE_RULE)
game_counter = 0
game_limit = 3
while game_counter < game_limit:
question_expression, correct_answer = game.get_question_and_answer()
print('Questi... |
"""Arithmetic progression Game."""
import random
PHRASE_RULE = 'What number is missing in the progression?'
def get_question_and_answer():
"""Engine of the Game."""
number_start = random.randint(1, 100)
number_dif = random.randint(1, 20)
number_elements = random.randint(5, 10)
progression_list ... |
#!/Library/Frameworks/Python.framework/Versions/3.7/bin/python3
import time
import sys
answer = input("Would you like to play a game? ")
if answer.lower().strip() == "yes":
#intro to the adventure, which will present three options to the player
answer = input("\nYou wake to find yourself in a dimly lit stone... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.