text stringlengths 37 1.41M |
|---|
from utils.binary_tree_helper import arr_to_binary_tree_helper
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def smallestFromLeaf(self, root: 'TreeNode') -> 'str':
def path_helper(cur,... |
class Calculator:
def add(self, num1, num2):
return num1 + num2
def subtract(self, num1, num2):
return num1 - num2
def multipy(self, num1, num2):
return num1 * num2
def divide(self, num1, num2):
if num2 == 0:
return 0
return num1 / num2
|
#Developer: Tyler Smith
#Date: 11.06.16
#Purpose: Program is intended to provide an interactive
# GUI experience for a user to have three options
# of which program they want to use on the main
# popup. The three programs that the user can use
# are the BMI calculato... |
#1
print('1')
print('''Twinkle, twinkle, little star,
How I wonder what you are!
Up above the world so high,
Like a diamond in the sky.
Twinkle twinkle little star,
How I wonder what you are''')
print('----------------------------------')
#2
print('2')
import sys
print("Python version")... |
# Author: Pavel Baranek
def welcome_phrase():
welcome = "Welcome in the game of TicTacToe!!!"
welcome1 = welcome.center(75)
print(len(welcome1) * "*")
print(welcome1)
print(len(welcome1) * "*")
def show_rules():
rules = """
THE RULES OF THE GAME ARE:
Two players a... |
import numpy as np
import random
import matplotlib.pyplot as plt
"""
Perceptron Class.
Does the perceptron training with the l2 regularisation coefficient.
"""
class Perceptron():
"""
init function.
no_of_inputs = 4. - Number of varibles in data set.
threshold = 20. - Number of iterations.... |
# # finding largest element
# def largest(root_node):
# if root_node.right:
# return largest(root_node.right)
# return root_node.value
# if the rightmost node in the binary search tree
# has a left subtree, then the 2nd largest element (in the overall tree)
# is the rightmost element in the subtree, or... |
import csv
import random
import math
import operator
def loadDataset(filename, split, trainingSet=[] , testSet=[]):
with open(filename, 'r') as csvfile:
lines = csv.reader(csvfile)
dataset = list(lines)
for x in range(len(dataset)-1):
for y in range(4):
dataset[x][y] = float(datas... |
import pygame
## window constants, these will be adjusted upon calling start_display
display_width = 600
display_height = 600
# colors
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
purple = (255, 0, 255)
###################### example class ######################... |
import sys
def factorial(n):
result = 1
for i in range(1, n+1):
result *= i
return result
def main(args):
print("Welcome to the Factorial Calulator!")
num = -1
cont = "y"
while (cont == "y") :
while (num < 1 or num > 10) :
num = input("enter an Integer that's gr... |
import re
re.match(r'^\d{3}\-\d{3,8}$', '010-12345')
re.match(r'^\d{3}\-\d{3,8}$', '010 12345')
test = '010 12345' #
if re.match(r'\d{3}\s\d{3,8}$', test): #
print('ok')
else:
print('failed')
m = re.match(r'^(\d{3})-(\d{3,8})$', '010-12345')
print(m)
print(m.group(1))
re.match(r'[^0-9]',test)
if re.match(r'... |
"""Find window of time when most authors were active.
For example::
>>> data = [
... ('Alice', 1901, 1950),
... ('Bob', 1920, 1960),
... ('Carol', 1908, 1945),
... ('Dave', 1951, 1960),
... ]
>>> most_active(data)
(1920, 1945)
(Alice, Bob, and Carol were all active the... |
#*********************************************#
#
# Review one Issue in Lecture 3
#
#*********************************************#
import numpy as np
import pandas as pd
from pandas import Series, DataFrame
alist = [1,2,3]
result = [(0 if c>2 else c) for c in alist]
print("alist:\n",result)
nlist = []
for c in al... |
# if and else statements with loop introduction
word = ['Tokyo','Taj Mahal', 'Pertarico', 'Honalulu', 'Vancover']
new_city = 'Fremont'
for city in word:
if new_city not in word:
print('\nOh, \n\n this is a city....\n\t let me add it:\n' + new_city + '\n\t\t')
word.append(new_city)
print(word)
# if-elif-else
a... |
import math
from functools import reduce
def lcm(a, b):
return a*b//math.gcd(a, b)
print(reduce(lcm, range(1, 21))) |
class Solution(object):
def isToeplitzMatrix1(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: bool
"""
dic = {}
m, n = len(matrix), len(matrix[0])
for i in range(m):
for j in range(n):
if (i - j) not in dic:
... |
from collections import defaultdict
from collections import deque
class Solution:
def solveSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""
row, column, square, visited = defaultdict(set), defaultdi... |
from functools import cmp_to_key
class Solution:
def largestNumber(self, nums):
"""
:type nums: List[int]
:rtype: str
"""
def compare(x, y):
if int(x + y) > int(y + x):
return -1
else:
return 1
nums = sorted(list... |
class Solution:
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
dic_r = [{},{},{},{},{},{},{},{},{}]
dic_c = [{},{},{},{},{},{},{},{},{}]
dic_s = [{},{},{},{},{},{},{},{},{}]
for i in range(9):
for j in ran... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def generateTrees1(self, n):
"""
:type n: int
:rtype: List[TreeNode]
"""
if n == 0:
r... |
# Definition for singly-linked list with a random pointer.
# class RandomListNode(object):
# def __init__(self, x):
# self.label = x
# self.next = None
# self.random = None
class Solution(object):
#O(n) space complexity
def copyRandomList1(self, head):
"""
:type head... |
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, left, right):
self.val = val
self.left = left
self.right = right
"""
class Solution(object):
def treeToDoublyList1(self, root):
"""
:type root: Node
:rtype: Node
"""
if not ro... |
# Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution(object):
#Binary search
def insert(self, intervals, newInterval):
"""
:type intervals: List[Interval]
:type newInterval: Interval
... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
#Space complexity:o(n)
def detectCycle1(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
node, ... |
class Solution:
def findMin1(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
t = nums[0]
while nums[0] > nums[-1]:
t = nums[-1]
nums = nums[:-1]
return t
def findMin2(self, nums):
if len(nums) == 1:
... |
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
re = str(x)[::-1]
while re[0] == '0' and len(re) > 1:
re = re[1:]
if re[-1] == '-':
re = '-' + re[:-1]
re = int(re)
return 0 if x >= 2**31 or... |
import functools
class Solution:
def fractionToDecimal(self, numerator, denominator):
"""
:type numerator: int
:type denominator: int
:rtype: str
"""
if numerator == 0:
return "0"
is_positive = (numerator > 0) is (denominator > 0)
numerator... |
class Node:
def __init__(self, val):
self.next = None
self.prev = None
self.val = val
self.key = None
class LRUCache:
def __init__(self, capacity):
"""
:type capacity: int
"""
self.capacity = capacity
self.size = 0
self.ha... |
price = float(input("Enter the price: "))
percentage = int(input("Enter the tip percentage: "))
def percent_to_decimal(x):
return x/100
decimal = percent_to_decimal(percentage)
def tip(y, z):
return y * z
tip_amount = tip(price, decimal)
print(tip_amount)
|
# DICTIONARIES
airport_code = "IAH"
airport_name = "Intercontinental Airport"
# Dictionary = {Key: Value}
# creating a dictionary
airport = {"IAH": "Intercontinental Airport" }
# access value from a dictionary
name = airport["IAH"]
print(name)
# Car -- make and model
car = {"make": "Honda", "model": "Accor... |
total = float(input("Enter the total: "))
tip_percentage = int(input("Enter your tip percentage: "))
def decimal(x):
return x/100
tip_decimal = decimal(tip_percentage)
def tip_calc(y, z):
return y * z
tip = tip_calc(total, tip_decimal)
def combine(a, b):
return a + b
total_amnt = comb... |
class Node:
def __init__(self, val):
self.val = val
self.next = None
class LL:
def __init__(self):
self.head = None
def insert(self, value):
n = Node(value)
print ('n.val', n.val)
if self.head == None:
print ('list empty')
self.head =... |
# TODO
# Given a 10 character string with F, B, L, R, use binary space partitioning
# to find which of the rows from 1 to 128 on a plane a code corresponds to
# e.g FBFBBFFRLR:
# 0) Start with the whole range, 0 to 127
# 1) F means lower half, 0 thru 63
# 2) B means upper half, 32 thru 63
# 3) F means lower half, mean... |
while True:
# get sentence from user
original = input("What would you like to translate?: ").strip().lower()
# split sentence into individual words
words = original.split()
# translate each word (loop through each word and convert)
new_words = []
# if word starts with vowel, add "yay"
for word i... |
string_of_words = input('Введите несколько слова через пробел: ')
entered_words = string_of_words.split(' ')
for ind, el in enumerate(entered_words, 1):
if len(el) > 10:
el = el[0:10]
print(f"{ind}. {el}") |
"""
题目:随机生成校验码
解析:
1. python pillow库的使用
2. 随机数的使用
步骤:
1. 导入庫函数
2. 定义图片颜色
3. 定义字体颜色
4. 定义随机字体的生成
5. 设置画布
6. 设置画笔
7. 在画布上画背景和字体
"""
# 导入庫函数
import os
import string
import random
from PIL import Image, ImageFont, ImageDraw, ImageFilter
# 定义背景颜色
def ran_color():
return (random.randint(64, 255),
r... |
#Library - Harish
#June 2021
#function
def greet():
print("Good Morning User!")
#function with return tuple type
def check_vowel(arg):
vowel ="aeiou"
l1 = list()
for ch in arg:
if ch in vowel:
l1.append(ch)
print("Vowel found :", end=" ")
for i in range(len(l1)):
... |
# Create open list
# Create closed list
# Define Maze
# Define Start and End node
# Add Start to Open_list
# Current = Start
# While(Open_list==0)
# N_up: Check if it is obstacle or
# How to select current?
# # importing the required module
import matplotlib.pyplot as plt
import numpy as np
def main():
# ma... |
def add_overflow(numberA, numberB, base):
temp = ''
for i in range(base):
temp += '1'
temp = int(temp, 2)
comA = format(numberA & temp, '0' + str(base) + 'b')
comB = format(numberB & temp, '0' + str(base) + 'b')
strA = str(comA)
strB = str(comB)
plus = 0
count = base
resu... |
def fib(n):
if n < 3:
return 1
else:
output=fib(n-2)+fib(n-1)
print(str(output)+' ')
return output
if __name__ == "__main__":
print(str(fib(23)))
# a = 1
# b = 1
# c = 0
# for i in range(23):
# print(a)
# c = a + b
# a = b
# b... |
from get_name import get_name
print("Enter 'q' at any time to quit.")
while True:
first_name = input("\nPlease enter your first name:")
if first_name == "q":
break
last_name = input("Please give me a last name:")
if last_name == "q":
break
name = get_name(first_name,last... |
#斐波那契数列递归计算f(n)的值
def fib(n):
if n ==0:
return 0
elif n ==1:
return 1
else:
return fib(n-1)+fib(n-2)
n = int(input(":"))
fib(n)
print(fib(n))
#我不知道在Leetcode怎么回事提交就一直显示fib没有定义
|
#在闭区间范围内统计奇数数目
class Solution:
def countOdds(self, low: int, high: int) -> int:
result = []
for x in range(low,high+1):
if x%2 == 0:
continue
else :
result.append(x)
return len(result)
low = int(input('please enter low value:'))
high =... |
class Queue_Error(Exception):
def Queue_Overflow(self):
print('Queue overflow')
def Queue_Undeflow(self):
print('Queue underflow')
'''
Queue Dict: using this method will leave a empty space, because to verify the fullness of the queue
we use this condition: q.head == q.tail+1, but at... |
class Node():
def __init__(self,data):
self.data = data
self.next = None
class Link_Error(Exception):
def Not_Found(self,data):
print('%d not found' % data)
class Single_Link_List():
def __init__(self):
self.head = None
self.temp = None
self.Lenght = 0
... |
import time as t
from os import path
def createFile(dest):
'''
the script creates a text fileat the passed in location
names file based on date
'''
date=t.localtime(t.time())
##FileName = Month_Day_Year
name='%d_%d_%d.txt'%(date[1],date[2],(date[0]%100))
if not (pat... |
'''
We are given a binary tree (with root node root), a target node, and an integer value K.
Return a list of the values of all nodes that have a distance K from the target node. The answer can be returned in any order.
Example 1:
Input: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, K = 2
Output: [7,4,1]
E... |
from unittest import TestCase
import ddt
class Solution:
def permuteUnique(self, nums):
ans=[]
nums.sort()
visited=set()
def DFS(perm, other_nums):
if not other_nums:
visited.add(''.join(perm))
ans.append(perm)
return
... |
'''
Given a non-empty array of integers, return the k most frequent elements.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2:
Input: nums = [1], k = 1
Output: [1]
Note:
You may assume k is always valid, 1 <=
k <= number of unique elements.
Your algorithm's time complexity must be better than... |
from collections import defaultdict
from unittest import TestCase
import ddt
'''
Write a program to solve a Sudoku puzzle by filling the empty cells.
A sudoku solution must satisfy all of the following rules:
Each of the digits 1-9 must occur exactly once in each row.
Each of the digits 1-9 must occur exactly once ... |
from unittest import TestCase
import ddt
'''
Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Example:
Given array nums = [-1, 2, 1, -4], ... |
from unittest import TestCase
import ddt
'''
Single Number
Given a non-empty array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1:
Input: [2,2,1]
Output: 1
Exa... |
from unittest import TestCase
import ddt
'''
Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.
Note that it is the kth smallest element in the sorted order, not the kth distinct element.
Example:
matrix = [
[1, 5, 9],
[6, ... |
class WordList:
def __init__(self, word_list_path):
self.word_list_path = word_list_path
self.word_list = []
self.__read_word_list()
def __read_word_list(self):
with open(self.word_list_path, 'r') as file:
for line in file:
if line:
... |
#! /usr/bin/env python3
# we will store the current largest number here
matched = "Well done, Friend! You are free now."
# input the first value
number = int(input("Enter the magic number: "))
while number != 777:
# is number larger than largest_number?
if number == matched:
# yes, update largest_numb... |
# this class implements an iterator
# python needs to be told when to stop iterating, this is done by raising StopIteration exception
class ReverseString():
def __init__(self, data):
self.data = data
self.index = len(data)
def __iter__(self):
return self
def __next__(self):
... |
import math
from World.node import *
import sys
def dir_dist(node1, node2):
"""
Calculates the direct distance bewteen each points
"""
return math.sqrt(math.pow(node1.x - node2.x, 2) +
math.pow(node1.y - node2.y, 2))
def shortest_dist(agent_pos, containers_pos, cont_goals):
"... |
# https://leetcode.com/problems/search-a-2d-matrix
class Solution(object):
# Time complexity: O(logM + LogN)
# Space complexity: O(1)
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if not matrix or... |
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if (len(s) != len(t)):
return False
else:
return collections.Counter(s) == collections.Counter(t)
# Time complexity: O(N)
# Spac... |
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: Tre... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 6 17:00:07 2020
@author: conpucter
"""
'''
this task is not done yet
this search doesn't work with extreme numbers like 0 and 73
'''
array = [0, 1, 21, 33, 45, 45, 61, 71, 72, 73]
target = 71
def array_keeper(array):
print("array keeper i\'m ... |
"""
CP1404/CP5632 Practical
Demos of various os module examples
"""
import shutil
import os
def main():
"""Demo os module functions."""
print("Starting directory is: {}".format(os.getcwd()))
# Change to desired directory
os.chdir('Lyrics/Christmas')
# Loop through each file in the... |
import random
def main():
score = int(input('Enter your score: '))
result=get_result(score)
random_score = random.randint(0, 100)
print('Random score:',random_score)
result = get_result(random_score)
def get_result(score):
if score<50:
print('Your result is Fail')
elif ... |
FILENAME = "subject_data.txt"
def main():
data = get_data()
print(data)
print(get_details())
def get_data():
"""Read data from file formatted like: subject,lecturer,number of students."""
input_file = open(FILENAME)
list = []
for line in input_file:
line = line.strip(... |
import unittest
from problem import is_valid_credit_card
def test_with_valid_credit_cards():
numbers = [
49927398716,
378282246310005, # AMEX
6011111111111117, # DISCOVER
5555555555554444, # MASTERCARD
4111111111111111 # VISA
]
for number in numbers:
as... |
def validate_palindrom_using_for_loop(string):
n = len(string)
start = 0
end = n-1
for i in xrange(n/2):
if not(string[start].isalnum()):
start += 1
continue
elif not(string[end].isalnum()):
end -= 1
continue
elif(string[start] != s... |
# Define a function max() that takes two numbers as arguments and returns the largest of them. Use the if-then-else construct available in Python
def max(num1,num2):
''' takes two numbers and return maximum of them'''
if num1 > num2:
return num1
return num2
if __name__ == "__main__":
inputs = r... |
# Represent a small bilingual lexicon as a Python dictionary in the following fashion {"merry":"god", "christmas":"jul", "and":"och", "happy":gott", "new":"nytt", "year":"ar"} and use it to translate your Christmas cards from English into Swedish. Use the higher order function map() to write a function translate() that... |
def check_palindrom_using_inbuilt_functions(input_string):
inp = list(input_string)
rev = list(input_string)
rev.reverse()
if inp == rev:
print "palindrom"
else:
print "not palindrom"
def validate_palindrom_using_for_loop(string):
n = len(string)
for i in xrange(n/2)... |
#A pangram is a sentence that contains all the letters of the English alphabet at least once, for example: The quick brown fox jumps over the lazy dog. Your task here is to write a function to check a sentence to see if it is a pangram or not.
def pangram(string):
result = "Pangram"
all_char = [x for x in rang... |
# Write a function that takes a character (i.e. a string of length 1) and returns True if it is a vowel, False otherwise.
def is_vowel(character):
vowels = "aeiou"
return character.lower() in vowels
if __name__ == "__main__":
char = raw_input("Enter single character: ")
print is_vowel(char)
|
class Father:
def __init__(self):
print("__init__() of Father ")
self.name = "Gaurav"
class Mother:
def __init__(self):
print("__init__ of Mother ")
self.name = "Maity"
# Order of 'Mother' and 'Father' decides whose members are accessed if they have same member names
# Whichever class-name comes firs... |
import math
class Point:
def __init__(self, p1, p2):
self.__p1 = p1
self.__p2 = p2
def __str__(self):
return "A message from point (" + str(self.__p1) + "," + str(self.__p2) + ")"
# Overloading '+' operator, __add__() is fixed
def __add__(self, point_object):
return Point(self.__p1 + point_object.__p1, ... |
class BTNode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def BTInput():
n = int(input())
if n == -1:
return None
new_node = BTNode(n)
new_node.left = BTInput()
new_node.right = BTInput()
return new_node
def BTPrint(root):
if root == None:
return
print(f"{... |
class BTNode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def BTInput():
n = int(input())
if n == -1:
return None
new_node = BTNode(n)
new_node.left = BTInput()
new_node.right = BTInput()
return new_node
def BTPrint(root):
if root == None:
return
print(f"{... |
c = "#"
s = input("Enter a string containing duplicates : ")
def DelimitDuplicate(s, si):
# Base case when si reached the end of string
if si >= len(s)-1:
return s
if s[si] == s[si + 1]:
modified_string = s[:si+1] + c + s[si+1:]
return DelimitDuplicate(modified_string, si + 1)
... |
class BTnode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def BTinput():
new_node = int(input("-> "))
if new_node == -1:
return
else:
root = BTnode(new_node)
root.left = BTinput()
root.right = BTinput()
return root
def BSTinput(l):
if len(l) == 0:
return Non... |
class Node:
def __init__(self, data):
self.data = data
self.next = None
def print_list(self, head):
ptr = head
while ptr is not None:
print(f"{ptr.data}->", end = ' ')
ptr = ptr.next
print("None")
def length(self, head):
ptr = head
count = 0
while ptr is not None:
count += 1
ptr = ... |
import sys
sys.setrecursionlimit(5000)
n = int(input("Enter the number to search : "))
user_input = input("Enter the list (space separated) : ")
input_list = [int(i) for i in user_input.strip().split(' ')]
# Recursive approach
def FindNumber(index):
if input_list[index] == n:
print(f"{n} found at index : {index}")... |
# Implementing graphs using adjacency matrix
class Graph:
def __init__(self, nVertices):
self.nVertices = nVertices
self.adjMatrix = [[0 for i in range(nVertices)] for j in range(nVertices)]
def addEdge(self, v1, v2):
if (v1 > self.nVertices - 1) or (v1 < 0) or (v2 > self.nVertices - 1) or (v2 < 0):
return... |
input_string = input("Enter the string : ")
c = input("Enter the character to be replaced : ")
r = input(f"Enter the character which replaces {c} : ")
new_list = list(input_string)
for index in range(0, len(new_list)):
if new_list[index] == c:
new_list[index] = r
result_string = ''.join(new_list)
print(result_str... |
import queue
class TreeNode:
def __init__(self, data):
self.data = data
self.children = list()
def levelWiseInput():
q = queue.Queue()
n = int(input("Enter the root node : "))
root = TreeNode(n)
q.put(root)
while not q.empty():
node = q.get()
print(f"How many children does {node.data} have ?", end = '... |
import sys
def lcs(str1, str2, i, j, dp):
if (i > len(str1) - 1) or j > (len(str2) - 1):
return 0
# If the ith and jth elements of str1 and st2 respectively, are same
if str1[i] == str2[j]:
if dp[i+1][j+1] == None:
smallans = lcs(str1, str2, i+1, j+1, dp)
dp[i+1][j+1] = smallans
ans = 1 + smallans... |
def printSumToK(l, i, k, subl):
if i == len(l):
return
if k == 0:
for j in subl:
print(j, end = ' ')
print()
# including l[i]
printSumToK(l, i+1, k-l[i], subl + [l[i]])
# excluding l[i]
printSumToK(l, i+1, k, subl)
array = [int(j) for j in input("Enter an array of integers: ").split()]
total_su... |
import numpy as np
import os
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
#Load the dataset
titanic = sns.load_dataset('titanic')
#print(titanic.head())
#visualise the count of survivors
sns.countplot(data = titanic, x = titanic['sex']) #There is an overwhelming likelihood that... |
from Maze import *
import random
import turtle
import unittest
class testMaze(unittest.TestCase):
"""
This class inherits from a class called TestCase which is
defined in the unittest module.
When you inherit from a class, you get all the methods that are
defined in that class for free.
Since... |
class Graph:
def __init__(self):
self._adjacency_dict = {}
def add_vertex(self, value):
vertex = Vertex(value)
self._adjacency_dict[vertex] = []
return vertex
def add_edge(self, start_vertex, end_vertex, weight =1):
if start_vertex not in self._adjacency_dict:... |
"""Helper functions for plotting."""
import matplotlib.pyplot as plt
import numpy as np
def plot_x_vs_y(dataset, model):
"""Plots x vs y. Do not have to change this function.
Args:
dataset(list): processed dataset, from data_tools.
model(LinearRegression): Linear regression model.
"""
... |
#Question no 20
'''
Represent a small bilingual lexicon as a Python dictionary in the following fashion
{ "merry":"god", "christmas":"jul", "and":"och", "happy":gott", "new":"nytt", "year":"år" }
and use it to translate your Christmas cards from English into Swedish. That is, write a function `translate()`
that takes... |
#Question no 15
'''
Write a function find_longest_word() that takes a list of words
and returns the length of the longest one.
'''
def longest(lstofwords):
listofnumber=[]
for i in lstofwords:
listofnumber.append(len(i))
listofnumber.sort()
print("Length of longest word in list is : ... |
"""
Reads in a .csv file and outputs each case.
To run this: `python analysis_0.py yourfile.csv`
"""
import csv
import sys
filename = sys.argv[1]
with open(filename, 'r') as f:
data = csv.reader(f)
for case in data:
print(case)
|
import string
def read_file(filename):
""" Return the contents of a file as a sring """
return open(filename).read()
if __name__ == '__main__':
s = read_file('book_section.txt')
t = s.split(' ')
for word in t:
word = word.replace(' ', '')
word = word.translate(string.maketrans("",... |
'''
Exercise 2.3:
Assume that we execute the following assignment statements:
width = 17
height = 12.0
delimiter = '.'
For each of the following expressions, write the value of the expression and the type (of the value of the expression).
width/2
width/2.0
height/3
1 + 2 * 5
delimiter * 5
Use the Python interpreter to ... |
'''
Exercise 1.8 if you run a 10km race in 43 minutes and 30 seconds, what is your
average time per mile. what is your average speed in mile per hour.
There are 1.61 km in a mile.
'''
distance_in_km = 10
time_in_min = 43+(30.0/60)
distance_in_miles = distance_in_km/1.61
time_in_hrs=time_in_min/60
avg_time_per_mile=ti... |
'''
You have a histogram. Try to find size of the biggest rectangle you can build out of the histogram bars:)
'''
def largest_histogram(histogram):
maximum=max(histogram)
local_max=0
q=len(histogram)
for i in range(1,maximum+1):
macks=0
for i1 in range(0,q):
... |
def quickSort(A,p,r):
if(p<r and r>=0):
#partition() : use r as a pivot, modifying array as below order. and return pivot index
# (elements lower than pivot) - (pivot) - (elements higher than pivot)
q=partition(A,p,r)
#execute quickSort() recursively
quickSort(A,p,q-1)
... |
import stack_practice
def reverse(str):
length = len(str)
reversed = ''
for i in range(length-1,-1,-1):
ch = str[i]
reversed = reversed + ch
return reversed
str = 'abcdefg'
print(reverse(str))
#################### or ####################
def reverse_by_stack(str):
ch_stack = st... |
'''
d(n) = no. of methods representing n by only sum of 1 or 2 or 3
then
d(n) =
d(n-1) + 1 + (by adding 1)
d(n-2) + 1 + (by adding 2)
d(n-3) + 1 (by adding 3)
'''
def d(n, memo):
if n <= 0:
return 0
if n in memo:
return memo[n]
result = 0
if d(n-1, memo) ... |
class Deque(object):
def __init__(self):
self.data = []
def push_front(self, x):
self.data.insert(0, x)
def push_back(self, x):
self.data.append(x)
def pop_front(self):
if self.empty() == 1:
return -1
else:
return self.data.pop(0)
d... |
def is_arithmetic_num(num):
result = True
num_arr = []
while num != 0:
num_arr.append(num % 10)
num //= 10
if len(num_arr) <= 2:
result = True
return result
else:
gap = num_arr[0] - num_arr[1]
for i in range(1, len(num_arr)-1):
if (num_ar... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.