text stringlengths 37 1.41M |
|---|
# Min heap, the keys of parent nodes are less than or equal to those of the
# children and the lowest's key is in the root node
class Heap:
# The init method or constructor
def __init__(self, howMany):
self.maxSize = howMany # maximum number of items that can be stored
self.graphToHeap = {} # maps a graph node index to its index in the heap
self.heapToGraph = {} # maps an index in the heap its graph node index
self.lastIndex = -1 # index of the last item in the heap
self.minCost = np.ones((self.maxSize)) * float('inf') # allocate the memory
# PUBLIC methods
def empty(self):
return self.lastIndex == -1
def getMinCost(self, graphIndex):
x = self.heapToGraph[graphIndex]
return self.minCost[x]
def push(self, graphIndex, value):
# if self.lastIndex+1 >= self.maxSize:
# return
self.lastIndex = self.lastIndex + 1
self.minCost[self.lastIndex] = value
self.graphToHeap[graphIndex] = self.lastIndex
self.heapToGraph[self.lastIndex] = graphIndex
current = self.lastIndex
# heapify upwards
while (current > 0 and self.minCost[current] < self.minCost[self._parent(current)]):
self.swap(current, self._parent(current))
current = self._parent(current)
def pop(self):
if not self.empty():
popped = self.minCost[0]
x = self.heapToGraph[0]
self.minCost[0] = self.minCost[self.lastIndex]
self.minCost[self.lastIndex] = float('inf')
y = self.heapToGraph[self.lastIndex]
self.heapToGraph[0] = y
self.lastIndex = self.lastIndex - 1
self.graphToHeap[y] = 0
self.heapify(0) # heapify down
return (x, popped)
def promote(self, graphIndex, newCost):
self.minCost[self.graphToHeap[graphIndex]] = newCost
# heapify from the parent or not
self.heapify(self.graphToHeap[graphIndex])
# heapify down
def heapify(self, x):
if not ((x >= ((self.lastIndex + 1) // 2) and x <= self.lastIndex + 1)):
if (self.minCost[x] > self.minCost[self._leftC(x)] or self.minCost[x] > self.minCost[self._rightC(x)]):
if self.minCost[self._leftC(x)] < self.minCost[self._rightC(x)]:
self.swap(x, self._leftC(x))
self.heapify(self._leftC(x))
else:
self.swap(x, self._rightC(x))
self.heapify(self._rightC(x))
def printHeap(self):
# useful for debugging
for i in range(0, self.maxSize // 2):
if self._rightC(i) < self.maxSize:
print("p = %5.3f l = %5.3f r = %5.3f" %
(self.minCost[i], self.minCost[self._leftC(i)], self.minCost[self._rightC(i)]))
else:
print("p = %5.3f l = %5.3f" %
(self.minCost[i], self.minCost[self._leftC(i)]))
def _parent(self, index):
return floor((index - 1) / 2)
def _leftC(self, index):
return 2 * index + 1
def _rightC(self, index):
return 2 * index + 2
def swap(self, x, y):
i = self.heapToGraph[x]
j = self.heapToGraph[y]
self.minCost[x], self.minCost[y] = self.minCost[y], self.minCost[x]
self.graphToHeap[i] = y
self.graphToHeap[j] = x
self.heapToGraph[x] = j
self.heapToGraph[y] = i
|
"""A library to load the MNIST image data."""
import pickle
import gzip
import os
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
def load_data():
"""Return the MNIST data as a tuple containing the training data
and the test data.
The ``training_data`` is returned as a tuple with two entries.
The first entry contains the actual training images. This is a
numpy ndarray with 50,000 entries. Each entry is, in turn, a
numpy ndarray with 784 values, representing the 28 * 28 = 784
pixels in a single MNIST image.
The second entry in the ``training_data`` tuple is a numpy ndarray
containing 50,000 entries. Those entries are just the digit
values (0...9) for the corresponding images contained in the first
entry of the tuple.
``test_data`` contains 10,000 images."""
f = gzip.open("mnist.pkl.gz", 'rb')
training_data, validation_data, test_data = pickle.load(f, encoding="latin1")
f.close()
return (training_data, validation_data, test_data)
def load_data_wrapper():
"""Return a tuple containing ``(training_data, test_data)``.
In particular, ``training_data`` is a list containing 50,000
2-tuples ``(x, y)``. ``x`` is a 784-dimensional numpy.ndarray
containing the input image. ``y`` is a 10-dimensional
numpy.ndarray representing the unit vector corresponding to the
correct digit for ``x``.
``test_data`` is a list containing 10,000
2-tuples ``(x, y)``. ``x`` is a 784-dimensional
numpy.ndarry containing the input image, and ``y`` is the
corresponding classification, i.e., the digit values (integers)
corresponding to ``x``.
Obviously, this means we're using slightly different formats for
the training data and the test data. These formats
turn out to be the most convenient code."""
tr_d, va_d, te_d = load_data()
training_inputs = [np.reshape(x, (784, 1)) for x in tr_d[0]]
#test_inputs = [np.reshape(x, (784, 1)) for x in te_d[0]]
test_inputs = [np.reshape(x, (784, 1)) for x in va_d[0]]
n_components = 784
use_PCA = True
if use_PCA:
n_components = 50
pca = PCA(n_components)
x_train = np.hstack(training_inputs)
pca.fit(x_train.transpose())
x_transformed_train = pca.transform(x_train.transpose())
training_inputs = x_transformed_train
x_test = np.hstack(test_inputs)
x_transformed_test = pca.transform(x_test.transpose())
test_inputs = x_transformed_test
training_data = (training_inputs, tr_d[1])
test_data = (test_inputs, va_d[1])
return training_data, test_data, x_test.transpose()
|
# import pyspark class Row from module sql
from pyspark.sql import *
from pyspark import *
from pyspark import SparkContext
import pyspark
sc = SparkContext(appName="csv2")
# Create Example Data - Departments and Employees
# Create the Departments
department1 = Row(id='123456', name='Computer Science')
department2 = Row(id='789012', name='Mechanical Engineering')
department3 = Row(id='345678', name='Theater and Drama')
department4 = Row(id='901234', name='Indoor Recreation')
# Create the Employees
Employee = Row("firstName", "lastName", "email", "salary")
employee1 = Employee('michael', 'armbrust', 'no-reply@berkeley.edu', 100000)
employee2 = Employee('xiangrui', 'meng', 'no-reply@stanford.edu', 120000)
employee3 = Employee('matei', None, 'no-reply@waterloo.edu', 140000)
employee4 = Employee(None, 'wendell', 'no-reply@berkeley.edu', 160000)
# Create the DepartmentWithEmployees instances from Departments and Employees
departmentWithEmployees1 = Row(department=department1, employees=[employee1, employee2])
departmentWithEmployees2 = Row(department=department2, employees=[employee3, employee4])
departmentWithEmployees3 = Row(department=department3, employees=[employee1, employee4])
departmentWithEmployees4 = Row(department=department4, employees=[employee2, employee3])
print(department1)
print(departmentWithEmployees1.employees[0].email)
departmentsWithEmployeesSeq1 = [departmentWithEmployees1, departmentWithEmployees2]
df1 = sc.createDataFrame(departmentsWithEmployeesSeq1)
departmentsWithEmployeesSeq2 = [departmentWithEmployees3, departmentWithEmployees4]
df2 = sc.createDataFrame(departmentsWithEmployeesSeq2)
unionDF = df1.unionAll(df2)
#dbutils.fs.rm("/tmp/databricks-df-example.parquet", True)
unionDF.write.parquet("databricks-df-example.parquet")
explodeDF = unionDF.selectExpr("e.firstName", "e.lastName", "e.email", "e.salary")
explodeDF.show()
filterDF = explodeDF.filter(explodeDF.firstName == "xiangrui").sort(explodeDF.lastName)
|
def two_sort(array):
x = [x[0] for x in sorted(array)]
print(x)
for el in x:
many = x.count(el)
if many > 1:
print(x.count(el), "litera:", el)
# c x[el]
for i in range(many):
x.remove(el)
# print(x.count(el), "litera:", el)
#print(len(x))
print(x)
nowalista = []
for i in range(len(x)-1):
nowalista.append(x[i]+'***')
nowalista.append(x[-1])
fullStr = ''.join(nowalista)
print(fullStr)
return fullStr
#print(x)
#print(nowalista)
# result = print(*x, sep="***")
# print(type(result))
# return result
test = two_sort(["bitcoin", "take", "over", "the", "world", "maybe", "who", "knows", "perhaps"])
# test2 = two_sort(["Lets", "all", "go", "on", "holiday", "somewhere", "very", "cold"])
|
def filter_list(l):
x = [x for x in l if type(x) == type(1)]
print(x)
return x
filter_list([1,2,'a','b',123])
def filter_1(l):
x = [x for x in l if isinstance(x, int)]
print(x)
return x
filter_1([1,2,'aasf','1','123',123])
def filter_2(l):
x = list(filter(lambda x: isinstance(x, int),l))
print(x)
return x
filter_2([1,2,'a','b',3232])
|
# coding: UTF-8
import chainer
from chainer import Variable
import numpy as np
# numpyの配列を作成
input_array = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float32)
print(input_array)
# Variableオブジェクトを作成
x = Variable(input_array)
print(x.data)
# 計算
# y = x * 2 + 1
y = x ** 2 + 2 * x +1 # y'=2*x+2
print(y.data)
# 微分値を求める
# 要素が複数の場合は xxx.grad に初期値が必要
y.grad = np.ones((2, 3), dtype=np.float32)
# y→x と遡って微分値を求める
y.backward()
# y=x*2+1 の微分形は y=2
print(x.grad) |
#!/usr/bin/env python3
# Michal Glos
# Polynomial class
#
# The objective of this project is to create polynomial
# class, with python "magic" methods equal, not equal
# adding, power and string representation. Implementation
# should also include its derivative, its value when x is constant
# and differention of function value between two parameters (Function at_value)
#
class Polynomial():
""" Class which can hold polynoms and perform basic operations over them such as addition, exponentioation, derivation, differention and comparison """
def __init__(self, *args, **kwargs):
""" Initializes new instance of Polynomial class, accepts several ints as args, list of ints or keyword arguments"""
pol_list = list() # list for adding *args
for arg in args: # iterate through args
if type(arg) == list:
for i in arg[:1:-1]: # getting rid of redundant zeros at the end of the list
if i == 0:
arg.pop()
else:
break
self.polynom_list = arg # if arg is list, save list as polynom_list and return
return None
else: # else append the value
pol_list.append(arg)
for variable, value in kwargs.items(): # iterate through **kwargs
while int(variable[1:]) >= len(pol_list): # of index out of range, append zeros to polynom_list, then rewrite them with actual value
pol_list.append(0)
pol_list[int(variable[1:])] = value
for i in pol_list[:1:-1]: # getting rid of redundant zeros at the end of the list
if i == 0:
pol_list.pop()
else:
break
self.polynom_list = pol_list
def __eq__(self, other):
""" self == other - returns true if objects are instances of Polynomial and their polynoms are equal"""
if not isinstance(other, Polynomial): # can compare just instances of the same class
return NotImplemented
cmp_list_self, cmp_list_other = self.polynom_list.copy(), other.polynom_list.copy() # copying list of polynom values from both operands
for i in cmp_list_self[::-1]: # getting rid of redundant zeros at the end of the list
if i == 0:
cmp_list_self.pop()
else:
break
for i in cmp_list_other[::-1]: # getting rid of redundant zeros at the end of the list
if i == 0:
cmp_list_other.pop()
else:
break
return cmp_list_self == cmp_list_other # copmaring both lists
def __ne__(self, other):
""" logical not of equal function """
return not self.__eq__(other) # returns negated __eq__ function
def __add__(self, other):
""" Allows user to add two Polynomial classes, returns sum of polynoms"""
if not isinstance(other, Polynomial): # if different class instance, return NotImplemented
return NotImplemented
long_list, short_list = (self.polynom_list.copy(), other.polynom_list.copy()) if len(self.polynom_list) >= len(other.polynom_list) else (other.polynom_list.copy(), self.polynom_list.copy())
# Assigning longer of operands to longer list and vice versa
for i in range(len(short_list)): # iterates through longer list, if there is a value in shorter list on the same index, sums both values and saves them to longer list
if i < len(short_list):
long_list[i] += short_list[i]
else:
return Polynomial(long_list) # if iterated to the end of short list, next values of longer list won't be changed, returns longer list
return Polynomial(long_list)
def __pow__(self, other):
""" Allows pow of Polynomial instance by other (int), returns Polynomial """
if not isinstance(other, int): # if exponent is not int, function is not defined
return NotImplemented
powered_polynom_list = [0] * len(self.polynom_list) # empty polynom, numbers to be assigned later
old_polynom_list = self.polynom_list.copy() # copy of Polynomial instance (for counting)
for i in range(other - 1): # repeating polynom multiplication
powered_polynom_list += [0] * ((len(self.polynom_list.copy())) - 1) # add to powered polygon space for larger exponents (double neght - 1)
for j in range(len(powered_polynom_list) - (len(self.polynom_list)) + 1): # iterate through powered polynom, multiply each item
for k in range(len(self.polynom_list)): # multiply each element
powered_polynom_list[j + k] += old_polynom_list[j] * self.polynom_list[k] # multiplying exponnents, add them => x^j * x^k = x^(j+k)
old_polynom_list = powered_polynom_list.copy() # moving result to old list for nex iteration
powered_polynom_list = [0] * len(powered_polynom_list) # assign zeros to blank list for next iteration
return Polynomial(old_polynom_list)
def __str__(self):
""" Prints polynom_list. Returns polynom as string (including multiplied X) """
if set(self.polynom_list)== {0}: # if list contains just zeros, return "0"
return "0"
polynom = ""
for i in range(0, len(self.polynom_list)): # iterate through polynom to determine its format of variable
if(self.polynom_list[i] == 0): # if 0x^n => ""
continue
elif( i == 0 ): # x^0 = 1 => 3x^0 = 3
polynom = str(self.polynom_list[i])
elif( abs(self.polynom_list[i]) == 1 ): # 1x^n = x^n
polynom = ("" if self.polynom_list[i] > 0 else "-") + "x^{} + ".format(i) + polynom if polynom != "" else "x^{}".format(i)
else: # full form of polygon nx^p
polynom = "{}x^{} + ".format(str(self.polynom_list[i]), i) + polynom if polynom != "" else "{}x^{}".format(str(self.polynom_list[i]), i)
return polynom.replace(" + -", " - ").replace("x^1", "x")
def derivative(self):
""" Returns derivated polynom as instance of Polynomial class"""
if len(self.polynom_list) == 1: # if polynom contains just constnt, it's derivative is 0
return Polynomial(0)
derivatited_list = [0] * (len(self.polynom_list) - 1) # blank list to assign derivated polynom
for i in range(1, len(self.polynom_list)): # each expression is derivated and assigned to derivated list
derivatited_list[i - 1] = self.polynom_list[i] * i
return Polynomial(derivatited_list)
def at_value(self, *args):
""" Calculates difference of function values of 2 arguments ( f(arg2) - f(arg2) ), if only one arguemnt is passed, returns f(arg) """
polynom_sum = 0
for number in args: # iterates through arguments
polynom_sum *= -1 # in case of second iteration (2 args) first value is negated
if type(number) == int or float: # check of argument datatypes
for i in range(len(self.polynom_list)): # sum all polynom items
polynom_sum += self.polynom_list[i] * (number**i)
else:
return NotImplemented
return polynom_sum
|
from tkinter import *
root = Tk()
def myClick():
myLabel = Label(root, text = "You Clicked!!")
myLabel.pack()
myButton = Button(root, text = "Click Me!", fg = "white", bg = "black", padx = 20, pady = 20, command=myClick)
myButton.pack()
root.mainloop() |
#! /usr/bin/env python
import argparse
import sys
from brew.utilities.temperature import fahrenheit_to_celsius
from brew.utilities.temperature import celsius_to_fahrenheit
def main(args):
if args.fahrenheit and args.celsius:
print("Must provide only one of Fahrenheit or Celsius")
sys.exit(1)
if args.fahrenheit:
out = fahrenheit_to_celsius(args.fahrenheit)
elif args.celsius:
out = celsius_to_fahrenheit(args.celsius)
print(round(out, 2))
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Temperature Conversion')
parser.add_argument('-c', '--celsius', metavar='C', type=float,
help='Temperature in Celsius')
parser.add_argument('-f', '--fahrenheit', metavar='F', type=float,
help='Temperature in Fahrenheit')
args = parser.parse_args()
main(args)
|
# 1. Add 2 numbers
a = 10
b = 25
print(a+b)
# 2. Try to add integer with string and see the output
c = '15'
# print(a+c) This line makes an error by the different data types
print(a+int(c))
# 3.Print variable and strings in one line with the help of f string
print(f"The c variable is: {c}")
# 4.How to add space and new line in the print statement
print("This is a \
simple string")
print("This is a \nsimple string")
|
class Solution:
'''
执行结果:通过
执行用时:40 ms, 在所有 Python3 提交中击败了63.88%的用户
内存消耗:15.1 MB, 在所有 Python3 提交中击败了5.24%的用户
'''
def generateMatrix(self, n):
matrix = [[0] * n for i in range(n)]
i,j = 0,0
val = 1
right_boundary = n - 1
down_boundary = n - 1
left_boundary = 0
up_boundary = 1
while val < n * n:
#向右
while j < right_boundary:
matrix[i][j] = val
val += 1
j += 1
right_boundary -= 1
#向下
while i < down_boundary:
matrix[i][j] = val
val += 1
i += 1
down_boundary -= 1
#向左
while j > left_boundary:
matrix[i][j] = val
val += 1
j -= 1
left_boundary += 1
#向上
while i > up_boundary:
matrix[i][j] = val
val += 1
i -= 1
up_boundary += 1
#补上最后一个
matrix[i][j] = val
print(matrix)
return matrix
s = Solution()
s.generateMatrix(1)
|
class Solution:
def rotate(self, matrix):
length = len(matrix)
matrix_copy = [[0] * length for i in range(length)]
for i in range(length):
k = 0
for j in reversed(range(length)):
matrix_copy[i][k] = matrix[j][i]
k += 1
#拷贝数组
for i in range(length):
for j in range(length):
matrix[i][j] = matrix_copy[i][j]
print(matrix)
s = Solution()
s.rotate([[1,2,3],[4,5,6],[7,8,9]])
|
class Solution:
'''
执行结果:通过
执行用时:48 ms, 在所有 Python3 提交中击败了16.48%的用户
内存消耗:15.1 MB, 在所有 Python3 提交中击败了69.19%的用户
两次二分法
'''
def searchMatrix(self, matrix, target):
if matrix[0][0] > target:
return False
if matrix[-1][-1] < target:
return False
def binarySearch_matrix(matrix,start,end,target):
if start >= end:
return start
middle = (start + end) // 2
if matrix[middle][0] > target:
return binarySearch_matrix(matrix,start,middle - 1,target)
elif matrix[middle][-1] < target:
return binarySearch_matrix(matrix,middle + 1,end,target)
else:
return middle
key = binarySearch_matrix(matrix,0,len(matrix) - 1,target)
def binarySearch_target(interval,start,end,target):
if start >= end:
return start
middle = (start + end) // 2
if interval[middle] > target:
return binarySearch_target(interval,start,middle - 1,target)
elif interval[middle] < target:
return binarySearch_target(interval,middle + 1,end,target)
else:
return middle
ans = binarySearch_target(matrix[key],0,len(matrix[0]) - 1,target)
if matrix[key][ans] == target:
return True
return False
|
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
'''
执行结果:通过
执行用时:36 ms, 在所有 Python3 提交中击败了99.04%的用户
内存消耗:14.8 MB, 在所有 Python3 提交中击败了75.49%的用户
一次通过Nice!!!这种题还是得好好画图,看清楚各种特殊情况。
'''
def deleteDuplicates(self, head: ListNode) -> ListNode:
#链表为空,直接返回
if not head:return
#链表长为1,直接返回链表
if not head.next:return head
#添加Dummy节点,方便处理从头开始重复的链表
dummy = ListNode('dummy',head)
'''
三指针
l:重复开始节点的前驱节点
m:重复开始节点
r:重复结束节点
'''
l,m,r = dummy,head,head.next
while r:
#重复区间
if m.val == r.val:
while r and r.val == m.val:
r = r.next
if r:
l.next = r
if r.next and r.val != r.next.val:
l = r
m = r.next
r = r.next.next
else:#此处l指针不能动
m = r
r = r.next
else:
l.next = None
#m、r不重复
else:#全部向后移动一位
l = l.next
m = m.next
r = r.next
return dummy.next
'''
执行结果:通过
执行用时:48 ms, 在所有 Python3 提交中击败了67.08%的用户
内存消耗:14.9 MB, 在所有 Python3 提交中击败了46.16%的用户
尝试代码简化,三指针降为双指针,令人惊讶的是时间还变长了!!!
'''
def deleteDuplicates2(self, head: ListNode) -> ListNode:
if not head or not head.next:return head
dummy = ListNode('dummy',head)
# slow为重复节点的前驱节点 quick为重复节点的结束节点
slow,quick = dummy,head
while quick:
#重复啦,重复啦!!
if quick.next and quick.val == quick.next.val:
dup = quick.val
while quick and quick.val == dup:
quick = quick.next
if quick:
slow.next = quick
if quick.next and quick.next.val != quick.val:
slow = quick
quick = quick.next
else:
slow.next = None
#不重复
else:#都向后挪一位
slow = slow.next
quick = quick.next
return dummy.next
|
class ListNode:#单链表
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def addTwoNumbers(self, l1, l2):
int1 = 0
int2 = 0
i = 0
while l1:
int1 += l1.val * (10**i)
i += 1
l1 = l1.next
j = 0
while l2:
int2 += l2.val * (10**j)
j += 1
l2 = l2.next
#print(int1,int2,int1+int2)
result = int1 + int2
root = None
current_node = None
#print('1',1,'#')
#rint(root.val)
for x in reversed(str(result)):
if not root:
root = ListNode(int(x))
current_node = root
else:
current_node.next = ListNode(int(x))
current_node = current_node.next
print(root.val)
self.printnode(root)
return root
'''
#列表形式
for i,x in enumerate(l1):
int1 += x * (10**i)#10的i次幂
for j,y in enumerate(l2):
int2 += y * (10**j)#10的j次幂
result = int1 + int2
l_res = list(str(result))#整形转字符
l_result = []
for x in reversed(l_res):#逆转列表
l_result.append(int(x))#字符转整形
print(l_result)
return l_result
'''
def printnode(self,node):
l = []
while node:
l.append(node.val)
node = node.next
print(l)
node1 = ListNode(4)
node2 = ListNode(6)
node3 = ListNode(8)
node4 = ListNode(9)
node1.next = node2
node2.next = node3
node3.next = node4
node5 = ListNode(5)
node6 = ListNode(7)
node7 = ListNode(1)
node8 = ListNode(2)
node5.next = node6
node6.next = node7
node7.next = node8
s = Solution()
s.addTwoNumbers(node1,node5) |
'''
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。
注意:答案中不可以包含重复的三元组。
示例 1:
输入:nums = [-1,0,1,2,-1,-4]
输出:[[-1,-1,2],[-1,0,1]]
示例 2:
输入:nums = []
输出:[]
示例 3:
输入:nums = [0]
输出:[]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/3sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
'''
class Solution:
def threeSum(self, nums):#超出时间限制
first_r = self.C(nums,len(nums),3)
second_r = []
result = []
print(first_r)
for x in first_r:
if set(x) not in second_r:
result.append(x)
second_r.append(set(x))
print(result)
return result
#要如何对列表去重呢?
def C(self,sequence,n,m,result=[]):
if type(sequence) != type([]): # 类型检查
return []
if n < m: # 参数合法性检查
return []
if m == 0:
#print(result)
return [result]
if len(result) == 2:
if -result[0]-result[1] not in sequence:
return []
else:
return[[result[0],result[1],-result[0]-result[1]]]
all_results = []
for index,value in enumerate(sequence):
r = self.C(sequence[index+1:],n,m-1,result+[value])
all_results.extend(r)
return all_results
def threeSum2(self, nums):#双指针
if not nums or len(nums) < 3:
return []
if nums.count(0) == len(nums):
print([0,0,0])
return [0,0,0]
result = []
nums.sort()#默认升序
for k,v in enumerate(nums):
if v > 0:
return result
if k > 0 and v == nums[k-1]:#跳过重复元素
continue
L = k + 1
R = len(nums) - 1
while(L < R):
if v + nums[L] + nums[R] == 0:
result.append([v,nums[L],nums[R]])
print(result)
while(L < R and nums[L] == nums[L + 1]):#跳过重复元素
L += 1
while(L < R and nums[R] == nums[R - 1]):#跳过重复元素
R -= 1
L += 1
R -= 1
elif v + nums[L] + nums[R] > 0:
R -= 1
else:
L += 1
return result
s = Solution()
s.threeSum2([-1,0,1,2,-1,-4])
print([-1,0,1]==[0,1,-1])
print(set([-1,0,1])==set([0,1,-1]))
print(set([0,1,-1]) in [set([-1,0,1]),set([-1,2,-1]),set([0,1,-1])]) |
print('This is Visual Studio Code!')
#计算a+b,a-b
a = input('input number a :')
a = int(a)#强制类型转换
b = input('input number b :')
b = int(b)#强制类型转换
c = a + b
d = a - b
print('a + b = %d a - b = %2d' % (c,d) )
#转义字符使用
print('I\'m learning Python 3.8')
#不转义使用
print(r'默认\\不转义\\')
#多行打印
print('''多行测试
line1
line2
line3 ''')
a = 'ABC'
b = a
a = 'XYZ'
print('''a = 'ABC'
b = a
a = 'XYZ' ''')
print(b)
#计算成绩提升率
s1 = input('请输入上次成绩:')
s1 = int(s1)
s2 = input('请输入当前成绩:')
s2 = int(s2)
r = (s2-s1)*100/s1
print('成绩提升率:%.3f %%' % r) |
'''
Given
an
arbitrary
ransom
note
string
and
another
string
containing
letters from
all
the
magazines,
write
a
function
that
will
return
true
if
the
ransom
note
can
be
constructed
from
the
magazines ;
otherwise,
it
will
return
false.
Each
letter
in
the
magazine
string
can
only
be
used
once
in
your
ransom
note.
Note:
You may assume that both strings contain only lowercase letters.
canConstruct("a", "b") -> false
canConstruct("aa", "ab") -> false
canConstruct("aa", "aab") -> true
'''
class Solution(object):
def canConstruct(self, ransomNote, magazine):
"""
:type ransomNote: str
:type magazine: str
:rtype: bool
"""
rList = list(ransomNote.lower().replace(" ",""))
mList = list(magazine.lower().replace(" ",""))
rSet = set(rList)
mSet = set(mList)
#mList =
# unique letters are not sufficient
if len(rSet) > len(mSet) :
return False
print(list(map(lambda x : {x : mList.count(x)},mSet)))
print(list(map(lambda x: {x: rList.count(x)}, rSet)))
for letter in rSet:
if rList.count(letter) > mList.count(letter):
return False
break
return True
|
#Enter the price of the House you wish to Buy
print("Enter the house price")
price = float(input())
#Enter the first name
print("Enter the first name:")
first_name = input()
#Enter the last name
print("Enter the last name:")
#Enter spouse's or partner's first and last name
last_name = input()
print("Enter spouse's or partner's first name: ")
p_first_name = input()
print("Enter spouse's or partner's last name: ")
p_last_name = input()
#Enter the email
print("Enter email: ")
email = input()
#Enter the phone number
print("Enter the phone number: ")
phone = input()
#Enter the mailing address
print("Enter the mailing address: ")
address = input()
#Enter city
print("Enter the City: ")
city = input()
#Enter State
print("Enter the State: ")
state = input()
#Enter zip code
print("Enter the zip code: ")
zipcode = input()
#Added CreditScore variable
print("Enter the client's credit score: ")
CreditScore = int(input())
# initializing variables
fullname = first_name + " " + last_name
partner_name = p_first_name + " " + p_last_name
credit_status = ""
downPayment = 0
# making a decision about the down-payment payable using if-else
if 780 <= CreditScore <= 850:
credit_status = "Excellent Credit"
downPayment = 0.10 * price
elif 740 <= CreditScore <= 779:
credit_status = "Very Good"
downPayment = 0.1 * price
elif 720 <= CreditScore <= 739:
credit_status = "Above Average"
downPayment = 0.3 * price
elif 680 <= CreditScore <= 719:
credit_status = "Average"
downPayment = 0.6 * price
elif 620 <= CreditScore <= 679:
credit_status = "Below Average"
downPayment = 0.18 * price
elif 580 <= CreditScore <= 619:
credit_status = "Poor Credit Score"
downPayment = 0.20 * price
elif CreditScore < 520:
credit_status = "Poor Credit Score"
downPayment = 0.25 * price
print()
print("Name: " + fullname)
print("Physical Address: " + address)
print("City: " + city + " State: " + state + " Zipcode: " + zipcode)
print()
print("New House Price: ${:,.2f}".format(price))
print("Downpayment: ${:,.2f}".format(downPayment))
print("Credit Score: " + str(CreditScore))
print("Credit Status: " + credit_status)
print()
print("CONGRATULATIONS - YOU NOW OWN YOUR DREAM HOME - " + fullname + " and " + partner_name) |
class grandparent:
def __init__(self,h):
self.house= h;
def grandparenthousepro(self):
print("grandparent house is :"+ self.house)
class parent(grandparent):
def __init__(self,c):
self.car = c;
super().__init__(h);
def parenthousepro(self):
print("parent house properties"+self.house);
print("parent car is "+self.car)
class child(parent):
def __init__(self,h,c,b):
self.bike=b;
super(). __init__(h,c);
def childpro(self):
print("child house i s:"+slef.house)
print("child house i s:"+slef.car)
print("child house i s:"+slef.bike)
sub1 = parent("doublexhouse ","hondacity","pleasure");
sub1.childpro();
sub1.parenthousepro();
sub1.grandparenthousepro();
|
#class decleration with methods and veriables
class pythontraning: #class decleration
board = "white board" #class variable
def bookwriting(self,name): #instance method decleration
print("i am writing of book"+str(name));
def listening(self,name):
print('i am listening the class perfectly'+str(name));
def understanding(self,name):
print('i am understandning the class '+str(name));
@staticmethod #static method decleration
def boardreading():
print("all of the plz read board")
@classmethod # class method decleration
def boardreading1(cls):
print("plz read board")
x = pythontraning(); # constructor creation with class name
x.pen="marker" # instance variable creation
x.bookwriting(x.pen) # object variable calling in method by
x.understanding("90%, x ")
y = pythontraning()
y.pen = "santoor"
y.bookwriting(y.pen)
print(pythontraning.board)
pythontraning.boardreading1(); #static method calling
pythontraning.boardreading();# class method calling
|
# https://www.youtube.com/watch?v=dO-HQOAUTyA&list=PLuhNJgi9DRWUS-nAXaXUNWtFvW2574-Tu&index=13
# Алгоритм Евклида
# Greatest common divisor (gcd)
# (a, b) = (a - b, b)
# def gcd(a, b):
# while a != 0 and b != 0:
# if a > b:
# a = a % b
# else:
# b = b % a
# return a + b
#
#
# print(gcd(30, 18))
def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a % b)
print(gcd(30, 18))
# 1/3 + 5/6 = ?
a = 1
b = 3
c = 1
d = 3
a, b = a * d + b * c, b * d
print(a // gcd(a, b), "/", b // gcd(a, b))
|
def fib(n):
if n == 0 or n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
for n in range(0,7):
print(fib(n))
print("===")
foo = fib
del fib
for n in range(0,7):
print(foo(n))
print("===")
|
#Python Module to check for input system arguments, it takes care of all of the input values and processes them ready for use by
#POSTREC. It also takes care of any "nonsense values" ie values that are not feasible to use, ormay have been entered in error.
#It also provides help messages for how to use the program in "function form" where it can be run directly from the terminal/
#command line
##Information on argparse: http://docs.python.org/3.4/library/argparse.html
import sys #Needed to check the input commands
import argparse #Needed to check the system arguments
def check_system_arguments(): #All arguments are put under a single function so that it can be called from the main program.
sys_array = [True, False , 0, False, False]
if (len(sys.argv) > 1): ##If some input arguments have been used, check them
def check_negative(value): ##This function checks if a negative value has been entered
ivalue = int(value) ##converts the input into a numerical value (was a string)
if value == "D" : ##default is accepted
return value
if ivalue < 0:
raise argparse.ArgumentTypeError("%s is an invalid positive integer" % value)
return value
def check_integration_range(value): ##Integration range is a max of 2000 to 0, this
ivalue = int(value) ##function checks the range
if ivalue < 0:
raise argparse.ArgumentTypeError("%s is an invalid positive integer" % value)
if ivalue > 2000:
raise argparse.ArgumentTypeError("%s is an invalid value, select between 2000 and 1" % value)
return float(value)
def check_step_size(value): ##Gives warning about using small step sizes
value = eval(value)
if value < 0.01:
print("\nStep size accepted, however be warned small step sizes cause long completion times")
return float(value)
def check_matter_temp_choice(value):
value = int(value)
if value != 1 and value != 2:
raise argparse.ArgumentTypeError("%s is an invalid choice" % value)
return value
def check_chemical_model(value):
value = int(value)
if value != 1 and value != 2 and value != 3 and value != 4:
raise argparse.ArgumentTypeError("%s is an invalid chemical model" % value)
return value
def check_matter_temp(value):
if value == "D" :
return value
ivalue = int(value)
if ivalue < 0:
raise argparse.ArgumentTypeError("%s is an invalid positive integer" % value)
if value > 10**6:
print("Accepted, but be warned large values can cause instability")
return value
##Below the possible arguments to the function are represented as classes, each with different attributes.
##Each variable has a "help" parameter, which can give the user insight into how to use the function
parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS, description='Inputs ready for integration, note to use a default setting for a particular variable, type "D"')
parser.add_argument('chemical_model',metavar='chemical_model',type=check_chemical_model,
help ='Chemical Model to use. 1 = full model 2=minimal model (faster) 3 = Abel et al 1996 4 = Galli & Palla 1998')
parser.add_argument('Start_point',metavar='Z_initial',type=check_integration_range,
help ='Start point of integration')
parser.add_argument('End_point', metavar='Z_final', type=check_integration_range,
help='End point of the integration')
parser.add_argument('Step_size', metavar='Step_size', type=float,
help='Step size used within the integration')
parser.add_argument('Matter_temperature', metavar='Matter_temperature', type=check_matter_temp,
help='Manual matter temperature at start of integration')
parser.add_argument('Particle_density', metavar='Particle_density', type=check_matter_temp,
help='Particle density used in integration (cm3)')
parser.add_argument('Plotting', metavar='Plotting', type=int, choices = {1,2},
help='Plot the results? 1 = no 2 = yes')
parser.add_argument('Source_function', metavar='Source_function', type=str,
help='Radiation source function to be used in the integration')
parser.add_argument('Startflux', help='Startpoint of the flux spectrum (must be positive)')
parser.add_argument('Endflux', help='endpoint of the flux spectrum (must be positive)')
args = parser.parse_args() ##creates all possible arguments defined above
##If arguments are present on the command line, they are processed and passed back to PostREC
return [True,[args.chemical_model,args.Start_point,args.End_point,args.Step_size, args.Matter_temperature, args.Particle_density ,args.Source_function,args.Plotting]]
else:
##If not, the boolean "False" value prompts PostREC into entering verbose mode, where the user is prompted for input.
return [False,0] |
#Use sequence list
name_b = ['sunvo','pongpan','SunvoDz']
name_b.append('Mahasarakham') #add last
print(name_b)
name_b.insert(0,'Tn.Group') #add first
print(name_b)
name_b.pop() #Delete last
print(name_b)
name_b.pop(1) #Delete array[1]
print(name_b)
number = ['0','1','2','5','4']
number.sort()
print(number)
number.reverse()
print(number)
|
a = ['one','two','tree','four','five']
for test in a:
print(test)
b = 0
while b<20:
b+=1
print("loop %d" %b)
for test_demo in range(5,10):
print(test_demo)
print('\n')
for test_demo in range(5,10+1):
print(test_demo)
print('\n')
for test_demo in range(0,10,2):
print(test_demo)
print('\n')
for test_demo in range(-50,10,10):
print(test_demo)
i=0
number = int(input("Multiplication : "))
while i<12:
i+=1
print('%d * %d = %d' %(number,i,(number*i)))
|
import string
def l_fileline(n):
with open("words1.txt", "w") as file:
alph = s.ascii_upper
l = [alph[i:i + n] + "\n" for i in range(0, len(alph), n)]
file.writelines(l)
l_fileline(n)(3) |
def hyp(string):
x = sorted(string)
print(*x , sep = '-')
hyp(input().split('-')) |
line = input()
words = line.split(' ')
numbers = [int(i) for i in words]
numbers.sort(key = lambda x: x == 0)
print(numbers) |
line = input()
words = line.split(' ')
numbers = [int(i) for i in words]
altitudes = []
al = 0
for i in range(len(numbers)):
al = al + numbers[i]
altitudes.append(al)
max = 0
for i in range(len(altitudes)):
if(altitudes[i] > max):
max = altitudes[i]
print(max)
|
num = 120
def test(num):
if num < 0:
raise ValueError('El número es negativo')
return num
def retest(num):
if test(num) > 100:
print('OK')
retest(-1) |
def words(string):
words_string = string.split()
word_count = {}
for i in words_string:
if i.isdigit():
i = int(i)
if word_count.get(i):
word_count[i] += 1
else:
word_count[i] = 1
return word_count
print (words("olly 12 12 12 in come 45 free come",)) |
def ari_geo(A):
length = len(A)
for i in range(1, length+1):
if A[i+1] - A[i] == A[i+2] - A[i+3]:
return "arithmetic"
elif A[i+1] / A[i] == A[i+2] / A[i+1]:
return "geometric"
elif A == None:
return 0
else:
return -1
print ari_geo([2,4,6,8,10]) |
people = [
('Joe',78),
('Janet',83),
('Brian',67)
]
def super_sum(*args):
return sum(args)
def hello_again(name,age):
return " I am {} and {} years old"
def max_min(A):
'''
Returns max value - min value
e.g. [10, 20, -5, 6]
'''
max_, min_ = A[0],A[0]
for i in A:
if i > max_:
max_ = i
if i < min_:
min_ = i
return max_ - min_ |
def sum_list(numlist):
sum_l = 0
for num in numlist:
sum_l += num
return sum_l
print sum_list([10,8,0,2]) |
class Asteroid:
def __init__(self, x, y):
self.x = x
self.y = y
class Robot:
def __init__(self, x, y, asteroid, direction):
self.x = x
self.y = y
self.direction = direction
self.asteroid = asteroid
if self.x > self.asteroid.x:
raise MissAsteroidError()
if self.y > self.asteroid.y:
raise MissAsteroidError()
def turn_left(self):
turns = {"E": "N",
"N": "W",
"W": "S",
"S": "E", }
self.direction = turns[self.direction]
def turn_right(self):
turns = {"N": "E",
"E": "S",
"S": "W",
"W": "N", }
self.direction = turns[self.direction]
def move_forward(self, steps):
if self.direction == "E":
if self.x + steps > self.asteroid.x:
raise ValueError("Robot fell from asteroid")
else:
self.x += steps
elif self.direction == "N":
if self.y + steps > self.asteroid.y:
raise ValueError("Robot fell from asteroid")
else:
self.y += steps
elif self.direction == "W":
if (self.x - steps) < 0:
raise ValueError("Robot fell from asteroid")
else:
self.x -= steps
elif self.direction == "S":
if self.y - steps < 0:
raise ValueError("Robot fell from asteroid")
else:
self.y -= steps
def move_backward(self, steps):
if self.direction == "E":
if self.x - steps < 0:
raise ValueError("Robot fell from asteroid")
else:
self.x -= steps
if self.direction == "N":
if self.y - steps < 0:
raise ValueError("Robot fell from asteroid")
else:
self.y -= steps
if self.direction == "W":
if self.y + steps > self.asteroid.y:
raise ValueError("Robot fell from asteroid")
else:
self.y += steps
if self.direction == "S":
if self.x + steps > self.asteroid.x:
raise ValueError("Robot fell from asteroid")
else:
self.x += steps
class MissAsteroidError(Exception):
print("Robot missed above asteroid")
if __name__ == '__main__':
asteroid = Asteroid(20, 30)
robot = Robot(10, 13, asteroid, "E")
robot.move_forward(20) |
import functools
def multiplier(l: list):
if isinstance(l, list) and all(isinstance(i, (int, float)) for i in l):
return functools.reduce(lambda a, b: a * b, l)
raise ValueError('The given data is invalid.')
|
def print_str_analytics(str):
printable = 0
a_num = 0
a_bet = 0
dec = 0
lower = 0
upper = 0
w_space = 0
for i in str:
if i.isprintable() == True:
printable += 1
if i.isalnum() == True:
a_num += 1
if i.isalpha() == True:
a_bet += 1
if i.isdecimal() == True:
dec += 1
if i.islower() == True:
lower += 1
if i.isupper() == True:
upper += 1
if i.isspace() == True:
w_space += 1
print(f"""|------------------------------------------------|
| String analytics |
|------------------------------------------------|
| '{str}'
|------------------------------------------------|
| Number of printable characters is: {printable}
| Number of alphanumeric characters is: {a_num}
| Number of alphabetic characters is: {a_bet}
| Number of decimal characters is: {dec}
| Number of lowercase letters is: {lower}
| Number of uppercase letters is: {upper}
| Number of whitespace characters is: {w_space}
|------------------------------------------------|""")
|
# 数组中的第K个最大元素
# 在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。
#
# 示例 1:
#
# 输入: [3,2,1,5,6,4] 和 k = 2
# 输出: 5
class Solution(object):
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
if not nums:
return None
val = [-2147483648]*k
for i in nums:
minimum = min(val)
if i > minimum:
val[val.index(minimum)] = i
return min(val)
# 先归并排序
def findKthLargest2(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
if not nums:
return None
num_sorted = self.sortNums(nums)
return num_sorted[-k]
def sortNums(self, nums):
ln = len(nums)
if ln <= 1:
return nums
mid = ln//2
num1 = self.sortNums(nums[:mid])
num2 = self.sortNums(nums[mid:])
num = self.combine(num1, num2)
return num
def combine(self, num1, num2):
l1 = len(num1)
l2 = len(num2)
i = 0
j = 0
sort_num = []
while i < l1 and j < l2:
if num1[i] < num2[j]:
sort_num.append(num1[i])
i += 1
else:
sort_num.append(num2[j])
j += 1
while i < l1:
sort_num.append(num1[i])
i += 1
while j < l2:
sort_num.append(num2[j])
j += 1
return sort_num
|
class Solution:
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
b = ""
length = 2**31
if len(strs) == 0:
return ""
for i in strs:
le = len(i)
if le < length:
length = le
for j in range(length):
for i in strs:
if i[j] != strs[0][j]:
return b
b += strs[0][j]
return b
s = Solution()
string = []
print(s.longestCommonPrefix(string))
|
# 奇偶链表
# 给定一个单链表,把所有的奇数节点和偶数节点分别排在一起。请注意,这里的奇数节点和偶数节点指的是节点编号的奇偶性,而不是节点的值的奇偶性。
#
# 请尝试使用原地算法完成。你的算法的空间复杂度应为 O(1),时间复杂度应为 O(nodes),nodes 为节点总数。
#
# 示例 1:
#
# 输入: 1->2->3->4->5->NULL
# 输出: 1->3->5->2->4->NULL
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
# 链表的最后一个一定是连接None,否则可能陷入死循环
def oddEvenList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:
return head
origin = head
even = head.next
while head.next and head.next.next:
temp = head.next
head.next = temp.next
head = head.next
if temp.next.next:
temp.next = temp.next.next
else:
temp.next = None
head.next = even
return origin
|
# 分数到小数
# 给定两个整数,分别表示分数的分子 numerator 和分母 denominator,以字符串形式返回小数。
#
# 如果小数部分为循环小数,则将循环的部分括在括号内。
#
# 示例 1:
#
# 输入: numerator = 1, denominator = 2
# 输出: "0.5"
class Solution(object):
def fractionToDecimal(self, numerator, denominator):
"""
:type numerator: int
:type denominator: int
:rtype: str
"""
# 这个题首先要考虑正负号的情况
# 判断是否循环要用 不断地乘10倍取余 的方法,当余数出现重复时,从重复的数字第一次出现的地方开始循环
if numerator == 0:
return '0'
flag = (int(numerator < 0))^(int(denominator < 0))
numerator = abs(numerator)
denominator = abs(denominator)
if numerator % denominator == 0:
if flag == 1:
return '-' + str(numerator//denominator)
else:
return str(numerator//denominator)
val = []
int_val = []
int_val.append(str(numerator//denominator))
int_val.append('.')
numerator = numerator%denominator
res = []
begin = -1
end = -1
while numerator:
if numerator not in res:
res.append(numerator)
else:
begin = res.index(numerator)
end = len(res)-1
break
val.append(str(numerator*10//denominator))
numerator = numerator * 10 % denominator
if flag == 1:
if begin == -1 and end == -1:
return '-'+''.join(int_val + val)
return '-'+''.join(int_val + val[:begin] + ['('] + val[begin:] + [')'])
else:
if begin == -1 and end == -1:
return ''.join(int_val + val)
return ''.join(int_val + val[:begin] + ['('] + val[begin:] + [')'])
|
# 两数相加
# 给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
#
# 如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
#
# 您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
#
# 示例:
#
# 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
# 输出:7 -> 0 -> 8
# 原因:342 + 465 = 807
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
# 原位为 r%10 进位为 r//10,方法2更好一点
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if not l1:
return l2
if not l2:
return l1
r = l1.val+l2.val
s = ListNode(r % 10)
sym = r//10
sc = s
l1 = l1.next
l2 = l2.next
while True:
if l1 and l2:
if sym == 1:
r = l1.val+l2.val + 1
else:
r = l1.val+l2.val
s.next = ListNode(r % 10)
sym = r//10
l1 = l1.next
l2 = l2.next
elif l1:
if sym == 1:
r = l1.val + 1
else:
r = l1.val
s.next = ListNode(r % 10)
sym = r//10
l1 = l1.next
elif l2:
if sym == 1:
r = l2.val + 1
else:
r = l2.val
s.next = ListNode(r % 10)
sym = r//10
l2 = l2.next
else:
if sym == 1:
s.next = ListNode(1)
break
s = s.next
return sc
# 依次判断l1和l2是否为None,加上不为None的值,carry为进位
def addTwoNumbers2(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
dummy = cur = ListNode(0)
carry = 0
while l1 or l2 or carry:
if l1:
carry += l1.val
l1 = l1.next
if l2:
carry += l2.val
l2 = l2.next
cur.next = ListNode(carry % 10)
cur = cur.next
carry //= 10
return dummy.next
|
# 全排列
# 给定一个没有重复数字的序列,返回其所有可能的全排列。
#
# 示例:
#
# 输入: [1,2,3]
# 输出:
# [
# [1,2,3],
# [1,3,2],
# [2,1,3],
# [2,3,1],
# [3,1,2],
# [3,2,1]
# ]
class Solution(object):
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
self.dfs(nums, [], res)
return res
def dfs(self, num, sub, res):
if not num:
res.append(sub)
else:
ln = len(num)
for i in range(ln):
self.dfs(num[:i]+num[i+1:], sub+[num[i]], res)
|
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def addnode(self, head, x):
for i in x:
s = ListNode(i)
head.next = s
head = head.next
class Solution:
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if not l1:
return l2
if not l2:
return l1
if l1.val > l2.val:
head = l2
l2 = l2.next
else:
head = l1
l1 = l1.next
merge = head
while l1 and l2:
if l1.val > l2.val:
head.next = l2
head = head.next
l2 = l2.next
else:
head.next = l1
head = head.next
l1 = l1.next
while l1:
head.next = l1
head = head.next
l1 = l1.next
while l2:
head.next = l2
head = head.next
l2 = l2.next
return merge
h1 = ListNode(1)
h1.addnode(h1, [2, 4])
h2 = ListNode(1)
h2.addnode(h2, [3, 4])
s = Solution()
h3 = s.mergeTwoLists(h1, h2)
while h3:
print(h3.val)
h3 = h3.next
|
class rect:
x, y = 0, 0
def __init__():
print("사각형생성")
class rect1(rect):
def size(self, x,y):
return x * y
class rect2(rect):
def size(x,y):
return x * y
rect_type = input("사각형의 종류\n 1)직사각형 2) 평행사변형 :")
if rect_type == '1' :
rec1 = rect1()
|
import turtle as t
t = t.Turtle()
t.shape("turtle")
n=60
# t.bgcolor("black")
t.color("green")
t.speed(0)
for x in range(n):
t.circle(80)
t.left(360/n)
input()
print("end")
|
import turtle as t
t = t.Turtle()
t.shape("turtle")
for x in range(15) :
t.forward(50)
t.right(190)
t.forward(50)
print("hello 하이!")
input()
|
import unittest
import palindrome
class TestPalindrome(unittest.TestCase):
def test_palindromeness(self):
value = palindrome.is_palindrome('racecar')
self.assertEqual(value, True)
def test_notpalindromeness(self):
value = palindrome.is_palindrome('hello')
self.assertEqual(value, False)
if __name__ == "__main__":
unittest.main()
|
# Найдите три ключа с самыми высокими значениями в словаре
my_dict = {'a':500, 'b':5874, 'c': 560,'d':400, 'e':5874, 'f': 20}
# Первый вариант:
import operator
max_elem =dict(sorted(my_dict.items(),key=operator.itemgetter(1),reverse=True))
i = 0
for key,value in max_elem.items():
if i <3:
print(key,'-',value)
i +=1
# Второй вариант:
max_elem=sorted(my_dict,key=my_dict.get,reverse=True)[:3]
print(max_elem)
# Третий вариант:
from heapq import nlargest
max_elem = nlargest(3,my_dict , key = my_dict.get)
print(max_elem) |
# Выведите первый и последний элемент списка.
import random
data_list = [random.randint(1,50) for i in range(1,11)]
print(data_list)
print('Первый элемент : ',data_list[0])
print('Последний элемент : ',data_list[-1]) |
# Вывести элементы меньше пяти
# Первый вариант:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
for i in a:
if i < 5 :
print(i)
# Второй вариант:
import functools
print(list(filter(lambda i: i < 5,a)))
# Третий вариант:
print([i for i in a if i < 5]) |
##Crea un programa que use la lista de números que está adjunta y reciba un número del usuario. Tu programa buscará en la lista la suma que sea igual al número que ingresó el usuario.
lista=[5, 2, 3, 1, 6, 7, 90, 4, 3, 8]
num = int(input())
x={}
list=[]
for x in lista:
for y in lista:
if x == y:
x+y
elif x+y == num:
x[x]=y
for x in lista:
for y in lista:
if x in x:
list.append()
|
import numpy as np
def equalize_histogram(image):
"""Generate an new image with an equalized histogram from the given image.
Note: currently, it only supports transformations for grayscale images.
# TODO: Add support for normalization.
Paramters
---------
image: np.ndarray
The input grayscale image.
Returns
-------
np.ndarray
The histogram equalization of input image with the same shape
and dtype.
"""
L = 256 # number of intensity levels
coefficient = L - 1
hist = np.histogram(image, bins=np.arange(L + 1), density=True)[0]
hist_cumsum = coefficient * np.cumsum(hist)
equalization_map = np.rint(hist_cumsum).astype(np.uint8)
return equalization_map[image]
def match_histogram(image, reference):
"""Generate an new image with the specified histogram from the given image.
Parameters
----------
image : np.ndarray
The input grayscale image.
reference : np.ndarray
The specified histogram of shape (256,) or an image from which
the specified histogram is calculated.
Returns
-------
np.ndarray
Transformed input image.
"""
L = 256
# image_hist: (256,)
image_hist = np.histogram(image, bins=np.arange(L + 1), density=True)[0]
image_cumhist = np.expand_dims(np.cumsum(image_hist), axis=1) # (256, 1)
assert reference.ndim in (1, 2)
if reference.ndim == 2:
reference_hist = np.histogram(reference,
bins=np.arange(L + 1),
density=True)[0] # (256,)
reference_cumhist = np.expand_dims(np.cumsum(reference_hist),
axis=0) # (1, 256)
elif reference.ndim == 1:
assert len(reference) == 256
reference_cumhist = np.cumsum(reference) # (256,)
reference_cumhist /= reference_cumhist[-1] # (256,); normalize
reference_cumhist = np.expand_dims(reference_cumhist,
axis=0) # (1, 256)
else:
pass # TODO: raise a proper exception here.
# abs_diff[i, j] = |image_cumhist[i] - reference_cumhist[j]|
abs_diff = np.abs(image_cumhist - reference_cumhist) # (256, 256)
matching_map = np.argmin(abs_diff, axis=1) # (256,)
return matching_map[image]
def gamma_correct(image, gamma=1.0):
"""Perform the gamma correction on image.
Note: currently, it only supports transformations for grayscale
images.
Parameters
----------
image: 2-dim ndarray
The input grayscale image.
gamma: nonnegative float
Gamma value.
Returns
-------
2-dim ndarray
Gamma corrected image with the same shape and dtype as input
image.
"""
# Sanity checks.
if gamma < 0.0:
raise ValueError('Gamma value should be non-negative')
if gamma == 1.0:
return image
# Gamma transformation lookup talbe.
L = 256
lookup_table = np.arange(L, dtype=np.float)
np.power(lookup_table / (L - 1), gamma, out=lookup_table)
np.rint(lookup_table * (L - 1), out=lookup_table)
lookup_table = lookup_table.astype(np.uint8)
return lookup_table[image]
def bit_planes(image):
"""Return the bit planes of an image.
Parameters
----------
image : np.ndarray
The input grayscale image.
Returns
-------
np.ndarray
8 bit planes. The first dimension indicates the order of bits
with zero corresponding to the least significant bit.
"""
bit_mask = 1
planes = np.empty((8, *image.shape), dtype=np.uint8)
for i in range(8):
np.bitwise_and(image, bit_mask, out=planes[i])
planes[i] //= bit_mask
bit_mask <<= 1
return planes
|
from enum import Enum
from random import choice
Gesture = Enum(
value="Gesture",
names= [
("F","finger"),
("P","proffer"),
("S","snap"),
("W","wave"),
("D","digit"),
("K","stab"),
("N","nothing"),
("c","clap")
# ("d","2 handed digit"),
# ("w","2 handed wave"),
# ("s","2 handed snap"),
# ("p","2 handed proffer"),
])
Valid = ['F','P','S','W','D','>','-','C']
Description = {'F': 'wriggles the fingers of',
'P': 'proffers the palm of',
'S': 'snaps the fingers of',
'W': 'waves',
'D': 'points the digit of',
'C': 'claps with',
'>': 'stabs with',
'-': 'does nothing with'}
def randomGesture():
return choice(['F','P','S','W','D','>','-','C'])
|
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 19 21:21:21 2017
@author: Brandon
"""
# Part 1 - Data Preprocessing
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Churn_Modelling.csv')
# Consider pd.get_dummies()
X = dataset.iloc[:, 3:13].values
y = dataset.iloc[:, 13].values
person = pd.DataFrame([[600, "France", "Male", 40, 3, 60000, 2, 1, 1, 50000]]).values
# Encoding categorical data
# Encoding the Independent Variable
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
categorical_columns = [1,2]
for i in categorical_columns:
labelencoder_X = LabelEncoder()
X[:, i] = labelencoder_X.fit_transform(X[:, i])
person[:, i] = labelencoder_X.transform(person[:, i])
onehotencoder = OneHotEncoder(categorical_features = [1]) ## specify columns with categorical features
X = onehotencoder.fit_transform(X).toarray()
X = X[:, 1:] ## get rid of redundant dummy variable
person = onehotencoder.transform(person).toarray()
person = person[:, 1:] ## get rid of redundant dummy variable
"""
labelencoder_X_1 = LabelEncoder()
X[:, 1] = labelencoder_X_1.fit_transform(X[:, 1])
labelencoder_X_2 = LabelEncoder()
X[:, 2] = labelencoder_X_2.fit_transform(X[:, 2])
onehotencoder = OneHotEncoder(categorical_features = 1)
X = onehotencoder.fit_transform(X).toarray()
X = X[:, 1:]
"""
# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)
# Feature Scaling
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
person = sc.transform(person)
# Part 2 - Making the ANN
# Importing the Keras libraries and packages
import keras
from keras.models import Sequential
from keras.layers import Dense
# Initializing the ANN
classifier = Sequential()
# Adding the input layer and the first hidden layer
# Fixed according to documentation
classifier.add(Dense(units = 6, activation = 'relu', kernel_initializer = 'uniform', input_shape = (11,)))
# Fixed according to ipython output
#classifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu', input_dim = 11))
""" Tutorial
classifier.add(Dense(units = 6, init = 'uniform', activation = 'relu', input_dim = 11))
"""
# Adding the second hidden layer
classifier.add(Dense(units = 6, activation = 'relu', kernel_initializer = 'uniform'))
# Adding the output layer
classifier.add(Dense(units = 1, activation = 'sigmoid', kernel_initializer = 'uniform'))
# Use activation = 'softmax' function for more then 2 output choices?
# Compiling the ANN
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
# categorical_crossentropy for non binary dependent variable
#Fitting the ANN to the Training set
classifier.fit(X_train, y_train, batch_size = 10, epochs = 100)
# Part 3 - Making the predictions and evaluating the model
# Predicting the Test set results
y_pred = classifier.predict(X_test)
y_pred = (y_pred > 0.5)
person_pred = classifier.predict(person)
person_pred = (person_pred > 0.5)
# Making the Confusion Matrix
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)
correct = 1506 + 215
accuracy = correct / 2000
"""
Predict Subset of Dataset
Geography: France
Credit Score: 600
Gender: Male
Age: 40 years old
Tenure: 3 years
Balance: $60000
Number of Products: 2
Does this customer have a credit card ? Yes
Is this customer an Active Member: Yes
Estimated Salary: $50000
"""
"""
0, 0 = France
0, 1 = Spain
1, 0 = Germany
0 = Female
1 = Male
"""
new_prediction = classifier.predict(sc.transform(np.array([[0.0, 0, 600, 1, 40, 3, 60000, 2, 1, 1, 50000]])))
new_prediction = (person_pred > 0.5) |
#!/usr/bin/python
import curses
import random
import time
from math import sqrt
# initialization
stdscr = curses.initscr()
curses.start_color()
curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)
curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK)
curses.init_pair(3, curses.COLOR_WHITE, curses.COLOR_BLACK)
curses.init_pair(4, curses.COLOR_BLACK, curses.COLOR_WHITE)
curses.noecho()
curses.cbreak()
stdscr.keypad(1)
cheat = 0
def draw_frame(board,board_y,board_x):
"""drawing frame borders and edges"""
# drawing boards frames
for frame_x in range(0,board_x):
board.addch(0,frame_x,'-')
board.addch(pad_y,frame_x,'-')
for frame_y in range(0,board_y):
board.addch(frame_y,0,'|')
board.addch(frame_y,pad_x,'|')
# making the edges prettier
for edge in [[0,0],[board_y,0],[0,pad_x],[pad_y,pad_x]]:
board.addch(edge[0],edge[1],'+')
def rand_table(bombs,holes,board_y,board_x):
board_size = board_y * board_x
bomb_chance = board_size / bombs
hole_chance = board_size / holes
board = []
for y in range(0,board_y):
board.append([])
for x in range(0,board_x):
board[y].append('')
while bombs > 0 or holes > 0:
rand_y = random.randrange(1,board_y)
rand_x = random.randrange(1,board_x)
if board[rand_y][rand_x] == '':
if bombs > 0:
board[rand_y][rand_x] = 'B'
bombs -= 1;
else:
board[rand_y][rand_x] = 'O'
holes -= 1;
return board
def rand_liron(board,board_y,board_x):
liron = [];
for y in range(0,board_y):
for x in range(0,board_x):
if board[y][x] == 'O':
liron.append([y,x]);
return liron[random.randrange(0,len(liron))]
def rand_player(board,board_y,board_x):
player = [];
for y in range(1,board_y):
for x in range(1,board_x):
if board[y][x] == '':
player.append([y,x]);
return player[random.randrange(0,len(player))]
def draw_objs(pad,board,board_y,board_x):
for y in range(0,board_y):
for x in range(0,board_x):
if board[y][x] == 'B':
pad.addstr(y,x, 'B', curses.color_pair(1) )
elif board[y][x] == 'O':
pad.addstr(y,x, 'O', curses.color_pair(2) )
elif board[y][x] == 'L':
pad.addstr(y,x, 'L', curses.color_pair(4) )
def board_message(message,color = 'red'):
colors = {'red': curses.color_pair(1), 'green': curses.color_pair(2), 'white': curses.color_pair(3)}
pad.addstr(pad_y + 1,1, message,colors[color])
pad.refresh(0,0, 0,0, pad_y + 1,pad_x)
# board size
pad_x = 60
pad_y = 30
# difficulty
bombs = 60
holes = 50
game_time = 120
# creating the board
pad = curses.newpad(pad_y + 2 , pad_x + 2)
draw_frame(pad,pad_y,pad_x)
board = rand_table(bombs = bombs, holes = holes, board_y = pad_y, board_x = pad_x)
# select place for a player
y,x = rand_player(board,pad_y,pad_x)
pad.addch(y,x,'*')
# select a hole for liron
liron = rand_liron(board,pad_y,pad_x)
if cheat == 1:
board[liron[0]][liron[1]] = "L"
# draw the shit
draw_objs(pad,board,pad_y,pad_x)
# calculating time
future_time = time.time() + game_time
# player last distance
distance = ''
warmcold = ''
# main loop, movement
while 1:
pad.nodelay(1);
time_left = future_time - time.time()
if time_left < 0:
board_message("ata lo taamod be mivhan ha metziut")
break
message = "%3.2f - %s\t%s" % (time_left, "seconds left", warmcold)
board_message(message,color = "white")
c = pad.getch()
if c != -1:
# clear the last place
pad.addch(y,x,' ');
if c == ord('l') and (x + 1 < pad_x):x += 1 # right
if c == ord('h') and (x - 1 > 0): x -= 1 # left
if c == ord('k') and (y - 1 > 0): y -= 1 # up
if c == ord('j') and (y + 1 < pad_y): y += 1 # down
if c == ord('q'): break # quit
draw_objs(pad,board,pad_y,pad_x)
pad.addch(y,x,'*')
if board[y][x] == 'B':
board_message("ata lo taamod be mivhan ha metziut")
time.sleep(5)
break
elif board[y][x] == 'O' or board[y][x] == 'L':
if y == liron[0] and x == liron[1]:
board_message("ata taamod be mivhan ha metziut", color = "green")
time.sleep(5)
break
else:
y_dist = abs(y - liron[0])
x_dist = abs(x - liron[1])
t_dist = sqrt(y_dist**2 + x_dist**2)
if distance:
if t_dist < distance:
warmcold = "warmer"
elif t_dist == distance:
warmcold = "pfft..."
else:
warmcold = "colder"
distance = t_dist
#warmcold = "%d %d " % (x_dist,y_dist)
# end of proggie
curses.endwin()
|
print("Hola Mundo!")
print("Bienvenid@ haremos una suma ")
try:
w=int(input("Dame un número "))
e=int(input("Dame un segundo número "))
print("La suma de "+str(w)+"+"+str(e)+"="+str(w+e))
except ValueError:
print("Ingresa un dato invalida.Intenta de nuevo") |
# -*- coding: utf-8 -*-
def get_check_code(fcode):
"""
Get final check digit with mod 11, 10 encryption algorithm
:param fcode: top 14 digits of registration number
:type fcode: str or list of int
:return: final check digit
:rtype: int
"""
fcode = list(map(int, fcode))
assert len(fcode) == 14, "Inputted fcode should be 14 digits."
p = 10
for i in range(14):
p = p % 11
if p == 0: p = 11
s = p + fcode[i]
s = s % 10
if s == 0: s = 10
p = s * 2
# print(i, fcode[i], s, p)
p = p % 11
if p <= 1:
a1 = 1 - p
else:
a1 = 11 - p
return str(a1)
if __name__ == '__main__':
origin_code = '110108012660422'
fcode = origin_code[0:14]
|
#!/usr/bin/env python
# coding=utf-8
Table = { '1975' : 'Holy Grail',
'1979' : 'Life of Brian',
'1983' : 'The meaning of Life'}
x = '1979'
Table[x] = 'Little women'
y = Table[x]
print y
|
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
# load dataset
fashion_mnist = tf.keras.datasets.fashion_mnist
(X_train, Y_train), (X_test, Y_test) = fashion_mnist.load_data()
X_train, X_test = X_train / 255, X_test / 255
print('The train dataset is of shape: {0}'.format(X_train.shape))
print('The test dataset is of shape: {0}'.format(X_test.shape))
print('Each instance is of shape: {0}'.format(X_test[0].shape))
# prepare the dataset
X_train = np.expand_dims(X_train, -1)
X_test = np.expand_dims(X_test, -1)
print('Now the train dataset is of shape: {0}'.format(X_train.shape))
# build the model
model = tf.keras.models.Sequential([tf.keras.layers.Input(X_train[0].shape),
tf.keras.layers.Conv2D(32, kernel_size=(3, 3), strides=2, activation='relu'),
tf.keras.layers.Conv2D(64, kernel_size=(3, 3), strides=2, activation='relu'),
tf.keras.layers.Conv2D(128, kernel_size=(3, 3), strides=2, activation='relu'),
tf.keras.layers.Flatten(),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(512, activation='relu'),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10, activation='softmax')])
# compile and train
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
r = model.fit(X_train, Y_train, validation_data=(X_test, Y_test), epochs=15)
plt.plot(r.history['loss'], label='loss')
plt.plot(r.history['val_loss'], label='val_loss')
plt.legend()
plt.show()
plt.plot(r.history['accuracy'], label='acc')
plt.plot(r.history['val_accuracy'], label='val_acc')
plt.legend()
plt.show()
|
def SimpleSymbols(str):
# code goes here
prev = ''
prev_is_letter = False
for c in str:
if prev_is_letter and c != '+':
return 'false'
if 'a' <= c <= 'z':
prev_is_letter = True
if prev != '+':
return 'false'
else:
prev_is_letter = False
prev = c
if prev_is_letter:
return 'false'
return 'true'
# keep this function call here
print(SimpleSymbols(input()))
|
from datetime import datetime
def date_time(time: str) -> str:
dt = datetime.strptime(time, '%d.%m.%Y %H:%M')
# univesal solution
return dt.strftime(f'%d %B %Y year %H hour{(dt.hour != 1)*"s"} %M minute{(dt.minute != 1)*"s"}').lstrip("0").replace(" 0", " ")
# on linux
# return dt.strftime(f'%-d %B %Y year %-H hour{(dt.hour != 1)*"s"} %-M minute{(dt.minute != 1)*"s"}')
# on windows
# return dt.strftime(f'%#d %B %Y year %#H hour{(dt.hour != 1)*"s"} %#M minute{(dt.minute != 1)*"s"}')
if __name__ == '__main__':
print("Example:")
print(date_time('01.01.2000 00:00'))
#These "asserts" using only for self-checking and not necessary for auto-testing
assert date_time("01.01.2000 00:00") == "1 January 2000 year 0 hours 0 minutes", "Millenium"
assert date_time("09.05.1945 06:30") == "9 May 1945 year 6 hours 30 minutes", "Victory"
assert date_time("20.11.1990 03:55") == "20 November 1990 year 3 hours 55 minutes", "Somebody was born"
print("Coding complete? Click 'Check' to earn cool rewards!") |
def long_repeat(line):
"""
length the longest substring that consists of the same char
"""
# your code here
if len(line) == 0:
return 0
cur = line[0]
curlen = 0
max = 0
for c in line:
if c == cur:
curlen += 1
else:
cur = c
if curlen > max:
max = curlen
curlen = 1
return max
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert long_repeat('sdsffffse') == 4, "First"
assert long_repeat('ddvvrwwwrggg') == 3, "Second"
assert long_repeat('abababaab') == 2, "Third"
assert long_repeat('') == 0, "Empty"
print('"Run" is good. How is "Check"?') |
#Uses python3
import sys
import queue
from math import sqrt
from heapq import heapify, heappush, heappop
class priority_dict(dict):
"""Dictionary that can be used as a priority queue.
Keys of the dictionary are items to be put into the queue, and values
are their respective priorities. All dictionary methods work as expected.
The advantage over a standard heapq-based priority queue is
that priorities of items can be efficiently updated (amortized O(1))
using code as 'thedict[item] = new_priority.'
The 'smallest' method can be used to return the object with lowest
priority, and 'pop_smallest' also removes it.
The 'sorted_iter' method provides a destructive sorted iterator.
"""
def __init__(self, *args, **kwargs):
super(priority_dict, self).__init__(*args, **kwargs)
self._rebuild_heap()
def _rebuild_heap(self):
self._heap = [(v, k) for k, v in self.items()]
heapify(self._heap)
def smallest(self):
"""Return the item with the lowest priority.
Raises IndexError if the object is empty.
"""
heap = self._heap
v, k = heap[0]
while k not in self or self[k] != v:
heappop(heap)
v, k = heap[0]
return k
def pop_smallest(self):
"""Return the item with the lowest priority and remove it.
Raises IndexError if the object is empty.
"""
heap = self._heap
v, k = heappop(heap)
while k not in self or self[k] != v:
v, k = heappop(heap)
del self[k]
return k
def __setitem__(self, key, val):
# We are not going to remove the previous value from the heap,
# since this would have a cost O(n).
super(priority_dict, self).__setitem__(key, val)
if len(self._heap) < 2 * len(self):
heappush(self._heap, (val, key))
else:
# When the heap grows larger than 2 * len(self), we rebuild it
# from scratch to avoid wasting too much memory.
self._rebuild_heap()
def setdefault(self, key, val):
if key not in self:
self[key] = val
return val
return self[key]
def update(self, *args, **kwargs):
# Reimplementing dict.update is tricky -- see e.g.
# http://mail.python.org/pipermail/python-ideas/2007-May/000744.html
# We just rebuild the heap from scratch after passing to super.
super(priority_dict, self).update(*args, **kwargs)
self._rebuild_heap()
def sorted_iter(self):
"""Sorted iterator of the priority dictionary items.
Beware: this will destroy elements as they are returned.
"""
while self:
yield self.pop_smallest()
def distance(a,b):
return sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2)
def minimum_distance(x, y):
result = 0.
#write your code here
adj = [ [] for _ in range(len(x))]
for i,xinst in enumerate(x):
for j in range(len(x)):
if i != j:
adj[i].append(
(j, distance( (x[i],y[i]), (x[j], y[j])))
)
cost = [ sys.maxsize for _ in range(len(x))]
cost[0] = 0
q = priority_dict()
for n in range(len(x)):
q[n] = cost[n]
while not len(q) == 0: # q.empty():
v = q.pop_smallest()
result += cost[v]
for z in adj[v]:
if z[0] in q and cost[z[0]] > z[1]:
cost[z[0]] = z[1]
q[z[0]] = z[1]
return result
def solve_minimum_distance(input):
data = list(map(int, input.split()))
n = data[0]
x = data[1::2]
y = data[2::2]
return minimum_distance(x, y)
if __name__ == '__main__':
input = sys.stdin.read()
print("{0:.9f}".format(solve_minimum_distance(input)))
|
class ClassName(object):
college="East clg"#class shared by all instances
"""docstring for ClassName"""
def __init__(self,name): #instance variable unique to each instance
super(ClassName, self).__init__()
self.name=name
d=ClassName("Millan")
print(d.name)
print(d.college) #share by all classname
|
a = "Hello Milu"
print(len(a)) #len() method is use for geting the length |
thisDict = {
"Brand":"Tata",
"Model":"Nano",
"Year": "2013"
}
for x,y in thisDict.items():
print(x,y) |
print ("Задание 2")
def everything(n, s_n, b_d, c, em, tel):
return ["Вы", n, s_n, "рождены",b_d, ", живете в населенном пункте ", c,'. Ваш email', em, ",телефон", tel]
name = input('Введите ваше имя ')
surmane = input("Введите вашу фамилию ")
bd = input("Ваша дата рождения ")
city = input ("В каком городе вы живете? ")
email = input("Ваш email ")
tel = input("Ваш номер телефона ")
otvet = everything(name, surmane, bd, city, email, tel)
for i in otvet:
print (i,end = ' ') |
from collections import deque
import sys
mystack = deque()
def show(s):
print(mystack)
while(1):
print("[1] for pushing onto stack.")
print("[2] for popping from stack.")
print("[3] to exit.")
user_io = int(input('Enter your choice:'))
if(user_io == 1):
x = int(input('Enter number'))
mystack.append(x)
show(mystack)
elif(user_io == 2):
mystack.pop()
show(mystack)
else:
print("Thank You!")
sys.exit(0)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 29 07:49:54 2019
@author: saadmashkoor
"""
"""upper_confidence_bound.py - Reinforcement Learning using UCB to solve the
multi-armed bandit problem in the context of ads and clickthrough rates"""
# Import libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Import dataset
dataset = pd.read_csv('Ads_CTR_Optimisation.csv')
"""
--------------------------------Business Problem---------------------------------
An SUV company has prepared 10 different versions of an
advertisement for their vehicle. We want to choose the version of the ad that will
maximize conversion rate i.e. maximize the number of users who click on the ad.
We need to implement a strategy to quickly find out which version of the ad will give
the most clicks.
-----------------------------------Procedure-------------------------------------
We have 10 versions of the ad. Each time a user logs in to the website, we will show
them one version of the ad. Every time the user clicks on the ad, our algo gets a
reward of 1. Every ad that isn't clicked is a penalty - no reward.
The ad chosen for a given iteration will be based on the results of previous iterations.
It won't be random selection. The model will iteratively learn which ads most users
are likely to click on. If we used random selections, the reward is in the range of
1100 - 1300. This means the random selection's click conversion rate is only 13%.
We can do better than this!
Also, we get a nearly uniform distribution of the ad click frequency. We don't have
any insights about choosing the best ad.
The dataset is just used for simulation. We won't be using it in the conventional
sense of extracting features/labels/etc. We've created 10k users and predefined
the ads they will click on. This helps us train the network without requiring actual
real time responses from people IRL.
A user can click on no ads or multiple ads.
"""
"""
------------------------------UCB Implementation---------------------------------
"""
N_ROUNDS = 10000 # number of times we will show a version of the ad
d = len(dataset.columns) # number of ads that can be shown to a user
# List to store number of times each ad has been selected by a user - init 0
numbers_of_selections = [0] * d
# Sum of rewards for each ad - init 0
sums_of_rewards = [0] * d
# empty list to keep track of ads selected in each round
ads_selected = []
# variable to store the total reward at the end of all iterations
total_reward = 0
# For each round in the `N_ROUNDS` of showing an ad to a user
for n in range(0, N_ROUNDS):
# create a max upper bound variable for the best ad for each user
max_upper_bound = 0
# create a variable to remember index of the ad selected
ucb_ad_index = 0
# for every ad in the list of possible ads
for i in range(0, d):
# if the ad has already been shown and selected before
if (numbers_of_selections[i] > 0):
# Compute the average reward for this ad up to this round - total rewards/total selections
avg_reward = sums_of_rewards[i] / numbers_of_selections[i]
# Confidence interval for this ad [avg - delta, avg + delta]
# n + 1 to account for zero-indexing in Python
delta_i = np.sqrt(3/2 * np.log(n + 1) / numbers_of_selections[i])
# Compute the **upper** confidence bound for this ad
upper_bound = avg_reward + delta_i
# if no prior selection, assume a very large upper bound. This
# is a very complicated way of ensuring that at each ad is selected at
# least to give some historical data to our algo to base future selections on
else:
upper_bound = 1e400
# Update the max upper bound and remember its corresponding ad
if (upper_bound > max_upper_bound):
max_upper_bound = upper_bound
ucb_ad_index = i
# for this round, append the selected ad to the vector of selected ads
ads_selected.append(ucb_ad_index)
# update the number of times the ad has been selected
numbers_of_selections[ucb_ad_index] += 1
# compute the reward by comparing dataset's selected ad with ad shown by algo
reward = dataset.values[n,ucb_ad_index] # if correct, this will be 1
# update the sums of rewards for this ad
sums_of_rewards[ucb_ad_index] += reward
# update the final reward after all users have been shown the ad.
total_reward += reward
"""
--------------------------------Interpretation-----------------------------------
- Doubled the total reward compared to random selection.
- For the first ten users, we showed the first 10 ads in sequence.
- This gave the algorithm information about how users responded to each of the
10 possible ads. The algo then used this data to refine its selection of ads
for future users.
- Towards the last few rounds, the algorithm consistently shows ad 5 to all users.
This means it has identified ad 4 as the one that will maximise reward/conversion rate.
(Index is 4 but ad is 5 because 0 indexing)
"""
"""
--------------------------------Visualization------------------------------------
"""
plt.figure(); plt.hist(ads_selected, edgecolor='black'); plt.xlabel("Advertisement");
plt.ylabel("Frequency of Selection"); plt.title("Ads Selection Count")
|
class A:
name=""
def __init__(self,a,b):
self.a=a
self.b=b
def __str__(self):
return f"{self.a} and {self.b}"
@classmethod
def test(cls):
return cls(3,4)
if __name__=="__main__":
a=A(2,3)
b=A.test()
print(b.__dict__)
print(a.__dict__)
|
class USA:
def capital(self):
print("The capital of usa is washington")
def icon(self):
print("Statue of liberty")
def language(self):
print("The language of USA is english")
class India:
def capital(self):
print("The capital of india is delhi")
def icon(self):
print("Taj mahal")
def language(self):
print("Hindi is the language of india")
def describe(d):
d.capital()
d.icon()
d.language()
if __name__=="__main__":
i=India()
u=USA()
countries=[i,u]
for c in countries:
describe(c)
|
import unittest
from main import compound_words
class EnglishWordTestCase(unittest.TestCase):
def setUp(self):
self.input_sequence = ['paris', 'applewatch', 'ipod', 'amsterdam', 'bigbook', 'orange', 'waterbottle']
def test_gives_correct_output(self):
self.assertEqual(compound_words(self.input_sequence), ['applewatch', 'bigbook', 'waterbottle'])
if __name__ == "__main__":
import unittest.main
|
dict_list = ["water","big","apple","watch","banana","york","amsterdam","orange","macintosh","bottle","book"]
input_list = ["paris","applewatch","ipod","amsterdam","bigbook","orange","waterbottle", "booking"]
dict_set = set(dict_list)
input_set = set(input_list)
compound_words = set([])
for word in dict_set:
for input_word in input_set:
if word in input_word and input_word.strip(word) in dict_list:
compound_words.add(input_word)
print(compound_words) |
def factorial(x):
current = 1
for i in range(1,x+1):
current = i * current
return current
def sumofdigits(x):
current = 0
for i in str(x):
current += int(i)
return current
print sumofdigits(factorial(100))
|
def load_file(filename):
f = open(filename, "r")
return f.readlines()
def sudoku():
sudoku_grids = []
grid = []
for i in load_file("/Users/sam/Desktop/python/Project Euler/p096_sudoku.txt"):
if i[0:4] == 'Grid':
continue
else:
grid.append(list(i.strip('\n')))
if len(grid) == 9:
sudoku_grids.append(grid)
grid = []
return sudoku_grids
def columns_of_grid(grid,y):
a_column = []
for i in grid:
a_column.append(i[y])
#print(a_column)
return a_column
def squares_of_grid(grid):
squares = []
for i in range(0,9,3):
a_square = []
for a in grid:
a_square += a[i:i + 3]
if len(a_square) == 9:
squares.append(a_square)
a_square = []
continue
return squares
def which_square(lst,x,y):
if x < 3 and y < 3:
return lst[0]
elif x < 6 and y < 3:
return lst[1]
elif x < 9 and y < 3:
return lst[2]
elif x < 3 and y < 6:
return lst[3]
elif x < 6 and y < 6:
return lst[4]
elif x < 9 and y < 6:
return lst[5]
elif x < 3 and y < 9:
return lst[6]
elif x < 6 and y < 9:
return lst[7]
elif x < 9 and y < 9:
return lst[8]
def how_many_options(grid,x,y):
lst = [0,1,2,3,4,5,6,7,8,9]
rcs = (columns_of_grid(grid,y)) + (grid[x]) + (which_square(squares_of_grid(grid),x,y))
for i in set(rcs):
lst.remove(int(i))
return [len(lst),lst]
def fill_a_space(grid,x,y):
a = how_many_options(grid,x,y)
if a[0] == 1:
grid[x][y] = str(a[1][0])
elif a[0] == 0:
return 'incorrect'
return grid
def iterate(grid):
for a in range(len(grid)):
for b in range(len(grid[a])):
if grid[a][b] == '0':
x = fill_a_space(grid,a,b)
if x == 'incorrect':
return 'error'
else:
x
return grid
def is_solved(grid):
for i in grid:
for j in i:
if j == '0':
return False
return True
def least_options(grid):
smallest = [0,0,9,[]]
for i in range(len(grid)):
for j in range(len(grid[i])):
if grid[i][j] == '0':
x = how_many_options(grid,i,j)
if x[0] < smallest[2]:
smallest = [i,j,x[0],x[1]]
if smallest[2] == 1:
return smallest
return smallest
def grid_copy(grid):
new_grid = []
for i in grid:
new_grid.append(i[:])
return new_grid
def fill_a_grid(grid):
x = 0
while x < 81:
z = iterate(grid)
if z == 'error':
return None
elif least_options(z)[2] != 1:
break
x += 1
if is_solved(grid):
return int(''.join(grid[0][0:3]))
else:
y = least_options(grid)
for i in y[3]:
a = grid_copy(grid)
a[y[0]][y[1]] = str(i)
#print(y,a)
f = fill_a_grid(a)
#print('f',f)
if f != None :
return f
#PROBLEM IS IN THE FILL_A_GRID SECTION, ANY LAYER COULD BE INCORRECT. ONCE TOP LEVEL IS INCORRECT PYTHON WILL RETURN NONE.
def answer():
x = 0
for i in sudoku():
y = fill_a_grid(i)
x += y
return x
print(answer())
#print(least_options([['0', '0', '3', '0', '2', '0', '6', '0', '0'], ['9', '0', '0', '3', '0', '5', '0', '0', '1'], ['0', '0', '1', '8', '0', '6', '4', '0', '0'], ['0', '0', '8', '1', '0', '2', '9', '0', '0'], ['7', '0', '0', '0', '4', '0', '0', '0', '8'], ['0', '0', '6', '7', '0', '8', '2', '0', '0'], ['0', '0', '2', '6', '0', '9', '5', '0', '0'], ['8', '0', '0', '2', '0', '3', '0', '0', '9'], ['0', '0', '5', '0', '1', '0', '3', '0', '0']]))
#print(fill_a_grid(sudoku()[1]))
#print(sudoku()[49][8])
|
import math
def triangular(x):
a = 1
while type(a) == int:
t = a * (1 + a) / 2
if len(factors(t)) >= x:
return t
else:
a += 1
def factors(x):
flist = []
for i in range(1,int(math.sqrt(x)) + 1):
if x % i == 0:
flist.append(i)
flist.append(x / i)
return flist
print(triangular(500))
|
def digit_sum(x):
y = 0
for i in str(x):
y += int(i)
return y
largest = 0
for a in range(1,100):
for b in range(1,100):
d = digit_sum(a ** b)
if d > largest:
largest = d
print(largest)
|
def nextfibs(list1):
l = len(list1)
return list1[l-1] + list1[l-2]
def newfibnumber(x):
fibs = [1,1]
curret_fib = 2
while len(str(curret_fib)) < x:
fibs.append(curret_fib)
curret_fib = nextfibs(fibs)
return fibs
print(len(newfibnumber(1000)) + 1)
|
# 5. Программа запрашивает у пользователя строку чисел, разделенных пробелом.
# При нажатии Enter должна выводиться сумма чисел.
# Пользователь может продолжить ввод чисел, разделенных пробелом и снова нажать Enter.
# Сумма вновь введенных чисел будет добавляться к уже подсчитанной сумме.
# Но если вместо числа вводится специальный символ, выполнение программы завершается.
# Если специальный символ введен после нескольких чисел,
# то вначале нужно добавить сумму этих чисел к полученной ранее сумме и после этого завершить программу.
def my_sum():
res_sum = 0
ex = True
while ex == True:
num = input("Введите число разделённое через пробел"
" или 'Q' для выхода -").split()
res = 0
for el in range(len(num)):
if num[el] == 'q' or num[el] == 'Q':
ex = False
break
else:
res += int(num[el])
res_sum += res
print(f"Текущая сумма:{res_sum}")
print(f"Финальная сумма:{res_sum}")
my_sum()
# ------------------Вариант---------------------------------
def sum_num():
s = 0
while True:
num = input("Введите числа через пробел : -для выхода 'q'. ").split()
for el in num:
if el == 'q':
return s
else:
try:
s += int(el)
except ValueError:
print("Для выхода 'q'.")
print(f"Результат-{s}")
print(sum_num())
|
# Напишите программу, доказывающую или проверяющую, что для множества натуральных чисел выполняется
# равенство: 1+2+...+n = n(n+1)/2, где n - любое натуральное число.
n = int(input('Введите любое натурльное число: '))
print(f'1+2+...+{n} = {sum(range(0, n+1))}\n'
f'n(n+1)/2 = {n * (n+1) / 2}\n'
f'Равенство выполняется')
|
list_num = []
num1 = list_num.append(int(input('Введите первое число: ')))
num2 = list_num.append(int(input('Введите второе число: ')))
num3 = list_num.append(int(input('Введите третье число: ')))
list_num.sort()
print(f'Число {list_num[1]} - среднее')
|
bit_and = 5 & 6
bit_or = 5 | 6
bit_xor = 5 ^ 6
bit_left = 5 << 2
bit_right = 5 >> 2
print(f'Выполним логические побитовые операции над числами 5 и 6:\n'
f'5 = {bin(5)}\n'
f'6 = {bin(6)}\n'
f'5 & 6 = {bin(bit_and)} or {bit_and}\n'
f'5 | 6 = {bin(bit_or)} or {bit_or}\n'
f'5 ^ 6 = {bin(bit_xor)} or {bit_or}\n'
f'Сдвиг влево на два = {bin(bit_left)} or {bit_left}\n'
f'Сдвиг вправо на два = {bin(bit_right)} or {bit_right}')
# Объяснение: побитовый сдвиг вправо для положительных чисел равносилен целочисленному делению на 2 в степени n,
# где n - величина сдвига. Побитовый сдвиг влево равносилен умножению на 2 в степени n.
|
# In[10]:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# In[11]:
#importando datos
data = np.loadtxt("resultados_schro.txt", dtype = type(0.0))
# In[12]:
#metodo para animacion
fig = plt.figure()
ax = plt.axes(xlim=(-60,60), ylim=(-0.01,0.01))
line, = ax.plot([], [], lw=2)
def init():
line.set_data([],[])
return line,
def animate(i):
x = np.linspace(-75,75,len(data[0]))
y = data[i]
line.set_data(x,y)
return line,
anim = animation.FuncAnimation(fig, animate, init_func = init, frames = len(data), interval = 1.5/100.0, blit = True)
plt.show()
|
""" Calculate ionic densities consistent with the Poisson-Bolzmann equation.
Copyright 2019 Simulation Lab
University of Freiburg
Author: Lukas Elflein <elfleinl@cs.uni-freiburg.de>
"""
import numpy as np
import matplotlib.pyplot as plt
import scipy.constants as sc
import decimal
np.random.seed(74)
def debye(rho_bulk, charge, permittivity=79, temperature=298.15):
"""Calculate the Debye length.
The Dybe length indicates at which distance a charge will be screened off.
Arguments:
rho_bulk: dictionary of the bulk number densites for each ionic species [1/m^3]
charge: dictionary of the charge of each ionic species [1]
permittivity: capacitance of the ionic solution [1]
temperature: Temperature of the solution [K]
Returns:
float: the Debye length [m], should be around 10^-19
Example: the Debye length of 10^-4 M salt water is 30.4 nm.
>>> density = sc.Avogadro * 1000 * 10**-4
>>> rho = {'Na': density, 'Cl': density}
>>> charge = {'Na': 1, 'Cl': -1}
>>> deb = debye(rho_bulk=rho, charge=charge) * 10**9
>>> deb - 30.4 < 0.5
True
"""
# The numerator of the expression in the square root
# e_r * e_0 * k_B * T
numerator = permittivity * sc.epsilon_0 * sc.Boltzmann * temperature
# The divisor of the expression in the square root
# \sum_i rho_i e^2 z_i^2
divisor = 0
for key in rho_bulk.keys():
divisor += rho_bulk[key] * sc.elementary_charge ** 2 * charge[key] ** 2
# The complete square root
return np.sqrt(numerator / divisor)
def gamma(surface_potential, temperature):
"""Calculate term from Gouy-Chapmann theory.
Arguments:
surface_potential: Electrostatic potential at the metal/solution boundary in Volts, e.g. 0.05 [V]
temperature: Temperature of the solution in Kelvin, e.g. 300 [K]
Returns:
float
"""
product = sc.elementary_charge * surface_potential / (4 * sc.Stefan_Boltzmann * temperature)
return np.tanh(product)
def potential(location, rho_bulk, charge, surface_potential, temperature=300, permittivity=80):
"""The potential near a charged surface in an ionic solution.
A single value is returned, which specifies the value of the potential at this distance.
The decimal package is used for increased precision.
If only normal float precision is used, the potential is a step function.
Steps in the potential result in unphysical particle concentrations.
Arguments:
location: z-distance from the surface [m]
temperature: Temperature of the soultion [Kelvin]
gamma: term from Gouy-Chapmann theory
kappa: the inverse of the debye length
charge: dictionary of the charge of each ionic species
permittivity: capacitance of the ionic solution []
temperature: Temperature of the solution [Kelvin]
Returns:
psi: Electrostatic potential [V]
"""
# Increase the precision of the calculation to 30 digits to ensure a smooth potential
decimal.getcontext().prec = 30
# Calculate the term in front of the log, containing a bunch of constants
prefactor = decimal.Decimal(2 * sc.Stefan_Boltzmann * temperature / sc.elementary_charge)
# For the later calculations we need the debye length
debye_value = debye(rho_bulk=rho_bulk, charge=charge, permittivity=permittivity, temperature=temperature)
kappa = 1/debye_value
# We also need to evaluate the gamma function
gamma_value = decimal.Decimal(gamma(surface_potential=surface_potential, temperature=temperature))
# The e^{-kz} term
exponential = decimal.Decimal(np.exp(-kappa * location))
# The fraction inside the log
numerator = decimal.Decimal(1) + gamma_value * exponential
divisor = decimal.Decimal(1) - gamma_value * exponential
# This is the complete term for the potential
psi = prefactor * (numerator / divisor).ln()
# Convert to float again for better handling in plotting etc.
psi = float(psi)
return psi
def charge_density(location, rho_bulk, charge, surface_potential, temperature=300, permittivity=80, species='Na'):
"""The density of ions near a charged surface.
Calculates the number density of ions of a species, at a distance of "location"
away from a metal/solution interface. The metal is charged, and thus the density
is not homogeneous but higher (lower) than bulk concentration for opposite (equally)
charged ions, converging to the bulk concentration at high distances.
Arguments:
location: z-distance from the surface [m]
rho_bulk: dictionary of ionic concentrations far from the surface [m^-3]
charge: dictionary of the charge of each ionic species [e]
surface_potential: eletrostatic potential at the metal/liquid interface [V]
temperature: Temperature of the solution [K]
permittivity: relative permittivity of the ionic solution, 80 for water [1]
species: the atom name the density shoul be calculated for.
Must be contained in `rho_bulk` and `charge`.
Returns:
rho: number density of ions of given species [1/m^3]
"""
# Evaluate the potential at the current location
potential_value = potential(location, rho_bulk, charge, surface_potential, temperature, permittivity)
# The density is an exponential function of the potential
rho = np.exp(-1 * charge[species] * sc.elementary_charge * potential_value / (sc.Boltzmann * temperature))
# The density is scaled relative to the bulk concentration
rho *= rho_bulk[species]
return rho
def test():
"""Run docstring unittests"""
import doctest
doctest.testmod()
def main():
"""Do stuff."""
print('Done.')
if __name__ == '__main__':
# Run doctests
test()
# Execute everything else
main()
|
#Esto es comentario equisde
print("Hola Mundo!")
print("Adios Mundo!")
5+1
print(4+6)
print(5-2)
print(3*4)
print(20/4)
#precedencia de operadores
print(5+8*(3+2))
#Tipos de datos
print(type(2))
print(type(8.62))
print(type("Texto"))
print(type('Texto'))
print(type("5"))
#Variables
mensaje = "Esto es un mensaje"
print(mensaje)
mensaje = "mensaje hackeado"
print(mensaje)
print(type(mensaje))
mensaje = 100
print(type(mensaje))
mensaje = 100.1
print(type(mensaje))
mis3animales = "Perico, Gallo, Chivo"
print(mis3animales)
tresAñimales = "Perico, Gallo, Chivo"
print(tresAñimales)
#concatenacoón de strings
muchoTexto = "Mucho Texto"
pocoTexto = "Poco Texto"
print(muchoTexto + " " + pocoTexto)
#str() int() float()
edad = 20
print("La edad del usuario es: " + str(edad))
print("El tipo de dato edad es: " + str(type(edad)))
import math
grados = 45.0
radianes = grados * math.pi / 180.0
seno = math.sin(radianes)
print("Seno de 45º: " + str(seno))
def saludar(nommbre):
print("Hola " + nommbre)
print("¿Cómo estás?")
print("Te saludo de lejos por eso del virus papu")
def despedir():
print("Ya me voy papu")
print("Ya que pase todo esto nos besamos")
def concatenar(parte1, parte2):
return parte1 + parte2
print("Esto no es parte de la función")
saludar("Carlos")
despedir()
frase = concatenar("Hola " , "Adiós")
print(frase) |
# for item in iterator:
# do something with the item
my_fruits = ['apple','orange','grapes']
for fruit in my_fruits:
if fruit == 'apple' or fruit == 'grapes':
print(f'Sudharsan likes {fruit}')
else:
print(f'Sudharsan does not like {fruit}')
for index in range(len(my_fruits)):
if my_fruits[index]=='orange':
print(f'Sudharsan does not like {fruit}')
else:
print(f'Sudharsan like {fruit}')
|
weight = 75
address ="103 vaniyambadi"
import os,pandas
print(type(weight))
print(type(address))
print(type(os))
print(type(os.path.join))
print(address.upper())
print(weight.upper()) |
from collections import Counter
counter = Counter(a=4,b=3,c=2)
print(counter)
name = Counter('sudharsan')
print(name)
new_counter =Counter(a=2,b=3)
counter.subtract(new_counter)
print(counter)
counter.update(a=4,b=1)
print(counter)
from collections import namedtuple
# a tuple in which we can access the values via the name(specific argument like name)
book=namedtuple('Book','name author price')
book=namedtuple('Book',['name', 'author', 'price'])
book1 = book('origin of species','charles drawin', 500)
print(book1)
print(book1.name)
print(book1.price)
print(book1._fields)
# collections deque
from collections import deque
d = deque('hello world')
print(d)
d.append('!')
d.extend(['!','!','.'])
d.appendleft('0')
print(d)
d.popleft()
print(d)
# it shifts n digits
d.rotate(2)
print(d) |
'''
Decorators allow us to wrap another function in order to extend the behavior of the wrapped function,
without permanently modifying it
'''
import time
def timer(function):
def wrapper(*args,**kwargs):
startTime = time.time()
result=function(*args,**kwargs)
endTime = time.time()
timeTaken = (endTime-startTime)
return (timeTaken,result)
return wrapper
def addNumbers(start,end):
sum=0
for num in range(start,end):
sum += num
# dealy some time to see the result
time.sleep(0.01)
return sum
addNumbers = timer(addNumbers)
result=addNumbers(1,100)
print(result)
# This can also be achived by decorators
@timer
def addNumbers(start,end):
sum=0
for num in range(start,end+1):
sum += num
# dealy some time to see the result
time.sleep(0.01)
return sum
@timer
def multiply(start,end):
mul=1
for num in range(start,end):
mul *= num
return mul
result=addNumbers(1,100)
print(result)
multiply_result = multiply(1,10)
print(multiply_result) |
vegetables =['ladies finger','potato','beans', 'brinjal']
def containsI(str):
if 'i' in str.lower():
return True
def strRev(str):
return str[::-1]
result = list(filter(containsI,vegetables))
print(result)
# using filter and map togeather
result = tuple(map(strRev,filter(containsI,vegetables)))
print(result)
reverse_vegetable_list = list(map(strRev,vegetables))
print(reverse_vegetable_list)
# lambda is in next file :)
filter_reverse_vegetables_having_e = list(filter((lambda str: True if ('e' in str.lower()) else False),reverse_vegetable_list))
print(filter_reverse_vegetables_having_e)
undo_reverse = set(map(strRev,filter_reverse_vegetables_having_e))
print('vegetables having e',undo_reverse) |
chars = [
'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
'abcdefghijklmnopqrstuvwxyz'
]
arr_len = 2
alpha_len = 26
# Find out if character is a letter & if so, return it's indices
# Not allowed to use the inbuilt find function
def find(char):
for i in range(arr_len):
for j in range(alpha_len):
if char == chars[i][j]:
return [i, j]
def encrypt(key, msg):
key_ind = 0
for char in msg:
num = find(char)
if num:
num[1] += find(key[key_ind])[1]
num[1] %= alpha_len
print(chars[num[0]][num[1]], end='')
key_ind += 1
if key_ind == len(key):
key_ind = 0
else:
print(char, end='')
if __name__ == "__main__":
encrypt(input('Key: '), input('Message: '))
|
#encoding: UTF-8
# Autor: Roberto Téllez Perezyera, A01374866
### Descripcion: Este programa calcula la distancia recorrida por un auto a la velocidad que indique el usuario, así
# como el tiempo requerido para que se recorran 500 kilómetros.
# A partir de aquí escribe tu programa
strVel = input ("Introduce con números la velocidad del auto: ")
vel = float(strVel)
dist6Hrs = vel * 6
dist10Hrs = vel * 10
timeFor500 = (500 / vel)
print ("Distancia recorrida en 6 horas: ", dist6Hrs, "km.")
print ("Distancia recorrida en 10 horas: ", dist10Hrs, "km.")
print ("Para recorrer 500 km, el auto tardará", timeFor500, "horas.") |
class BinaryTreeList:
def __init__(self, value = None):
self.value = value
self.left = None
self.right = None
def add(self, val):
if val <= self.value:
if self.left:
self.left.add(val)
else:
self.left = BinaryTreeList(val)
else:
if self.right:
self.right.add(val)
else:
self.right = BinaryTreeList(val)
class binaryTree:
def __init__(self):
self.root = None
def add(self, value):
if self.root == None:
self.root = BinaryTreeList(value)
else:
self.root.add(value)
def find(self, target):
node = self.root
while node:
if target == node.value:
return True
else:
if target < node.value:
node = node.left
else:
node = node.right
return False
A=binaryTree()
A.add(5)
A.add(3)
A.add(10)
A.add(51)
A.add(34)
A.add(7)
A.add(13)
print("find 51", A.find(51))
print("find 10", A.find(10))
import timeit
print("The timeit for this program is: ",timeit.timeit("binaryTree", globals=globals(), number=5))
|
from collections import Counter
with open("input.txt") as f:
entries = [
line
for line in f.read().split("\n\n")
]
def part1(entries):
count = 0
for entry in entries:
count += len(Counter(entry.replace("\n", "")).keys())
return count
def part2(entries):
count = 0
for entry in entries:
answers = entry.splitlines()
yesses = set(answers[0])
for answer in answers:
yesses = yesses.intersection(answer)
count += len(yesses)
return count
print("Day 6:")
print("Part 1:"),
print(part1(entries))
print("Part 2:"),
print(part2(entries)) |
def longestDigitsPrefix(inputString):
result = ""
for e in inputString:
if e.isdigit():
result += e
else:
break
return result
|
def avoidObstacles(inputArray):
inputArray.sort()
step = 1
location = 0
while True:
if location not in inputArray:
if location < max(inputArray):
location += step
else:
return step
else:
step += 1
location = 0 |
def adjacentElementsProduct(inputArray):
result = inputArray[0] * inputArray[1]
for i in range(len(inputArray)-1):
num = inputArray[i] * inputArray[i+1]
result = num if num > result else result
return result
|
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 6 09:56:09 2019
@author: Paul
"""
import copy
def read_data(filename):
"""
Reads orbital map file into a list
"""
data = []
f = open(filename, 'r')
for line in f:
data += line.strip().split('\n')
f.close()
return data
def direct_orbits(map):
"""
Takes map, a list of orbital map orbit instructions.
Return a dictionary consisting of
keys: each orbital object
values: the object the object in keys is directly orbiting.
"""
orbits_dict = {}
print("Building direct orbit dictionary....")
# Iterate through map and add each orbital object and the object it directly orbits
for entry in map:
orbits_dict[entry[4:]] = [entry[:3]]
return orbits_dict
def all_orbits(direct):
"""
Takes a dict with keys of orbital bodies and values of the orbital body
the key body is directly orbiting.
Returns a dictionary with values of all direct and indirect orbits of each
object as the values. Indirect orbits are shown as 1 item lists inside the orbit list.
Also returns the total number of direct and indirect orbits in the map.
"""
ind_orbits_dict = copy.deepcopy(direct)
print("Building indirect orbit dictionary....")
# Iterate through all orbital objects in the direct orbits dictionary
for planet, orbiting in direct.items():
orbit_found = True
# Start by looking for the object each one is directly orbiting
to_find = orbiting[0][:]
# If an indirect orbit is found, then that objects direct orbit must be checked
while orbit_found:
orbit_found = False
# Iterate through the orbit list to find the next orbit
for entry in direct:
# If another orbit is found, search for the orbit of that new object
if to_find == entry:
ind_orbits_dict[planet].append(direct[entry][:][0])
orbit_found = True
to_find = direct[entry][:][0]
num_orbits = 0
# Count total orbits in the dictionary
for entry in ind_orbits_dict.values():
num_orbits += len(entry)
return ind_orbits_dict, num_orbits
def find_orbital_distance(obj_1, obj_2, ind_orbs):
"""
Takes two strings, obj_1 and obj_2 and a dictionary of all the direct and
indirect orbits in the orbital map.
Searches for a common orbit in the orbit lists of both objects and then
determines the number of orbits from each object to the common orbit.
Returns the minimum number of orbital transfers required such that both
objects are orbiting the same body.
"""
orbits1 = ind_orbs[obj_1]
orbits2 = ind_orbs[obj_2]
dist_orb1_com = 0
dist_orb2_com = 0
print("Finding common orbits....")
for orbit in orbits1:
if orbit in orbits2:
print("Common orbit found: ", orbit)
dist_orb1_com = orbits1.index(orbit)
dist_orb2_com = orbits2.index(orbit)
break
return dist_orb1_com + dist_orb2_com
orbit_map = read_data("day6input.txt")
#orbit_map = read_data("day6testinput.txt") #Test input
#orbit_map = read_data("day6pt2testinput.txt") #Test input for part 2
#print(orbit_map)
direct_orbs = direct_orbits(orbit_map)
#print(direct_orbs)
indirect_orbs, num_orbs = all_orbits(direct_orbs)
#print(indirect_orbs)
print("Part 1: Total number of direct and indirect orbits: ", num_orbs)
transfers = find_orbital_distance('YOU', 'SAN', indirect_orbs)
print("Part 2: Number of orbital transfers required 'YOU' to 'SAN': ", transfers)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.