text stringlengths 37 1.41M |
|---|
"""
Code borrowed from:
https://stackoverflow.com/questions/48878053/tensorflow-gradient-with-respect-to-matrix
"""
import numpy as np
import tensorflow as tf
import tensorflow.contrib.eager as tfe
def _map(f, x, dtype=None, parallel_iterations=10):
"""
Apply f to each of the elements in x using the specified number of parallel
iterations.
Important points:
1.) By "elements in x", we mean that we will be applying f to
x[0], ... , x[tf.shape(x)[0] - 1].
2.) The output size of f(x[i]) can be arbitrary. However, if the dtype
of that output is different than the dtype of x, you need to specify
that as an additional argument.
"""
if dtype is None:
dtype = x.dtype
n = tf.shape(x)[0]
loop_vars = [
tf.constant(0, n.dtype),
tf.TensorArray(dtype, size=n),
]
_, fx = tf.while_loop(
lambda j, _: j < n,
lambda j, result: (j + 1, result.write(j, f(x[j]))),
loop_vars,
parallel_iterations=parallel_iterations
)
return fx.stack()
def jacobian(fx, x, parallel_iterations=10):
"""Given a tensor fx, which is a function of x, vectorize fx (via
tf.reshape(fx, [-1])) and then compute the Jacobian of each entry of fx
with respect to x.
Specifically, if x has shape (n1, n2, ..., np) and fx has L entries
(tf.size(fx) = L), then the output will be (L, n1, n2, ..., np), where
output[i] will be (n1, n2, ..., np) with each entry denoting the gradient
of output[i] wrt the corresponding element of x.
"""
def _grads(fxi, x):
x = np.array(x)
if tf.executing_eagerly():
grad_fn = tfe.gradients_function(fxi)
grad = grad_fn(x[0])[0]
else:
grad_fn = tf.gradients(fxi, x)
grad = grad_fn(x[0])[0]
return grad
return _map(_grads(fx, x),
# lambda fxi: tf.gradients(fxi, x)[0],
tf.reshape(fx, [-1]),
dtype=x.dtype,
parallel_iterations=parallel_iterations)
|
def shapeArea(n):
area = 0
if n == 1 :
return 1
for i in range(1,(2*n-1),2):
area += 2*i
print(area)
return(area +( 2*n -1))
|
# 自定义类
class Person(object):
# 构造方法
def __init__(self):
self.name = 'xiaowang'
self.__age = 12 # 私有属性
# 私有的类属性
__country = '中国'
# 获取私有属性()实例方法
def get_age(self):
return self.__age
# 实例方法(对象方法)修改私有属性
def set_age(self, new_age):
self.__age = new_age
# 类方法 获取私有类属性
@classmethod
def get_country(cls):
return cls.__country
# 类方法 修改私有类属性
@classmethod
def set_country(cls, new_country):
cls.__country = new_country
# 静态方法
''''''
@staticmethod
def hello():
print('今天天气不错')
'''使用静态方法
01- 类名.静态方法名 Person.hello()
02- 对象名.静态方法名
xiaoming = Person()
xiaoming.hello()
'''
xiaoming = Person()
xiaoming.hello()
'''python中类中的方法总结
- 实例方法(对象方法)
-定义格式: def 实例方法名(self):
-调用格式:对象名.实例方法名()
-使用场景:在方法中需要self
- 类方法(对私有属性取值或者赋值)
-定义格式: @classmethod
def 类方法名(cls):
-调用格式:类名.类方法名()或者对象名.类方法名()
-使用场景:在方法中需要cls(类名)
- 静态方法(一般不用)
-定义格式: @staticmethod
def 静态方法名(cls):
-调用格式:类名.类方法名()或者对象名.类方法名()
-使用场景:在方法中不需要self也不需要cls
'''
|
# 返回一个函数
def my_calc_return (x):
if x == 2:
def calc(y):
return y * y
if x == 3:
def calc(y):
return y * y * y
return calc # 使用calc()return失败:TypeError: calc() missing 1 required positional argument: 'y'
mcalc = my_calc_return(3)
print(mcalc(3))
'''
递归:函数中自己调用自己
重点:要明确递归结束的条件
优点:写法简单
缺点:效率低
要求:运算量每次递归逐渐减小
逻辑:每一次运算结果是,下一次运算的条件
'''
# def myfunction(x):
# print(x)
# myfunction(x+1)
#
# myfunction(1)
# 执行结果:RecursionError: maximum recursion depth exceeded while calling a Python object
'''
阶乘计算,5的阶乘 5 * 4 * 3 * 2 * 1
'''
def f(x):
if x == 1:
return 1
print('计算' + str(x) + '*' + str(x-1))
return x * f(x-1)
print(f(5)) |
# 定义师傅类-古法
class Master(object):
# 方法
def make_cake(self):
print('古法煎饼果子')
# 自定义师傅类-现代
class School(object):
# 方法
def make_cake(self):
print('现代煎饼果子')
# 自定义徒弟类
class Prentice(Master, School):
# 方法
def make_cake(self):
print('猫式煎饼果子')
# 古法
def make_old_cake(self):
# 如果子类重写了父类已有的方法
# 但是子类还想用父类同名的方法
# 解决方法:父类名.对象方法名(self)
Master.make_cake(self)
'''方式二:新式类使用super (子类类名, self).父类方法名()'''
super(Prentice, self).make_cake()
# 现代
def make_new_cake(self):
School.make_cake(self)
damao = Prentice()
damao.make_cake()
# 古法
damao.make_old_cake()
# 现代
damao.make_new_cake() |
"""
Define a function that can receive two integral numbers in string form
and compute their sum and then print it in console.
"""
def sum(string1, string2):
total = int(string1) + int(string2)
print(total)
return total
sum('100', '20')
|
"""
Write a program that accepts a sentence and calculate the number of letters and digits.
Suppose the following input is supplied to the program:
hello world! 123
Then, the output should be:
LETTERS 10
DIGITS 3
"""
def calcNum(userInput):
numLetters = 0
numDigits = 0
for char in userInput:
if char.isalpha():
numLetters = numLetters + 1
elif char.isdigit():
numDigits = numDigits + 1
print('LETTERS {}'.format(numLetters))
print('DIGITS {}'.format(numDigits))
calcNum('hello world! 123')
|
"""
Write a program to compute:
f(n)=f(n-1)+100 when n>0
and f(0)=1
with a given n input by console (n>0).
Example:
If the following n is given as input to the program:
5
Then, the output of the program should be:
500
In case of input data being supplied to the question, it should be assumed to be a console input.
Hints:
We can define recursive function in Python.
"""
def calcAnswer(num):
if num == 0:
return 0
return calcAnswer(num - 1) + 100
print(calcAnswer(5))
|
import re
"""
Assuming that we have some email addresses in the "username@companyname.com" format,
please write program to print the user name of a given email address.
Both user names and company names are composed of letters only.
Example:
If the following email address is given as input to the program:
john@google.com
Then, the output of the program should be:
john
"""
def parseEmail(email):
pattern = '(\w+)@\w+.com'
prog = re.match(pattern, email)
print(prog.group(1))
parseEmail('john@google.com')
|
"""
Write a program to compute 1/2+2/3+3/4+...+n/n+1 with a given n input by console (n>0).
Example:
If the following n is given as input to the program:
5
Then, the output of the program should be:
3.55
In case of input data being supplied to the question, it should be assumed to be a console input.
Hints:
Use float() to convert an integer to a float
"""
def calcAnswer(num):
sum = 0
for i in range(1, num + 1):
sum += float(i/(i + 1))
print(float(sum))
calcAnswer(5)
|
"""
Please write assert statements to verify that every number in the list [2,4,6,8] is even.
Hints:
Use "assert expression" to make assertion.
"""
list = [i for i in range(2, 9) if i % 2 == 0]
for num in list:
assert num % 2 == 0
|
"""
Write a program which can map() and filter() to make a list whose elements are
square of even number in [1,2,3,4,5,6,7,8,9,10].
"""
def squareEvens(userInput):
evens = list(filter(lambda x : x % 2 == 0, userInput))
squares = list(map(lambda x : x * x, evens))
print(squares)
squareEvens([1,2,3,4,5,6,7,8,9,10])
|
"""
Write a program to solve a classic ancient Chinese puzzle:
We count 35 heads and 94 legs among the chickens and rabbits in a farm. How many rabbits and how many chickens do we have?
Hint:
Use for loop to iterate all possible solutions.
"""
def numRabbitsChickens(heads, legs):
for i in range(heads): # i is the number of chickens, heads - i is the number of rabbits
totalLegs = 4 * (heads - i) + 2 * i
if totalLegs == legs:
print('%d chickens, %d rabbits'%(i, heads - i))
break
numRabbitsChickens(35, 94)
|
"""
Please write a program using generator to print the numbers
which can be divisible by 5 and 7 between 0 and n in comma separated form while n is input by console.
Example:
If the following n is given as input to the program:
100
Then, the output of the program should be:
0,35,70
Hints:
Use yield to produce the next value in generator.
"""
def divisible5And7(stop):
i = 0
while i <= stop:
if i % 5 == 0 and i % 7 == 0:
yield i
i += 1
result = []
for i in divisible5And7(100):
result.append(str(i))
print(','.join(result))
|
classnumber=int(input("Please enter the number of classes :"))
for i in range (classnumber):
studentnumber = int(input("Please enter the number of the students:"))
while studentnumber>50:
print("Wrong")
studentnumber = int(input("Please enter a new number:"))
Name = []
Score = []
count = 0
print("Please enter a student'name:(input '*' to end)")
TempName = input()
if TempName !="*":
print("Please enter this student's score:")
TempScore = float(input())
Name.append(TempName)
Score.append(TempScore)
count+=1
print("Enter the next student' name:(input '*' to end)")
TempName = input()
if TempName !="*":
print("Enter this student'score:")
TempScore = float(input())
K = 0
while K<count:
print(Name[K],Score[K])
K+=1
|
#This program is used to calculate tax
Taxableincome=int(input("Enter the Taxableincome:"))
#Get the user’s Taxable income
if(Taxableincome<0)
Print("You can not input a negative number")
#Prevent the user from inputing a negative number mistakenly
if(Taxableincome>=0)and(Taxableincome<=50000)
Tax Rate=0.05
Tax= Taxableincome* Tax Rate
#Calculate the tax
else
if (Taxableincome>50000)AND(Taxableincome<=100000)
Tax Rate=0.07
Tax=2500+( Taxableincome-50000)* Tax Rate
else
Tax Rate=0.09
Tax=6000+( Taxableincome-100000)* Tax Rate
Print(“Tax”)
|
#输入
String1=str(input("请输入字符串1:"))
String2=str(input("请输入字符串2:"))
String3=""
#根据用户需要,进行操作
while 1:
print("比较,按1;追加,按2;拷贝,按3;结束,按0")
K=int((input()))
if K==0:
break
elif K==1:
if String1>String2:
print("String 1>String 2")
elif String1==String2:
print("String 1=String 2")
elif String1<String2:
print("String 1<String 2")
elif K==2:
String3=String1+String2
print("结果为:"+String3)
elif K==3:
String1=String2
print("字符串1为"+String1)
|
"""
Pig Latin is a game of alterations played on the English language game.
To create the Pig Latin form of an English word the initial consonant sound is transposed to the end of the word
and an ay is affixed (Ex.: "banana" would yield anana-bay). Read Wikipedia for more information on rules.
"""
import re
def pig_latin_word_creator(word):
# Locate the first instance of a vowel
vowel_search = vowel_regex.search(word) # Match object; contains the matched vowel
# If a match is found, split up the word
# Otherwise, no vowels were found in the given word and return the word
if vowel_search:
# Split the string at that first instance, but retain the vowel using partition
partition_list = word.partition(vowel_search.group())
beginning, middle, end = partition_list # unpack tuple
# Create pig latin word from pieces of the partitioned word
pig_latin_end = beginning + "ay"
pig_latin_beginning = middle + end + "-"
pig_latin_word = pig_latin_beginning + pig_latin_end
else:
pig_latin_word = word
return pig_latin_word
# Create a regex pattern of vowels
vowel_regex = re.compile(r'[aeiouAEIOU]')
# Prompt the user for an input
# TO-DO: expand to sentence
str = input("Enter a word:").strip()
word_list = str.split(" ")
pig_latin_sentence = ""
for index in word_list:
pig_latin_sentence += pig_latin_word_creator(index) + " "
print(pig_latin_sentence)
|
"""
Leetcode #75
"""
from typing import List
class Solution:
# two pass
def sortColors_COUNTING_SORT(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
counter = [0, 0, 0] # one for each 0, 1, and 2
for i in nums:
counter[i] += 1
i = 0
for k in range(len(counter)):
while counter[k] > 0:
nums[i] = k
i += 1
counter[k] -= 1
# Single pass
# great solution
# Dutch National Flag Problen
# https://en.wikipedia.org/wiki/Dutch_national_flag_problem
# see pseudocode section in this wiki page
def sortColors(self, nums: List[int]) -> None:
if len(nums) < 2: return nums
low, high, i = 0, len(nums)-1, 0
while i <= high:
if nums[i] == 2:
nums[i], nums[high] = nums[high], nums[i]
high -= 1
elif nums[i] == 1:
i += 1
else:
nums[i], nums[low] = nums[low], nums[i]
i, low = i + 1, low + 1
return nums
if __name__ == "__main__":
nums = [2,0,2,1,1,0]
Solution().sortColors_COUNTING_SORT(nums)
print(nums) # [0,0,1,1,2,2]
nums = [2,0,2,1,1,0]
Solution().sortColors(nums)
print(nums) # [0,0,1,1,2,2]
|
"""
Leetcode #1433
"""
from collections import Counter
class Solution:
def checkIfCanBreak(self, s1: str, s2: str) -> bool:
def check(d1, d2):
diff = 0
for c in "abcdefghijklmnopqrstuvwxyz":
diff += d1[c] - d2[c]
if diff < 0: # if anytime diff < 0, return false
return False
return True
d1 = Counter(s1)
d2 = Counter(s2)
return check(d1, d2) or check(d2, d1)
def checkIfCanBreak_Sort(self, s1: str, s2: str) -> bool:
a = sorted(s1)
b = sorted(s2)
i = 0
while i < len(a) and a[i] >= b[i]:
i += 1
if i == len(a): return True
i = 0
while i < len(b) and b[i] >= a[i]:
i += 1
if i == len(b): return True
return False
if __name__ == "__main__":
solution = Solution()
assert solution.checkIfCanBreak("abc", "xya") == True
assert solution.checkIfCanBreak("abe", "acd") == False
assert solution.checkIfCanBreak("leetcodee", "interview") == True
assert solution.checkIfCanBreak_Sort("abc", "xya") == True
assert solution.checkIfCanBreak_Sort("abe", "acd") == False
assert solution.checkIfCanBreak_Sort("leetcodee", "interview") == True
|
"""
Leetcode #79
"""
from typing import List
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
if not board or not word:
return False
if not board[0]:
return False
m = len(board)
n = len(board[0])
# using separate visited array
# but you can do that without using it
# by just setting board[i][j] == "#" or any char when visiting a cell
# then reset it back to original value
visited = [[False]*n for x in range(m)]
def helper(i, j, idx):
if idx == len(word):
return True
if i < 0 or i >= m or j < 0 or j >= n or board[i][j] != word[idx] or visited[i][j]:
return False
# Mark visited
visited[i][j] = True
# Search in adjacent cells
# left, right, top, bottom (4 recursive calls)
if helper(i+1, j, idx+1) or helper(i-1, j, idx+1) or helper(i, j+1, idx+1) or helper(i, j-1, idx+1):
return True
# reset visited array for next further searches
visited[i][j] = False
return False
for i in range(m):
for j in range(n):
if board[i][j] == word[0] and helper(i, j, 0):
return True
return False
if __name__ == "__main__":
solution = Solution()
matrix = [
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
assert solution.exist(matrix, "ABCCED") == True
assert solution.exist(matrix, "SEE") == True
assert solution.exist(matrix, "ABCB") == False
|
"""
Leetcode #207
"""
from collections import defaultdict
from typing import List
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
if not prerequisites:
return True
# 0: unlearned, 1: learning, 2: learned
self.course_status = [0] * numCourses
# Collect advanced course for base course
self.course_dict = defaultdict(set)
for a, b in prerequisites:
self.course_dict[b].add(a)
for course in range(numCourses):
if self.dfs_is_cycle(course):
return False
return True
def dfs_is_cycle(self, course):
if self.course_status[course] == 1:
return True
if self.course_status[course] == 2:
return False
# mark this course as learning
self.course_status[course] = 1
for adv in self.course_dict[course]:
if self.dfs_is_cycle(adv): return True
# mark this course as learned
self.course_status[course] = 2
return False
if __name__ == "__main__":
solution = Solution()
assert solution.canFinish(2, [[1, 0]]) == True
assert solution.canFinish(2, [[0, 1]]) == True
assert solution.canFinish(2, [[1, 0], [0, 1]]) == False
|
"""
Leetcode # 146
"""
from typing import Dict, List
class DoublyLinkedNode:
def __init__(self, key: int, value: int) -> None:
self.key = key
self.value = value
self.prev = None
self.next = None
class LRUCache:
def __init__(self, capacity: int) -> None:
self.size = 0
self.capacity = capacity
self.head = DoublyLinkedNode(-1, -1)
self.tail = DoublyLinkedNode(-1, -1)
self.head.next = self.tail
self.tail.prev = self.head
self.cache = dict()
def __move_node_to_head(self, node: DoublyLinkedNode) -> None:
pred = self.head
succ = self.head.next
succ.prev = node
pred.next = node
node.prev = pred
node.next = succ
def __remove_node_links(self, node: DoublyLinkedNode) -> None:
pred = node.prev
succ = node.next
succ.prev = pred
pred.next = succ
node.prev = None
node.next = None
def __remove_tail(self) -> int:
to_delete = self.tail.prev
k = to_delete.key
pred = to_delete.prev
self.tail.prev = pred
pred.next = self.tail
del to_delete
return k
def get(self, key: int) -> int:
if key not in self.cache: return -1
node = self.cache[key]
# make frequently accessed keys to head
self.__remove_node_links(node)
self.__move_node_to_head(node)
return node.value
def put(self, key: int, value: int) -> None:
if key not in self.cache and self.size == self.capacity:
self.size -= 1
tail_key = self.__remove_tail()
del self.cache[tail_key]
if key not in self.cache:
self.size += 1
else:
old_node = self.cache[key]
self.__remove_node_links(old_node)
del self.cache[key]
node = DoublyLinkedNode(key, value)
self.cache[key] = node
self.__move_node_to_head(node)
if __name__ == "__main__":
lru = LRUCache(3)
assert lru.get(1) == -1
lru.put(1, "foo")
lru.put(2, "bar")
lru.put(3, "baz")
assert lru.get(1) == "foo"
lru.get(1)
lru.get(1)
lru.get(1)
lru.get(3)
lru.put(4, "qux")
assert lru.get(4) == "qux"
assert lru.get(2) == -1 # 2 is evicted as it was least accessed (fetched)
lru.get(4)
lru.get(4)
lru.put(5, "quux")
assert lru.get(5) == "quux"
|
"""
Leetcode #60
"""
class Solution:
count = 0
perm = None
def getPermutation(self, n: int, k: int) -> str:
nums = [i for i in range(1, n+1)]
res = []
store = {}
def helper(nums, curr):
if len(curr) == len(nums):
self.count = self.count + 1
if self.count == k:
self.perm = curr[:]
return True
return
for i in nums:
if store.get(i):
continue
curr.append(i)
store[i] = True
if (helper(nums, curr)): return
store[i] = False
curr.pop()
helper(nums, [])
return "".join(map(str, self.perm))
def getPermutation_OPTI(self, n: int, k: int) -> str:
nums = [i for i in range(1, n+1)]
res = ""
k -= 1
while n:
n -= 1
index, k = divmod(k, math.factorial(n))
res += str(nums.pop(index))
return res
if __name__ == "__main__":
solution = Solution()
print(solution.getPermutation(3, 3))
|
"""
1.8 - Write an algorithm such that if in an element in MxN matrix is 0
All elements in that row become should become 0
"""
from typing import List
# assuming all element in matrix are >= 0
def algo(matrix: List[List[int]]) -> List[List[int]]:
M = len(matrix)
N = len(matrix[0])
# mark location as -1 when element at this location is 0
# O(MN)
for i in range(M):
for j in range(N):
if matrix[i][j] == 0:
matrix[i][j] = -1
# now whenever -1 is found, replace all entire elements
# in that row and col to 0
for i in range(M):
for j in range(N):
if matrix[i][j] == -1:
# Zero entire col
for k in range(N):
matrix[i][k] = 0
# Zero entire row
for l in range(M):
matrix[l][j] = 0
return matrix
# It works for all integers
def algoOptimized(matrix: List[List[int]]) -> List[List[int]]:
def nullifyRow(matrix, rowNum):
for i in range(len(matrix[rowNum])):
matrix[rowNum][i] = 0
return matrix
def nullifyCol(matrix, colNum):
for i in range(len(matrix)):
matrix[i][colNum] = 0
return matrix
M = len(matrix)
N = len(matrix[0])
rows = M*[0]
cols = N*[0]
for i in range(M):
for j in range(N):
if matrix[i][j] == 0:
rows[i] = 1
cols[j] = 1
for i in range(len(rows)):
if rows[i]: nullifyRow(matrix, i)
for j in range(len(cols)):
if cols[j]: nullifyCol(matrix, j)
return matrix
if __name__ == "__main__":
matrix1 = [[1, 2, 3],
[0, 5, 6],
[7, 8, 0]]
output = [[0, 2, 0],
[0, 0, 0],
[0, 0, 0]]
assert algo(matrix1) == output
matrix2 = [[1, 2, 3],
[0, 5, 6],
[7, 8, 0]]
output = [[0, 2, 0],
[0, 0, 0],
[0, 0, 0]]
assert algoOptimized(matrix2) == output
|
"""
Leetcode #575
"""
from typing import List
class Solution:
def distributeCandies_OPTI(self, candies: List[int]) -> int:
unique = set(candies)
# max number of candies sister can get will be atmost len(candies) / 2
if len(unique) >= len(candies) // 2:
return len(candies) // 2
else:
return len(unique)
def distributeCandies(self, candies: List[int]) -> int:
count = 0
N = len(candies)
for i in range(N//2):
# max number of candies sister can get will be atmost len(candies) / 2
if count >= N // 2:
break
if candies[i] != float("-inf"):
count += 1
for j in range(i+1, N):
if candies[i] == candies[j]:
candies[j] == float("-inf")
return count
if __name__ == "__main__":
solution = Solution()
assert solution.distributeCandies([1,1,2,2,3,3]) == 3
assert solution.distributeCandies([1,1,2,3]) == 2
assert solution.distributeCandies_OPTI([1,1,2,2,3,3]) == 3
assert solution.distributeCandies_OPTI([1,1,2,3]) == 2
|
"""
2.1 - Write a code to remove duplicates from unsorted linked list
"""
# Definition of a ListNode
class ListNode():
def __init__(self, val):
self.val = val
self.next = None
def dedupe(head: ListNode) -> ListNode:
if not head:
return None
if not head.next:
return head
store = {}
tmp = head
# Mark first node as True
store[tmp.val] = True
while tmp.next:
if store.get(tmp.next.val):
# remove it
tmp.next = tmp.next.next
else:
store[tmp.val] = True
tmp = tmp.next
return head
# O(n^2) solution
# as no buffer is allowed to track occurrences
def dedupe_no_buffer(head: ListNode) -> ListNode:
if not head:
return None
if not head.next:
return head
current = head
# O(n^2)
while current:
tmp = current
while tmp.next != None:
if tmp.next.val == current.val:
tmp.next = tmp.next.next
else:
tmp = tmp.next
current = current.next
return head
if __name__ == "__main__":
def printll(ll: ListNode):
while ll:
print(ll.val, end="->")
ll = ll.next
print()
ll1 = ListNode(1)
ll1.next = ListNode(5)
ll1.next.next = ListNode(2)
ll1.next.next.next = ListNode(5)
ll1.next.next.next.next = ListNode(5)
printll(dedupe(ll1))
printll(dedupe_no_buffer(ll1))
|
"""
Leetcode #1451
"""
from collections import defaultdict
class Solution:
def arrangeWords(self, text: str) -> str:
if not text:
return ""
arr = text.split()
# sorting in python is stable
# so relative index of same level keys are maintained
# keep will always come before calm and code in "Keep calm and code on"
arr = sorted(arr, key=len)
return " ".join(arr).capitalize()
if __name__ == "__main__":
solution = Solution()
assert solution.arrangeWords("Leetcode is cool") == "Is cool leetcode"
assert solution.arrangeWords("Keep calm and code on") == "On and keep calm code"
assert solution.arrangeWords("To be or not to be") == "To be or to be not"
|
"""
Leetcode #1443
"""
from typing import List
from collections import defaultdict
class Solution:
def minTime(self, n: int, edges: List[List[int]], hasApple: List[bool]) -> int:
tree = defaultdict(list)
# to avoid loop as graph is not unidirected
visited = set()
for u, v in edges:
tree[u].append(v)
tree[v].append(u)
dist = 0
def helper(node):
nonlocal dist
if node in visited: return False
visited.add(node)
found = hasApple[node]
for child in tree[node]:
if helper(child):
dist += 2
found = True
return found or hasApple[node]
helper(0)
return dist
if __name__ == "__main__":
solution = Solution()
assert solution.minTime(7,
[[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]],
[False,False,True,False,True,True,False]) == 8
|
"""
Leetcode #153
"""
from typing import List
class Solution:
def findMin(self, nums: List[int]) -> int:
if not nums:
return
left = 0
right = len(nums) - 1
while left < right:
mid = left + (right - left) // 2
if nums[mid] < nums[right]:
right = mid
else:
left = mid+1
return nums[right]
if __name__ == "__main__":
assert Solution().findMin([3,4,5,1,2] ) == 1
assert Solution().findMin([3,4,5,6,1,2] ) == 1
assert Solution().findMin([4,5,6,7,0,1,2]) == 0
|
"""
Leetcode #282
"""
from typing import List
class Solution:
def addOperators(self, num: str, target: int) -> List[str]:
if num == "":
return []
N = len(num)
res = []
def helper(idx, curr, value, prev_num):
if idx >= len(num):
if value == target:
res.append(curr)
return None
for j in range(idx+1, len(num)+1):
string = num[idx:j]
number = int(string)
# avoid "00*"
if string != "0" and num[idx] == "0":
continue
if not curr:
helper(j, string, number, number)
else:
helper(j, curr + "+" + string, value + number, number)
helper(j, curr + "-" + string, value - number, -number)
helper(j, curr + "*" + string, value - prev_num + (prev_num * number), prev_num * number)
helper(0, "", 0, 0)
return res
if __name__ == "__main__":
solution = Solution()
print(solution.addOperators("123", 6)) # ["1+2+3", "1*2*3"]
print(solution.addOperators("232", 8)) # ["2*3+2", "2+3*2"]
|
"""
Leetcode #63
"""
from typing import List
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
if not obstacleGrid or not obstacleGrid[0]:
return 0
if obstacleGrid[0][0] == 1:
return 0
m = len(obstacleGrid)
n = len(obstacleGrid[0])
matrix = [[0]*n for x in range(m)]
# set element in first column to 1
# as there is only 1 way to reach them
for i in range(n):
if obstacleGrid[0][i] == 1:
break
matrix[0][i] = 1
# set element in first row to 1
# as there is only 1 way to reach them
for i in range(m):
if obstacleGrid[i][0] == 1:
break
matrix[i][0] = 1
# expand like we're increasing m and n
for i in range(1, m):
for j in range(1, n):
# if it is one, then skip this
if obstacleGrid[i][j] == 1:
continue
# only way to reach current cell is from either up or left
matrix[i][j] = matrix[i-1][j] + matrix[i][j-1]
return matrix[-1][-1]
if __name__ == "__main__":
solution = Solution()
assert solution.uniquePathsWithObstacles([[0,0,0], [0,1,0], [0,0,0]]) == 2
|
"""
Leetcode #313
"""
from typing import List
class Solution:
def nthSuperUglyNumber(self, n: int, primes: List[int]) -> int:
if not n or n == 0 or n == 1:
return n
res = [0] * n
res[0] = 1
# tracker multication for each prime
# after each iteration
# like 2 for 2, 1 for 7, 1 for 13, 1 for 19
tracker = [0] * len(primes)
for i in range(1, n):
res[i] = float("inf")
for j in range(len(primes)):
if primes[j] * res[tracker[j]] == res[i-1]:
tracker[j] += 1
res[i] = min(res[i], primes[j] * res[tracker[j]])
return res[n-1]
if __name__ == "__main__":
assert Solution().nthSuperUglyNumber(12, [2,7,13,19]) == 32
|
"""
Leetcode #1400
"""
from collections import Counter
class Solution:
def canConstruct(self, s: str, k: int) -> bool:
if len(s) < k:
return False
count = Counter(s)
odd = 0
# count odd frequencies, if odd < k then palindrome can be constructed
for i in count:
odd += (count[i] % 2)
return True if odd <= k else False
if __name__ == "__main__":
solution = Solution()
assert solution.canConstruct("annabelle", 2) == True
assert solution.canConstruct("leetcode", 3) == False
|
"""
Leetcode #1252
"""
from typing import List
class Solution:
def oddCells(self, n: int, m: int, indices: List[List[int]]) -> int:
if not indices:
return 0
rows = [0] * n
cols = [0] * m
for r, c in indices:
rows[r] += 1
cols[c] += 1
# we'll just be simulating changes using count from rows and cols above
count = 0
for i in range(n):
for j in range(m):
if (rows[i] + cols[j]) % 2 != 0:
count += 1
return count
if __name__ == "__main__":
solution = Solution()
assert solution.oddCells(2, 3, [[0,1],[1,1]]) == 6
|
"""
Leetcode #86
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def partition(self, head: ListNode, x: int) -> ListNode:
if not head:
return None
if not head.next:
return head
before = ListNode(0)
b_tmp = before
after = ListNode(0)
a_tmp = after
curr = head
while curr:
# here beware, that don't put <=
# as in ques. it is stated that
# all nodes less than x come before nodes greater than or equal to x
if curr.val < x:
b_tmp.next = curr
b_tmp = b_tmp.next
else:
a_tmp.next = curr
a_tmp = a_tmp.next
curr = curr.next
a_tmp.next = None
b_tmp.next = after.next
return before.next
if __name__ == "__main__":
def printll(ll: ListNode):
while ll:
print(ll.val, end="->")
ll = ll.next
print()
ll = ListNode(1)
ll.next = ListNode(4)
ll.next.next = ListNode(3)
ll.next.next.next = ListNode(2)
ll.next.next.next.next = ListNode(5)
ll.next.next.next.next.next = ListNode(2)
printll(Solution().partition(ll, 3))
|
"""
Leetcode #309
"""
from typing import List
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if not prices:
return 0
free = 0
have = cool = float('-inf')
for p in prices:
free, have, cool = max(free, cool), max(have, free - p), have + p
return max(free, cool)
if __name__ == "__main__":
assert Solution().maxProfit([1,2,3,0,2]) == 3
|
"""
Leetcode 230
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def kthSmallest(self, root: TreeNode, k: int) -> int:
if not root:
return 0
i = 0
for val in self.inorder(root):
# k-1 because i is starting from 0
if i == k-1:
return val
else:
i += 1
def inorder(self, root):
if not root:
return
yield from self.inorder(root.left)
yield root.val
yield from self.inorder(root.right)
if __name__ == "__main__":
solution = Solution()
root1 = TreeNode(3)
root1.left = TreeNode(1)
root1.left.right = TreeNode(2)
root1.right = TreeNode(4)
assert solution.kthSmallest(root1, 1) == 1
root2 = TreeNode(5)
root2.left = TreeNode(3)
root2.left.left = TreeNode(2)
root2.left.left.left = TreeNode(1)
root2.left.right = TreeNode(4)
root2.right = TreeNode(6)
|
"""
Leetcode #173
"""
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class BSTIterator():
def __init__(self, root: TreeNode):
if node is None:
return iter([])
yield from self._generator(node.left)
yield node.val
yield from self._generator(node.right)
self.node = root
self._node_itr = self._generator(root)
self._next = next(self._node_itr, None)
def next(self) -> int:
"""
@return the next smallest number
"""
_next = self._next
self._next = next(self._node_itr, None)
return _next
def hasNext(self) -> bool:
"""
@return whether we have a next smallest number
"""
return self._next is not None
def _generator(self, node):
if node is None:
return iter([])
yield from self._generator(node.left)
yield node.val
yield from self._generator(node.right)
if __name__ == "__main__":
root = TreeNode(7)
root.left = TreeNode(3)
root.right = TreeNode(15)
root.right.left = TreeNode(9)
root.right.right = TreeNode(20)
itr = BSTIterator(root)
assert itr.next() == 3
assert itr.next() == 7
assert itr.hasNext() == True
assert itr.next() == 9
assert itr.hasNext() == True
assert itr.next() == 15
assert itr.hasNext() == True
assert itr.next() == 20
assert itr.hasNext() == False
|
# build a web app for movies that allows users to
# list - add existing movies to a custom list
# - display query results to table - check
# search - query the model to return matching items - check
# add - add new Movies to the model - check
# edit - edit existing entries - check
# delete - delete existing entries - check
# movies should be stored in a database - check
# should contain the csv data linked to you - check
# should have a process for ingesting that csv into the database - check
# should also use Flask, allowing users to interactively edit that database - check
# Bonus: create a javascript frontend using a framework such as React, Vue or Angular for a more "modern" editing experience.
# import relevant modules
from flask import Flask, request, redirect, render_template, url_for, session
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import desc
import datetime
# define your app
app = Flask(__name__)
app.config['DEBUG'] = True
# configure it to connect to the database
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://movie-list:8938PNiGrqtBi5V@localhost:8889/movie-list'
app.config['SQLALCHEMY_ECHO'] = True
# create a reference to database and its methods
db = SQLAlchemy(app)
app.secret_key = 'aroundtheworldin80days'
# define any classes - used to construct objects, usually an entry in a table.
# in MVC, classes should be defined in the model
# class defining movie objects
class Movie(db.Model):
# the csv contains the following fields:
# Release Year, Title, Origin/Ethnicity, Director, Cast, Genre, Wiki Page, Plot
id = db.Column(db.Integer, primary_key=True)
release_year = db.Column(db.Integer)
title = db.Column(db.String(120))
origin_ethnicity = db.Column(db.String(120))
director = db.Column(db.String(255))
cast = db.Column(db.Text)
genre = db.Column(db.String(120))
wiki_page = db.Column(db.String(255))
plot = db.Column(db.Text)
is_visible = db.Column(db.Boolean)
def __init__(self, release_year, title, origin_ethnicity, director, cast, genre, wiki_page, plot):
self.release_year = release_year
self.title = title
self.origin_ethnicity = origin_ethnicity
self.director = director
self.cast = cast
self.genre = genre
self.wiki_page = wiki_page
self.plot = plot
self.is_visible = True
class UserMovie(db.Model):
# create a model for storing user-created list of movies
id = db.Column(db.Integer, primary_key=True)
movie_id = db.Column(db.Integer, unique=True)
date_added = db.Column(db.DateTime)
is_visible = db.Column(db.Boolean)
def __init__(self, movie_id, date_added):
self.movie_id = movie_id
self.date_added = date_added
self.is_visible = True
# define your request handlers, one for each page
# include any logic, say for validation or updating the database
# return rendered templates or redirect.
@app.route('/')
def index():
# pass db info. Should support pagination as there are 34,000 entries
page = request.args.get('page', 1, type=int)
records = Movie.query.filter_by(is_visible=1).order_by(desc(Movie.release_year)).paginate(page, 20, False)
next_url = url_for('index', page=records.next_num) \
if records.has_next else None
prev_url = url_for('index', page=records.prev_num) \
if records.has_prev else None
return render_template('index.html', records=records.items, next_url=next_url, prev_url=prev_url)
@app.route('/movie')
def movie():
# for displaying individual Movies
movie_id = request.args.get('id')
movie = Movie.query.filter_by(id=movie_id).first()
return render_template('individual_movie.html', movie=movie)
@app.route('/search', methods=['POST', 'GET'])
def search():
if request.method == 'POST':
# decide how to pass and handle queries
# search by column or search all?
# start with column
search_term = request.form['search_term']
column = request.form['column']
search_term_two = request.form['search_term_two']
column_two = request.form['column_two']
page = request.args.get('page', 1, type=int)
# Could not get pagination to work with search results. Commented out pagination attibutes.
if column == 'release_year':
search_results = Movie.query.filter(Movie.release_year.contains(int(search_term))).all() #.paginate(page, 20, False)
elif column == 'title':
search_results = Movie.query.filter(Movie.title.contains(search_term)).all() #.paginate(page, 20, False)
elif column == 'origin_ethnicity':
search_results = Movie.query.filter(Movie.origin_ethnicity.contains(search_term)).all() #.paginate(page, 20, False)
elif column == 'director':
search_results = Movie.query.filter(Movie.director.contains(search_term)).all() #.paginate(page, 20, False)
elif column == 'cast':
search_results = Movie.query.filter(Movie.cast.contains(search_term)).all() #.paginate(page, 20, False)
elif column == 'genre':
search_results = Movie.query.filter(Movie.genre.contains(search_term)).all() #.paginate(page, 20, False)
# next_url = url_for('search', page=search_results.next_num) \
# if search_results.has_next else None
# prev_url = url_for('search', page=search_results.prev_num) \
# if search_results.has_prev else None
if search_term_two:
# function that filters a list of Movies (search results) by an additional term and column
def filter_search_results(results, term_two):
filtered_results = []
for result in results:
if column_two == 'release_year':
term_two = int(term_two)
if term_two == result.release_year:
filtered_results.append(result)
elif column_two == 'title' and term_two in result.title:
filtered_results.append(result)
elif column_two == 'origin_ethnicity' and term_two in result.origin_ethnicity:
filtered_results.append(result)
elif column_two == 'director' and term_two in result.director:
filtered_results.append(result)
elif column_two == 'cast' and term_two in result.cast:
filtered_results.append(result)
elif column_two == 'genre' and term_two in result.genre:
filtered_results.append(result)
return filtered_results
filtered_results = filter_search_results(search_results, search_term_two)
# currently returns un-paginated results
return render_template('search.html', search_results=filtered_results) #.items, next_url=next_url, prev_url=prev_url)
else:
# currently returns un-paginated results
return render_template('search.html', search_results=search_results)
# use session data to enable search results to persist through pagination
# if request.method != 'POST' and 'search_term' in session:
# next_url = url_for('search', page=search_results.next_num) \
# if search_results.has_next else None
# prev_url = url_for('search', page=search_results.prev_num) \
# if search_results.has_prev else None
# return render_template('search.html', search_results=search_results.items, next_url=next_url, prev_url=prev_url)
return render_template('search.html')
@app.route('/add-movie', methods=['POST', 'GET'])
def add_movie():
if request.method =='POST':
# retrieve form data
# release_year, title, origin_ethnicity, director, cast, genre, wiki_page, plot
release_year = request.form["release_year"]
title = request.form["title"]
origin_ethnicity = request.form["origin_ethnicity"]
director = request.form["director"]
cast = request.form["cast"]
genre = request.form["genre"]
wiki_page = request.form["wiki_page"]
plot = request.form["plot"]
new_movie = Movie(release_year, title, origin_ethnicity, director, cast, genre, wiki_page, plot)
# stage
db.session.add(new_movie)
# commit to database
db.session.commit()
return redirect('/movie?id=' + str(new_movie.id))
return render_template('add-movie.html')
@app.route('/edit-movie', methods=['POST', 'GET'])
def edit_movie():
if request.method =='POST':
# retrieve form data
# release_year, title, origin_ethnicity, director, cast, genre, wiki_page, plot
movie_id = request.form["movie_id"]
release_year = request.form["release_year"]
title = request.form["title"]
origin_ethnicity = request.form["origin_ethnicity"]
director = request.form["director"]
cast = request.form["cast"]
genre = request.form["genre"]
wiki_page = request.form["wiki_page"]
plot = request.form["plot"]
target_movie = Movie.query.filter_by(id=movie_id).first()
# if performing validation pre-edit, now is the time.
# stage
target_movie.release_year = release_year
target_movie.title = title
target_movie.origin_ethnicity = origin_ethnicity
target_movie.director = director
target_movie.cast = cast
target_movie.genre = genre
target_movie.wiki_page = wiki_page
target_movie.plot = plot
# commit to database
db.session.commit()
return redirect('/movie?id=' + str(movie_id))
movie_id = request.args.get('id')
movie = Movie.query.filter_by(id=movie_id).first()
#print(movie.title)
return render_template('edit-movie.html', movie=movie)
@app.route('/delete-movie', methods=['POST', 'GET'])
def delete_movie():
if request.method == 'POST':
# retrieve form database
movie_id = request.form["movie_id"]
target_movie = Movie.query.filter_by(id=movie_id).first()
# set is_visible to False
target_movie.is_visible = 0
db.session.commit()
return redirect('/')
movie_id = request.args.get('id')
movie = Movie.query.filter_by(id=movie_id).first()
return render_template('delete-movie.html', movie=movie)
@app.route('/add-to-list')
def add_to_list():
movie_id = request.args.get('id')
current_date = datetime.datetime.today()
existing_user_movie = UserMovie.query.filter_by(movie_id=movie_id).first()
# if user previously added movie to list and removed it, it would be invisible
if existing_user_movie:
existing_user_movie.is_visible = 1
db.session.commit()
else:
new_user_movie = UserMovie(movie_id, current_date)
db.session.add(new_user_movie)
db.session.commit()
return redirect('/user-movies')
@app.route('/remove-from-list')
def remove_from_list():
movie_id = request.args.get('id')
discarded_user_movie = UserMovie.query.filter_by(movie_id=movie_id).first()
discarded_user_movie.is_visible = 0
db.session.commit()
return redirect('/user-movies')
@app.route('/user-movies')
def user_movies():
user_movies = UserMovie.query.filter_by(is_visible=1).all()
movies = []
for movie in user_movies:
movies.append(Movie.query.filter_by(id=movie.movie_id).filter_by(is_visible=1).first())
return render_template('user-movies.html', movies=movies)
# run the app
if __name__ == "__main__":
app.run()
|
import nltk
from nltk.stem import *
from nltk import tokenize
from nltk.corpus import wordnet as wn
import re
from nltk.corpus import stopwords
import sys
stopWords = stopwords.words('english')
# user_text = str(sys.argv[1])
usertext = str(sys.argv[1])
# usertext = "I've felt really tired the last few days. I have some congestion, I feel feverish, have difficulty breathing, and can't stop coughing. I traveled to my home in New York from South Korea and have been sick ever since."
symptoms = ["fever", "cough", "shortness of breath",
"fatigue", "headache", "aches and pains", "sore throat", "chills",
"nausea", "nasal congestion", "diarrhea"]
#maybe link this part to some json or list of places with high infection rates
locations = ["china", "italy", "europe", "japan", "iran", "south korea", "france", "spain", "germany", "switzerland", "washington", "new york", "california"]
def symptom_match(usertext, symptoms, locations):
usertext = usertext.lower()
stemmer = SnowballStemmer("english", ignore_stopwords=True)
#function below creates bigrams based on a tokenized list from user input
def all_bigrams(tokens):
def bigram_at(tokens, i):
# Takes a list of tokens and an index i and returns the bigram at that index
return (tokens[i], tokens[i+1])
big = []
for i in range(len(tokens)-1):
big.append(bigram_at(tokens, i))
return big
#change list of tuples (bigrams) back into bigram strings, separated by string s
def bigram_strings(l,s):
newlist = []
if l == []:
return ""
else:
r = l[0][0]+s
if len(l)>1:
for i in l[1:]:
r = r+i[0]+s
newlist.append(r.strip())
r = i[0]+s
return newlist
user_tokens = tokenize.word_tokenize(usertext)
user_bigrams = all_bigrams(user_tokens)
user_bigram_list = bigram_strings(user_bigrams," ") #used to compare against 2 word symptoms or locations
userinput = tokenize.word_tokenize(usertext)
corpusdict= {}
for eachitem in symptoms:
l = []
l.append(stemmer.stem(eachitem))
for inp in userinput:
if inp not in stopWords:
if len(inp)>4:
if inp in eachitem or eachitem in inp:
l.append(inp)
if stemmer.stem(inp) in eachitem:
l.append(stemmer.stem(inp))
corpusdict[eachitem]= l
userdict = {}
for eachword in userinput:
userdict[eachword] = stemmer.stem(eachword)
#this is just to give us the actual symptom name as listed in our symptom list, even though the stems match (used below)
def get_key(value, d):
for key, val in d.items():
if value == val:
return key
def get_listkey(value,d):
for key, val in d.items():
for listitem in val:
if listitem == value:
return key
newlist =[]
for humanword, humanstem in userdict.items():
for symptomlist in corpusdict.values():
for symptom in symptomlist:
if humanword == symptom or humanstem ==symptom:
newlist.append(get_listkey(symptom,corpusdict))
# newlist2 =[]
for gram in user_bigram_list:
stemmed = stemmer.stem(gram)
for symptom in corpusdict.values():
if stemmed == symptom:
newlist.append(get_key(symptom,corpusdict))
newlist3 =[]
for gram in user_bigram_list:
for location in locations:
if gram == location:
newlist3.append(gram)
newlist = list(set((newlist)))
# print(newlist)
if len(newlist) == 0:
print("No matches found")
if len(newlist) > 0:
print(";".join(newlist) + ";")
symptom_match(usertext, symptoms, locations)
|
total=0
for num in range(1,11):
total=total+num
print(total) |
def mean(value):
if type(value) == dict:
ave = sum(value.values())/len(value)
else:
ave = sum(value)/len(value)
return ave
studentscore = {"Joe": 8.9, "Fred": 9.3, "Zel": 5.6, "Matt": 7.4}
grades = [1, 2, 3, 4]
print(mean(studentscore))
print(mean(grades))
|
from queue import deque
class Node:
"""Klasa reprezentująca węzeł drzewa binarnego."""
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
def __str__(self):
return str(self.data)
def dfs(top):
"""Przeszukanie DFS"""
if top is None:
return
print(top)
dfs(top.left)
dfs(top.right)
def bfs(top):
if top is None:
return
Q = deque()
Q.append(top)
while len(Q) > 0:
node = Q.popleft()
print(node)
if node.left:
Q.append(node.left)
if node.right:
Q.append(node.right)
root = Node(1)
# Pierwszy poziom
root.left = Node(2)
root.right = Node(3)
# Drugi poziom lewo
root.left.left = Node(4)
root.left.right = Node(5)
# Drugi poziom prawo
root.right.left = Node(6)
root.right.right = Node(7)
# Trzeci poziom lewo
root.left.left.left = Node(8)
root.left.left.right = Node(9)
root.left.right.left = Node(10)
root.left.right.right = Node(11)
# Trzeci poziom prawo
root.right.left.left = Node(12)
root.right.left.right = Node(13)
root.right.right.left = Node(14)
root.right.right.right = Node(15)
print('METODA DFS PREORDER')
dfs(root)
print('METODA BFS')
bfs(root) |
#Inicio
num=0
print("Este programa solicita números positivos.")
print("Cuando ya no quieras ingresar números, ingresa un número negativo")
while num>=0:
num=int(input("Dame un número: "))
#indentación de instrucciones del while
#Fin while
#Fin |
import os,os.path
def file_Count_in_Dir():
print(len([name for name in os.listdir('d:') if os.path.isfile(name)]))
def file_list():
ls=os.listdir('.')
file_count = len(ls)
print(file_count)
#This function give us the count of file in a directory
def file_only():
import pdb
pdb.set_trace()
onlyfiles=next(os.walk(r'D:\TEM-Tivoli Endpoint Manager\Git_Repo\site-Patches_for_Ubuntu_1404\Fixlets\amd64\Security'))[2]
print(len(onlyfiles))
file_only()
#file_list()
#file_Count_in_Dir()
|
def not_string(str):
if(str[:3]=="not"):return str;
else:return "not "+str
|
def love6(a, b):
if(abs(a-b) == 6 or a==6 or b == 6 or a+b==6):return True
return False
|
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#importing data
dataset = pd.read_csv("Position_Salaries.csv")
X = dataset.iloc[:,1:2].values
y = dataset.iloc[:,2].values
#Splitting the dataset
#from sklearn.cross_validation import train_test_split
#X_train, X_test, y_train, y_test = train_test_split(X,y, test_size = 0.2, random_state = 0)
#No feature scaling needed
#fitting linear regression
from sklearn.linear_model import LinearRegression
lin_reg = LinearRegression()
lin_reg.fit(X,y)
#Polynomial regression
n = 3 #degree of polynomial
from sklearn.preprocessing import PolynomialFeatures
poly_reg = PolynomialFeatures(degree=n)
X_poly = poly_reg.fit_transform(X) #Transformed X into a 2 degree polynomial metrix
lin_reg2 = LinearRegression()
lin_reg2.fit(X_poly,y)
#Visualize Linear Regression Results
plt.scatter(X,y,color='red')
plt.plot(X, lin_reg.predict(X),color='blue')
plt.title("Truth or Bluff - Linear Regression")
plt.xlabel("Position")
plt.ylabel("Salary")
plt.show()
#Visualize Polynomial Regression
plt.scatter(X,y,color='red')
plt.plot(X, lin_reg2.predict(X_poly),color='blue')
plt.title("Truth or Bluff - Polynomial Regression")
plt.xlabel("Position")
plt.ylabel("Salary")
plt.show()
#Visualize Polynomial Regression - smooth
X_grid = np.arange(1,10,0.1)
X_grid = X_grid.reshape((len(X_grid),1))
plt.scatter(X,y,color='red')
plt.plot(X_grid, lin_reg2.predict(poly_reg.fit_transform(X_grid)),color='blue')
plt.title("Truth or Bluff - Polynomial Regression")
plt.xlabel("Position")
plt.ylabel("Salary")
plt.show()
#Predicting the result - linear regression
lin_reg.predict(6.5)
#Predicting the result - polynomial regression
lin_reg2.predict(poly_reg.fit_transform(6.5)) |
"""Word Finder: finds random words from a dictionary."""
import random
class WordFinder:
# read words.txt (one word per line).
# makes attribute of a list of those words.
# print out "[num-of-words-read] words read"
# create function random() that returns a random word from the list
def __init__(self, word_list):
"""Initialize WordFinder class setting arg as variable"""
self.word_list = word_list
def random(self):
"""Select random word from list of words in text file
Increase counter index to return number of lines read"""
counter = 0
words = list(open(self.word_list, 'r'))
for word in range(len(words)):
random_word = random.choice(words)
counter += 1
if words[word] == random_word:
print(f"{word} words read")
return random_word.strip()
# random_word = random.choice(words)
# print(random_word, fileinput.lineno())
class SpecialWordFinder(WordFinder):
def __init__(self, word_list):
super().__init__(word_list)
def random(self):
rand = super().random()
if rand and not rand.startswith('#'):
return rand
|
a = int(input("Введите число: "))
b = int(input("Введите число: "))
c = a + b
print ("Сложение равно: ",c )
|
from nltk.tokenize import RegexpTokenizer
from nltk.stem.wordnet import WordNetLemmatizer
'''
Since the dataset is small, using NLTK stop words stripped it off many words that were important for this context
So I wrote a small script to get words and their frequencies in the whole document, and manually selected
inconsequential words to make this list
'''
stop_words = ['the', 'you', 'i', 'are', 'is', 'a', 'me', 'to', 'can', 'this', 'your', 'have', 'any', 'of', 'we', 'very',
'could', 'please', 'it', 'with', 'here', 'if', 'my', 'am']
def lemmatize_sentence(tokens):
lemmatizer = WordNetLemmatizer()
lemmatized_tokens = [lemmatizer.lemmatize(word) for word in tokens]
return lemmatized_tokens
def tokenize_and_remove_punctuation(sentence):
tokenizer = RegexpTokenizer(r'\w+')
tokens = tokenizer.tokenize(sentence)
return tokens
def remove_stopwords(word_tokens):
filtered_tokens = []
for w in word_tokens:
if w not in stop_words:
filtered_tokens.append(w)
return filtered_tokens
'''
Convert to lower case,
remove punctuation
lemmatize
'''
def preprocess_main(sent):
sent = sent.lower()
tokens = tokenize_and_remove_punctuation(sent)
lemmatized_tokens = lemmatize_sentence(tokens)
orig = lemmatized_tokens
filtered_tokens = remove_stopwords(lemmatized_tokens)
if len(filtered_tokens) == 0:
# if stop word removal removes everything, don't do it
filtered_tokens = orig
normalized_sent = " ".join(filtered_tokens)
return normalized_sent
|
""" simple madlib """
print('Tell me a verb.')
VERB = input()
print(VERB)
print('And one more verb, please.')
NIIVERB = input()
print(NIIVERB)
print('I have a question: Who do you hate most?')
HATED = input()
print(HATED)
print('And tell me something you did in the past that you hated doing? (past tense)')
HATEVERB = input()
print(HATEVERB)
print('When you ' + VERB + ', you are going to actually ' + NIIVERB + ' because ' + HATED + ' ' + HATEVERB + '.')
|
print("!Important Message!")
print("# If you want odd no please input 1st no as Odd #")
print("# If you want even no please input 1st no as even #")
a=int(input("Enter Starting No(According to You Ending No)="))
b=int(input("Enter Ending No(Accoridng to you Starting No)="))
if a == b:
print("!Invalid! **Both the values are Same**")
for i in range(b,a,-2):
print(i)
|
n = input("Enter any character : ")
if n.isupper() :
print( n, "!Is an UPPERCASE alphabet!")
elif n.islower() :
print(n, "!Is a lowercase alphabet!.")
else :
print( n, "!Is Not an Alphabetical Character!") |
a=float(input("Enter a="))
b=float(input("Enter b="))
oper=input("Choose a math operation (+,/,%,**, -, *): ") # Choice of operator
if oper=='+':
s1=a+b # Addition
print(a,"Added with",b,"gives = ",s1)
elif oper=='/':
s2=a/b # Quotient
print(a,"Divided By",b,"gives quotient = ",s2)
elif oper=='%':
s3=a%b # Remainder
s7=a/b
print(a,"When Divided by",b,"gives remainder",s3, "& quotient=",s7)
elif oper=='**':
s4=a**b # Power (Exponent)
print(a,"to the power",b,"gives = ",s4)
elif oper=='-':
s5=a-b # Subtraction
print(a,"subtracted from",b,"gives = ",s5)
elif oper=='*':
s6=a*b # Multiplication
print(a,"multiplied by",b,"gives = ",s6)
else:
print("!Entered Invalid Arithmetic Operator!")
|
a=float(input("Enter 1st no="))
b=float(input("Enter 2nd no="))
c=float(input("Enter 3rd no="))
d=float(input("Enter 4rd no="))
e=float(input("Enter 5th no="))
choice=float(input("Choose any no out of the five no entered="))
if choice==a:
sum1=a*1,a*2,a*3
print("Multiple of",a,"are",sum1,"...")
elif choice==b:
sum2=b*1,b*2,b*3
print("Multiple of",b,"are", sum2,"...")
elif choice == c:
sum3 = c * 1, c * 2, c * 3
print("Multiple of",c,"are", sum3,"...")
elif choice==d:
sum4=d*1,d*2,d*3
print("Multiple of",d,"are", sum4,"...")
elif choice==e:
sum5=e*1,e*2,e*3
print("Multiple of",e,"are", sum5,"...")
else:
print("!Invalid Choice!")
|
words=["Aniket","Biswas","DPS","CLass","Eleven","Section","A","Science"]
def getWord():
import random
return random.choice (words)
word = getWord ()
word = list (word)
print ("You have to guess this word.\n", "- " * len (word))
answer = "_" * len (word)
answer = list (answer)
while True:
if answer == word:
print ("You completed the word, Hurray!!")
break
guess = input ("Enter your guess: ")
if guess in word:
for i in range (len (word)):
if word[i] == guess:
answer[i] = guess
print ("Correct guess")
print (" ".join (answer))
else:
print ("Wrong guess, Try again")
|
a=float(input("Enter Marks 1="))
b=float(input("Enter Marks 2="))
c=float(input("Enter Marks 3="))
d=float(input("Enter Marks 4="))
e=float(input("Enter Marks 5="))
avg=(a+b+c+d+e)/5
total=(a+b+c+d+e)
print(avg)
|
"""
>>> [factorial_reduce(n) for n in range(6)]
[1, 1, 2, 6, 24, 120]
"""
def factorial_reduce(n):
"""
>>> [factorial_reduce(n) for n in range(6)]
[1, 1, 2, 6, 24, 120]
"""
return reduce(lambda a, x: a * x, range(1, n + 1))
def factorial(n):
r = 1
for i in range(1, n + 1):
r *= i
return r
def fac(n, res=1):
if n == 1:
return res
else:
res *= n
return fac(n - 1, res)
|
import itertools
def f1(x, y, z):
return (x, z + 2, z)
def f2(x, y, z):
return (y + z * 2, y, z)
def f3(x, y, z):
return (y - 3, y, z)
def f4(x, y, z):
return (x, y, x + y)
arr_fun = [f1, f2, f3, f4]
def get_max():
max = float("-infinity")
result = []
for arr in itertools.permutations(arr_fun):
xyz = (1, 2, 3)
for fun in arr:
xyz = fun(*xyz)
if xyz[0] > max:
max = xyz[0]
result = arr
return max, result
m, vector = get_max()
print m
print vector
|
def reverse1(string):
return " ".join(reversed(string.split(" ")))
def reverse2(string):
return " ".join(string.split(" ")[::-1])
def reverse3(string):
words = []
whitespaces = set(string.whitespace)
index = 0
for i in range(len(str)):
if i not in whitespaces:
index = i
else:
pass
string = "Interviews are awesome!"
print reverse2(string) |
class ArrayMap(object):
def __init__(self):
self.d = {}
self.l = []
def append(self, item):
self.l.append(item)
self.d[self.l.index(item)] = item
def __getitem__(self, item):
return self.l[item]
def __setitem__(self, key, value):
pass
a = ArrayMap()
a.append("Artsiom")
a.append(15)
a.append("Sasha")
a.append(12.45)
print 13 |
import random
def qsort(iterable, key=lambda x: x, reverse=False):
if len(iterable) < 2:
return iterable
else:
pivot_index = random.randint(0, len(iterable) - 1)
pivot = iterable[pivot_index]
lesser = [x for x in
iterable[:pivot_index] + iterable[pivot_index + 1:] if
key(x) <= pivot]
greater = [x for x in
iterable[:pivot_index] + iterable[pivot_index + 1:]
if key(x) > pivot]
if reverse:
return qsort(greater, key=key, reverse=reverse) \
+ [pivot] + qsort(lesser, reverse=reverse)
else:
return qsort(lesser, key=key, reverse=reverse) \
+ [pivot] + qsort(greater, reverse=reverse)
if __name__ == "__main__":
arr = [1, 5, 2, 2, 4, 135, 8, 100, 3, 1, 0, 0, 0]
print qsort(arr, reverse=True)
print (sorted(arr, reverse=True))
# print random.randint(0, 2)
a = [0, 1, 2, 3, 4, 5, 6, 7, 8]
print a[3:]
print a[:3]
|
class Solution:
def confusingNumber(self, n: int) -> bool:
rotation_map = {'0': '0', '1': '1', '6': '9', '8': '8', '9': '6'}
str_num = str(n)
new_num = ''
for c in str_num:
if c in rotation_map:
new_num += str(rotation_map[c])
else:
return False
return new_num[::-1] != str_num |
class Solution:
def displayTable(self, orders: List[List[str]]) -> List[List[str]]:
MENU = []
ot = {}
for order in orders:
table = order[1]
item = order[2]
if table not in ot:
ot[table] = {}
if item not in ot[table]:
ot[table][item] = 0
ot[table][item] = ot[table][item]+1
if item not in MENU:
MENU.append(item)
MENU.sort()
result = [["Table"] + MENU]
for table, item in sorted(ot.items(), key=lambda x: int(x[0])):
temp = [table]
for m in MENU:
if m in item:
temp.append(str(item[m]))
else:
temp.append(str(0))
result.append(temp)
return result
|
class Solution:
def isPalindrome(self, s):
if s == s[::-1]:
return True
return False
def longestPalindrome(self, s: str) -> str:
for i in range(len(s)+1):
for j in range(i+1):
substr = s[j:len(s)-i+j]
if self.isPalindrome(substr):
return substr
return "" |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Functions related to kernel density estimation.
Created on Tue Nov 10 18:26:34 2020
@author: jeremylhour
"""
import numpy as np
def epanechnikov_kernel(x):
"""
epanechnikov_kernel:
Epanechnikov kernel function,
as suggested in Athey and Imbens (2006).
:param x: np.array
"""
y = (1-(x**2)/5) * 3/(4*np.sqrt(5))
y[np.where(abs(x) > np.sqrt(5))] = 0
return y
def kernel_density_estimator(x, data):
"""
kernel_density_estimator:
implement kernel density estimator with Silverman's rule of thumb,
as suggested in Athey and Imbens (2006).
:param x: new points
:param data: data to estimate the function
"""
h_silverman = 1.06 * data.std() / (len(data)**(1/5))
y = (x[np.newaxis].T - data)/h_silverman # Broadcast to an array dimension len(x) * len(data)
y = epanechnikov_kernel(y)/h_silverman
return y.mean(axis=1) |
x = int(input())
n = int(input())
soma = 1
cont = 0
while (soma*x)<n:
soma = soma + 1
print("O numero",x,"tem",soma-1,"multiplos menores que","{:.0f}.".format(n))
|
i = int(input())
if i<16:
print("nao eleitor")
elif i>=18 and i<=65:
print("eleitor obrigatorio")
else:
print("eleitor facultativo")
|
n1 = int(input())
n2 = int(input())
if n1>n2:
print(n1)
elif n2>n1:
print(n2)
else:
print(n1)
|
# Linguagem de Programação II
# AC02 ADS-EaD - Classes e Herança
# ------------------ #
# Criando uma classe #
# ------------------ #
# Crie a classe Mamifero seguindo o exemplo da classe Reptil
# Para esta AC não utilizem o @property ainda
class Reptil:
"""
Classe mãe - não deve ser editada
Observem que criei os atributos (características) no inicializador
da classe, o __init__, recebendo os valores como parâmetros e
que NÃO utilizei o @property ainda.
"""
def __init__(self, nome, cor, idade):
self.nome = nome
self.cor = cor
self.idade = idade
def tomar_sol(self):
return '{} tomando sol'.format(self.nome)
def botar_ovo(self):
if self.idade > 2:
return '{} botou um ovo'.format(self.nome)
else:
return '{} ainda não atingiu maturidade sexual'.format(self.nome)
class Mamifero:
"""
Complete a classe seguindo o exemplo da classe Reptil,
adaptando as características de acordo com a imagem fornecida
junto ao enunciado no Classroom.
Atenção aos nomes dos atributos e métodos, pois eles devem estar
escritos exatamente como os da imagem, com letra minúscula,
separados por um sublinhado _ e sem cedilha nem acentos.
Qualquer erro de digitação implicará em uma falha nos testes
e portanto perda de pontuação.
"""
def __init__(self, nome, cor_pelo, idade, tipo_pata):
self.nome = nome
self.cor_pelo = cor_pelo
self.idade = idade
self.tipo_pata = tipo_pata
def correr(self):
"""Retorna a frase: '<nome> correndo'
Onde <nome> é o nome dado à istância do animal em questão.
"""
return '{} correndo'.format(self.nome)
def mamar(self):
"""
Se o animal tiver 1 ano ou menos, retorna:
'<nome> mamando'
Caso contrário, retorna:
'<nome> já desmamou'
"""
if self.idade > 1:
return '{} já desmamou'.format(self.nome)
else:
return '{} mamando'.format(self.nome)
# ------------------------- #
# Criando as classes filhas #
# ------------------------- #
# Crie as classes filhas Cavalo, Cachoro, Gato, Cobra e Jacaré
# seguindo o exemplo da classe Camaleao abaixo
# Para esta AC não utilizem o @property ainda
class Camaleao(Reptil):
"""
Exemplo de solução do exercício:
Além dos atributos da classe mãe, possui o atributo:
inseto_favorito, do tipo string.
Implementa os métodos específicos:
mudar_de_cor() e comer_inseto()
Notem que não é preciso implementar o método tomar_sol()
nem o método botar_ovo(), pois eles são herdados automaticamente
da classe mãe, que é definida ali em cima,
na declaração da classe filha.
"""
def __init__(self, nome, cor, idade, inseto_favorito):
"""
O super é uma forma de acessar o método inicializador
da classe mãe e delegar a ele o trabalho de atribuir os
valores para os atributos comuns a todas as classes filhas
(atributos provenientes da classe mãe).
seria equivalente a copiar o código aqui e redefinir manualmente
todos os atributos:
self.nome = nome
self.cor = cor
self.idade = idade
Ou seja, podemos utilizar o super para reaproveitar o código
da classe mãe sem precisar digitá-lo ou copiá-lo
"""
super().__init__(nome, cor, idade)
self.inseto_favorito = inseto_favorito
def mudar_de_cor(self):
return '{} mudando de cor'.format(self.nome)
def comer_inseto(self):
return '{} comendo inseto'.format(self.nome)
"""
Implementem aqui as cinco classes filhas de Mamifero ou Reptil,
de acordo com o caso, conforme dado no diagrama apresentado no padrão UML.
Os atributos específicos de cada classe filha DEVEM OBRIGATORIAMENTE ser
recebidos como parâmetros no momento da criação, a única exceção é o
número de vidas do gato, que SEMPRE é inicializado em 7.
Os métodos de cada classe filha devem sempre RETORNAR uma string
no seguinte formato '<nome do animal> <método em questão no gerúndio>'
Sem nenhuma pontuação, conforme os exemplos a seguir.
Exemplo:
método trocar_pele() retorna: '<nome> trocando de pele'
método dormir() retorna: '<nome> dormindo'
método miar() retorna: '<nome> miando'
Onde <nome> é o nome dado para cada animal (o valor atributo `nome` de
cada instância, não o nome da classe)
"""
class Cavalo(Mamifero):
"""
Além dos atributos da classe mãe, possui o atributo:
cor_crina, do tipo string.
Implementa os métodos específicos:
galopar() e relinchar()
"""
def __init__(self, nome, cor_pelo, idade, tipo_pata, cor_crina):
super().__init__(nome, cor_pelo, idade, tipo_pata)
self.cor_crina = cor_crina
def galopar(self):
return '{} galopando'.format(self.nome)
def relinchar(self):
return '{} relinchando'.format(self.nome)
class Cachorro(Mamifero):
"""
Além dos atributos da classe mãe, possui o atributo:
raca, do tipo string. (raça, porém sem o ç)
Implementa os métodos específicos:
latir() e rosnar()
"""
def __init__(self, nome, cor_pelo, idade, tipo_pata, raca):
super().__init__(nome, cor_pelo, idade, tipo_pata)
self.raca = raca
def latir(self):
return '{} latindo'.format(self.nome)
def rosnar(self):
return '{} rosnando'.format(self.nome)
class Gato(Mamifero):
"""
Além dos atributos da classe mãe, possui o atributo:
vidas, do tipo inteiro. (não deve ser recebido como parâmetro,
começa sempre em 7 quando um novo gato é instanciado)
Implementa os métodos específicos:
miar() e morrer()
No início do método morrer, você deve verificar quantas vidas o gato
ainda tem sobrando, se for igual a zero, retornar:
'<nome> morreu'
se ainda houver vidas sobrando, subtrair 1 de vida e retornar:
'<nome> tem <vidas> vidas sobrando'
Onde <vidas> é o número de vidas restantes do gato, ou seja, quantas
vidas "extras" ele ainda tem, além da atual.
"""
def __init__(self, nome, cor_pelo, idade, tipo_pata):
super().__init__(nome, cor_pelo, idade, tipo_pata)
self.vidas = 7
def miar(self):
return '{} miando'.format(self.nome)
def morrer(self):
self.vidas = self.vidas - 1
if self.vidas <= 0:
return '{} morreu'.format(self.nome)
else:
return '{} tem {} vidas sobrando'.format(self.nome, self.vidas)
class Cobra(Reptil):
"""
Além dos atributos da classe mãe, possui o atributo:
veneno, do tipo booleano.
Implementa os métodos específicos:
rastejar() e trocar_pele()
"""
def __init__(self, nome, cor, idade, veneno):
super().__init__(nome, cor, idade)
self.veneno = veneno
def rastejar(self):
return '{} rastejando'.format(self.nome)
def trocar_pele(self):
return '{} trocando de pele'.format(self.nome)
class Jacare(Reptil):
"""
Além dos atributos da classe mãe, possui o atributo:
num_dentes, do tipo inteiro.
Implementa os métodos específicos:
atacar() e dormir()
"""
def __init__(self, nome, cor, idade, num_dentes):
super().__init__(nome, cor, idade)
self.num_dentes = num_dentes
def atacar(self):
return '{} atacando'.format(self.nome)
def dormir(self):
return '{} dormindo'.format(self.nome)
|
question = input("Give me a word in spanish")
if question == "cat":
print("Gato")
if question === "dog":
print("perro")
if question === "horse":
print("caballo")
else:
print("No entiendo")
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/7/4 15:52
# @Author : wenlei
'''
判断一棵二叉树是否是搜索二叉树
'''
class Node():
def __init__(self, x):
self.value = x
self.left = None
self.right = None
class Stack():
def __init__(self):
self.arr = []
def push(self, num):
self.arr.append(num)
def pop(self):
if self.isEmpty():
raise Exception('The stack is empty')
return (self.arr.pop())
def peek(self):
if self.isEmpty():
raise Exception('The stack is empty')
return (self.arr[-1])
def isEmpty(self):
if not self.arr or len(self.arr) < 1:
return True
class Queue():
def __init__(self):
self.arr = []
def push(self, num):
self.arr.append(num)
def pop(self):
if self.isEmpty():
raise Exception('The stack is empty')
return (self.arr.pop(0))
def peek(self):
if self.isEmpty():
raise Exception('The stack is empty')
return (self.arr[0])
def isEmpty(self):
if not self.arr or len(self.arr) < 1:
return True
def size(self):
return len(self.arr)
def isBST(head):
min = -9999999999
if head:
stack = Stack()
while not stack.isEmpty() or head:
if head:
stack.push(head)
head = head.left
else:
head = stack.pop()
if head.value < min:
return False
else:
min = head.value
head = head.right
return True
# moriis遍历方法(暂时不用懂)
def isBSTMoriis(head):
pass
def isCBT(head):
if not head:
return True
queue = Queue()
queue.push(head)
leaf = False # 情况2是否开启
while not queue.isEmpty():
head = queue.pop()
left = head.left
right = head .right
if (not left and right) or (leaf and (left or right)):
return False
if left:
queue.push(left)
if right:
queue.push(right)
else:
leaf = True
return True
# for test
def printTree(head):
print('Binary Tree:')
printInOrder(head, 0, 'H', 17)
print('\n')
def printInOrder(head, height, to, length):
if not head:
return
printInOrder(head.right, height + 1, 'v', length)
val = to + str(head.value) + to
lenM = len(val)
lenL = (length - lenM) // 2
lenR = length - lenM - lenL
val = getSpace(lenL) + val + getSpace(lenR)
print(getSpace(height * length) + val)
printInOrder(head.left, height + 1, "^", length)
def getSpace(num):
space = " "
tmp = []
for i in range(num):
tmp.append(space)
return ''.join(tmp)
if __name__ == '__main__':
head = Node(4)
head.left = Node(2)
head.right = Node(6)
head.left.left = Node(1)
head.left.right = Node(3)
head.right.left = Node(5)
printTree(head)
print(isBST(head))
print(isCBT(head)) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/7/4 14:11
# @Author : wenlei
'''
判断一棵二叉树是否是平衡二叉树
'''
class Node():
def __init__(self, x):
self.value = x
self.left = None
self.right = None
# 解法1
class ReturnData():
def __init__(self, isB, h):
self.isB = isB
self.h = h
def isBalance(head):
return process(head).isB
def process(head):
if not head:
return ReturnData(True, 0)
left = process(head.left)
if not left.isB:
return ReturnData(False, 0)
right = process(head.right)
if not right.isB:
return ReturnData(False, 0)
if abs(left.h - right.h) > 1:
return ReturnData(False, 0)
return ReturnData(True, max(left.h, right.h) + 1)
# 解法2
def isBalance(head):
res = [None]
res[0] = True
getHeight(head, 1, res)
return res[0]
def getHeight(head, level, res):
if not head:
return level
lH = getHeight(head.left, level + 1, res)
if not res[0]:
return level
rH = getHeight(head.right, level + 1, res)
if not res[0]:
return level
if abs(lH - rH) > 1:
res[0] = False
return max(lH, rH)
if __name__ == '__main__':
head = Node(1)
head.left = Node(2)
head.right = Node(3)
head.left.left = Node(4)
head.left.right = Node(5)
head.right.left = Node(6)
head.right.right = Node(7)
head.right.left.left = Node(8)
print(isBalance(head))
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2020/8/24 17:32
# @Author : wenlei
# 一个数组,求任一元素减去该元素右边任一元素的差值的最大值。
# 暴力解法时间复杂度是o(n^2),下面的解法可以达到O(N)
def maxDifference(nums):
res = float('-inf')
ma = nums[0]
for num in nums[1:]:
res = max(res, ma - num)
ma = max(ma, num)
return res
if __name__ == '__main__':
nums = [1, 1, 1]
print(maxDifference(nums))
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2020/6/24 20:26
# @Author : wenlei
'''
用一个数组实现固定大小的队列和栈
'''
class ArrayStack():
def __init__(self, init_size):
if init_size < 0:
raise Exception('stack size less than 0')
self.arr = [None] * init_size
self.index = 0 # 新数应存放的位置
def push(self, num):
if self.index == len(self.arr):
raise Exception('stack full')
self.arr[self.index] = num
self.index += 1
def pop(self):
if self.index == 0:
raise Exception('stack empty')
self.index -= 1
return self.arr[self.index]
# 获取栈顶元素
def peak(self):
if self.index == 0:
return None
return self.arr[self.index - 1]
class ArrayQueue():
def __init__(self, init_size):
if init_size < 0:
raise Exception('queue size less than 0')
self.arr = [None] * init_size
self.end = 0
self.start = 0
self.size = 0
def push(self, num):
self.size += 1
if self.size > len(self.arr):
raise Exception('stack full')
self.arr[self.end] = num
self.end = 0 if self.end == len(self.arr) - 1 else self.end + 1
def pop(self):
if self.size == 0:
raise Exception('stack empty')
self.size -= 1
tmp = self.start
self.start = 0 if self.start == len(self.arr) - 1 else self.start + 1
return self.arr[tmp]
def peak(self):
if self.size == 0:
return None
return self.arr[self.start]
if __name__ == '__main__':
stack = ArrayQueue(3)
stack.push(1)
stack.push(2)
print(stack.pop())
stack.push(3)
print(stack.pop())
stack.push(4)
stack.push(5)
print(stack.peak())
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/7/27 9:49
# @Author : wenlei
'''
二分查找:
1. 一个数 返回所在下标
2. 数的左右边界 [1,2,3,3,3,4] 查找3返回[2, 4]
参考:https://www.cnblogs.com/kyoner/p/11080078.html
'''
def binarySearch1(nums, target):
'查找一个数'
l, r = 0, len(nums) - 1
while l <= r: # [l, r]
m = l + (r - l) // 2
if nums[m] < target: l = m + 1
elif nums[m] > target: r = m - 1
else: return m
return -1 # 找不到该元素
def binarySearch2(nums, target):
'查找左边界'
if not nums: return -1
l, r = 0, len(nums)
while l < r: # [l, r)
m = l + (r - l) // 2
if nums[m] < target: l = m + 1
elif nums[m] >= target: r = m
# 此时l == r, l表示了target左边有多少个小于它的数, 取值范围为[0, len(nums)]
if l == len(nums): return -1
return l if nums[l] == target else -1
def binarySearch3(nums, target):
'寻找右边界'
if not nums: return -1
l, r = 0, len(nums)
while l < r:
m = l + (r - l) // 2
if nums[m] <= target: l = m + 1
elif nums[m] > target: r = m
# 此时l == r, r - 1表示了target右边有多少个大于它的数, 取值范围为[0, len(nums)]
if r == 0: return -1
return r - 1 if nums[r - 1] == target else -1
if __name__ == '__main__':
nums = [1,2,3,3,4]
target= 5
print(binarySearch1(nums, target)) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/7/10 10:24
# @Author : wenlei
'''
母牛问题
'''
def countCow1(n):
if n < 4:
return n
return countCow1(n - 1) + countCow1(n - 3)
def countCow2(n):
if n < 4:
return n
res = 3
resPre = 2
resPrePre = 1
for i in range(4, n + 1):
tmp = res
res = res + resPrePre
resPrePre = resPre
resPre = tmp
return res
if __name__ == '__main__':
n = 7
print(countCow1(n))
print(countCow2(n))
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2020/6/29 20:13
# @Author : wenlei
'''
打印两个有序链表的公共部分
'''
class Node():
def __init__(self, x):
self.val = x
self.next = None
def printCommonPart(head1, head2):
while head1 and head2:
if head1.val < head2.val:
head1 = head1.next
elif head1.val > head2.val:
head2 = head2.next
else:
print(head1.val)
head1 = head1.next
head2 = head2.next
if __name__ == '__main__':
head1 = Node(2)
head1.next = Node(3)
head1.next.next = Node(5)
head1.next.next.next = Node(6)
head2 = Node(1)
head2.next = Node(2)
head2.next.next = Node(5)
head2.next.next.next = Node(7)
printCommonPart(head1, head2) |
def reversort(n, arr):
cost = 0
for i in range(n - 1):
m = min(arr[i:])
j = arr.index(m) + 1
arr[i: j] = reversed(arr[i: j])
cost += j - i
return cost
if __name__ == '__main__':
test_cases = int(input())
for test_case in range(1, test_cases + 1):
size = int(input())
arr = list(map(int, input().split()))
print(f"Case #{test_case}: {reversort(size, arr)}")
|
class Bicycle(object):
def __init__(self, model, weight, cost):
self.model = model
self.weight = weight
self.cost = cost
class Shop(object):
def __init__(self, name, inventory, margin=20%):
self.name = model
self.inventory = inventory
self.margin = margin
self.profit = 0
def funcnom(self, var1, var2):
#Add bike into inventory
#Sell bike
#Print inventory for each bike it carries
#Print profit
#Print affordable bikes given customer
class Customer(object):
def __init__(self, model, funds=0):
self.name = model
self.funds = funds
self.inventory = []
def funcnom(self, var1, var2):
#Buy a bike, name of purchase, cost, subtract from funds
#money left in funds |
'''Program to print the discount if the CP is greater than 1000
Developer:Aakash
Date:21.02.2020
--------------------------------'''
a=int(input("Enter your CP="))
if(a>1000):
print("You are elegible for Discount!")
b=(10/100)*a
print("Your discount amount is=Rs",b)
else:
print("Oops! You are not elegible for Discount!")
|
'''Program to print the grading of student
Developer:Aakash
Date:21.02.2020
--------------------------------'''
a=int(input("Enter your Percentage="))
if(a<25):
print("You are getting the grade 'F'")
elif(a<45 or a>25):
print("You are getting the grade 'E'")
elif(a<50 or a>45):
print("You are getting the grade 'D'")
elif(a<60 or a>50):
print("You are getting the grade 'C'")
elif(a<80 or a>60):
print("You are getting the grade 'B'")
elif(a>80):
print("You are getting the grade 'A'")
else:
print("Oops! You are not putting wrong value!")
|
'''Program to print the sum of 1-2+3+4-5+6-7.............n
Developer:Aakash
Date:03.03.2020
--------------------------------'''
a=int(input("Enter the number for which you want sum up="))
i=1;j=2
su=0;sm=0;
while(i<=a):
su=su+i
i=i+2
print("The odd sum is=",su)
while(j<=a):
sm=sm+j
j=j+2
print("The even sum is=",sm)
print("The desired sum is=",su-sm)
|
'''Program to print the leap year
Developer:Aakash
Date:24.02.2020
--------------------------------'''
year=int(input("Enter the year="))
if((year%400 == 0)or((year%4 == 0)and(year%100!= 0))):
print("You are entering a leap year")
else:
print("Oops! You are not entering a leap year!")
|
t=int(input())
while t>0:
n=int(input())
count=0
while n>0:
if n%2==1:
count+=1
n=int(n/2)
if count==1:
print("YES")
else:
print("NO")
t-=1
|
def checkTheProductOfNumbers(integers):
total = 1
length = len(integers)
digits = integers[:]
while length > 0:
total *= digits[length - 1]
length -= 1
return total
print(checkTheProductOfNumbers([4, 5, 5, 6, 7]))
|
import random
#sekwencja slow do wyboru
WORDS = ("python", "anagram", "latwy", "skomplikowany", "odpowiedz", "ksylofon")
word = random.choice(WORDS)
correct = word
anagram = ""
while word:
position = random.randrange(len(word))
anagram += word[position]
word = word[:position] + word[(position + 1):]
print("\nZgadnij, jakie to slowo: ", anagram)
guess = ("\nTwoja odpowiedz: ")
while guess != correct and guess != "":
print("Niestety, to nie to slowo")
guess = input("Twoja odpowiedz ")
input("\nDobrze, aby zakonczyc, nacisnij Enter.") |
#Demonstruje zmienne i metody prywatne
class Critter(object):
"""Wirtualny pupil"""
def __init__(self, name, mood):
print('Urodzil sie niey zwierzak!')
self.name = name
self.__mood = mood #Atrybut prywatny
def talk(self):
print('\nJestem', self.name)
print('W tej chwili czuje sie', self.__mood, '\n')
def __private_method(self):
print('To jest metoda prywatna.')
def public_method(self):
print('To jest metoda publiczna')
self.__private_method()
crit = Critter(name='Reksio', mood='szczesliwy')
crit.talk()
crit.public_method() |
class Critter(object):
"""Wirtualny pupil"""
def __init__(self, name):
print('Urodzil sie nowy zwierzak')
self.__name = name
@property
def name(self):
return self.__name
@name.setter
def name(self, new_name):
if new_name == "":
print('Pusty lancuch - nie mozna przypisac')
else:
self.__name = new_name
print('Zmiana sie powiodla')
def talk(self):
print('Czesc, jestem', self.name)
#Main part
crit = Critter('Reksio')
crit.talk()
#przez wlasciwosc:
print('Imie mojego zwierzaka to', end = ' ')
print(crit.name)
print('\nProbuje zmienic imie mojego zwierzaka na pusty lancuch znakow...')
crit.name=''
print('Teraz nazywa sie', crit.name) |
# 10.Calcular el área y perímetro de un rectángulo.
class Recatangulo:
def __init__(self,ancho,alto):
self.ancho=ancho
self.alto=alto
def area(self):
area=self.alto*self.ancho
return area
def perimetro(self):
perimetro=(self.alto*2)+(self.ancho*2)
return perimetro
r1=Recatangulo(4,2)
area=r1.area()
perimetro=r1.perimetro()
print("El area es:",area)
print("El perimetro es:",perimetro)
|
# Log a single temperature record from the json data, create a graph to go with it.
import requests
import logging
import json
from datetime import datetime
from matplotlib import pyplot as plt
from matplotlib.pyplot import figure
from dbconnector import DBConnector
from const import Const
from config import Config
class LogTemperature:
def __init__(self):
self.config = Config()
# setup variables
self.const = Const();
# Set logging level and info
logging.basicConfig(level=self.config.LOG_LEVEL, format=self.const.LOG_FORMAT)
# Use the database connection to retrieve the temperature information.
def retrieveTemperatureData(self):
temperatureData = requests.get(self.config.DATA_KNMI_JSON_LOCATION).json()
db = DBConnector()
alerttext = ''
if temperatureData['liveweer'][0]['alarm'] == 1:
alerttext = temperatureData['liveweer'][0]['alarmtxt']
db.insertTemperatureLog(datetime.now(),temperatureData['liveweer'][0]['temp'],alerttext)
# Create the graph to send the temperature information
def createGraph(self):
db = DBConnector()
temperatureData = db.getTemperatureGraphData()
x = [] # times
y = [] # temps
for i in range(len(temperatureData)-1,-1,-1):
x.append(temperatureData[i][0].strftime(self.const.TEMPERATURE_GRAPH_DATE_FORMAT))
y.append(temperatureData[i][1])
figure(num=None, figsize=(16, 9), dpi=100, facecolor='w', edgecolor='k')
plt.plot(x,y)
plt.xlabel("Time")
plt.ylabel("Temperature")
plt.title('Temperature over time')
logging.info('Save historic data graph for temperature')
plt.savefig(self.const.TEMPERATURE_GRAPH_FILENAME)
if __name__ == '__main__':
temperatureLogger = LogTemperature()
temperatureLogger.retrieveTemperatureData()
temperatureLogger.createGraph() |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#Importing Data
election = pd.read_csv("file:///E:/excelr/Excelr Data/Assignments/Logisitc Regression/election_data.csv")
print(election)
election.head()
#removing CASENUM
election.drop(["Election-id"],axis=1)
temp = election.drop(["Election-id"],axis=1,inplace=True)
?election.drop
##temp = claimants.drop(claimants.index[[0,1,2,3]],axis=0)
election.head(4)# to see top 10 observations
# usage lambda and apply function
# apply function => we use to apply custom function operation on
# each column
# lambda just an another syntax to apply a function on each value
# without using for loop
election.isnull().sum()
sns.boxplot(x="Result",y="Year",data=election)
plt.boxplot(election.Year)
plt.boxplot(election.AS)
plt.boxplot(election.PR)
election.describe()
##sample to apply
election.apply(lambda x:x.mean())
election.mean()
#Imputating the missing values with most repeated values in that column
# lambda x:x.fillna(x.value_counts().index[0])
# the a
bove line gives you the most repeated value in each column
election.Result.value_counts()
election.Result.value_counts().index[0]#1 # gets you the most occuring value
election.Result.mode()[0]#1
election.isnull().sum()
election.isna().sum()
election.iloc[:,0:0] = Result.iloc[:,0:0].apply(lambda x:x.fillna(x.mode()[0]))
election.isnull().sum()
#claimants.SEATBELT = claimants.SEATBELT.fillna(claimants.SEATBELT.value_counts().index[0])
election.iloc[:,0:0].columns
election.Year = election.Year.fillna(election.Year.mean())
# filling the missing value with mean of that column
election.iloc[:,1:] = election.iloc[:,1:].apply(lambda x:x.fillna(x.mean()))
election.AS=election.AS.fillna(election.AS.mean())
election.iloc[:,2:] = election.iloc[:,2:].apply(lambda x:x.fillna(x.mean()))
election.PR=election.PR.fillna(election.PR.mean())
election.iloc[:,3:] = election.iloc[:,3:].apply(lambda x:x.fillna(x.mean()))
# Checking if we have na values or not
election.isnull().sum() # No null values
from scipy import stats
import scipy.stats as st
st.chisqprob = lambda chisq, df: stats.chi2.sf(chisq, df)
#Model building
import statsmodels.formula.api as sm
logit_model=sm.logit('Result~Year+AS+PR',data=election).fit()
#summary
logit_model.summary()
y_pred = logit_model.predict(election)
election["pred_prob"] = y_pred
# Creating new column for storing predicted class of Attorney
# filling all the cells with zeroes
election["Att_val"] = 0
# taking threshold value as 0.5 and above the prob value will be treated
# as correct value
election.loc[y_pred>=0.5,"Att_val"] = 1
election.Att_val
from sklearn.metrics import classification_report
classification_report(election.Att_val,election.Result)
# confusion matrix
confusion_matrix = pd.crosstab(election['Result'],election.Att_val)
confusion_matrix
accuracy = (4+3)/(9) # 0.7777
accuracy
# ROC curve
from sklearn import metrics
# fpr => false positive rate
# tpr => true positive rate
fpr, tpr, threshold = metrics.roc_curve(election.Result, y_pred)
# the above function is applicable for binary classification class
plt.plot(fpr,tpr);plt.xlabel("False Positive");plt.ylabel("True Positive")
roc_auc = metrics.auc(fpr, tpr) # area under ROC curve
### Dividing data into train and test data sets
election.drop("Att_val",axis=1,inplace=True)
from sklearn.model_selection import train_test_split
train,test = train_test_split(election,test_size=0.3)
# checking na values
train.isnull().sum();test.isnull().sum()
# Building a model on train data set
train_model = sm.logit('Result~Year+AS+PR',data = train).fit()
#summary
train_model.summary()
train_pred = train_model.predict(train.iloc[:,1:])
# Creating new column for storing predicted class of Attorney
# filling all the cells with zeroes
train["train_pred"] = np.zeros(938)
# taking threshold value as 0.5 and above the prob value will be treated
# as correct value
train.loc[train_pred>0.5,"train_pred"] = 1
# confusion matrix
confusion_matrix = pd.election(train['Result'],train.train_pred)
confusion_matrix
accuracy_train = (3+4)/(9) # 0.77777777
accuracy_train
# Prediction on Test data set
test_pred = train_model.predict(test)
# Creating new column for storing predicted class of Attorney
# filling all the cells with zeroes
test["test_pred"] = np.zeros(402)
# taking threshold value as 0.5 and above the prob value will be treated
# as correct value
test.loc[test_pred>0.5,"test_pred"] = 1
# confusion matrix
confusion_matrix = pd.crosstab(test['Result'],test.test_pred)
confusion_matrix
accuracy_test = (7)/(9) # 0.7777777
accuracy_test
|
# Program Input Variabel #
print("""
|---------------------------------------------------|
| Program Input Data Mahasiswa |
| ====================================== |
|---------------------------------------------------|
""")
import json
x = 1
DataInputMahasiswa = {}
while x > 0:
print("\n================================================================================")
print("\nSelamat datang di program sederhana ini. \nSilahkan masukkan data diri anda")
answer = input("Lanjut untuk memasukkan data anda? (Yes/No) ")
print("\n================================================================================")
if answer == "yes" or answer == "Yes":
print("\n================================================================================")
Nama = str(input("Masukkan Nama = "))
NIM = int(input("Masukkan NIM = "))
SMT = int(input("Masukkan Tahun Semester Mahasiswa = "))
TinggiBadan = float(input("Masukkan Tinggi Badan dalam cm = "))
BeratBadan = float(input("Masukkan Berat Badan Mahasiswa = "))
Umur = int(input("Masukkan Umur = "))
Hobi = str(input("Masukkan Hobi Mahasiswa = "))
print("\n================================================================================")
Data = {"Nama Mahasiswa": Nama,
"NIM Mahasiswa": NIM,
"Tahun Semester Mahasiswa": SMT,
"Tinggi Badan Mahasiswa": TinggiBadan,
"Berat Badan Mahasiswa": BeratBadan,
"Umur Mahasiswa": Umur,
"Hobi Mahasiswa": Hobi}
print("\nDiperoleh data Mahasiswa sebagai berikut : ")
print(json.dumps(Data, indent=7))
else:
print("\n================================================================================")
print("\nProgram telah selesai berjalan. Terima kasih telah mencoba :D")
print("\n================================================================================")
break |
kullanici = input("Aklinizda bir sayi tuttu iseniz oyunumuza baslayabiliriz,lutfen entere basiniz")
import random
pctahmin = random.randint(0,100)
print("pc tahmini =",pctahmin)
while True:
kullanici_inputu = input("sayi kucukse +,buyukse - yazin :" )
if kullanici_inputu == "-":
print("kullanici inputu = ",kullanici_inputu)
pctahmin =random.randint(0,pctahmin)
print("pc tahmini =",pctahmin)
elif kullanici_inputu == "+":
print("kullanici inputu = ",kullanici_inputu)
pctahmin = random.randint(pctahmin,100)
print("pc tahmini =", pctahmin)
else:
print("kullanici inputu =",input("enter"))
|
import time
'''
Timer class. Emulates behaviour of matlab's tic/toc
'''
start = None
def tic():
global start
start = time.time()
def toc(verbose=True):
global start
if start is None:
print "Timer is not running!"
return 0
else:
elapsed = time.time() - start
if verbose:
print "Time elapsed: %lfs" % elapsed
start = None
return elapsed
class tictoc(object):
def __init__(self,verbose=None):
self.verbose = verbose
self.start = None
pass
def tic(self):
self.start = time.time()
def toc(self,verbose=None):
verbose = verbose if self.verbose is None else self.verbose
verbose = True if verbose is None else False
if self.start is None:
raise Exception("Timer is not running!")
elapsed = time.time() - self.start
if self.verbose:
print "Time elapsed: %lfs" % elapsed
self.start = None
return elapsed
|
#!/usr/local/bin python3
# -*- coding: utf-8 -*-
def sort_lines_with_n(filepath: str, delimiter: str, col_num: int, reverse: bool) -> list:
"""
入力ファイルの指定カラムでソートする関数
Parameters
----------
filepath: str
入力ファイルパス
delimiter: str
デリミタ文字
col_num: int
指定カラム
reverse: bool
逆順にするか否か
Return
----------
指定カラムの異なり文字列の集合
"""
origin = []
with open(filepath, 'r') as f:
for line in f:
line_split = line.split(delimiter)
line_split[-1] = line_split[-1].rstrip('\n')
origin.append(line_split)
return sorted(origin, key = lambda x: x[col_num-1], reverse = reverse)
def main():
in_filepath = './hightemp.txt'
sorted_lines = sort_lines_with_n(in_filepath, '\t', 3, False)
for line in sorted_lines:
print('\t'.join(line))
if __name__ == '__main__':
main()
|
#!/usr/local/bin python3
# -*- coding: utf-8 -*-
def reverse_str(string: str) -> str:
"""
受け取った文字列を逆順にして返す
Parameter
----------
string: str
逆順にしたい文字列
Return
----------
逆順になった文字列
"""
return string[::-1]
def main():
in_str = 'stressed'
rev_str = reverse_str(in_str)
print('文字列(入力): {}'.format(in_str))
print('文字列(逆順): {}'.format(rev_str))
if __name__ == '__main__':
main() |
#!/usr/local/bin python3
# -*- coding: utf-8 -*-
def joint_alt_str(string1: str, string2: str) -> str:
"""
入力された2つの文字列を交互に結合して1つの文字列にする関数
Parameters
----------
string1, string2: str
結合したい文字列
Return
----------
join_str: str
結合後の文字列
"""
join_str = ''
for c1, c2 in zip(string1, string2):
join_str += c1 + c2
return join_str
def main():
str1 = 'パトカー'
str2 = 'タクシー'
join_str = joint_alt_str(str1, str2)
print('文字列(入力): {},{}'.format(str1, str2))
print('文字列(結合): {}'.format(join_str))
if __name__ == '__main__':
main() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.