text stringlengths 37 1.41M |
|---|
# Read It
# Demonstrates reading from a text file
print("Opening and closing the file.")
text_file = open("read_it.txt", "r")
# text_file.close()
print("\nReading characters from the file.")
# text_file = open("read_it.txt", "r")
print(text_file.read(1))
print(text_file.read(5))
# text_file.close()
print("\nReading... |
from functools import wraps
from time import *
def rec_time(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time()
result = func(*args, **kwargs)
print(f'{func.__name__}: {time() - start}秒')
return result
# * must return the wrapper, otherwise args cannot be pas... |
a = int(input('a = '))
b = int(input('b = '))
print('%d / %d = %f' % (a, b, a / b))
print('%d // %d = %d' % (a, b, a // b))
print('%d %% %d = %d' % (a, b, a % b))
print('%d ** %d = %d' % (a, b, a ** b))
a = 100
b = 12.345
c = 1 + 5j
d = 'hello, world'
e = True
print(type(a))
print(type(b))
print(type(c))
print(type(d... |
# Longevity
# Demonstrates text and entry widgets, and the Grid layout manager
from tkinter import *
class Application(Frame):
""" GUI application which can reveal the secret of longevity. """
def __init__(self, master):
""" Initialize the frame. """
super(Application, self).__init__(master)
... |
#!/usr/bin/env python
from __future__ import print_function
from builtins import input
#--------------------------------------------
#
# tic tac toe
#
# Copyright (C) 2017 Reliance Systems, Inc.
#
# Author: Matt Krueger <mkrueger@rstms.net>
# Date: 2017-08-24
# http://www.rstms.net
#
#--------------------------------... |
"""
Given a string s and an array of strings words, return the number of words[i] that is a subsequence of s.
A subsequence of a string is a new string generated from the original string with some characters
(can be none) deleted without changing the relative order of the remaining characters.
For example, "ace" is ... |
"""
Given an array of meeting time intervals intervals where intervals[i] = [starti, endi],
return the minimum number of conference rooms required.
O(N log N) Time and O(N) Space
"""
from queue import PriorityQueue
def minMeetingRooms(intervals):
if not intervals:
return 0
intervals.sort(key=lambda ... |
"""
A storekeeper is a game in which the player pushes boxes around in a warehouse trying to get them to target locations.
The game is represented by an m x n grid of characters grid where each element is a wall, floor, or box.
Your task is to move the box 'B' to the target position 'T' under the following rules:
Th... |
"""
You are given the root of a binary tree containing digits from 0 to 9 only.
Each root-to-leaf path in the tree represents a number.
For example, the root-to-leaf path 1 -> 2 -> 3 represents the number 123.
Return the total sum of all root-to-leaf numbers.
1
/ \
2 3
nput: root = [1,2,3]
Output: 25
Exp... |
"""
An array nums of length n is beautiful if:
nums is a permutation of the integers in the range [1, n].
For every 0 <= i < j < n, there is no index k with i < k < j where 2 * nums[k] == nums[i] + nums[j].
Given the integer n, return any beautiful array nums of length n. There will be at least one valid
answer for t... |
"""
There are n bulbs that are initially off. You first turn on all the bulbs, then you turn off every second bulb.
On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on).
For the ith round, you toggle every i bulb. For the nth round, you only toggle the last bulb.
Return ... |
"""
You are given an n x n integer matrix grid where each value grid[i][j]
represents the elevation at that point (i, j).
The rain starts to fall. At time t, the depth of the water everywhere is t.
You can swim from a square to another 4-directionally adjacent square if and only
if the elevation of both squares ind... |
"""
Return the exclusive time of each function in an array, where the value at the ith index
represents the exclusive time for the function with ID i.
A function's exclusive time is the sum of execution times for all function calls in the program.
Example: n = 2, logs = ["0:start:0","1:start:2","1:end:5","0:end:6"]... |
"""
We are given an array asteroids of integers representing asteroids in a row.
For each asteroid, the absolute value represents its size, and the sign represents
its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed.
Find out the state of the asteroids after all colli... |
"""
There are n cars traveling at different speeds in the same direction along a one-lane road.
You are given an array cars of length n, where cars[i] = [positioni, speedi] represents:
positioni is the distance between the ith car and the beginning of the road in meters.
It is guaranteed that positioni < positioni+1... |
"""
Given a string s which represents an expression, evaluate this expression and return its value.
The Algorithm:
Put all the numbers with their correct sign into the stack.
Put '(' and the operator before that into the stack.
If we see the ')', pop from the stack until we get to '('. Update the num by the evaluat... |
"""
Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals,
and return an array of the non-overlapping intervals that cover all the intervals in the input.
Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2... |
"""
Given the root of a binary tree, the value of a target node target, and an integer k,
return an array of the values of all nodes that have a distance k from the target node.
You can return the answer in any order.
Input Tree
3
/ \
5 1
/ \ / \
6 2 0 8
/ \
7 4
target = 5, k = ... |
"""
You have a long flowerbed in which some of the plots are planted, and some are not.
However, flowers cannot be planted in adjacent plots.
Given an integer array flowerbed containing 0's and 1's, where 0 means empty and 1 means not empty,
and an integer n, return if n new flowers can be planted in the flowerbed w... |
"""
ou are given an m x n binary matrix grid. An island is a group of 1's (representing land)
connected 4-directionally (horizontal or vertical.) You may assume all four edges of the
grid are surrounded by water.
The area of an island is the number of cells with a value 1 in the island.
Return the maximum area of a... |
"""
Given a string path, which is an absolute path (starting with a slash '/')
to a file or directory in a Unix-style file system, convert it to the simplified canonical path.
Input: path = "/home/"
Output: "/home"
Input: path = "/../"
Output: "/"
Input: path = "/home//foo/"
Output: "/home/foo"
Input: path = "/a/.... |
"""
Given the root of a binary tree, return the length of the diameter of the tree.
The diameter of a binary tree is the length of the longest path between any
two nodes in a tree. This path may or may not pass through the root.
Input Tree
4
/ \
2 5
/ \
1 3
Output: 3 which is the length of 1->2->4->5... |
import numpy as np
import matplotlib.pyplot as plt
data = np.genfromtxt('/Users/pptem/PycharmProjects/ML-Assignments/resources/Assignment_1/ex1data1.txt', delimiter=',')
X = data.shape[0] #number of training example
Y = data.shape[1] #number of features
print('Dimensions of data ', X, Y)
population = data[:, 0]
pro... |
from typing import List, Tuple
from argparse import ArgumentParser, Namespace
import requests
from data import Point, Warehouse
def double(number: str) -> float:
'''Convert string containing double with , to Python float object
:param number: Text representation of float number
:type number: str
:ret... |
def estudiante(n):
notas=[]
nombre=[]
promedio=[]
mensaje = []
for i in range(n):
name= input(f'Ingrese su nombre {i+1}: ')
nombre.append(name)
nota1 = int(input('Ingrese Nota 1: '))
nota2 = int(input('Ingrese Nota 2: '))
nota3 = int(input('Ingrese... |
import unittest
from day9.day9a import List, insert_after
class TestList(unittest.TestCase):
def test_insert_after_value(self):
l1 = List(1)
insert_after(l1, 2)
self.assertEqual(l1.next.value, 2)
def test_insert_after_previous(self):
l1 = List(1)
insert_after(l1, 2... |
def get_data():
with open('input.txt', 'r') as f:
values = [int(line) for line in f.readlines()]
return values
def find_repeating_frequency(values):
already_seen = set()
current_frequency = 0
already_seen.add(current_frequency)
while(True):
for v in values:
current_f... |
#!/usr/bin/python3
""" The N queens puzzle challenge
"""
import sys
def printSolution(board):
"""print the coordinates row and column for the position of
each N queen in the posible solution
Arg:
- board: matrix[n][n], list of list
"""
solution = []
for i in range(len(board)):
... |
import unittest
def binary_search(arr,size,key):
low = 0
print "Array : ",arr," to be searched for: ",key
high = size - 1
mid = int((low+high) / 2)
while low <= high:
temp=0
if key == int(arr[mid]):
print "Found ",key," at position: ",mid+1,"\n"
return mid+1
temp=1
break
elif key > int(arr[mid]):... |
def checker(str1):
file_data=""
with open('input.txt','rt') as f:
for line in f:
file_data = file_data + line
a = file_data.split('.')
print 'Original File: ', a
b = str1.split('.')
print 'Input Text ', b
for i in range(len(a)-1):
a[i]=str(a[i]).str... |
class BFS():
def __init__(self):
self.map={'A':{ 'B', 'C'},
'B':{ 'D', 'E','A'},
'C':{ 'F', 'G','A'},
'D':{ 'B', 'E'},
'E':{ 'B', 'D'},
'F':{ 'C'},
'G':{ 'C'}
}
vertex='A'
... |
class HashTable():
def __init__(self):
self.hash_table=[[]for _ in range(16)]
def insert_number(self,key,value):
hash_value=self.compute_hash_value(key)
self.hash_table[hash_value].append(value)
def insert_string(self,key,value):
hash_value=self.compute_hash_value_strin... |
class Node():
def __init__(self,data=None,next=None,prev=None):
self.data=data
self.next=next
self.prev=next
class DoublyLinkedList():
def __init__(self):
self.head=None
self.size=0
def add_node(self,data):
new_node=Node(data)
if self.hea... |
def ShellInsertSort(alist, dk):
n = len(alist)
for i in range(dk, n):
if alist[i] < alist[i-dk]:
tmp = alist[i]
j = i-dk
while j>=0:
if tmp < alist[j]:
alist[j+dk] = alist[j]
alist[j] = tmp
j -= dk
return alist
def ShellSort(array, len_array): # 希尔排序
dk = int(len_array/2) # 增量
whi... |
__author__ = 'sharon'
def censor(text, word):
text = text.split()
for index, item in enumerate(text):
if item == word:
text[index] = "*" * len(item)
return " ".join(text)
# practice to write item count in list; similar to list.count()
def count(sequence, item):
found = 0
for i... |
# Écrire un programme qui affiche le résultat de la multiplication
# d’un entier et d’un réel saisis préalablement au clavier.
a = int(input("Saisir le premier entier : "))
b = int(input("Saisir le second entier : "))
c = a*b
print(f'{a} x {b} = {c}') |
from Bio import SeqIO
import argparse
def main():
parser = argparse.ArgumentParser(description='Verify that a multi-FASTA has sufficiently long sequences for'
'Nextstrain phylodynamic analysis and proper genome completeness')
parser.add_argument('--input_fasta'... |
import tkinter
import tkinter.messagebox
window = tkinter.Tk()
window.title("Alert Message GUI")
tkinter.messagebox.showinfo("Alert Message", "This is just a alert message!")
response = tkinter.messagebox.askquestion("Simple Question","Do you love Python?")
if response == "Yes":
tkinter.Label(window, text ... |
from turtle import *
from random import *
Screen()
def tree(length, angle, factor, degree):
if degree > 0:
degree = degree - 1
left(angle)
forward(length*factor)
#print(degree)
tree(length * factor, angle, factor, degree)
backward(length*factor)
right... |
class Vector():
def __init__(self, l):
assert type(l) == type([])
for i in l:
assert type(i) == type(2) or type(i) == type(0.1)
self.l = l
def dim(self):
return len(self.l)
def __getitem__(self, i):
assert i > 0 and i < len(self.l) + 1
return self.l[i - 1]
def __setitem__(self, i, x):
assert i > 0 ... |
import json
keys= ["user", "job_title", "job_description", "wage", "hours", "employer_name", "company_name", "neighborhood", "contact_method", "contact_info"
]
answers = {} # curly brackets for dictionaries
print("**************************************************")
for items in range(len(keys)):
user_answe... |
#Escape sequence caracters: Practice
tabby_cat = "\tI'm tabbed in."
persian_cat = "I'm split\non a line"
backslash_cat = "i'm \\ a \\ cat"
fat_cat = """
I'll do a grocery list here:
\t* Cat food;
\t* Fishies;
\t* Cantip\n\t* Grass
"""
print (tabby_cat)
print (persian_cat)
print (backslash_cat)
print ... |
# This file defines the chess board
class Board():
def generate_board(self):
board = []
colour_counter = 1
for rank in self.ranks:
for __file in self.files:
if colour_counter % 2 == 0:
board.append([__file, rank, 'white'])
... |
# This is my first neuron based on the Neural Networks from Scratch book
# Chapter 2 - page 27
inputs = [1,2,3,4]
weights = [[0.2,0.8,0.6,-0.5],]
bias = [2,]
#output = (inputs[0]*weights[0] +
# inputs[1]*weights[1] +
# inputs[2]*weights[2] +
# inputs[3]*weights[3] + bias)
#print ( "The res... |
# 2520 is the smallest number that can be divided by
# each of the numbers from 1 to 10 without any remainder.
# What is the smallest positive nuber that is evenly divisible
# by all of the numbers from 1 to 20?
# We are essentially looking for the smallest common multiple (NOK)
# Using a simple algorithm
# This me... |
# This excercise shows that the variables in a functions are not neccessarily directly connected
# To the arguments of the script
def cheese_and_crackers (cheese_count, boxes_of_crackers):
print ("You have %d of cheese!" %(cheese_count))
print ("You have %d cboxes of crackers" %(boxes_of_crackers))
p... |
from pprint import pprint
from math import sqrt
# List comprehention
words = [] # A list of words
sentence = "This is a sentance that is going to be used for demonstration"
words = sentence.split()
print (words)
words_len = [len(word) for word in words]
print (words_len)
# Set comprehention
words_len = {len(word) for ... |
# You are given the following information
# 1 Jan 1900 was a Monday. - It was actually a Tuesday
# 31 days - Jan, Mar, May, Jul, Aug, Oct, Dec
# 30 days - Apr, Jun, Sep, Nov - They skipped September
# 28-29 days - Feb
# A leap year occurs on any year evenly divisible by 4, but not on a century (100) unless it is div... |
# 32nd Exercise from the book
# Loops and lists
# What is a list?
# here is an example of a few lists
hairs = ['brown', 'blond', 'red']
eyes = ['brown', 'blue', 'green']
weights = [1, 2, 3, 4, 5]
the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'di... |
# If the numbers 1 to 5 are written out in words: one, two, three, four, five
# then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
# If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words,
# how many letters would be used?
# NOTE Do not count spaces or hyphens. Ex. 342 (Three h... |
#!usr/bin/python3
import sys
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import math
import os
# Program written for Homework 5, MATH 693B. Problem outline from
# Strikwerda 3.1.2
# Program solves the advection equation in 1D using the Forward-Time Backwards-
# Space (FTBS) scheme and... |
"""
Python program for DNA De-Novo assembly
This naive implementation based on De-Bruijn graph algorithm.
The Constructor of the graph takes a list of DNA k-mers (reads)
and produces 2 vertices from each k-mers: right k-1 mer and left k-1 mer.
To recover the genome, find the Eulerian trail in the graph and reassem... |
import sys
import numpy as np
from graph_gen import *
def has_cycle(sets):
# return True if the graph has cycle; return False if not
a = np.array(sets) # Create a 2d array object
node_arr = a[(a == 1)]
nodes = node_arr.size # Get amount of nodes
n = nodes
b = a
while n > 0:
b = ... |
#Leetcode 258 Add Digits
#input: 38 / output: 2
def addDigits(self, num):
if num == 0:
return 0
else:
return (num -1) % 9 + 1 |
jeito = False
while True:
if jeito == True:
print('\n')
else:
pass
ini = int(input('Valor inicial: '))
fim = int(input('Valor final: '))
qBit = int(input('Quantidade de bits (dever ser 8, 16, 32): '))
hexa = 0
casa = 0
if qBit == 8 and (ini > 255 or fim > 2... |
from string import *
def subStringMatchExact(target, key):
tup = ()
for x in range(0, len(target)):
if find(target, key, x) == x:
tup += (x,)
return tup
print subStringMatchExact("aabaa","aa")
print subStringMatchExact("aaaa","aa")
|
"""
In this project, I will scrape data Frontpage Slickdeals from slickdeals.net.
For each deal, I will collect the information about the following:
Vendor Name
Item Name
List Price (If available)
Discounted price
"""
from bs4 import BeautifulSoup as soup
import requests as Req
# The url of the websit... |
'''
Module for preprocessing dream corpus into interpretations
For each entry in a dream corpus:
vocab1: definition1
vocab2: definition2
vocab3: definition3
...
We want to split the definitions by interpretation. We define an interpretation
as a nuanced definition of a dream entry.
Example: Abbey
Interpretation 1:... |
from typing import Iterator
import requests
import lxml.html
def main():
"""main method"""
response = requests.get('https://gihyo.jp/db')
urls = scrape_list_page(response)
for url in urls:
print(url)
def scrape_list_page(response:requests.Response)->Iterator[str]:
html = lxml.html.fromstri... |
#!/usr/bin/python
from operator import itemgetter
def outlierCleaner(predictions, ages, net_worths):
"""
Clean away the 10% of points that have the largest
residual errors (difference between the prediction
and the actual net worth).
Return a list of tuples named cleaned_data where... |
class product:
def __init__(self, pid, name, brand, category, cost, rating, discount):
self.pid = pid
self.name = name
self.brand = brand
self.category = category
self.cost = cost
self.rating = rating
self.discount = discount
def keys(self, choice):
... |
#non secure
count = 0
def func():
global count
count = count + 1
for i in range(3):
func()
print("Non closure:",count)
#-----------------------
#secure - this is called closure
def outer():
c = 0
def inner():
nonlocal c
c = c + 1
def get():
nonlocal c
print("Cl... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# car.py
# zdefinuj klase samochodu z nast. atrybutami i metodami:
# marka np. Fiat
# model np. Tipo
# rok produkcji, np. 2002
# metoda wiek(), ktory zwroci w latach
from datetime import date
from osoba_obj import Osoba
class Kierowca(Osoba): #atrybut klasy, współdzielo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/4/7 2:41 下午
# @Author : MaJiong
# @File : Offer_39.py
# @Software: PyCharm
from typing import List
class Solution:
def majorityElement(self, nums: List[int]) -> int:
vote = major = 0
for x in nums:
if vote == 0:
... |
import turtle as t # підключення бібліотеки
from random import randint
from turtle import *
screen = t.getscreen() # вікно
t.title("Черепашка")
my_turtle = t.Turtle()
my_turtle.shape("turtle") # square , triangle , classic
#my_turtle.color("green")
my_turtle.color("black","red")
my_turtle.shapesize(2,2,0)
#for i in ran... |
import math
import sys
# Global variables
to_be_saved_human = None
list_of_hostage = []
list_of_zombies = []
# Functions
def jump_closer_to_hostage(james):
list_of_hostage.sort(key=lambda hostage: hostage.new_rank_v2)
debug("closest : " + str(list_of_hostage[0]))
debug("James: " + str(james... |
import math
class cartesianPoint:
pass
#Creating instances of the cartesianPoint class
cp1 = cartesianPoint()
cp2 = cartesianPoint()
##NB# When the above is called, python allocates a specific spot in
##NB# memory that corresponds to that instance. Right now it has a
##NB# pointer back to the class
###Each insta... |
#This is the basic structure of a for loop.
##Print out each string in the following array/data structure.
print("TrialI,MethodI")
print(" ")
friends = ["Basten","Gullit","Jhontu"]
for letter in friends:
print(letter)
##Print out each string using len() fn.
print(" ")
print("TrialI,MethodII")
for index in range(l... |
#This is to understand the conept of tuples as used in python.
#Tuple is a type of data structure, with indexing starting from 0.
##Creating x,y coord using Tuples
coordinates =(4,5)
print(coordinates[1])
#A tuple is immutable, meaning it cannot be changed or modified.
#ie, once a tuple is created, it cannot be modifi... |
#Std if statement procedure for Boolean variables
isMale = True
isTall = False
if isMale and isTall:
print ("You are MAle and/or Tall")
elif isMale and not(isTall):
print ("You are MAle and Short")
elif not(isMale) and (isTall):
print ("You are a Tall not Male")
else:
print ("You are not MAle and not Tall"... |
marked=int(input("enter the price"))
if marked>10000:
print(20/100*marked)
elif marked>7000 and marked<=10000:
print(15/100*marked)
elif marked<=7000:
print(10/100*marked)
print("net amount to pay",marked)
|
tax = 0
pr=int(input("Enter the price of bike"))
if pr > 100000:
tax = 15/100*pr
elif pr >50000 and pr <=100000:
tax = 10/100*pr
else:
tax = 5/100*pr
print("Tax to be paid ",tax)
|
num=int(input("enter the first number"))
if num%2==0 and num%3==0:
print(num%2,num%3,"are divisible")
else:
print("not divisible")
|
working=int(input("enter the total working days"))
absent=int(input("enter the days of absent"))
days=(working-absent)/working*100
print("Your attendance is ",days)
if days>75:
print("student eligible for exam")
else:
print("student not eligible for exam")
|
class Maxheap:
def __init__(self):
self.heap=[0]
def push(self,data):
if self.heap==[0]:
self.heap.append(data)
elif len(self.heap)==2:
self.heap.append(data)
if self.heap[1]<self.heap[-1]:
self.swap(1,len(self.heap)-1)
else:
self.heap.append(data)
self.bubble_up(len(self.heap)-1... |
def quickSort(array):
if len(array) < 2:
return array
pivot = array[0]
lesser = [i for i in array[1:] if i < pivot]
greater = [j for j in array[1:] if j >= pivot]
return quickSort(lesser) + [pivot] + quickSort(greater)
print(quickSort([3,1,8,4,9,5,4,2])) |
import sys
if __name__ == "__main__":
if len(sys.argv) > 1:
sys.argv[1] = int(sys.argv[1])
a = 0
b = 1
c = 1
if sys.argv[1] < 3:
if sys.argv[1] == 1:
b = a
else:
for i in range(sys.argv[1]-2):
c = b + a
... |
import os
def rename_files():
#(1) get file names from the folder
list_files = os.listdir("/home/anhvh/workspace/selfStudy/online_courses/udacity/prog_foundation_w_Python/lesson1_use_functions/prank")
#print(list_files)
curPath = os.getcwd()
os.chdir("/home/anhvh/workspace/selfStudy/online_courses/udacity/prog_... |
"""
UNIT 2: Logic Puzzle
You will write code to solve the following logic puzzle:
1. The person who arrived on Wednesday bought the laptop.
2. The programmer is not Wilkes.
3. Of the programmer and the person who bought the droid,
one is Wilkes and the other is Hamming.
4. The writer is not Minsky.
5. Neither Knut... |
# DECORATOR:
"""
@func_1
func_2
equivalent to: func_2 = func_1(func_2)
"""
from functools import update_wrapper
# Rewrite decorator to avoid repeating update_wrapper in each decorator function
def decorator(d):
"d a decorator: d wraps a function f. decorator of d will update automatically information from f to t... |
"""Use computer to calculate some conditional probability"""
import itertools
from fractions import Fraction
# PROBLEM 1: calculate the probability of having 2 boys in a family having at least 1 boy and 2 children in total
sex = 'BG'
def product(*args):
"""Return the cartesian products of all arg from args"""
... |
#!/usr/bin/python
a = 60 #60 = 0011 1100
b = 13 #13 = 0000 1101
c = 0
c = a & b
print("Line 1 - Value of c is ", c)
c = a | b
print("Line 2 - Value of c is ", c)
c = a ^ b
print("Line 3 - Value of c is ", c)
c = ~a
print("Line 4 - Value of c is ", c)
c = a << 2
print("Line 5 - Value of c is ", c)
c = a >> 2
prin... |
# """A Markov chain generator that can tweet random messages."""
# import os
# import sys
# from random import choice
# import twitter
# def open_and_read_file(filenames):
# """Take list of files. Open them, read them, and return one long string."""
# body = ""
# for filename in filenames:
# te... |
#
# Author: Babeanu Alexandru
# S-number: s3004872
# Date: 18-02-2017
# Challenge: Fractal
#
# Program description:
#
# This program reads an integer t corresponding to the number of following input
# lines. It then reads t lines containing 3 integers, k (representing the order
# of the Hilbert Curve) and ... |
class paren:
def __init__(self):
self.open=[]
self.i=None
def checkvalid(self, str):
valid=False
for each in str:
if each=='(' or each=='{' or each=='[':
self.open.append(each)
elif each==')' or each=='}' or each==']':
if len(self.open)!=0:
... |
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.data = [] # array for stack init
self.min = float("inf") # initialize current min to infinity
def push(self, x: int) -> None:
if x < self.min: # while pushing, we pu... |
"""CP1404 Practical - Programming language do-from-scratch exercise"""
import datetime
class Guitar:
def __init__(self, name="", year=0, cost=0):
""" Initializes a guitar instance with default values """
self.name = name.title()
self.year = year
self.cost = cost
def __repr__(... |
MIN_LENGTH = 5
def validate_password(user_input):
return len(user_input) >= MIN_LENGTH
def main():
password = get_password()
print_password(password)
def print_password(password):
for char in password:
print("*", end="")
def get_password():
password = input("Please enter a password ... |
"""
CP1404/CP5632 Practical
Taxi Simulator
"""
from prac_08.silver_service_taxi import SilverServiceTaxi
from prac_08.taxi import Taxi
MENU_STRING = "q)uit, c)hoose, d)rive"
def main():
current_taxi = None
taxis = [Taxi("Prius", 100), SilverServiceTaxi("Limo", 100, 2), SilverServiceTaxi("Hummer", 200, 4)]
... |
"""
Shop
The total is usually a few cents off due to floating point error. Could be fixed by using a decimal type
"""
numItems = int(input("Number of items: "))
while numItems <= 0:
print("Invalid number of items entered!")
numItems = int(input("Number of items: "))
prices = []
for i in range(numItems):
... |
# s = 'My Name is Julia'
# #
# # if 'Name' in s:
# # print('Substring found')
#
# index = s.find('Name')
# if index != -1:
# print(f'Substring found at index {index}')
# #возвращает индекс первого вхождения подстроки в строку
def test_substring(full_string, substring):
assert substring in full_string, "exp... |
# Nirel Marie M. Ibarra
# 192468
# March 22, 2021
# I have not discussed the Python language code in my program
# with anyone other than my instructor or the teaching assistants
# assigned to this course
# I have not used Python language code obatained from another student
# or any other unauthorized source, either m... |
#This script finds the number of times an author uses a word in an html book
import urllib3
target_word = input(str("What word do you want to know the frequency of?..."))
url=input(str("What is the url of the html text?..."))
instance = urllib3.PoolManager()
responce = instance.request('GET', url)
html = str(... |
# Dylan Wanser
# Integration Project Stage 1
# A haphazard amalgamation of what I have learned so far
print("My creator is named Dylan!")
print("I took him way too long to make, but he's proud of his project.")
print("Which option would you like to explore today?")
print("1. Quiz")
print("2. Jokes")
print("3.... |
#!/usr/bin/env python
def check_in_range(n):
if n in range(3,319):
print( " %s is in the range"%str(n))
is_in_range = True
else :
print("The number is outside the given range.")
is_in_range = False
return is_in_range
|
"""
Module containing time and distance comparison functions.
"""
from datetime import datetime
from math import sin, cos, sqrt, atan2, radians
def day_hour_minute():
"""
Get the current day, hour, and minute for California.
Add 1 to weekday to match the foodtruck api.
"""
x = datetim... |
"""
Stacked submission by Rohit Nimkar (nehalnimkar@gmail.com)
"""
if __name__ == '__main__':
# size of the grid
n = int(input())
# initial coordinates
x, y = map(int, input().split())
# number of moves
m = int(input())
fall = False
for i in range(m):
dir, steps = input().split(... |
import time
# commentいれるとか工夫しろよ
def simple_watch():
if hasattr(simple_watch, "start"):
start = simple_watch.start
end = time.time()
elapsed = end - start
simple_watch.start = end
return elapsed
else:
simple_watch.start = time.time()
return 0
def to_str... |
"""
This is a program that generates a sequence of "hello", "mu", "quack" given the probabilities below
Output is saved to a file, one line per sequence and the amount of sequences can be chosen
"""
import random
import sys
import os.path
"""
Takes a dictionary of dictionaries, outer dict key = current state, value = ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
def nextMove(n, r, c, grid):
for i in range(len(grid)):
for j in range(len(grid)):
if grid[i][j] == 'p':
if i > r:
return 'DOWN'
elif i < r:
return 'UP'
elif j > c:... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.