text stringlengths 37 1.41M |
|---|
#! /usr/bin/env python
""" Helper functions for crypto. """
import string
def alphabet_position(letter):
""" returns the 0-based numerical position of the letter within the alphabet """
return string.ascii_letters.find(letter) % 26
def rotate_character(char, rot):
""" return new char rotated by given numb... |
#1
import turtle
def draw_square(t, sz):
"""Get turtle t to draw a square with sz side"""
for i in range(4):
t.forward(sz)
t.left(90)
def main():
wn = turtle.Screen()
wn.bgcolor("lightgreen")
alex = turtle.Turtle()
alex.color("salmon")
for i in range(5):
draw_squ... |
#1
## original
for i in range(1000):
print("We like Python's turtles!")
## update
number_of_reps = int(input("How many repetitions of the message?"))
for i in range(number_of_reps):
print("We like Python's turtles!")
#2
bottles = int(input("How many bottles?"))
line1a = "bottle"
line1b = "of beer"
line1c = "on... |
#1
from test import testEqual
testEqual('Python'[1] , 'y')
testEqual('Strings are sequences of characters.'[5] , 'g')
testEqual(len('wonderful') , 9)
testEqual('Mystery'[:4] , 'Myst')
testEqual('p' in 'Pineapple' , True)
testEqual('apple' in 'Pineapple' , True)
testEqual('pear' not in 'Pineapple' , True)
testEqual('ap... |
'''
1. Use the draw_square function we wrote in this chapter to draw the image shown below. Assume each side is 20 units.
(Hint: notice that the turtle has already moved away from the ending point of the last square when the program ends.)
'''
import turtle
def draw_square(t, sz):
"""Get turtle t to draw a square... |
import random
Color = ['Red', 'Blue', 'White', 'Yellow', 'Green']
class CardLostCity:
def __init__(self, color, num):
self.color = color
self.num = num
def __repr__(self):
return self.color[0]+str(self.num)
def __gt__(self, other):
if not isinstance(other, CardLostCity):... |
import numpy as np
def sigmoid(x):
return 1/(1+np.exp(-x))
def sigmoid_derivative(x):
return sigmoid(x)*(1-sigmoid(x))
def relu(x):
return 0 if x <= 0 else x
def leaky_relu(x):
return x/100 if x <= 0 else x
def softmax(x, axis):
"""
Softmax function. In this implementation, we take the axis a... |
#!/bin/python3.5
class Node:
"""
Node that represents a tree
"""
def __init__(self, data):
"""
Node Constructor
"""
self.left = None
self.right = None
self.data = data
def insert(self, data):
if self.data < data:
if self.left == None:
self.left = Node(data)
el... |
from random import randint
class Node(object):
"""
Node object implemented with strings
string: '012345678' is in bidimensional matrix mode:
| 0 | 1 | 2 |
| 3 | 4 | 5 |
| 6 | 7 | 8 |
"""
def __init__(self, matrix=None, depth=0):
if not matrix:
self.mat... |
with open("z1.txt", 'r') as input_file:
file_contents = input_file.read()
def char_remove(file_contents):
char = [",", ".", ":", ";", "!", "?"]
for i in file_contents.lower():
if i in char:
file_contents = file_contents.replace(i, "")
return file_contents
... |
#!/usr/bin/env python
__author__ = "Juan Grajales"
__license__ = "GPL"
__email__ = "juafelgrajales@utp.edu.co"
import os
from homework_classes import HomeworkClasses
def main():
n_iter = 100 # Número de iteraciones a realizar
n_samples = 41 # Porcentaje aceptado de inliers para detener el proceso
nro... |
from math import sqrt
class Point:
def __init__(self, x = 0.0, y = 0.0):
self.x = x
self.y = y
def __str__ (self):
return "({}, {})".format(self.x, self.y)
def distance_from_origin(self):
d= sqrt(self.x ** 2 + self.y ** 2)
return d
def __eq__ (self,p ):
... |
username = 'Charly'
level = 0
musica = None
rock= None
pop=None
rap= None
print(f'Hello, {username}' )
# Ask user input
print("Te hare algunas preguntas sobre la musica que te gusta, para ver si eres un melomano de verdad (Sino quieres contestar entonces no lo eres)")
print(" ")
print("Comencemos")
print(" ")
musica=... |
def get_sep(sep, sep_len):
return sep * sep_len
print(get_sep('_-', 50))
sep = get_sep('*', 2)
print('раз {} два {}'.format(sep, sep))
|
def my_filter(numbers, predicate):
result = []
for number in numbers:
if predicate(number):
result.append(number)
return result
some_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print(my_filter(some_numbers, lambda number: number % 2 != 0))
print(my_filter(some_numbers, lambda number: num... |
numbers = [2, 3, -5, 7, 1, -34, -6, 7, 34, -5, 5]
result = [number for number in numbers if number > 0]
print(result)
print(type(result))
pairs = {(1, 'a'), (2, 'b'), (3, 'c')}
result = {pair[0]: pair[1] for pair in pairs}
print(result)
print(type(result))
|
#this script will create a blank input file if it does not already exist
#1.1 it will back up the input file only if the input file is not blank
#1.2 will back up the input file only if the input file does not have the same contents as the latest output file
#Both 1.1 and 1.2 logic comes from content_handler
impo... |
'''
Exercise 1: Write a program to read through a file and print the contents of the file (line by line)
all in upper case. Executing the program will look as follows:
python shout.py
Enter a file name: mbox-short.txt
FROM STEPHEN.MARQUARD@UCT.AC.ZA SAT JAN 5 09:14:16 2008
RETURN-PATH: <POSTMASTER@COLLAB.SAKAIPROJEC... |
'''Exercise 1: Write a while loop that starts at the last character in the string and works its way backwards to the first character in the string,
printing each letter on a separate line, except backwards.'''
fruit = 'banana'
# print(fruit[-1])
index = -1
#length = len(fruit)
#index = length -1
while index < len(fr... |
'''
Exercise 3:
Encapsulate this code in a function named count, and generalize it so that it accepts the string and the letter as arguments.
word = 'banana'
count = 0
def count(word):
for letter in word:
if letter == 'a':
count = count + 1
print(count)
count('word')
#print(c... |
def computepay(hours, rate) :
if float_hours > 40 :
pay = float(hours) * float(rate)
overtime = (float_hours - 40.0) * (float_rates * 0.5)
pay = pay + overtime
else:
print("Regular")
pay = float(hours) * float(rate)
return pay
hours = input('Enter Hours:')
rate = inp... |
'''
To return a result from a function, we use the return statement in our function.
For example, we could make a very simple function called addtwo that adds two numbers together and returns a result.
'''
def addtwo(a, b):
added = a + b
return added
x = addtwo(3, 5)
print(x) |
'''
7.2 Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form:
X-DSPAM-Confidence: 0.8475
Count these lines and extract the floating point values from each of the lines and compute the average of those values and produce an output as shown below.... |
'''
We can use this regular expression in a program to read all the lines in a file and print out anything that looks like an email address as follows:
'''
# Search for lines that have an at sign between characters
import re
hand = open('mbox-short.txt')
for line in hand:
line = line.rstrip()
x = re.findall('\... |
'''
Exercise 1: [wordlist2]
Write a program that reads the words in words.txt and stores them as keys in a dictionary.
It doesn't matter what the values are.
Then you can use the in operator as a fast way to check whether a string is in the dictionary.
'''
word_list = dict()
file = open('words.txt')
for word in fi... |
import json
# That is probably not the best way to create a .json file. But it is much easier than generation of object having
# necessary format.
def create_json(output_path, user_name, task_1_result, task_2_result):
with open(output_path, 'w') as file:
file.write("{\n")
file.write('"user": ' + ... |
#!/usr/bin/env python3
"""Exercice 7 (Partie Pile) du TP5"""
def est_vide(fil):
"""Retourne True dans le cas ou la pile et vide"""
assert isinstance(fil, list)
if fil == []:
return True
return False
def enfiler(fil, element):
"""enfile un element sur le fil en parametre"""
assert isins... |
#!/usr/bin/env python3
"""Programme qui échange la casse d'une chaine de characteres en entrée"""
def main():
"""Echange la casse manuellement"""
string = input("SwApCasE>> ")
swap_str = ""
for letter in string:
nbr = ord(letter)
if ord('A') <= nbr <= ord('Z'):
swap_str +=... |
#!/usr/bin/env python3
"""Check ipv4 compris entre 0 et 255"""
def check_ipv4(ipv4):
"""Check ipv4 compris entre 0 et 255"""
if len(ipv4) == 4:
return None
check = True
for i in ipv4:
if i < 0 or i > 255:
check = False
return check
def ipv4_from_ints(a1, a2, a3, a4):
... |
locations={
0:"you are studying python in your computer",
1:"you are standing on the road before a small brick building",
2:"you are at the top of a hill",
3:"you are inside the building",
4:"you are in a valley behind the stream",
5:"you are in a forest"
}
exits=[{"Q":0}, #THIS IS A LIST OF DI... |
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 18 09:37:53 2020
@author: 53013
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val... |
class Solution:
def calculate(self, s):
stack = ['#']
for x in s:
if x = ' ':
continue
if
print(calculate([],'1 6 54+ 5')) |
# -*- coding: utf-8 -*-
"""
Created on Fri May 7 15:54:26 2021
@author: 53013
"""
class Solution:
def __init__(self):
from collections import defaultdict
record = defaultdict(int)
def deleteAndEarn(self, nums):
if len(nums) <=2:
return max(nums)
n = len(nums)
... |
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 21 10:49:14 2020
@author: 53013
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def __init__(self):
self.record = {}
def... |
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 5 10:14:35 2020
@author: 53013
"""
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def __init__(self):
self.record = {}
de... |
""" Simple code that creates a segfault using numpy. Used to learn
debugging segfaults with GDB.
"""
import numpy as np
from numpy.lib import stride_tricks
def make_big_array(small_array):
big_array = stride_tricks.as_strided(small_array,
shape=(2e6, 2e6), strides=(32, 32)... |
"""
================================================================
Use the RidgeCV and LassoCV to set the regularization parameter
================================================================
"""
############################################################
# Load the diabetes dataset
from sklearn.datasets impo... |
"""
A simple, good-looking plot
===========================
Demoing some simple features of matplotlib
"""
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(5, 4), dpi=72)
axes = fig.add_axes([0.01, 0.01, .98, 0.98])
X = np.linspace(0, 2, 200)
Y = np... |
"""
Boxplot with matplotlib
=======================
An example of doing box plots with matplotlib
"""
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(8, 5))
axes = plt.subplot(111)
n = 5
Z = np.zeros((n, 4))
X = np.linspace(0, 2, n)
Y = np.random.random((n, 4))
plt.boxplot(Y)
plt.xti... |
"""
Bar plot advanced
==================
An more elaborate bar plot example
"""
import numpy as np
import matplotlib.pyplot as plt
n = 16
X = np.arange(n)
Y1 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)
Y2 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)
plt.bar(X, Y1, facecolor='#9999ff', edgecolor='w... |
# Author: Kevin Liu
# Problems available at https://leetcode.com/
# Start Date: 08/01/2021
# Start Time: 01:00 PM ET
# Complete Date:
# Complete Time:
# Note: Problem may or may not be completed in one sitting.
# Add Two Numbers
# https://leetcode.com/problems/add-two-numbers/
# You are given two non-empty linked l... |
# Author: Kevin Liu
# Problems available at https://leetcode.com/
# Start Date: 08/03/2021
# Start Time: 02:54 PM ET
# Complete Date: 08/03/2021
# Complete Time: 03:28 PM ET
# Note: Problem may or may not be completed in one sitting.
# Roman to Integer
# https://leetcode.com/problems/roman-to-integer/
# Roman numeral... |
import sys
def lower_bound(answer:list, num:int)->int:
low = 0
high = len(answer)-1
while low < high :
mid = (low + high)//2
if answer[mid] >= num :
high = mid
else :
low = mid + 1
return high
if __name__ == "__main__":
N = int(sys.stdin.readline())... |
import random
from copy import deepcopy
class Matrix:
def __init__(self, td_arr):
for row in td_arr:
for col in row:
if not isinstance(col, (int, float)):
raise Exception("Array should contain only numeric items!!!")
tuple_of_len = tuple(map(lambda... |
"""Uses word with blanks to generate the same word six times with varying numbers
of letters replaced by blanks "_"
"""
from random import randint
from baldpanda_site.worksheets.blanked_words.word_with_blanks import WordWithBlanks
class SixWordsWithBlanks:
"""Object repeating the same word six times with varying ... |
print("Привет, мой друг! я разрешаю тебе запустиь любой код пайтона")
name="Feda"
age=17
mass=55
print(("Hello, {}! {}, you yersold {:f}! and {} ").format(name, age, mass, name))
#print(" %(a)s %(b)i %(c)f %(a)s" %{"a":name,"b":age,"c":mass})
|
class MyList:
def __init__(self,l=[]):
#делает копию контейнера
self._l=list(l)
def __repr__(self):
return repr(self._l)
def __len__(self):
return len(self._l)
def __contains__(self,value):
return value in self._l
def __bool__(self):
return bool(self._... |
import numbers
class Number:
def __init__(self,value):
self.value=value
def __repr__(self):
return "Number {}".format(self.value)
def __add__(self,other):
#для сложение с другими числами
if isinstance(other,numbers.Number):
return Number(self.value+other)
... |
import os
import time
import random
def load_data():
with open('data.txt', 'r+', encoding='utf-8') as df:
words = [word for word in df]
return words
def random_name():
'''Pick up just a single word randomness from a list of words'''
random_word = random.choice(load_data())
return random_word
def no... |
"""
Tool for generating formulas
Given user's input for lmer, creates a formula and
its name
"""
def formula_creator():
"""
Creates a formula based on user's input for Lmer,
and a name describing the formula.
"""
outcome = input('Input outcome value:')
print()
level_list = []
print('I... |
#!/usr/bin/env python
# Just run the program, give it a key, give it your message,
# give the key to your friend, let him run the program,
# give it the key, give it the encoded text and you're done.
import string
def encrypt():
while True:
try:
key = input("Please enter the encryption key (a whole number... |
'''
Created on Oct 17, 2020
@author: maria
'''
#import NumPy
import numpy as np
#create structured data type
dt = np.dtype('i1')
#create array using structured data type
arr = np.array([(-1),(0),(3),(4)], dtype = dt)
print('Before converting')
print(arr)
print(arr.dtype)
print('\n')
#convert data type
newarr = arr.as... |
'''
Created on Jan 26, 2021
@author: maria
'''
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
langs = ['English', 'Spanish', 'German', 'Russian']
students = [50, 34, 20, 28]
plt.bar(langs, students)
ax.set_ylabel('Numbers of Students')
ax.set_title('Number of students in language class... |
'''
Created on Oct 29, 2020
@author: maria
'''
str1 = 'Hello'
print('test len function')
print(len(str1))
print('\n')
class Employees:
#create blueprint of an instance of this class
empCount = 0
def __init__(self, name, year):
self.name = name
self.year = year
Employees.empCount +=... |
#!/usr/bin/python3
# classes.py by Bill Weinman [http://bw.org/]
# This is an exercise file from Python 3 Essential Training on lynda.com
# Copyright 2010 The BearHeart Group, LLC
class Animal:
def talk(self): print ('I have something to say')
def walk(self): print (' Hey! I'' walking here!')
def clothes(s... |
#!/usr/bin/python3
# functions.py by Bill Weinman [http://bw.org/]
# This is an exercise file from Python 3 Essential Training on lynda.com
# Copyright 2010 The BearHeart Group, LLC
## use one star argument, *arg, and two star variable(keyword argument) for passing arbitrary arguments to function
# *arg, pass as all ... |
# Pregunta diferentes tipos de datos, sin validación.
fecha y hora de importación
# Los datos se tienen, se preguntan o se calculan.
# y pueden ser de diferente tipo.
def main ():
# Los datos string se preguntan y procesan sin intermediación.
strDato = input ( "Dame un dato string:" )
# Los datos numéricos se p... |
# list of valid command names
valid_commands = ['off', 'help', 'forward', 'back', 'right', 'left', 'sprint','replay',\
'reverse','replay silent','replay reversed','replay reversed silent']
# variables tracking position and direction
position_x = 0
position_y = 0
directions = ['forward', 'right', 'back', 'left','sprin... |
# TODO: Step 1 - get shape (it can't be blank and must be a valid shape!)
def get_shape():
shape = ' '
while shape == ' ':
shape = input("Shape?: ")
shape = shape.lower()
if shape == 'pyramid' or shape == 'square' or shape == 'triangle' or shape == 'diamond' or shape=='x':
... |
# Make sure your output matches the assignment *exactly*
computer_usage = int(input())
if computer_usage < 2:
print("That seems reasonable")
elif computer_usage < 4:
print("Do you have time for anything else?")
else:
print("You need to get outside more!")
|
factorial = int(input())
prod = 1
while factorial != 1:
prod *= factorial
factorial -= 1
print(prod)
|
student_score = float(input())
total_score = float(input())
grade_percentage = (student_score / total_score) * 100
if grade_percentage > 90.0:
print("A")
elif grade_percentage > 80.0:
print("B")
elif grade_percentage > 70.0:
print("C")
elif grade_percentage > 60.0:
print("D")
else:
print("F")
|
scores = input().split()
# put your python code here
incorrect_count = 0
correct_count = 0
for i in scores:
if i == 'I':
incorrect_count += 1
elif i == 'C':
if incorrect_count < 3:
correct_count += 1
else:
continue
if incorrect_count < 3:
print("You won")
el... |
import random
from cards import Card
from property import valid_suits, valid_ranks
class Deck:
"The Deck class is a collection of 52 cards. "
def __init__(self):
self._cards =[ Card(s,n) for s in valid_suits for n in valid_ranks]
print (self._cards)
print (len(self._cards))
def shuffle(self):
ran... |
import unittest
from wordCount import wordCount
w1 = wordCount()
class testPalindrome(unittest.TestCase):
def test_count(self):
self.assertEqual(w1.wordCount('Hello'), 1)
self.assertEqual(w1.wordCount('My name is.'), 3)
self.assertEqual(w1.wordCount('This sentence has five words.'), 5)
... |
from bs4 import BeautifulSoup
from requests import get
# practice scraping the local HTML file alice.html
def main():
# open alice.html as read-only and read
f = open('alice.html', 'r')
s = f.read()
# use BeautifulSoup to parse the HTML file
soup = BeautifulSoup(s,'html.parser')
# print out t... |
#!/usr/bin/env python3
'''
Write a program that will take a list of words as input and will return back
the longest word and its length in one tuple.
Example:
input: ['Python', 'is', 'a', 'widely', 'used', 'high-level', 'programming',
'language', 'for', 'general-purpose', 'programming,', 'created',
'b... |
print('hiya Joshua! I am going to show you the fibunacci sequence\n it is a series where the previous number is added to the next number in the sequence')
print('i will ask for a number, this number will correspond to the\n number of numbers in the sequence i will print to the screen')
show = int(input('So Joshua, how... |
def bubble_sort(ar):
count = 0
for i in range(len(ar)-1,0,-1):
for x in range(i):
if int(ar[x]) > int(ar[x+1]):
ar[x], ar[x+1] = ar[x+1], ar[x]
print(ar)
count +=1
print(count)
return ar
ar = input("Enter the list of numbers to be sorted: ")
... |
#github python challenge
#With a given integral number n, write a program to generate
# a dictionary that contains (i, i*i) such that is an integral number between
# 1 and n (both included). and then the program should print the dictionary.
def lim(n):
ret = {}
for i in range(1,n+1):
ret[i] = i... |
print('''Hiya Joshua, Montblanc here, I have an exercise for you!
I am gonna ask for two input from you!''')
a = input('PUT Your first input here, must be a number kupo!: ')
b = input("Second Input kupo!: ")
print('this is what happens when we add your inputs like this,' + a +" + " + b + "= " + a+b)
print('This is wha... |
import calendar
from datetime import date
day_of_week_dict = {"Monday":0, "Tuesday":1, "Wednesday":2, "Thursday":3, "Friday":4, "Saturday":5, "Sunday":6}
week_dict = {"1st":[1], "2nd":[2], "3rd":[3], "4th":[4], "5th":[5], "teenth":[13, 14, 15, 16, 17, 18, 19]}
def meetup(year, month, week, day_of_week):
c = [i fo... |
# Print The String
# print("day-1\nPython Function")
# String Concatination
# print("Hello "+"Srikanth")
# Decleration of Variable and Printing The same
# msg = "Hi! to every one"
# print(msg)
# Taking Input And Printing The Same
# print("Hello "+input("What Is Your Name ?"))
# Code To Caliculate The Number Of Char... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
import random
def randrepl(matchobj):
# Strategy:
# 'abcde' -> ['a'], ['b', 'c', 'd'], ['e']
# -> ['a'], ['c', 'd', 'b'], ['e']
# -> ['a', 'c', 'd', 'b', 'e']
# -> 'abdbe'
inner = list(matchobj.group(1))
... |
#!/usr/bin/env python
import numpy as np
def sudoku_solve():
global solved
global curr_no_of_cells_filled
global current_solution
global mins
global count_of_options
global list_of_options
if solved == 1:
return 0
if option_calculator() == 0:
local_list_of_options = ... |
f_name = input("What's your first name?: ").capitalize()
l_name = input("What's your last_name?: ").capitalize()
course = input("Name of your course?: ").lower()
students = int(input("How many students are there in you class:? "))
print(f'My name is {f_name}, and my last name is {l_name}.\nI am participating in t... |
#a
students = ['Rasmus','Susan','Fredrik','Aleksis','Tonje']
#b
print(students[2])
#c
print(students[2][0])
#d
students[2]='Ole'
#e
students[2] += ' Nordmann'
#f
students.append('Johan')
#g
students.insert(4,'Monty Python')
print(students)
#h
print(len(students))
students.remove('Ole Nordmann')
print(len(students))
... |
#거북이 만든다.
import turtle
wn=turtle.Screen()
t1=turtle.Turtle()
#배경을 그리자.
bg=open('background.txt')
mycoords=[]
t1.pensize(3)
t1.speed(10)
for i in range(0,28,2):
for line in fres:
line1=line.split(',')
mycoords.append(line[i],line1[i+1].strip())
for coord in mycoords:
x1=int(coord... |
sum=0
for i in range(1,1000):
if i %3==0 or i%5==0:
result=sum=sum+i
print result |
list={'Sanket':20,'Saksham':15,'Priyanka':20}
check = input('Enter the key')
if check in list:
print(list[check])
|
#!/usr/bin/env python
# coding: utf-8
# # Module 1
# #### In this assignment, you will work with ufo sightings data.
# - The data includes various data points about individual ufo sightings
# - Data File(s): ufo-sightings.csv
# In[1]:
###########################################################
### EXECUTE THIS CEL... |
#!/usr/bin/python
from rps_lib import \
RpsCommand, Player, RpsLogic, RpsStats
RPS_SCORE_FILENAME = "scores.txt"
def main():
print "******"
print "Rock Paper Scissors"
print "******"
player_one_wins = 0
player_two_wins = 0
num_draws = 0
stats = RpsStats.load_stats(RPS_SCORE_FILENAME)
if stats:
... |
import numpy as np
# for i in range(len(list)):
# exp = list[i]
# index = alphabet.index(str(exp))
# new_index = index + 2
# if new_index > (len(alphabet)-1):
# new_index = (new_index - len(alphabet)) + 1
# encrypted_input[i] = alphabet[new_index]
# encrypt = encrypted_input[0] + encrypted... |
class Solution(object):
def run(self):
print(str(self.isValid('()')) + ' expected true')
print(str(self.isValid('(]')) + ' expected false')
print(str(self.isValid('([]]')) + ' expected false')
print(str(self.isValid('[(])')) + ' expected false')
print(str(self.isValid('{()[... |
# Missing Number
from typing import List
class Solution:
def run(self):
nums = [0,2,1]
print(f'{self.missingNumber(nums)} - expected 0')
def missingNumber(self, nums: List[int]) -> int:
# Sum of [1,n] = n*(n+1)/2
# x+S = n*(n+1)/2, S is sum of array
# x = Su... |
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def __str__(self):
if self is not None:
return f'{self.val}: [{self.left},{self.right}]'
return 'None'
class Solution(object)... |
# Add Two Numbers
class ListNode(object):
def __init__(self, x, next=None):
self.val = x
self.next = None
def __str__(self):
if self is not None:
if self.next:
return f'{self.val}: {self.next}'
else:
return f'{self.val}'
... |
# Non-decreasing Array
from typing import List
class Solution:
def run(self):
nums = [4,2,3,4,5]
print(f'{self.checkPossibility(nums)} - expected True')
nums = [4,2,1]
print(f'{self.checkPossibility(nums)} - expected False')
nums = []
print(f'{self.check... |
#!/usr/local/bin/python
import sys
def incrementa(num, base):
max = True
for p in num:
if p != base - 1:
max = False
break
if max:
num[0] = 1
for i in range(1, len(num)):
num[i] = 0
num.append(0)
return num
if num[-1] < bas... |
#线性插值法
def linear(x,x1,x2,y1,y2):
if x2-x1==0:
result=y1
else:
result=y1+(x-x1)*(y2-y1)/(x2-x1)
return result |
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 28 17:09:33 2019
@author: Kleber
"""
# Classe simples de grafo com principais funcionalidades
class Grafo(object):
"""
inicializa um objeto do tipo grafo
se nao tiver dicionario ou nada for dado,
um dicionario vazio sera usado
"""
... |
import random
class Dice():
def __init__(self, dice = [6,6], JailRoll = 3):
if not isinstance(dice, list):
raise TypeError("dice must be a list")
if not isinstance(JailRoll, int):
raise TypeError("JailOnRoll must be set to an integer")
self.dice = dice
self.JailOnRoll = JailRoll
self.Do... |
import os
import re
def rename_files():
# (1) get file names from a folder
file_list = os.listdir(r"C:\Users\akash\Downloads\prank")
# print(file_list)
saved_path = os.getcwd()
print("Current Working Directory is " + saved_path)
os.chdir(r"C:\Users\akash\Downloads\prank")
# (2) for each f... |
import numpy as np
def softmax(input):
"""
Takes numpy array as input and returns a list of probablities of each class
"""
return np.exp(input)/sum(np.exp(input))
def sigmoid(x):
return 1 / (1+np.exp(-x))
def relu(x):
return np.max(0, x)
# def tanh(x):
# return |
# Each vertex in theoritical array of vertices
class Vertex:
def __init__(self,v):
self.id = v
self.adjacent = []
def addAdjacent(self,vertex,weight=0):
self.adjacent.append([vertex,weight])
class Graph:
def __init__(self):
#List of vertex objects
#In form of []->[[... |
#!/usr/bin/env python3
import argparse
import os
def compare(f1, f2, type):
with open(f1, 'r') as fp:
# readlines() returns a list of lines with '\n' included.
list1 = fp.readlines()
with open(f2, 'r') as fp:
list2 = fp.readlines()
filename = '{}-{}-{}'.format(os.path.basename(f... |
# python3
import sys
import threading
class Node:
def __init__(self, val):
self.val = val
self.children = []
def createTree(nodes) :
root = None
for node in nodes :
if node.val == -1:
root = node
else :
nodes[node.val].children.append(node)
retu... |
class Point:
def __init__(self, x, y):
self.x = float(x)
self.y = float(y)
def collinear(self, p, q):
if p.x - self.x == 0 and q.x - self.x == 0:
return True
if p.x - self.x == 0 or q.x - self.x == 0:
return False
m1 = (p.y-self.y)/(p.x-self.x)
m2 = (q.y-self.y)/(q.x-self.x)
return m1 == m2
... |
# vi:et:ts=4 sw=4 sts=4
"""
This module contains the RegexParser and Pattern decorator
"""
import logging
import re
from pyparser import Parser
_ATTRIBUTE_NAME = '_pyparser_re_pattern'
class pattern(object):
"""
This class is a decorator that'll attach a regular expression attribute
to a function tha... |
class Max_heap:
# heap is an adt: abstract data type
# it is a complete binary tree
# max heap is a heap that parent is always bigger than childs
# it has 2 basic func
# max() to return the max value
# extract_max() to pop the max value and maintain the rest a max heap
# if you keep the resu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.