text stringlengths 37 1.41M |
|---|
# -*- coding:utf-8 -*-
val1 = 1
val2 = 1
if val1 and val2:
print("A")
elif val1 or val2:
print("B")
if val1 > val2:
print("a")
elif val1 < val2:
print("b")
print("test")
val3 = ['a', 'b', 'c']
if 'a' in val3:
print(val3)
|
person = {'name':'a',
'age':30,
'phone':'01000000000'}
print(person.keys())
print(person.values())
print(person.items())
for key in person.keys():
print('key is ', key)
print('val is ', person[key])
print("-"*10)
for value in person.values():
print('val is ',value)
print("-"*10)
for (key, val) in person.items():
print('key is ', key)
print('val is ', val)
|
x = int(input("Input number to convert"))
y = []
while x > 0:
if x%2 == 1:
y.insert(0,"1")
x//=2
print(x)
elif x%2 == 0:
y.insert(0,"0")
x//=2
print(x)
print(''.join(y))
|
# Write a binary search function. It should take a sorted sequence and
# the item it is looking for. It should return the index of the item if found.
# It should return -1 if the item is not found.
def binary_search(sequence,key):
for i in range(len(sequence)):
if sequence[i] == key:
return i
else:
return -1
sequence=input("Enter a string::")
sequence = sequence.split()
key = input("Enter a key to search::")
print("search found!!") if (binary_search(sorted(sequence),key) !=-1) else print("search not found")
|
# 7. Create a list of tuples of first name, last name, and age for your friends and colleagues. If you don't know the age, put in None. Calculate the average age, skipping over any None values. Print out
# each name, followed by old or young if they are above or below the average age
sample_list= [('nabin','hyan',22),('ajit','nakarmi',23),('sagar','koju',21),('subash','shrestha',20)]
sum =0
for i in sample_list:
sum += i[-1]
else:
avg = sum/len(sample_list)
for i in sample_list:
if i[-1] < avg:
print(f"-->> {i[0].title()} is younger than the average age {avg}\n")
else:
print(f"-->> {i[0].title()} is older than the average age {avg}\n")
|
class User:
def __init__(self, name, email):
self.name = name
self.email = email
self.account_balance = 0
# adding the deposit method
def make_deposit(self, amount): # takes an argument that is the amount of the deposit
self.account_balance += amount # the specific user's account increases by the amount of the value received
return self
def make_withdrawal(self, amount):
self.account_balance -= amount
return self
def display_user_balance(self):
print("User: " + self.name + ", Balance: ", (self.account_balance))
# bonus add a transfer_money method and have the first user transfer money to the third user and then print both users' balances
def transfer_money(self, other_user, amount):
self.account_balance -= amount
other_user.account_balance += amount
print("User: " + self.name + ", Balance: ", (self.account_balance))
print("User: " + other_user.name + ", Balance: ", (other_user.account_balance))
#Create 3 instances of the User class
bear = User("Bear", "bear@gmail.com")
bugs = User("Bugs", "bugs@gmail.com")
blitzen = User("Blitzen", "blitzen@gmail.com")
#Have the first user make 3 deposits and 1 withdrawal and then display their balance
bear.make_deposit(100).make_deposit(200).make_deposit(300).make_withdrawal(100).display_user_balance()
#Have the second user make 2 deposits and 2 withdrawals and then display their balance
bugs.make_deposit(50).make_deposit(1000).make_withdrawal(10).make_withdrawal(300).display_user_balance()
#Have the third user make 1 deposit and 3 withdrawals and then display their balance
blitzen.make_deposit(50).make_withdrawal(10).make_withdrawal(300).make_withdrawal(200).display_user_balance()
bear.transfer_money(blitzen, 460) |
from util import Stack
class Graph:
def __init__(self):
self.nodes = {}
def add_node(self, node):
if node not in self.nodes:
self.nodes[node] = set()
def add_edge(self, child, parent):
self.nodes[child].add(parent)
def getNeighbors(self, child):
return self.nodes[child]
# Three steps to solve almost any graphs problem
## Describe in terms of graphs
### Nodes: people
### Edges: if they're parent-child
## Build our graph
### Build a graph class
### Don't write an adjency list or matrix, just get neighbors
## Choose a graph algorithm
### traversal or search? No node we're looking for, no node at which we'll stop, visit all
### breadth or depth? Either one since it's a traversal, depth would be better for a search for longest path
def dft(graph, starting_node):
stack = Stack()
stack.push((starting_node, 0))
visited = set()
# could build a dictionary or set or
# track two variables as we go
visited_pairs = set()
while stack.size() > 0:
current_pair = stack.pop()
visited_pairs.add(current_pair)
current_node = current_pair[0]
current_distance = current_pair[1]
if current_node not in visited:
visited.add(current_node)
parents = graph.getNeighbors(current_node)
for parent in parents:
parent_distance = current_distance + 1
stack.push((parent, parent_distance))
longest_distance = 0
aged_one = -1
for pair in visited_pairs:
node = pair[0]
distance = pair[1]
if distance > longest_distance:
longest_distance = distance
aged_one = node
return aged_one
def earliest_ancestor(ancestors, starting_node):
# build our graph
graph = Graph()
for parent, child in ancestors:
graph.add_node(child)
graph.add_node(parent)
graph.add_edge(child, parent)
# run dft
aged_one = dft(graph, starting_node)
# choose the most distant ancestor
return aged_one |
# Module that contains the necessary functions to implement the VAM
# Author: Harish Balakrishnan
import numpy as np
import copy
def generate_family_of_partitions(list_of_elements):
"""
Function that generates the family of partitions
Parameters
----------
list_of_elements : list
The collection of elements for which we seek the family of partitions. For example,
if list_of_elements = [1,2,3], then this function will return [[[1, 2, 3]], [[1], [2, 3]], [[1, 2], [3]], [[2],
[1, 3]], [[1], [2], [3]]]
Returns
-------
list
List of the family of partitions
"""
# Thanks to alexis: https://stackoverflow.com/questions/19368375/set-partitions-in-python
def partition(l):
if len(l) == 1:
yield [l]
return
first = l[0]
for smaller in partition(l[1:]):
# insert `first` in each of the subpartition's subsets
for n, subset in enumerate(smaller):
yield smaller[:n] + [[first] + subset] + smaller[n + 1:]
# put `first` in its own subset
yield [[first]] + smaller
family = []
for p in partition(list_of_elements):
family.append(p)
return family
def generate_sub_prototypes(family):
"""
Function that generates the sub-prototypes or pseudo-exemplars
Parameters
----------
family : list
List containing the family of all possible representation models for a given category. For example, if category
A had five exemplars, then this list should contain all the 52 possible pseudo-exemplar sets.
Returns
-------
list
List of all sub-prototypes or pseudo-exemplars for the given family of representations of a category.
"""
# Creating a deep copy of family
new_family = copy.deepcopy(family)
bell_no = len(new_family)
for i in range(bell_no):
for j in range(len(new_family[i])):
if len(new_family[i][j]) != 1:
new_sub = list((np.sum(new_family[i][j], axis=0)) / len(new_family[i][j]))
new_family[i][j] = [new_sub]
new_new_family = []
for i in range(len(new_family)):
list_of_lists = new_family[i]
flattened = [val for sublist in list_of_lists for val in sublist]
new_new_family.append(flattened)
return new_new_family
def similarity(stimulus_i, stimulus_j, w, c, r, alpha):
"""
Function that calculates the similarity of stimulus_i and stimulus_j (equation 2 in [WoGB05]_)
Parameters
----------
stimulus_i : list
Stimulus representation in the psychological space. For example, stimulus_i could be [0, 1, 1, 0]
stimulus_j : list
Stimulus representation in the psychological space. For example, stimulus_i could be [1, 0, 0, 1]
w : list
List of weights corresponding to each dimension of the stimulus in the psychological space
c : float
Scale parameter that is used in the distance calculation
r : int
Minkowski’s distance metric. A value of 1 corresponds to city-block metric (generally used when the stimuli has
separable dimensions) ; A value of 2 corresponds to Eucledian distance metric (generally used when the stimuli
has integral dimensions)
alpha : int
Parameter that scales the psychological distance between stimulus_i and stimulus_j. The value of alpha = 2
corresponds to the gaussian similarity
Returns
-------
float
The similarity between stimulus_i and stimulus_j
"""
def distance():
"""
Calculates the distance between two stimulus in the psychological space (equation 3 in [WoGB05]_)
Returns
-------
np.float64
Distance scaled by the scale parameter 'c'
"""
s = 0.0
N = len(stimulus_i)
for idx in range(N):
s += (w[idx] * abs(stimulus_i[idx] - stimulus_j[idx]) ** r)
s = s ** (1 / r)
return c * s
return np.exp(-((distance()) ** alpha))
def similarity_of_i_to_category(stimulus_i, category_exemplars, w, c, r, alpha):
"""
Function that calculates the similarity of stimulus_i to a particular category exemplars (equation 11 in [WoGB05]_)
Parameters
----------
stimulus_i : list
Stimulus representation in the psychological space. For example, stimulus_i could be [0, 1, 1, 0]
category_exemplars : list
List of category (pseudo)exemplars
w : list
List of weights corresponding to each dimension of the stimulus in the psychological space
c : float
Scale parameter that is used in the distance calculation
r : int
Minkowski’s distance metric. A value of 1 corresponds to city-block metric (generally used when the stimuli has
separable dimensions) ; A value of 2 corresponds to Eucledian distance metric (generally used when the stimuli
has integral dimensions)
alpha : int
Parameter that scales the psychological distance between stimulus_i and stimulus_j. The value of alpha = 2
corresponds to the gaussian similarity
Returns
-------
float
The similarity of stimulus_i to category_exemplars
"""
N = len(category_exemplars)
s = 0.0
for i in range(N):
s += similarity(stimulus_i, category_exemplars[i], w, c, r, alpha)
return s
def probability_of_category_A(stimulus_i, category_a_exemplars, category_b_exemplars, w, c, r, alpha, b):
"""
Function that calculates the probability of stimulus_i belonging to category A. Note that this assumes there are
only two categories in total, which is typical of categorization experiments (equation 1 in [WoGB05]_)
Parameters
----------
stimulus_i : list
Stimulus representation in the psychological space. For example, stimulus_i could be [0, 1, 1, 0]
category_a_exemplars : list
List of category A (pseudo)exemplars
category_b_exemplars : list
List of category B (pseudo)exemplars
w : list
List of weights corresponding to each dimension of the stimulus in the psychological space
c : float
Scale parameter that is used in the distance calculation
r : int
Minkowski’s distance metric. A value of 1 corresponds to city-block metric (generally used when the stimuli has
separable dimensions) ; A value of 2 corresponds to Eucledian distance metric (generally used when the stimuli
has integral dimensions)
alpha : int
Parameter that scales the psychological distance between stimulus_i and stimulus_j. The value of alpha = 2
corresponds to the gaussian similarity
b : list
List of biases for the categories
Returns
-------
float
Calculates the probability of stimulus_i belonging to category A
"""
numerator = b[0] * similarity_of_i_to_category(stimulus_i, category_a_exemplars, w, c, r, alpha)
denominator = numerator + b[1] * similarity_of_i_to_category(stimulus_i, category_b_exemplars, w, c, r, alpha)
return numerator / denominator
|
import zipfile
import shutil
f = open('file_one.txt', 'w+')
f.write('File one!!!')
f.close()
f = open('file_two.txt', 'w+')
f.write('File two!!!')
f.close()
comp_file = zipfile.ZipFile('comp_file.zip', 'w')
comp_file.write('file_one.txt', compress_type=zipfile.ZIP_DEFLATED)
comp_file.write('file_two.txt', compress_type=zipfile.ZIP_DEFLATED)
comp_file.close()
zip_obj = zipfile.ZipFile('comp_file.zip', 'r')
zip_obj.extractall('extracted_content')
dir_to_zip = '/home/dm3f90/workspace/python/practice_exercises/compressing_files/extracted_content'
output_filename = 'example'
shutil.make_archive(output_filename, 'zip', dir_to_zip)
shutil.unpack_archive('example.zip', 'final_unzip', 'zip')
|
while 1:
try:
x = input('Enter the first number: ')
y = input('Enter the second number: ')
value = int(x)/int(y)
print('x/y is' + str(value))
except:
print ('Invalid input. Please try again')
else:
break
|
try:
x = input('Enter the first number: ')
y = input('Enter the second number: ')
print (int(x)/int(y))
except(ZeroDivisionError,TypeError,ValueError), e:
print(e)
|
try:
print "Performing an action which may throw an exception."
except Exception as error:
print "An exception was thrown!"
print str(error)
else:
print "Everything looks great!"
finally:
print "Finally is called directly after executing the try statement whether an exception is thrown or not."
|
"""
Parse humanized strings like 128M to 16K to something a machine can understand
"""
from decimal import Decimal
d = {
'k': 3,
'K': 3,
'm': 6,
'M': 6,
'b': 9,
'B': 9,
}
def parse_string(text):
""" Parse humanized strings like 128M to 16K to something a machine can understand """
if text[-1] in d:
num, magnitude = text[:-1], text[-1]
return int(Decimal(num) * 10 ** d[magnitude])
else:
return int(Decimal(text))
|
class Color():
BLACK = 1
RED = 2
class Node():
def __init__(self, data=None, parent=None, color=Color.RED):
self.data = data
self.parent = parent
self.color = color
self.left = self.right = None
class RBT():
def __init__(self):
self.NIL = Node(None, None, Color.BLACK)
self.root = self.NIL
self.size = 0
def left_rotate(self, x):
y = x.right
x.right = y.left
if y.left != self.NIL:
y.left.parent = x
y.parent = x.parent
if x.parent == self.NIL:
self.root = y
elif x == x.parent.left:
x.parent.left = y
else:
x.parent.right = y
y.left = x
x.p = y
def right_rotate(self, x):
y = x.left
x.left = y.right
if y.right != self.NIL:
y.right.parent = x
y.parent = x.parent
if x.parent == self.NIL:
self.root = y
elif x == x.parent.left:
x.parent.left = y
else:
x.parent.right = y
y.right = x
x.parent = y
def insert(self, data):
parent = self.NIL
current = self.root
while current != self.NIL:
parent = current
if data < current.data:
current = current.left
else:
current = current.right
new_node = Node(data, parent)
if parent == self.NIL:
self.root = new_node
elif new_node.data < parent.data:
parent.left = new_node
else:
parent.right = new_node
new_node.left = self.NIL
new_node.right = self.NIL
self.insert_fix_up(new_node)
def insert_fix_up(self, new_node):
while new_node.parent.color == Color.RED:
if new_node.parent == new_node.parent.parent.left:
uncle = new_node.parent.parent.right
if uncle.color == Color.RED:
new_node.parent.color = uncle.color = Color.BLACK
new_node.parent.parent.color = Color.RED
new_node = new_node.parent.parent
elif new_node == new_node.parent.right:
new_node = new_node.parent
self.left_rotate(new_node)
new_node.parent.color = Color.BLACK
new_node.parent.parent.color = Color.RED
self.right_rotate(new_node.parent.parent)
else:
uncle = new_node.parent.parent.left
if uncle.color == Color.RED:
new_node.parent.color = uncle.color = Color.BLACK
new_node.parent.parent.color = Color.RED
new_node = new_node.parent.parent
else:
if new_node == new_node.parent.left:
new_node = new_node.parent
self.right_rotate(new_node)
new_node.parent.color = Color.BLACK
new_node.parent.parent.color = Color.RED
self.left_rotate(new_node.parent.parent)
self.root.color = Color.BLACK
def transplant(self, u, v):
if u.parent == self.NIL:
self.root = v
elif u == u.parent.left:
u.parent.left = v
else:
u.parent.right = v
v.parent = u.parent
def delete(self, node):
temp_node = node
temp_node_original_color = temp_node.color
if node.left == self.NIL:
x = node.right
self.transplant(node, node.right)
elif node.right == self.NIL:
x = node.left
self.transplant(node, node.left)
else:
temp_node = self.minimum(node.right)
temp_node_original_color = temp_node.color
x = temp_node.right
if temp_node.parent == node:
x.parent = temp_node
else:
self.transplant(node, temp_node)
temp_node.right = node.right
temp_node.right.parent = temp_node
self.transplant(node, temp_node)
temp_node.left = node.left
temp_node.left.parent = temp_node
temp_node.color = node.color
if temp_node_original_color == Color.BLACK:
self.delete_fix_up(x)
def minimum(self, node):
current = node
while current.left != self.NIL:
current = current.left
return current
def delete_fix_up(self, x):
pass |
class Node():
def __init__(self, prev=None, data=None, next=None):
self.prev = prev
self.data = data
self.next = next
class LinkedList():
def __init__(self):
self.head = Node()
def insert(self, data):
newNode = Node(self.head, data, None)
if self.head.next != None:
self.head.next.prev = newNode
newNode.next = self.head.next
self.head.next = newNode
def find(self, data):
current = self.head.next
while current is not None and current.data != data:
current = current.next
return current
def remove(self, node):
if node.next:
node.next.prev = node.prev
node.prev.next = node.next
else:
node.prev.next = None |
lista = [0, 1, 3, 2, 23, 43, 2, 1, 5, 2, 5, 2, 56, 23, 0, -1, 2, 2]
listb = [4, 0, 1, 0, 4, 4, 4, 4, 0, 1, 1, 1,-6, 7]
def main(list):
final = {}
x = 0
while x < len(list):
if list[x] not in final:
final[list[x]] = 1
else:
final[list[x]] += 1
x += 1
final_keys = final.keys()
final_values = final.values()
highest_value = final_values[0]
y = 1
while y < len(final_values):
if final_values[y] > highest_value:
highest_value = final_values[y]
y += 1
test = final_values.index(highest_value)
print final_keys[test]
if __name__ == "__main__":
print "Most Frequent for a: "
str(main(lista))
print "Most Frequent for b: "
str(main(listb)) |
"""
1, import random
2, user input
3, function to generate a random string of same length as user input.
4, function to compare the randomly generated string to the user's string and giving it a score each time it generates and compare.
"""
import random
def random_str(user_str):
"""This function will produce a random string of same lenght as the user Enter"""
#generated string
gen_str = ''
#all alpha char with white space
char = ' abcdefghijklmnopqrstuvwxyz'
for i in range(len(user_str)):
#picking a random character from alpha char
cha = char[random.randrange(27)]
#adding character to generated string
gen_str += cha
return gen_str
def check_str(user_str, gen_str):
"""This function will make sure if the generated string is equal to user string or not"""
if user_str.lower() == gen_str:
return True
return False
def main(user_str):
"""This function runs the above two funcitons and return the number of times
that monkey hit the keyboard to randomly get the user string"""
#score of monkey
scr = 0
while True:
#getting a random generated string
gen_str = random_str(user_str)
# print(f'{gen_str} ---->> Monkey hitting key-board >>> {scr} times')
if check_str(user_str, gen_str):
scr += 1
break
else:
scr += 1
continue
return f'Monkey hit the key-board {scr} times to enter your input.'
inp = input('Enter here --->>> ')
print(main(inp))
|
import math
#183 is a sastry number as 183184 is a #perfect square number of 432
def sastry_num(n):
"""returns True if a number n is sastry number,False otherwise"""
num = str(n) + str(n+1)
sqt = math.sqrt(int(num))
if int(sqt) - sqt == 0:
return True
return False
|
def count_all(txt):
"""gives you number of letters and digits in a string"""
dic = {"LETTERS": 0, "DIGITS": 0}
for i in txt:
if i.isnumeric():
dic["DIGITS"] += 1
elif i.isalpha():
dic["LETTERS"] += 1
else:
pass
return dic
print(count_all("roc4 2y77g99")) |
def Turtle4():
"""gives a pattern of star with a bit of 3d effect"""
import turtle
roc = turtle.Turtle()
roc.speed(0)
roc.hideturtle()
roc.getscreen().bgcolor("black")
roc.color("silver")
for i in range(1000):
i += 100
roc.forward(i)
# roc.circle(i)
roc.left(168.5)
|
def largest_even(lst):
if max(lst) % 2 == 0:
return max(lst)
elif (max(lst) - 1) % 2 == 0:
return max(lst) - 1
else:
pass
lst = [3, 9, 5, 8, 4, 7, 3, 6, 6]
print(largest_even(lst)) |
class Solution:
def sortList(self, head):
if not head or not head.next:
return head
return self.merge(*list(map(self.sortList, self.split(head))))
def split(self, head):
fast = slow = head
while fast.next and fast.next.next:
fast = fast.next.next
slow = slow.next
slow.next, slow = None, slow.next
return head, slow
def merge(self, left, right):
merged = p = ListNode()
while left and right:
if left.val <= right.val:
p.next, left, p.next.next = left, left.next, None
else:
p.next, right, p.next.next = right, right.next, None
p = p.next
p.next = left or right
return merged.next |
from Animal import Animal
class Cat(Animal):
# 子类中定义"hair"属性
def __init__(self):
self.hair = "短毛"
super().__init__("露露", "橘色", "2岁", "女")
# 子类中定义"catch_mouse"方法
def catch_mouse(self):
print(f"{self.name}会抓老鼠")
# 重写父类"animal_bark"方法
def animal_bark(self):
print(f"{self.name}饿了会喵喵叫")
def animal_introduce(self):
print(f"大家好,我是{self.name}今年{self.age}了是个{self.gender}宝宝长着{self.color}的{self.hair}。")
if __name__ == '__main__':
# 实例化类
cat = Cat()
# 调用"catch_mouse"方法
# cat.catch_mouse()
# 调用重写的"animal_bark"方法
cat.animal_introduce()
cat.catch_mouse()
cat.animal_bark()
|
from typing import List
import timeit
# Brute Force Solution with O(n^2) complexity. Not optimal solution BUT NECESSARY to understand because it's used by
# further COMPLEX problems like 3sum and 4sum:
"""
# Optimal solution for such problems is O(n) linear time
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(len(nums)):
for j in range(i + 1, len(nums)): # This is the crux of the problem.
if nums[i] + nums[j] == target:
return [i, j]
# In the second for loop's condition, j start from i+1 position because there is no need to recalculate
# the addition till ith element since it will be already done by previous iterations.
"""
# Tip: We are using above brute force solution in 3sum & 4sum problem with a little extension of the logic.
# For bringing above solution in linear time, make use of HASHMAP/Dictionary(uses little extra space but that's okay)
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
storage_dict = {}
for i in range(len(nums)):
complement = target - nums[i] # Find complement and see if complement is present in dictionary.
if complement in storage_dict:
return [storage_dict[complement], i]
storage_dict[nums[i]] = i
return [] # If list is traversed completed and no complement found then return empty list.
# Un-comment the below code to check how much time the dictionary code is taking:
# def test():
# nums = [11, 15, 2, 7, 6, 4]
# target = 11
# sol = Solution()
#
# if __name__ == '__main__':
# import timeit
# print(timeit.timeit("test()", setup="from __main__ import test"))
nums = [11, 15, 2, 7, 6, 4]
target = 11
sol = Solution()
print(sol.twoSum(nums, target))
|
# My own version/implementation of Trie. This code can't be submitted to Leetcode due to
# different definition of insert and search functions. Below this
"""
class Trie:
def insert(self, word: str, currnode, index) -> None:
if index == len(word):
currnode.endFlag = True
return
if not currnode:
return
if currnode.trielist.__contains__(word[index]):
currnode = currnode.trielist[word[index]]
return self.insert(word, currnode, index + 1)
node = Node()
currnode.trielist[word[index]] = node
self.insert(word, node, index + 1)
def search(self, word: str, currnode, index) -> bool:
if index == len(word):
if currnode.endFlag == True:
return True
else:
return False
if not currnode:
return False
if currnode.trielist.__contains__(word[index]):
currnode = currnode.trielist[word[index]]
return self.search(word, currnode, index + 1)
return False
def startsWith(self, prefix: str, currnode, index) -> bool:
if index == len(prefix):
return True
if not currnode:
return False
if currnode.trielist.__contains__(prefix[index]):
currnode = currnode.trielist[prefix[index]]
return self.startsWith(prefix, currnode, index + 1)
return False
class Node:
def __init__(self, trielist=None, endFlag=False, next=None):
if trielist is None:
trielist = {}
self.trielist = trielist
self.endFlag = endFlag
"""
# Modified my code for Leetcode implementation:
class Trie:
def __init__(self):
self.masternode = Node()
self.index = 0
def insert(self, word: str) -> None:
currnode = self.masternode
index = 0
def insertutil(word: str, currnode, index) -> None:
if index == len(word):
currnode.endFlag = True
return
if not currnode:
return
if currnode.trielist.__contains__(word[index]):
currnode = currnode.trielist[word[index]]
return insertutil(word, currnode, index + 1)
node = Node()
currnode.trielist[word[index]] = node
insertutil(word, node, index + 1)
insertutil(word,currnode,index)
print("Inserted word : {}".format(word))
def search(self, word: str) -> bool:
currnode = self.masternode
index = 0
def searchutil(word: str, currnode, index) -> bool:
if index == len(word):
if currnode.endFlag == True:
return True
else:
return False
if not currnode:
return False
if currnode.trielist.__contains__(word[index]):
currnode = currnode.trielist[word[index]]
return searchutil(word, currnode, index + 1)
return False
return searchutil(word, currnode,index)
def startsWith(self, prefix: str) -> bool:
currnode = self.masternode
index = 0
def startsWithutil(prefix: str, currnode, index) -> bool:
if index == len(prefix):
return True
if not currnode:
return False
if currnode.trielist.__contains__(prefix[index]):
currnode = currnode.trielist[prefix[index]]
return startsWithutil(prefix, currnode, index + 1)
return False
return startsWithutil(prefix, currnode, index)
class Node:
def __init__(self, trielist=None, endFlag=False):
if trielist is None:
trielist = {}
self.trielist = trielist
self.endFlag = endFlag
word = "roshan"
word2 = "roshax"
word3 = "ros"
node = Node()
obj = Trie()
obj.insert(word)
obj.insert(word2)
print("Whole word search! Found \"{}\"? : {}".format(word, obj.search(word)))
print("Whole word search! Found \"{}\"? : {}".format(word3, obj.search(word3)))
print("Prefix of word search! Found \"{}\"? : {}".format(word3, obj.startsWith(word3)))
"""
*************************** Succinct and Optimized code from Leetcode comments ***************************
Non-Recursive Code i.e. Iterative Code:
class TrieNode:
# Initialize your data structure here.
def __init__(self):
self.word=False
self.children={}
class Trie:
def __init__(self):
self.root = TrieNode()
# @param {string} word
# @return {void}
# Inserts a word into the trie.
def insert(self, word):
node=self.root
for i in word:
if i not in node.children:
node.children[i]=TrieNode()
node=node.children[i]
node.word=True
# @param {string} word
# @return {boolean}
# Returns if the word is in the trie.
def search(self, word):
node=self.root
for i in word:
if i not in node.children:
return False
node=node.children[i]
return node.word
# @param {string} prefix
# @return {boolean}
# Returns if there is any word in the trie
# that starts with the given prefix.
def startsWith(self, prefix):
node=self.root
for i in prefix:
if i not in node.children:
return False
node=node.children[i]
return True
# Your Trie object will be instantiated and called as such:
# trie = Trie()
# trie.insert("somestring")
# trie.search("key")
"""
|
# Developed this on my own after reading of algorithm:
# Algorithm is : compare first element in each list, whichever ele is smaller, create its node and increment
# the pointer for that list
# Read comments for why recursive approach can lead to stackoverflow error for large lists:
# https://leetcode.com/problems/merge-two-sorted-lists/discuss/9713/A-recursive-solution
class Node:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def mergeTwoLists(self, node1, node2):
if not node1 and not node2: # If both nodes are empty, we reached end of the lists.
return
if not node1: # One of the lists ran out of nodes, so now point return nodes from the second list.
return node2 # No need to create new nodes for remaining nodes, we can just point it to existing node.
if not node2:
return node1
# if not node1 or not node2: # Above can also be written in this manner
# return node1 or node2
if node1.val == node2.val:
newnode = Node(node1.val) # Could have also used node2, doesn't matter since node values are same
newnode.next = self.mergeTwoLists(node1.next, node2)
return newnode
if node1.val < node2.val:
newnode = Node(node1.val) # Since node1 is small, create new node1 and increment existing one's pointer
newnode.next = self.mergeTwoLists(node1.next, node2) # Sending node.next / i.e. Incrementing pointer
return newnode
if node2.val < node1.val:
newnode = Node(node2.val)
newnode.next = self.mergeTwoLists(node1, node2.next)
return newnode
if __name__ == "__main__":
node1 = Node(1)
node1.next = Node(3)
node1.next.next = Node(5)
node1.next.next.next = Node(7)
node2 = Node(2)
node2.next = Node(4)
node2.next.next = Node(6)
node2.next.next.next = Node(8)
sol = Solution()
solnode = sol.mergeTwoLists(node1, node2)
while solnode:
print(solnode.val)
solnode = solnode.next
|
"""Most initial Solution by me:
class Solution:
result = []
def kthSmallestutil(self, root: TreeNode, k) -> int:
if len(self.result) >= k: # If k is small, no need to store all numbers in list, helps reduce space complexity
return
if not root:
return
else:
self.kthSmallestutil(root.left, k)
self.result.append(root.val)
self.kthSmallestutil(root.right, k)
def kthSmallest(self, root: TreeNode, k: int) -> int:
self.kthSmallestutil(root, k)
return self.result[k - 1]
This code has 2 problems:
1) It is working locally but on leetcode it is giving wrong output. (Try to figure out why)
2) It is storing nodes in result LIST unnecessarily, which increases space complexity. Below approach just
decrements the k value till it reaches zero and then returns that result. So zero space utilization.
"""
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def kthSmallestutil(self, root: TreeNode) -> int:
if self.found: # To exit as soon as possible
return
if not root:
return
self.kthSmallestutil(root.left)
self.k -= 1
if self.k == 0:
self.result = root.val
self.found = True
return
self.kthSmallestutil(root.right)
def kthSmallest(self, root: TreeNode, k: int) -> int:
self.result = None
self.found = False # To exit as soon as possible
self.k = k
self.kthSmallestutil(root)
return self.result
master = TreeNode(4)
master.left = TreeNode(2)
master.right = TreeNode(6)
master.right.right = TreeNode(7)
master.right.left = TreeNode(5)
master.left.left = TreeNode(1)
master.left.right = TreeNode(3)
sol = Solution()
print(sol.kthSmallest(master, 2))
|
# 8iyyExWzn5PX99g
s = input('请输入一段文字:')
i = -1
while i >= -1 * len(s):
print(s[i], end="")
i = i - 1
# 麦苗儿青菜花儿黄 王东渝 |
# -*- coding:utf-8 _*-
__author__ = 'ronething'
"""
实现一个可以支持 slice 切片操作的 class
不可修改序列
"""
import numbers
class Group:
def __init__(self, group_name, company_name, staffs):
self.group_name = group_name
self.company_name = company_name
self.staffs = staffs
def __reversed__(self):
self.staffs.reverse()
def __getitem__(self, item):
cls = type(self)
if isinstance(item, slice):
return cls(
group_name=self.group_name,
company_name=self.company_name,
staffs=self.staffs[item])
elif isinstance(item, numbers.Integral):
return cls(
group_name=self.group_name,
company_name=self.company_name,
staffs=[self.staffs[item]])
def __len__(self):
return len(self.staffs)
def __iter__(self):
return iter(self.staffs)
def __contains__(self, item):
if item in self.staffs:
return True
else:
return False
staffs = ['panda', 'xzx', 'ronething']
group = Group(company_name='ahh..', group_name='user', staffs=staffs)
print(group[:2].staffs)
print(group[2].staffs)
print(len(group))
if 'panda' in group:
print('yes')
for i in group:
print(i)
reversed(group)
for i in group:
print(i)
|
# -*- coding:utf-8 _*-
__author__ = 'ronething'
import bisect
# 用来处理已排序的序列 用来维持已排序的序列 升序
# 二分查找
inter_list = []
bisect.insort(inter_list, 3)
bisect.insort(inter_list, 1)
bisect.insort(inter_list, 6)
bisect.insort(inter_list, 4)
bisect.insort(inter_list, 2)
bisect.insort(inter_list, 5)
# bisect_right or bisect_left 查找出插入位置 可用于有些要求比较严格的排序序列
print(bisect.bisect(inter_list, 3)) # 3 相当于 bisect_right
print(bisect.bisect_left(inter_list, 3)) # 2
print(inter_list) # [1, 2, 3, 4, 5, 6]
|
# -*- coding:utf-8 _*-
__author__ = 'ronething'
"""
tuple 比 list 好的地方
- immutable
- 性能优化
- 线程安全
- 可以作为 dict 的 key
- 拆包特性
如果拿 C lang 类比,tuple 对应 struce 、list 对应 array
"""
from collections import namedtuple
# 使用 namedtuple 创建一个类
User = namedtuple('User', ['name', 'age', 'height'])
user_tuple = ('ronething', 20, 126)
user = User(*user_tuple)
user_info = user._asdict() # OrderedDict([('name', 'ronething'), ('age', 20), ('height', 126)])
# user = User._make(user_tuple) 与上面一样效果
print(user.name, user.age, user.height)
|
# -*- coding:utf-8 _*-
__author__ = 'ronething'
"""
什么是迭代协议 __iter__
迭代器是什么 迭代器是访问集合内元素的一种方式,一般用来遍历数据
可迭代和迭代器 不一样 实现 __iter__ 可迭代 实现 __iter__ and __next__ 迭代器
"""
from collections.abc import Iterable, Iterator
a = [1, 2]
print(isinstance(a, Iterable)) # True
print(isinstance(a, Iterator)) # False
b = iter(a)
print(isinstance(b, Iterable)) # True
print(isinstance(b, Iterator)) # True
|
import sys
import os.path
class dict_writer:
def __init__(self, dictionary = {}, file = "dict.txt"):
self.vars = dictionary
self.filename = file
self.does_exist = os.path.exists(self.filename)
def generate_file(self, dictionary = None):
"""
Writes the current value of self.vars to the file specified by self.filename.
If a custom dictionary is supplied by using the keyword argument "dictionary," then
the specified dictionary will be written instead.
"""
if dictionary == None: dictionary = self.vars
with open (self.filename, 'w') as f:
for keys in dictionary.keys():
f.write(str(keys) + " = " + str(dictionary.get(keys)) + "\n")
def read_file(self, sanity = True):
"""
Reads the file specified by self.filename (defined at initalization) and returns the contents of the file as a dictionary.
If sanity checking is turned off with the use of the keyword argument "sanity = false" keys in the file will not
be checked against the dictionary supplied at initialization.
"""
_dict = {}
with open (self.filename, 'r') as f:
for line in enumerate(f):
value = line[1].strip()
if value.find("=") < 0 and not value == "":
sys.stderr.write("Missing '=' in "+self.filename+" on line " + str(line[0] + 1) + ". Cancelling read.\n")
return
else: valIndex = value.find("=")
key = value[0:valIndex].strip()
value = value[valIndex + 1:].strip()
hasQuote = False
if '"' in value and sanity:
hasQuote = True
value = self._parse_quote(value, '"', str(line[0] + 1))
if "'" in value and sanity:
hasQuote = True
value = self._parse_quote(value, "'", str(line[0] + 1))
if not hasQuote: value = value.replace(" ", "")
if self.vars.get(key) == None and not sanity:
sys.stderr.write('\nInvalid key assignment in '+self.filename+' on line '+str(line[0] + 1)+'.\n'+
"Ignoring line "+str(line[0] + 1)+'.\n\n')
else:
_dict.update({key: value})
return _dict
def get_dict(self):
"""Returns self.vars"""
return self.vars
def get_key(self, lineNum):
"""
Returns the key at the specified line number (lineNum) in self.filename.
If the line does not contain an entry, returns None
"""
with open(self.filename, 'r') as f:
for i in range(lineNum):
f.readline()
line = f.readline().strip()
if line.find("=") < 0 and not line == "":
sys.stderr.write("Missing '=' in "+self.filename+" on line " + str(lineNum + 1) + ".")
return None
else: valIndex = line.find("=")
key = line[:valIndex - 1]
return key
def get_val_from_line(self, lineNum):
"""
Returns the value at the specified line number (lineNum) in self.filename.
If the line does not contain an entry, returns None
"""
with open(self.filename, 'r') as f:
for i in range(lineNum):
f.readline()
line = f.readline().strip()
if line == "": return None
if line.find("=") < 0:
sys.stderr.write("Missing '=' in "+self.filename+" on line " + str(lineNum + 1) + ".")
return None
else: valIndex = line.find("=")
value = line[valIndex + 1:].strip()
return value
def get_definition(self, key):
"""
Searches the dictionary contained by the file at self.filename for the given key and returns it's definition.\n
If none is found, returns None
"""
lineNum = self._get_line(key)
if lineNum == -2:
return None
with open(self.filename, 'r') as f:
for i in range(lineNum):
f.readline()
line = f.readline()
value = line.strip()
if value.find("=") < 0:
sys.stderr.write("Missing '=' in "+self.filename+" on line " + str(lineNum + 1) + ". Continuing read after key.")
valIndex = len(key) + 1
else: valIndex = value.find("=")
value = value[valIndex + 1:].strip()
hasQuote = False
if '"' in value:
hasQuote = True
value = self._parse_quote(value, '"', str(line[0] + 1))
if "'" in value:
hasQuote = True
value = self._parse_quote(value, "'", str(line[0] + 1))
if not hasQuote: value = value.replace(" ", "")
return value
def update_value(self, _dict):
"""
Takes a dictionary as it's argument and updates the dictionary contained by the file at self.filename.
Does not update self.vars.
"""
tmp = self.read_file()
tmp.update(_dict)
self.generate_file(dictionary=tmp)
def get_length(self):
"""
Returns the number of lines in self.filename
"""
numLines = 0
with open (self.filename, 'r') as f:
curLine = f.readline()
while curLine != "":
curLine = f.readline()
numLines += 1
return numLines
def _parse_quote(self, readStr, char, lineNum):
"""
Internal class use only
Ensures that readStr has only one pair of quotes and that they are used correctly
"""
if len(readStr.strip()[:readStr.find(char)]) > 1:
sys.stderr.write('\nValue in '+self.filename+' on line '+lineNum+' contains a quote (" '+char+' ") but does not begin with it.\n' +
'If whitespace is needed within the value please begin and end value with a quote (" '+char+' ") character.\n'+
"Ignoring quotes on line "+lineNum+".\n\n")
return readStr.replace(char, "").strip()
else:
tmpStr = readStr[readStr.find(char) + 1:]
if tmpStr.find(char) < 0:
sys.stderr.write('\nValue in '+self.filename+' on line '+lineNum+' does not contain a corresponding quote (" '+char+' ").\n'
"Ignoring quotes on line "+lineNum+".\n\n")
return readStr.replace(char, "").strip()
if len(tmpStr[tmpStr.find(char) + 1:]) > 0:
sys.stderr.write('\nValue in '+self.filename+' on line '+lineNum+' continues after second quote (" '+char+' ").\n'+
"Ignoring extraneous text on line "+lineNum+".\n\n")
return tmpStr[:tmpStr.find(char)].strip()
#this should be unreachable, but is here just in case
return readStr
def _get_line(self, key):
"""
Internal class use only
Returns the line number in the self.filename of the given key.\n
If no key is found, returns -2
"""
with open(self.filename, 'r') as f:
for i,line in enumerate(f):
value = line.strip()
if value.find("=") < 0:
sys.stderr.write("Missing '=' in "+str(self.filename)+" on line " + str(i) + ". Continuing read after key.")
valIndex = len(key) + 1
else: valIndex = value.find("=")
match = value[0:valIndex].strip()
if key == match:
return i
return -2
#
"""
stats = dict_writer(file = "usage_stats.txt")
_max = [0, 0]
for i in range(0, stats.get_length()):
tmp = int(stats.get_val_from_line(i))
if _max[1] < tmp:
_max = [i, tmp]
print(str(_max))
""" |
import sys
def SieveOfEratosthenes(N):
# Let A be an array of Boolean values,
# indexed by integers 2 to n, initially all set to true.
primes = []
isPrime = [True] * (N + 1)
isPrime[0] = isPrime[1] = False
for i in range(int(N ** 0.5 + 1.5)):
if i > 1 :
if isPrime[i]:
for j in range(i * i, N + 1, i):
isPrime[j] = False
for i in range(2, len(isPrime)):
if isPrime[i] == True:
if i < N:
primes.append(i)
print ','.join(str(i) for i in primes)
with open(sys.argv[1], 'r') as input:
test_cases = input.read().strip().splitlines()
for test in test_cases:
if len(test) == 0:
continue
limit = int(test)
SieveOfEratosthenes(limit) |
for i in range(12):
table = []
for j in range(12):
table.append((i + 1) * (j + 1))
print '{:>3} {:>3} {:>3} {:>3} {:>3} {:>3} {:>3} {:>3} {:>3} {:>3} {:>3} {:>3}'.format(*table).strip()
print '\n' |
# Given two arrays write a function to find out if two arrays have the same frequency of digits.
array_1 = [1, 2, 3, 4]
array_2 = [1, 2, 3, 4]
frequency_1 = {}
frequency_2 = {}
# populate two dictionaries with key of the number in the array and the value is how frequent it shows up
def frequency(arr1, arr2, dict1, dict2):
for i in arr1:
if i not in dict1:
dict1[i] = 1
else:
dict1[i] += 1
for i in arr2:
if i not in dict2:
dict2[i] = 1
else:
dict2[i] += 1
frequency(array_1, array_2, frequency_1, frequency_2)
if frequency_1 == frequency_2:
print("The two arrays have the same frequency of digits.")
else:
print("The to arrays do not have the same frequency of digits.")
|
n = 0
if n%2 ==0:
print("Es par")
else:
print("No es par") |
edad = {'noe':19, 'yoselin':18, 'brendita':19}
for clave in edad:
print(edad[clave])
for clave in edad:
print (clave, edad[clave])
for clave, valor in edad.items():
print(clave, valor)
|
personajes = []
p = {'nombre':'miku uwu', 'clase':'cantante virtual', 'edad':'ni idea'}
personajes.append(p)
p = {'nombre':'kaito owo', 'clase':'cantante virtual', 'edad':'25'}
personajes.append(p)
p = {'nombre':'gummi nwn', 'clase':'cantante virtual', 'edad':'15'}
personajes.append(p)
print(personajes)
for p in personajes:
print(p['nombre'], p['clase'], p['edad'])
|
#! /home/user/miniconda3/bin/python
"""
This function gets the reverse complement
of given DNA sequences
Usage:
python reverse_complement.py <seq_file>
"""
import sys
seq_file = sys.argv[1]
def reverse_complement (seq_file:str):
complement = {'A':'T', 'C':'G', 'T':'A', 'G':'C'}
reverse_comp = "".join(complement[i] for i in seq[::-1])
return reverse_comp
if len(sys.argv) <2:
print(_Doc_)
else:
print()
seq_file = sys.argv[1]
|
"""Module with values calculations"""
from typing import List
def generate_fibonacci_values(number_of_precalculated_values: int) -> List[int]:
"""
Generates fibonacci values
:param number_of_precalculated_values: number of values to calculate
:return: list of calculated values
"""
data = list()
for i in range(number_of_precalculated_values + 1):
if i == 0 or i == 1:
data.append(1)
else:
data.append(data[i - 1] + data[i - 2])
return data
def generate_period_values(number_of_precalculated_values: int) -> List[int]:
"""
Generates period values
:param number_of_precalculated_values: number of values to calculate
:return: list of calculated values
"""
data = list()
repeated_values = [1, 0, -1, 0]
for i in range(number_of_precalculated_values + 1):
value_to_insert = repeated_values[i % len(repeated_values)]
data.append(value_to_insert)
return data
def generate_factorial_values(number_of_precalculated_values: int) -> List[int]:
"""
Generates factorial values
:param number_of_precalculated_values: number of values to calculate
:return: list of calculated values
"""
data = list()
for i in range(number_of_precalculated_values + 1):
if i == 0 or i == 1:
data.append(1)
else:
data.append(i * data[i - 1])
return data
def generate_exp_values(number_of_precalculated_values: int) -> List[int]:
"""
Generates exponential values
:param number_of_precalculated_values: number of values to calculate
:return: list of calculated values
"""
data = list()
for i in range(number_of_precalculated_values + 1):
value_to_insert = i ** 2 if i % 2 == 0 else i
data.append(value_to_insert)
return data
|
x = int(input())
list1 = [0]*x
for i in range(0,x):
list1[i] = int(input())
list1.sort()
print(list1) |
""" Sets are a collection of unique items. An item can be added
many times, but it will only exist once in the set"""
s = set()
s.add(1)
s.add(2)
print s
# set([1, 2])
for i in range(5):
s.add(i)
print s
# set([0, 1, 2, 3, 4])
for i in range(10):
s.add(i)
print s
# set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
""" You can compare two sets """
s1 = set([1, 2, 3, 4])
s2 = set([3, 4, 5, 6])
# get the union (elements in either set)
print s1 | s2
# set([1, 2, 3, 4, 5, 6])
# get the intersection (elements in both sets)
print s1 & s2
# set([3, 4])
# get the difference between 2 sets
print s1 - s2
# set([1, 2])
print s2 - s1
# set([5, 6])
""" Sets can be created using literals instead of calling set()"""
s1 = set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
s2 = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
print s2
# set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
print s1 == s2
# True
""" This can also be used to create sets using comprehension """
s3 = {i for i in xrange(10)}
print s3 == s2 == s1
# True
|
""" Take a list of items, and return a new list with items removed that do not match the filter criteria"""
# remove numbers from a list that are not even
n = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even = filter(lambda x: x % 2 == 0, n)
print even
# [2, 4, 6, 8, 10]
|
import os.path
import aes
import getpass
import random
import string
MY_PATH = os.path.abspath(os.path.dirname(__file__))
MY_PASSWORD = "justdoit"
PATH = os.path.join(MY_PATH, "config/password")
def change(old_password, password, password2, username="admin"):
"""Changing the password."""
if authenticate(username, old_password) == True:
if password == password2:
save_credentials(username, password)
return True
return False
def save_credentials(username, password):
authstring = "Username:'" + username + "'Password:'" + password + "'"
with open(PATH, "w") as pwd_file:
encrypted = aes.encrypt(MY_PASSWORD, authstring.encode())
pwd_file.write(encrypted)
def authenticate(username, password):
"""Authenticating the password and username."""
print("================= Authenticating =================")
list_1 = []
username2 = "Username:'" + username + "'Password:'" + password + "'"
if not os.path.isfile(PATH):
print("password file doesn't exist, creating default")
save_credentials("admin", "admin")
with open(PATH, "r") as pwd_file:
for line in pwd_file:
list_1.append(line)
if len(list_1) == 0:
return False
decrypted = aes.decrypt(MY_PASSWORD, list_1[0])
return bool(username2 in decrypted.decode())
def compare_new_passwords(password, password2):
"""Compares current password with the user inputed password"""
return bool(password != password2)
def compare_current_password(oldpassword, username="admin"):
return not bool(authenticate(username, oldpassword))
def authentication():
username = raw_input("USERNAME: ")
password = getpass.getpass("PASSWORD: ")
if authenticate(username, password):
print("Successfully authenticated!")
change_password = raw_input("Do you want to change password?<Yes/No>")
if "Yes" in change_password:
old_password = getpass.getpass("Old password: ")
new_password = getpass.getpass("New password: ")
confirm_password = getpass.getpass("Confirm new password: ")
if change(old_password, new_password, confirm_password, username):
print("Your password has been changed successfully!")
else:
print("Could't change your password!")
else:
print("Wrong credentials!")
print("Closing...")
def file_encryption():
""""File encryption/decryption using aes"""
print("File encryption/decryption using aes\n\n")
command = raw_input("Choose an action<Encrypt/Decrypt>: ")
path = raw_input("Please type the file path: ")
if os.path.exists(path):
with open(path, "r") as file_to_read:
text = file_to_read.read()
if not text:
print("File doesn't have content!")
else:
key = raw_input("Please type the key: ")
paths_directory = os.path.dirname(path)
rand_string = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(5))
file_extension = os.path.splitext(path)[1]
if command.lower() == "encrypt": #if input is encrypt
with open("%s\encryption_%s%s" % (paths_directory, rand_string, file_extension), "w+") as file_to_write:
encrypted_text = aes.encrypt(key, text.encode())
file_to_write.write(encrypted_text)
print("Encryption completed successfully!")
elif command.lower() == "decrypt": #else if input is decrypt
with open("%s\decryption_%s%s" % (paths_directory, rand_string, file_extension), "w+") as file_to_write:
decrypted_text = aes.decrypt(key, text)
if decrypted_text:
file_to_write.write(decrypted_text.decode())
print("Decryption completed successfully!")
else: #if input is not encrypt or decrypt
print("Command wasn't recognised!")
else:
print("File doesn't exists!")
print("Closing...")
file_encryption()
#authentication()
|
class MyClass:
def l(self):
li=[x**2 for x in range(1, 11)]
print(li)
def dict(self):
myDict = {x: x ** 2 for x in [1, 2, 3, 4, 5]}
print(myDict)
sDict = {x.upper(): x * 3 for x in 'coding '}
print(sDict)
tmp=MyClass()
tmp.l()
tmp.dict()
dict={1:'s',2:'ys',3:{5:2,4:5,1:'s'}}
print(dict.get(3))
dict.pop(2)
print(dict)
dict.popitem()
print(dict)
dict.clear()
print(dict) |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def helper(self, root, nodes):
if(root == None):
return 0
if(root.left == None and root.right == None):
nodes[root] = (0, 0)
return 1
left = self.helper(root.left, nodes)
right = self.helper(root.right, nodes)
nodes[root] = (left, right)
return max(left, right) + 1
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
nodes = dict()
self.helper(root, nodes)
# print nodes
for key in nodes.keys():
if(abs(nodes[key][0] - nodes[key][1]) > 1):
return False
return True |
# This is a sample form for research candidates
""" Name Age Sex Weight Allergies Preferences Dislikes (Estimated Physical Activeness) (Recent Health Issues) """
print ("College Research Board")
print ("Candidates are asked to fill out the following form")
print ("To be the part of the research")
print ("Please answer correctly")
print ("Research on 'Effect of Food on a Person's daily Life'")
print ("Form:")
nameOK = False
"""
while nameOK == Fasle:
if name == name.title():
nameOK = True
else:
print ("Please Enter the Initials in Upper Case.")"""
name = input("Enter Your Name:\n>.. ")
ageOk = False
age = int(input("Enter your age:\n>.. "))
if age >= 18:
ageOK = True
else:
print ("Sorry You have to be above 18 years to take participation in this research")
exit()
sex = input("Enter your Gender:\n>.. ")
for i in sex:
sx = i
break
weight = int(input("Enter your weight:\n>.. "))
print("This is your Identification Card")
print ("Name:", name.title())
print ("Age:" , age)
print ("Gender:",sx.title())
print ("Weight:" , weight)
|
import random
somay = random.randrange(1, 6)
for i in range(1, 7):
print("Nhap so di ")
sonhap = int(input())
if sonhap == somay:
print("Dung roi")
break
elif sonhap < somay:
print("be qua")
elif sonhap > somay:
print("lon qua ")
|
class A(object):
def __init__(self, num):
self.num = num
def __add__(self, other):
return A(self.num + other.num)
def get_num(self):
return self.num
A.get_num = get_num
|
class A(object):
x = 1
class B(A):
pass
class C(A):
pass
print(A.x, B.x, C.x) # 1 1 1
B.x = 2
print(A.x, B.x, C.x) # 1 2 1
A.x = 3
print(A.x, B.x, C.x) # 3 2 3 tại sao vậy?
'''
C doesn’t have its own x property, independent of A.
Thus, references to C.x are in fact references to A.x
C kế thừa từ A, C không thực sự sở hữu thuộc tính x mà nó tham chiếu đến thuộc tính x của A
''' |
n = 5
message = "Greater than 2" if n > 2 else "Smaller than or equal to 2"
print(message)
n = 5
message = "Hello" if n > 10 else "Goodbye" if n > 5 else "Good day"
print(message)
|
product = 1
nums = [1, 2, 3, 4]
for num in nums:
product = product * num
print(product)
from functools import reduce
product = reduce((lambda x, y: x * y), [1, 2, 3, 4])
print(product)
# Tính tổng
total = reduce(lambda a, x: a + x, [0, 1, 2, 3, 4])
print(total)
|
import json
while True:
username = input('Please input your name(q to quit): ')
if username == "q":
break
else:
filename = "usernames.json"
with open(filename, 'a') as f_obj:
username_full = '\nUsername: ' + username
json.dump(username_full, f_obj)
print('We will remamber your name: ', username) |
import random
'随机数划拳'
p = int(input('请随机输入你出的剪刀(1)、石头(2)、布(3):'))
i = random.randint(1,3)
print('你出的是%d,对方出的是%d' %(p,i))
if p == i:
print('平手,再来')
elif p > 3:
print('你的出拳不合法')
elif ((p == 1 and i == 3)
or (p == 2 and i == 1)
or (p ==3 and i == 2)):
print('恭喜,你赢了')
else:
print('你输了,笨死算了')
|
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 18 10:38:31 2018
@author: SONY
"""
import tkinter
from tkinter import *
def responce():
print(ivar1.get() + ivar2.get())
root=Tk()
root.title("sum of two numbers")
ivar1=IntVar()
ivar2=IntVar()
a=Entry(textvariable=ivar1)
b=Entry(textvariable=ivar2)
add=Button(root,text="Get Result!",command=responce)
a.pack()
b.pack()
add.pack()
root.mainloop() |
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 19 18:23:32 2018
@author: SONY
"""
import tkinter
from tkinter import *
from tkinter import messagebox
root = Tk()
root.title("messagebox tkinter-7")
def showinfobox():
messagebox.showinfo("Intell-eyes","showinfo from PythonGuru")
def showwarning():
messagebox.showwarning("Intell-eyes","showwarning from pythonguru")
def showerrorbox():
messagebox.showerror("Intell-eyes","showerror from pythonguru")
def askquestionbox():
result=messagebox.askquestion("Intell-eyes","Delete")
if result=="yes":
print("Deleted")
else:
print("I'm Not Deleted yet")
def askokcancelbox():
result=messagebox.askyesno("Intell-eyes","can you program in c/c++?")
if result==True:
print("That's Great!")
else:
print("Try to Learn c/c++!")
def askyesnobox():
result=messagebox.askyesno("Intell-eyes","Are you Learning Python?")
if result==True:
print("Then you are good engouh to undestanding this program")
else:
print("Improve your fundamentals of python, then you can undestand this python well!")
def askretrycancelbox():
result=messagebox.askretrycancel("Intell-eyes","Your facebook password is wrong!")
if result==true:
print("Retrying enter your password here!")
else:
print("Don't you use password")
ba=Button(root,text="showinfo!",command=showinfobox)
ba.pack()
bb=Button(root,text="showWarning!",command=showwarningbox)
bb.pack()
bc=Button(root,text="ShowError!",command=showerrorbox)
bc.pack()
bd=Button(root,text="askquestion!",command=showquestionbox)
bd.pack()
be=Button(root,text="askokcancel!",command=askokcancelbox)
be.pack()
bf=Button(root,text="askyesno!",command=askyesnobox)
bf.pack()
bg=Button(root,text="askretrycancel!",command=askretrycancelbox)
bg.pack()
root.mainloop() |
enums = []
onums = []
while True:
num = int(input("Enter a number [0 to stop] :"))
if num == 0:
break
if num % 2 == 0:
enums.append(num)
else:
onums.append(num)
for n in sorted(enums) + sorted(onums):
print(n)
|
PI = 22/7
if __name__ == '__main__':
print("Running num_funs module")
def is_even(n):
return n % 2 == 0
def is_prime(n):
for i in range(2, n // 2 + 1):
if n % i == 0:
return False
return True
|
def validador_recursivo(m, n):
if(m == 0):
return False
if(m%10 == n):
return True
else:
return validador_recursivo(int(m/10),n);
if __name__ == "__main__":
numero = int(input("ingrese un numero : "))
digito = int(input("ingrese el digito a verificar : "))
if (validador_recursivo(numero, digito)):
print("el digito " + str(digito) + " se encuentra en " + str(numero))
else:
print("el digito " + str(digito) + " no se encuentra en " + str(numero)) |
from math import *
opuesto = int(input("ingrese el valor del cateto opuesto "))
adyacente = int(input("ingrese el valor del cateto adyacente "))
hipotenusa = sqrt(opuesto**2 + adyacente**2)
print("hipotenusa = " + str(hipotenusa))
|
r = 's'
x = 0
while (r != 'N'):
x += 1
r = input(" desea continuar (S/N) ")
print("la pregunta se hizo " + str(x) + " veces ")
|
mayor = 0
menor = 0
contador = 0
acumulador = 0
while True:
numero = int(input("ingrese un numero (cero para terminar): "))
if numero == 0:
break
else:
if numero > mayor or mayor == 0:
mayor = numero
if numero < menor or menor == 0:
menor = numero
contador = contador + 1
acumulador = acumulador + numero
print("mayor = %i" %(mayor))
print("menor = %i" %(menor))
print("promedio = %i" %(acumulador/contador))
|
import sys
a = int(input("Ingrese el primer nmero: "))
b = int(input("Ingrese el segundo nmero: "))
if a < b :
menor = a
mayor = b
else :
menor = b
mayor = a
for i in range(menor + 1, mayor) :
if i % 2 == 0:
sys.stdout.write(str(i) + " ") |
a = int(input("Ingrese el primer numero: "))
b = int(input("Ingrese el segundo numero: "))
if a < b :
menor = a
mayor = b
else :
menor = b
mayor = a
for i in range(menor + 1, mayor) :
print(str(i),end=' ')
|
numero = int(input("ingrese el numero a evaluar: "))
if numero == 1 or numero == 3 or numero == 5 or numero == 7 or numero == 8 or numero == 10 or numero == 12:
print("31 dias")
elif numero == 2:
print("28 o 29 dias")
elif numero == 4 or numero == 6 or numero == 9 or numero == 11:
print("30 dias")
else:
print("numero no valido")
|
bandera = True
agno = int(input("ingrese el agno: "))
mes = int(input("ingrese mes: "))
dia = int(input("ingrese el dia: "))
if mes < 1 or mes > 12:
bandera = False
elif mes == 1 or mes == 3 or mes == 5 or mes == 7 or mes == 8 or mes == 10 or mes == 12:
if dia > 31:
bandera = False
elif mes == 2:
if agno % 4 == 0 and (agno % 100 != 0 or agno % 400 == 0):
if dia > 29:
bandera = False
else:
if dia > 28:
bandera = False
elif mes == 4 or mes == 6 or mes == 9 or mes == 11:
if dia > 30:
bandera = False
if bandera:
print("%i-%i-%i es valida" %(agno,mes,dia))
else:
print("%i-%i-%i no es valida" %(agno,mes,dia))
|
""" Advent of Code 2017 Day 21 Fractal Art """
# You find a program trying to generate some art. It uses a strange process
# that involves repeatedly enhancing the detail of an image through a set of
# rules.
#
# The image consists of a two-dimensional square grid of pixels that are
# either on (#) or off (.). The program always begins with this pattern:
#
# .#.
# ..#
# ###
# Because the pattern is both 3 pixels wide and 3 pixels tall, it is said to
# have a size of 3.
#
# Then, the program repeats the following process:
#
# If the size is evenly divisible by 2, break the pixels up into 2x2
# squares, and convert each 2x2 square into a 3x3 square by following the
# corresponding enhancement rule.
# Otherwise, the size is evenly divisible by 3; break the pixels up into 3x3
# squares, and convert each 3x3 square into a 4x4 square by following the
# corresponding enhancement rule.
# Because each square of pixels is replaced by a larger one, the image gains
# pixels and so its size increases.
#
# The artist's book of enhancement rules is nearby (your puzzle input);
# however, it seems to be missing rules. The artist explains that sometimes,
# one must rotate or flip the input pattern to find a match. (Never rotate
# or flip the output pattern, though.) Each pattern is written concisely:
# rows are listed as single units, ordered top-down, and separated by
# slashes. For example, the following rules correspond to the adjacent
# patterns:
#
# ../.# = ..
# .#
#
# .#.
# .#./..#/### = ..#
# ###
#
# #..#
# #..#/..../#..#/.##. = ....
# #..#
# .##.
# When searching for a rule to use, rotate and flip the pattern as
# necessary. For example, all of the following patterns match the same rule:
#
# .#. .#. #.. ###
# ..# #.. #.# ..#
# ### ### ##. .#.
# Suppose the book contained the following two rules:
#
# ../.# => ##./#../...
# .#./..#/### => #..#/..../..../#..#
# As before, the program begins with this pattern:
#
# .#.
# ..#
# ###
# The size of the grid (3) is not divisible by 2, but it is divisible by 3.
# It divides evenly into a single square; the square matches the second
# rule, which produces:
#
# #..#
# ....
# ....
# #..#
# The size of this enhanced grid (4) is evenly divisible by 2, so that rule
# is used. It divides evenly into four squares:
#
# #.|.#
# ..|..
# --+--
# ..|..
# #.|.#
# Each of these squares matches the same rule (../.# => ##./#../...), three
# of which require some flipping and rotation to line up with the rule. The
# output for the rule is the same in all four cases:
#
# ##.|##.
# #..|#..
# ...|...
# ---+---
# ##.|##.
# #..|#..
# ...|...
# Finally, the squares are joined into a new grid:
#
# ##.##.
# #..#..
# ......
# ##.##.
# #..#..
# ......
# Thus, after 2 iterations, the grid contains 12 pixels that are on.
#
# How many pixels stay on after 5 iterations?
# --- Part Two ---
# How many pixels stay on after 18 iterations?
import re
START = '.#./..#/###'
def build_rules(filename):
with open(filename, "r") as inputfile:
rules = {2:{}, 3:{}}
for line in inputfile:
before, after, size = build_rule(line.rstrip('\n'))
rules[size][before] = after
return rules
def build_rule(string):
raw_rule = re.split(r' => ', string)
size = raw_rule[0].count('/') + 1
return raw_rule[0], raw_rule[1], size
def enhance(image, rules):
size = image.count('/') + 1
num_row_sqrs = None
if size % 2 == 0:
square_size = 2
num_row_sqrs = (size / 2)
elif size % 3 == 0:
square_size = 3
num_row_sqrs = (size / 3)
squares = extract_squares(size, square_size, num_row_sqrs, image)
squares = evaluate_rules(rules, squares, square_size)
square_size += 1
size += 1
return combine_squares(squares, num_row_sqrs, square_size)
def rotate_square(square, size):
"Rotate Square 90 degrees right"
if size == 2:
rotated = square[3]
rotated += square[0]
rotated += square[2]
rotated += square[4]
rotated += square[1]
else:
rotated = square[8]
rotated += square[4]
rotated += square[0]
rotated += square[3]
rotated += square[9]
rotated += square[5]
rotated += square[1]
rotated += square[7]
rotated += square[10]
rotated += square[6]
rotated += square[2]
return rotated
def flip_square(square, size):
if size == 2:
flipped = square[1]
flipped = square[0]
flipped = square[2]
flipped = square[4]
flipped = square[3]
else:
flipped = square[2]
flipped += square[1]
flipped += square[0]
flipped += square[3]
flipped += square[6]
flipped += square[5]
flipped += square[4]
flipped += square[7]
flipped += square[10]
flipped += square[9]
flipped += square[8]
return flipped
def extract_squares(size, sq_size, num_sq_row, image):
rows = re.split('/', image)
sq_row = 0
sq_col = 0
squares = []
for row_count, row in enumerate(rows):
for col_count, char in enumerate(row):
row_mod = row_count % sq_size
row_div = row_count / sq_size
col_mod = col_count % sq_size
col_div = col_count / sq_size
curr_square = row_div*num_sq_row + col_div
if row_mod == 0 and col_mod == 0:
squares.append(char)
else:
squares[curr_square] += char
if col_mod == sq_size - 1:
squares[curr_square] += '/'
return map(lambda x: x.rstrip('/'), squares)
def evaluate_rules(rules, squares, square_size):
new_squares = []
for square in squares:
found = False
if rules[square_size].has_key(square):
new_squares.append(rules[square_size][square])
continue
#rotate
for ___ in xrange(3):
square = rotate_square(square, square_size)
if rules[square_size].has_key(square):
new_squares.append(rules[square_size][square])
found = True
break
if found is True:
continue
#flip
square = flip_square(square, square_size)
if rules[square_size].has_key(square):
new_squares.append(rules[square_size][square])
continue
#rotate flipped
for ___ in xrange(3):
square = rotate_square(square, square_size)
if rules[square_size].has_key(square):
new_squares.append(rules[square_size][square])
break
return new_squares
def combine_squares(squares, squares_per_row, square_size):
combined = ''
for offset in xrange(len(squares) / squares_per_row):
rows = []
for x in xrange(squares_per_row):
strings = re.split('/', squares[x + offset * squares_per_row])
if x == 0:
for string in strings:
rows.append(string)
else:
for count, string in enumerate(strings):
rows[count] += string
for row in rows:
combined += row
combined += '/'
return combined.rstrip('/')
def solve(filename, iterations):
rules = build_rules(filename)
image = START
for ___ in xrange(iterations):
image = enhance(image, rules)
print image.count('#')
if __name__ == "__main__":
print 'Part 1'
solve("./2017/day21.txt", 5)
print 'Part 2'
solve("./2017/day21.txt", 18)
|
"""Advent of Code 2017 Day 3 Spiral Memory"""
# You come across an experimental new kind of memory stored on an infinite
# two-dimensional grid.
#
# Each square on the grid is allocated in a spiral pattern starting at a
# location marked 1 and then counting up while spiraling outward. For
# example, the first few squares are allocated like this:
#
# 17 16 15 14 13
# 18 5 4 3 12
# 19 6 1 2 11
# 20 7 8 9 10
# 21 22 23---> ...
# While this is very space-efficient (no squares are skipped), requested
# data must be carried back to square 1 (the location of the only access
# port for this memory system) by programs that can only move up, down,
# left, or right. They always take the shortest path: the Manhattan Distance
# between the location of the data and square 1.
#
# For example:
#
# - Data from square 1 is carried 0 steps, since it's at the access port.
# - Data from square 12 is carried 3 steps, such as: down, left, left.
# - Data from square 23 is carried only 2 steps: up twice.
# - Data from square 1024 must be carried 31 steps.
import math
def distance(square):
""" Distance from center """
if square == 1:
return 0
sqrt = math.sqrt(float(square))
if sqrt.is_integer() and sqrt % 2 == 1:
closest_sq = int(sqrt)
else:
if int(sqrt) % 2 == 0:
closest_sq = int(sqrt) + 1
else:
closest_sq = int(sqrt) + 2
distance = closest_sq/2
square_size = int(math.pow(closest_sq, 2) - math.pow(closest_sq - 2, 2))
perimeter_loc = int(square) - int(math.pow(closest_sq - 2, 2))
return distance + (perimeter_loc % distance)
# --- Part Two ---
#
# As a stress test on the system, the programs here clear the grid and then
# store the value 1 in square 1. Then, in the same allocation order as shown
# above, they store the sum of the values in all adjacent squares, including
# diagonals.
#
# So, the first few squares' values are chosen as follows:
#
# Square 1 starts with the value 1.
# Square 2 has only one adjacent filled square (with value 1), so it also
# stores 1.
# Square 3 has both of the above squares as neighbors and stores the sum of
# their values, 2.
# Square 4 has all three of the aforementioned squares as neighbors and
# stores the sum of their values, 4.
# Square 5 only has the first and fourth squares as neighbors, so it gets
# the value 5.
# Once a square is written, its value does not change. Therefore, the first
# few squares would receive the following values:
#
# 147 142 133 122 59
# 304 5 4 2 57
# 330 10 1 1 54
# 351 11 23 25 26
# 362 747 806---> ...
# What is the first value written that is larger than your puzzle input?
def next_move(grid, last):
left = (last[0] - 1, last[1])
right = (last[0] + 1, last[1])
up = (last[0], last[1] + 1)
down = (last[0], last[1] - 1)
neighbors = [left, right, up, down]
exists = tuple(map(lambda x: True if grid.has_key(x) else False, neighbors))
if exists == (False, False, False, True) or exists == (False, True, False, True):
new_point = left
elif exists == (True, False, False, False) or exists == (True, False, False, True):
new_point = up
elif exists == (False, True, False, False) or exists == (False, True, True, False):
new_point = down
else:
new_point = right
return new_point
def adj_vals(grid, point):
points = []
points.append((point[0] - 1, point[1]))
points.append((point[0] + 1, point[1]))
points.append((point[0], point[1] + 1))
points.append((point[0], point[1] - 1))
points.append((points[0][0], points[2][1]))
points.append((points[0][0], points[3][1]))
points.append((points[1][0], points[2][1]))
points.append((points[1][0], points[3][1]))
return reduce(lambda x,y: x + y, map(lambda x: grid[x] if grid.has_key(x) else 0, points))
def build_grid(check_val):
if check_val == 0:
return 1
grid = {(0,0):1, (1,0):1}
last = (1,0)
while True:
new_point = next_move(grid, last)
new_val = adj_vals(grid, new_point)
if new_val > check_val:
return new_val
grid[new_point] = new_val
last = new_point
if __name__ == "__main__":
# Part 1
print distance(347991)
# Part 2
print build_grid(347991) |
""" Advent of Code 2017 Day 24 Electromagnetic Moat """
# The CPU itself is a large, black building surrounded by a bottomless pit.
# Enormous metal tubes extend outward from the side of the building at
# regular intervals and descend down into the void. There's no way to cross,
# but you need to get inside.
#
# No way, of course, other than building a bridge out of the magnetic
# components strewn about nearby.
#
# Each component has two ports, one on each end. The ports come in all
# different types, and only matching types can be connected. You take an
# inventory of the components by their port types (your puzzle input). Each
# port is identified by the number of pins it uses; more pins mean a
# stronger connection for your bridge. A 3/7 component, for example, has a
# type-3 port on one side, and a type-7 port on the other.
#
# Your side of the pit is metallic; a perfect surface to connect a magnetic,
# zero-pin port. Because of this, the first port you use must be of type 0.
# It doesn't matter what type of port you end with; your goal is just to
# make the bridge as strong as possible.
#
# The strength of a bridge is the sum of the port types in each component.
# For example, if your bridge is made of components 0/3, 3/7, and 7/4, your
# bridge has a strength of 0+3 + 3+7 + 7+4 = 24.
#
# For example, suppose you had the following components:
#
# 0/2
# 2/2
# 2/3
# 3/4
# 3/5
# 0/1
# 10/1
# 9/10
# With them, you could make the following valid bridges:
#
# 0/1
# 0/1--10/1
# 0/1--10/1--9/10
# 0/2
# 0/2--2/3
# 0/2--2/3--3/4
# 0/2--2/3--3/5
# 0/2--2/2
# 0/2--2/2--2/3
# 0/2--2/2--2/3--3/4
# 0/2--2/2--2/3--3/5
# (Note how, as shown by 10/1, order of ports within a component doesn't
# matter. However, you may only use each port on a component once.)
#
# Of these bridges, the strongest one is 0/1--10/1--9/10; it has a strength
# of 0+1 + 1+10 + 10+9 = 31.
#
# What is the strength of the strongest bridge you can make with the
# components you have available?
# --- Part Two ---
# The bridge you've built isn't long enough; you can't jump the rest of the
# way.
#
# In the example above, there are two longest bridges:
#
# 0/2--2/2--2/3--3/4
# 0/2--2/2--2/3--3/5
# Of them, the one which uses the 3/5 component is stronger; its strength is
# 0+2 + 2+2 + 2+3 + 3+5 = 19.
#
# What is the strength of the longest bridge you can make? If you can make
# multiple bridges of the longest length, pick the strongest one.
import re
import copy
class Component(object):
def __init__(self, component_id, x_pins, y_pins):
self.x_pins = x_pins
self.y_pins = y_pins
self.in_pins = None
self.out_pins = None
def reset(self):
""" Reset component orientation """
self.in_pins = None
self.out_pins = None
def set_input_pins(self, in_pins):
""" Set input component """
#orient pins x and y accordingly
if in_pins == self.x_pins:
self.in_pins = self.x_pins
self.out_pins = self.y_pins
else:
self.in_pins = self.y_pins
self.out_pins = self.x_pins
def generate_components(filename):
components = {}
with open(filename, "r") as inputfile:
for count, line in enumerate(inputfile):
ports = re.split('/', line.rstrip('\n'))
components[count] = Component(count, int(ports[0]), int(ports[1]))
return components
def find_strongest_bridge(bridges, components):
winning_str = 0
for bridge in bridges:
strength = calculate_strength(bridge, components)
if strength > winning_str:
winning_str = strength
return winning_str
def build_bridges(bridge, comp_dict, complete_bridges):
if len(bridge) == 0:
starters = filter(lambda x: comp_dict[x].x_pins == 0 or comp_dict[x].y_pins == 0, comp_dict.keys())
for comp_key in starters:
bridge = []
comp_dict[comp_key].set_input_pins(0)
bridge.append(comp_key)
build_bridges(bridge, comp_dict, complete_bridges)
bridge.pop()
comp_dict[comp_key].reset()
else:
possible = find_all_possible(bridge, comp_dict)
if possible:
for comp_key in possible:
tail_out_pins = get_tail(bridge, comp_dict)
curr_comp = comp_dict[comp_key]
curr_comp.set_input_pins(tail_out_pins)
bridge.append(comp_key)
build_bridges(bridge, comp_dict, complete_bridges)
bridge.pop()
comp_dict[comp_key].reset()
else:
complete_bridges.append(copy.copy(bridge))
def get_tail(bridge, comp_dict):
last_key = bridge[len(bridge) - 1]
return comp_dict[last_key].out_pins
def calculate_strength(bridge, comp_dict):
component_strengths = map(lambda x: comp_dict[x].x_pins + comp_dict[x].y_pins, bridge)
return reduce(lambda x, y: x + y, component_strengths)
def find_all_possible(bridge, comp_dict):
out_pins = get_tail(bridge, comp_dict)
key_set = set(comp_dict.keys())
bridge_set = set(bridge)
available_components = key_set.difference(bridge_set)
return filter(lambda x: comp_dict[x].x_pins == out_pins or comp_dict[x].y_pins == out_pins, list(available_components))
def find_longest(bridges):
long_size = 0
longest = []
for bridge in bridges:
size = len(bridge)
if size > long_size:
longest = [bridge]
long_size = size
elif size == long_size:
longest.append(bridge)
return longest
if __name__ == "__main__":
input_comps = generate_components("./2017/day24.txt")
my_bridges = []
build_bridges([], input_comps, my_bridges)
print(find_strongest_bridge(my_bridges, input_comps))
longs = find_longest(my_bridges)
print(find_strongest_bridge(longs, input_comps)) |
import random
def gen_rand_list(list_size):
list_build = []
for i in range(list_size):
list_build.append(random.randint(0,100))
return list_build
def data_output():
output = open("output/list.txt",'w')
print("This will generate a list of random integers from 0 to 100 of a specified length.")
print("Please specify the length of the list:")
length = input()
output.write(str(gen_rand_list(int(length))))
output.close()
print("List saved to list.txt in the output subfolder.")
print("Press Enter to exit.")
input() |
def show_menu():
print('~~~~ Welcome to your terminal checkbook! ~~~')
print('\n'*2)
print('What would you like to do?\n')
print('1) View current balance')
print('2) Record a debit withdraw')
print('3) Record a credit deposit')
print('4) exit')
#brings up menu options
user_input = '1'
while user_input != '4':
show_menu()
user_action = input('Your choice? ')
if user_action == '4':
print('Thanks, have a great day!')
user_input = '4'
elif user_action not in ['1','2','3']:
input('Invalid choice, try again. ')
elif user_action in ['1','2','3']:
# showing current balance
if user_action == '1':
with open('balance_storage_test.txt','r') as bs:
transactions = bs.readlines()
amt = 0
for line in transactions:
line = float(line)
amt += line
print('Your current balance is ${0:.2f}.'.format(amt))
exit = True
# recording a withdraw
elif user_action == '2':
user_input = input('How much would you like to withdraw? ')
with open('balance_storage_test.txt','a') as bs:
bs.write('\n')
withdraw = '-' + user_input
bs.write(withdraw)
exit = True
# recording a deposit
elif user_action == '3':
user_input = input('How much would you like to deposit? ')
with open('balance_storage_test.txt','a') as bs:
bs.write('\n')
bs.write(user_input)
exit = True
elif user_action == '4':
print('Thanks, have a great day!')
exit = True |
# Task - 1
def get_user_info(username: str, age: int, current_city: str) -> str:
"""Get user info"""
return f'{username}, {age} год(а), проживает в городе {current_city}'
# Task - 2
def get_max_number(*nums) -> int:
"""Get max number"""
return max(nums)
# Task - 3-4
def attack(attacker: dict, defender: dict):
"""Attack enemy and update health defender"""
damage_attacker: int = attacker.get('damage')
defender_health: int = defender.get('health')
armor_defender: float = defender.get('armor')
updated_health_defender: dict = {'health': defender_health - get_damage_done(damage_attacker, armor_defender)}
defender.update(updated_health_defender)
def get_damage_done(damage: int, armor: float):
"""Get sequent damage"""
return damage / armor
# username, age, current_city = input('Введите имя, возвраст, город через пробел: ').strip().split()
# print(get_user_info(username, age, current_city))
# print(get_max_number(1, 5, 3))
player: dict = {
"name": "Denis",
"health": 100,
"damage": 50,
"armor": 1.2
}
enemy: dict = {
"name": "Jora",
"health": 100,
"damage": 50,
"armor": 1.2
}
attack(enemy, player)
print(player)
|
userListCount = int(input("Enter number of elements: "))
userList = list(map(int,input("\nEnter the numbers: ").strip().split()))
userListLen = len(userList)
getSum = sum(userList)
mean = getSum / userListLen
print("Mean: " + str(mean))
userList.sort()
if userListLen % 2 == 0:
median1 = userList[userListLen//2]
median2 = userList[userListLen//2]
median = (median1 + median2) / 2
else:
median = userList[userListLen//2]
print("Median: " + str(median))
from collections import Counter
data = Counter(userList)
getMode = dict(data)
mode = [k for k, v in getMode.items() if v == max(list(data.values()))]
if len(getMode) == userListLen:
getMode = "None"
else:
getMode = "Mode: " + ", ".join(map(str, mode))
print(getMode)
range1 = min(userList)
range2 = max(userList)
range = (range2 - range1)
print("Range: " + str(range))
|
########################
# Author: ~wy
# Date: 25/12/2017
# Description: Lets you play the game via CLI
########################
from Game import Game
from GameAI import GameAI
from Answer import Answer
import random
import MastermindConstants
hidden_answer_prompt = "Enter Your Hidden Answer as 4 Letter String. " \
"e.g. YYYY for Yellow, Yellow, Yellow, Yellow. Colours " \
"are Y=Yellow,R=Red,G=Green,B=Blue,O=Orange,P=Purple\n"
guess_prompt = "Enter Your Guess. Colours" \
" are Y=Yellow,R=Red,G=Green,B=Blue,O=Orange,P=Purple\n"
def main():
print("Welcome to Mini Master Mind (PyMasterMind)")
mode_select = input("Please pick a mode. 1 = Computer creates a hidden answer. "
"2 = You create a hidden answer for your friend. "
"3 = You create a hidden answer for the computer to guess\n")
input_var = ""
if mode_select == "1":
arr = MastermindConstants.valid_keys
for i in range(0, 4):
input_var += random.choice(arr)
elif mode_select == "2":
input_var = input(hidden_answer_prompt)
assert (len(input_var) == 4), "Please enter 4 Letters"
elif mode_select == "3":
input_var = input(hidden_answer_prompt)
assert (len(input_var) == 4), "Please enter 4 Letters"
game_ai = GameAI()
g = Game()
g.pick_answer(input_var)
while g.get_level() < 7:
choices = []
print("You are starting level {}".format(g.get_level()))
if mode_select == "1" or mode_select == "2":
input_var = input(guess_prompt)
if len(input_var) != 4:
input_var = input(guess_prompt)
choices = list(input_var)
g.make_guess(choices)
if mode_select == "3":
if g.get_level() == 1:
recommended_guess = MastermindConstants.starting_recommendation
else:
recommended_guess = game_ai.smart_eval(debug=False)
choices = recommended_guess
g.make_guess(recommended_guess)
evaluation = g.get_evaluation()
print(g)
game_ai.cull_possibilities(choices, evaluation.get_evaluation())
if g.get_status() == "Won":
print("Well done, you have won.")
break
if g.get_status() != "Won":
print("The answer was {}".format(g.get_answer()))
print("Sorry, you failed this time.")
def play_game_ai(answer, game_ai, g):
g.pick_answer(answer)
while g.get_level() < 7:
if g.get_level() == 1:
recommended_guess = MastermindConstants.starting_recommendation
else:
recommended_guess = game_ai.smart_eval(debug=False)
g.make_guess(recommended_guess)
game_ai.cull_possibilities(recommended_guess, g.get_evaluation())
if g.get_status() == "Won":
break
return g.get_status()
def iter_game_ai():
""""
Plays every single game (i.e. for each hidden answer possible)
"""
i = 0
wins = 0
possibles = Answer.possible_answers()
game_ai = GameAI()
g = Game()
for p in possibles:
i += 1
game_ai.reset()
g.reset()
status = play_game_ai(p, game_ai, g)
if status == "Won":
wins += 1
print("{} / {} wins".format(wins, i))
if __name__ == "__main__":
iter_game_ai()
|
import sys
import random
vowels = ['a', 'e', 'i', 'o', 'u']
consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z']
arglen = len(sys.argv)
start = 2
end = 3
limit = 10
if arglen>1: limit = int(sys.argv[1])
if arglen>2: end = int(sys.argv[2])+1
if arglen>3: start = int(sys.argv[3])
else: start = end-1
if arglen>4:
user = str(sys.argv[4]).lower()
if user[0]=="-":
'''Avoid letters'''
filter_func = lambda x: x not in user
else:
'''Use letters'''
filter_func = lambda x: x in user
vowels = filter(filter_func, vowels)
if len(vowels)==0: vowels = ['']
consonants = filter(filter_func, consonants)
if len(consonants)==0: consonants = ['']
print ""
print "Limit:", limit
print "Max-Length:", end-1
print "Min-Length:", start
print "Vowels used:", "".join(vowels)
print "Consonants used:", "".join(consonants)
def random_select(vow, con, count):
'''Generate a pronounceable name from the given vowels and consonants'''
ret = []
i = 0
while i < count:
ran = []
if i > 0:
'''Prevent two vowels or consonants from being together'''
if ret[-1][-1] in vowels:
ran = [random.choice(con), random.choice(vow)]
else:
ran = [random.choice(vow), random.choice(con)]
else:
ran = [random.choice(vow), random.choice(con)]
random.shuffle(ran)
ran = "".join(ran)
i+= len(ran)
ret.append(ran)
return "".join(ret)[:count]
def random_select_n(vow, con, count, limit):
'''Iterate over random_select till limit is reached'''
ret = []
for i in xrange(limit):
tmp = (random_select(vow, con, count))
l=0
while tmp in ret:
tmp = (random_select(vow, con, count))
l+=1
if l>500: break
ret.append(tmp)
return ret
print ""
for i in xrange(start, end):
combos = random_select_n(vowels, consonants, i, limit)
j = 0
for item in combos:
print "".join(item)
j += 1
if j > limit: break
print ""
|
class Singleton(type):
def __init__(cls, name, bases, dct):
cls.__instance = None
type.__init__(cls, name, bases, dct)
def __call__(cls, *args, **kw):
if cls.__instance is None:
cls.__instance = type.__call__(cls, *args,**kw)
return cls.__instance
if __name__ == "__main__":
class A:
__metaclass__ = Singleton
def __init__(self):
self.i=1
def add(self):
self.i+=1
a = A()
b = A()
print a.i
print b.i
b.add()
print a.i
print b.i
assert a==b
print a == b # True, funciona! :-)
|
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import UserList
import traceback
class Sortable_list(UserList.UserList):
add = UserList.UserList.append
def top(self, x):
if -len(self) <= x < len(self):
self.append(self.pop(x))
else:
traceback.extract_stack()
raise IndexError("list index out of range")
def bottom(self, x):
if -len(self) <= x < len(self):
self.insert(0, self.pop(x))
else:
traceback.extract_stack()
raise IndexError("list index out of range")
def up(self, x):
if -len(self) <= x < len(self):
self.insert(x+1, self.pop(x))
else:
traceback.extract_stack()
raise IndexError("list index out of range")
def down(self, x):
if -len(self) <= x < len(self):
self.insert(x-1, self.pop(x))
else:
traceback.extract_stack()
raise IndexError("list index out of range")
#raw_input() |
def bigger(x,y):
return y if y>x else x
def lower(x,y):
return x if x<y else y
|
#Compute Parity of a word
#The parity of a binary word is 1 if the number of 1s in the word is odd;
#it is 0 if the number of 1s in even
#Need to count the number of 1s in a Binary word
#Better Solution (Time Complexity: O(k) where k = #1's in the word)
def better_parity(x):
'''
i/p: x, an int
o/p: 1, if number of 1s in x is odd
0, otherwise
'''
#Initializing flag to be 0
flag = 0
#while x > 0 (loop repeats only {#1s in word} times)
while x:
#set flag to be 1 if flag = 0 and to be 0 if flag = 1
flag = flag ^ 1
#bit-fiddling trick
x = x & x-1 #clears the lowest bit 1 (i.e., changes it to 0)
return flag
print(better_parity(9))
|
the_count = [1,2,3,4,5]
fruits = ['apples','oranges','pears','apricots']
change = [1,'pennies',2,'dimes',3,'dimes']
for number in the_count:
print "This is count:%d" %number
for fruit in fruits:
print "A fruit of type: %s" %fruit
for i in change:
print "i got %r" %i
# elements = []
# for i in range(0,6):
# print "adding %d to the list." % i
# elements.append(i)
elements = range(0,6)
# the below functions work in place
# elements.reverse()
# elements.sort()
# elements.remove(2)
# elements.extend(iterable)
# elements *= 2
# multipying list by int implies list values repeating themselves
# the below return values
# element.count(0)
# elements.index(value) returns first occurance of value
# elements[0:-1]
# elements.pop()
# elements.append(value) insert at the end
# elements.insert(value,index) inserts x before index
# elements.remove(value) removes first occurance of value
for i in elements:
print "element was: %d" %i |
# creating mapiing of state and abbrevation
# the syntax given in the textbook is giving syntax errors
# changes the square brackets to curly solved it
states = {
'Oregan' : 'OR',
'Florida' : 'FL',
'California' : 'CA',
'New York' : 'NY',
'Michigan' : 'MI'
}
# create basic set of states and some cities in them
cities = {
'CA' : 'San Francisco',
'MI' : 'Detroit',
'FL' : 'Jacksonville',
}
# add some more cities
cities['NY'] = 'New York'
cities['OR'] = 'Portland'
# print out some cities
print '-' *10
print "NY state has:", cities['NY']
print "OR state has:", cities['OR']
# print some states
print "-" *10
print "Michigan's abbrevation is",states['Michigan']
print "Florida's abbrevation is",states['Florida']
# doing it by using states then cities dict
print "-"*10
print "Michigan has: ",cities[states['Michigan']]
print "Florida has: ",cities[states['Florida']]
# print every state abbrevation
print "-"*10
# states.item() gives ??
for state,abbrevation in states.items():
print "%s is abbrevated %s" % (state,abbrevation)
# print every city in state
print '-' *10
for abrev,city in cities.items():
print "%s has %s city." % (abrev,city)
# now do both at the same time
print '-'*10
for state,abrev in states.items():
print "%s has %s abbrevation and has city %s" %(
state,abrev,cities[abrev])
# safely get an abbreavation by state that may not be there
print '-' * 10
state = states.get('Texas')
if not state:
print "Sorry,no Texas"
# get a city with default value
city = cities.get('TX',"does not exist")
print city
print "The city for the state 'TX' is %s" % city
|
formatter = "%r %r %r %r" # %r is for raw data but the values of %r are not given.
#note the formatter is string object
# print formatter
print formatter %(1,2,3,4)
#we gave 1,2,3,4 as the 4 %r values to formatter and print.
print formatter %("one","two","three","four")
# gave String one two three four to formatter.
print formatter %(True , False , False , True)
#gave boolean values true false false true
print formatter %(formatter, formatter, formatter, formatter)
# no idea what this does.. gave output as '%r %r %r %r' * 4
print formatter % (
"I had this thing." ,
"That you could type upright." ,
"But it didn't sing." ,
"So I said goodnight."
)# gave the strings in each line as input to %r of formatter |
# ex14.py
from sys import argv
script,user_name= argv #unpacking the arguments to script and user_name
prompt = '> ' #changing the value of prompt here would
# change the prompt for all raw_input
# this is taking the args
print "Hi %s i am the %s script" %(user_name,script)
print "I would like to ask you a few questions"
print "Do you like me %s?"%user_name
likes = raw_input(prompt)
print "Where do you live %s?" % user_name
lives = raw_input(prompt)
print "What kind of a computer do you have?"
computer = raw_input(prompt)
print """
alright you said about %r about liking me.
you live in %r . not sure where this is.
you said you have %r kind of computer. Nice.
""" % (likes, lives, computer) |
import random
def game():
words=['father','mother','sister','cousin','relative','grandmother','grandfather','uncle','aunt','tire',
'love','get','redo','heady','stomach','declare','crayon','hellish','thumb','dashing','pricey','educate',
'water','closed','induce','health','restrain','point','frog','polite','tiny','six','periodic','grandmother',
'vessel','tremendous','record','wry','cause','thick','squalid','delicate','nail','rewind','whip','spooky',
'owe','converge','lunchroom','rambunctious','shit','manager','canvas','mind','become','slim','implore',
'camp','growth','sea','tire','undesirable','river','design','eat','lewd','skate','unequaled','ugly','car','fit',
'abundant','willing','quickest','drain','bright','reigned','practise','adamant','bumpy','cloistered','shock',
'adhesive','confess','cannon','standing','celebrate','ocean','funny','dip','cultured']
word=random.choice(words)
l=len(word)
guess=[]
guess_word=[]
check=[None]*l
i=0
while i<l :
check[i]= " * "
i=i+1
print('The word is ',*check)
count=l
flag=0
print('You have ',l,' attempts left')
for i in range(2*l):
ch=input('Enter a char : ')
for k in range(l) :
if word[k]==ch.lower():
print('Correct..')
for j in range(l):
check[k]=ch.lower()
print(*check)
print('\nYou have ',count,' attempts left')
break
else :
count=count-1
guess.append(ch.lower())
print('Previous guess :',ch.lower())
print('Try again...')
print(*check)
print('\nYou have ',count,' attempts left.')
if count==0 :
print('Your attempts are over :(')
print('The correct word was ',word)
break
if word==check :
print('Congratulations!! You got it right ;)\n')
play_again()
def play_again():
print("If you want to play again, press Y else press N:\n")
inp=input()
if(inp=='Y'):
main()
else:
print("Thanks for playing!!!!\n")
def main():
game()
main()
|
import Tkinter as tk
top= tk.Tk();
top.title("Simple calculator")
def click(key):
if key=="=":
str1 = "0123456789."
if entry.get()[0] in str1:
result = eval(entry.get())
entry.insert(tk.END, "=" + str(result))
else:
entry.insert(tk.END,key)
button_list=[
'9','8','7',
'6','5','4',
'3','2','1',
'+','0','-',
"*","/","="
]
entry= tk.Entry(top, width=60)
entry.grid(row=1, columnspan=15)
r=2
c=0
for b in button_list:
rel="ridge"
command= lambda x=b: click(x)
tk.Button(top, text=b, width=20, relief=rel, command=command).grid(row=r, column=c)
c+=1
if c>2 and r>=2:
c=0
r+=1
top.mainloop()
|
def read_input_count():
inp_file = raw_input("Enter the input File Name: ")
print inp_file
with open(inp_file, "r") as inp:
alpa_dict = {chr(k):0 for k in range(65,123)}
for line in inp:
for sub_line in line:
if sub_line in alpa_dict:
alpa_dict[sub_line] = int(alpa_dict[sub_line]) + 1
for k,v in alpa_dict.iteritems():
if v > 0:
print "The number of times "+k+" appeared : "+str(v)
read_input_count() |
import re
# input is a list of tokens (token is a number or operator)
tokens = raw_input()
# remove whitespace
tokens = re.sub('\s+', '', tokens)
# split by addition/subtraction operators
tokens = re.split('(-|\+)', tokens)
# takes in a string of numbers, *s, and /s. returns the result
def solve_term(tokens):
tokens = re.split('(/|\*)', tokens)
ret = float(tokens[0])
for op, num in zip(tokens[1::2], tokens[2::2]):
num = float(num)
if op == '*':
ret *= num
else:
ret /= num
return ret
# initialize final result to the first term's value
result = solve_term(tokens[0])
# calculate the final result by adding/subtracting terms
for op, num in zip(tokens[1::2], tokens[2::2]):
result += solve_term(num) * (1 if op == '+' else -1)
print result
|
def IndexWords(InputText):
count = 2
for i in range(len(InputText)):
for word in InputText[i].split()[1:]:
CapitalizationCheck = list(word.strip(','))[0].isupper()
# print(CapitalizationCheck)
if CapitalizationCheck == True:
print('%s:%s' % (count, word))
ls.append(1)
else:
ls.append(0)
count += 1
count += 1
# print(CapitalizationCheck)
# print(ls)
if (CapitalizationCheck == False) and (ls == list(0 for i in range(len(ls)))):
print('None')
ls = []
IndexWords(input().replace(','," ").split('.')) |
# Random Selection
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#Importing the Dataset
dataset = pd.read_csv('Ads_CTR_Optimisation.csv')
# Implementing Random Selection
import random
N= 10000
d = 10
ads_selected = []
total_rewards = 0
for n in range(0,N):
ad = random.randrange(d)
ads_selected.append(ad)
reward = dataset.values[n,ad]
total_rewards += reward
# Visualising the Results -Histogram
plt.hist(ads_selected,rwidth=0.25)
plt.title('Histogram of Ads Selections')
plt.xlabel('Ads')
plt.ylabel('Number of times each ad was selected')
plt.show() |
# K means Clusterning
#Importing the Libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#Importing the dataset
dataset = pd.read_csv("Mall_Customers.csv")
X = dataset.iloc[:,[3,4]].values
# Using elbow method to find optimal number of clusters
from sklearn.cluster import KMeans
wcss = []
for i in range (1,11):
kmeans = KMeans(n_clusters=i ,init='k-means++',max_iter=300,n_init=10,random_state=0)
kmeans.fit(X)
wcss.append(kmeans.inertia_)
plt.plot(range(1,11),wcss)
plt.title("The Elbow Method")
plt.xlabel("Number of Clusters")
plt.ylabel("WCSS")
plt.show()
#applying KMeans to the dataset
kmeans = KMeans(n_clusters=5,init="k-means++",max_iter=30,n_init=10,random_state=0)
y_kmeans = kmeans.fit_predict(X)
#Visualising the clusters
plt.scatter(X[y_kmeans== 0,0],X[y_kmeans == 0,1],s = 100,c = 'red',label= 'Careful')
plt.scatter(X[y_kmeans== 1,0],X[y_kmeans == 1,1],s = 100,c = 'blue',label= 'Standard')
plt.scatter(X[y_kmeans== 2,0],X[y_kmeans == 2,1],s = 100,c = 'pink',label= 'Target')
plt.scatter(X[y_kmeans== 3,0],X[y_kmeans == 3,1],s = 100,c = 'magenta',label= 'Careless')
plt.scatter(X[y_kmeans== 4,0],X[y_kmeans == 4,1],s = 100,c = 'yellow',label= 'Sensible')
plt.scatter(kmeans.cluster_centers_[:,0],kmeans.cluster_centers_[:,1],s = 300,c = 'black',label= 'Centroids')
plt.title("Cluster of Clients")
plt.xlabel("Annual Income (K$)")
plt.ylabel("Spending Score(1-100)")
plt.legend()
plt.show() |
"""
As discussed in the last approach, once we've fixed a nums[i],nums[j]nums[i],nums[j] pair, we just need to determine a nums[k]nums[k] which falls in the range (nums[i],nums[j])(nums[i],nums[j]). Further, to maximize the likelihood of any arbitrary nums[k]nums[k] falling in this range, we need to try to keep this range as much as possible. But, in the last approach, we tried to work only on nums[i]nums[i]. But, it'll be a better choice, if we can somehow work out on nums[j]nums[j] as well.
To do so, we can look at the given numsnums array in the form of a graph, as shown below:
From the above graph, which consists of rising and falling slopes, we know, the best qualifiers to act as the nums[i],nums[j]nums[i],nums[j] pair, as discussed above, to maximize the range nums[i], nums[j]nums[i],nums[j], at any instant, while traversing the numsnums array, will be the points at the endpoints of a local rising slope. Thus, once we've found such points, we can traverse over the numsnums array to find a nums[k]nums[k] satisfying the given 132 criteria.
To find these points at the ends of a local rising slope, we can traverse over the given numsnums array. While traversing, we can keep a track of the minimum point found after the last peak(nums[s]nums[s]).
Now, whenever we encounter a falling slope, say, at index ii, we know, that nums[i-1]nums[i−1] was the endpoint of the last rising slope found. Thus, we can scan over the kk indices(k>i), to find a 132 pattern.
But, instead of traversing over numsnums to find a kk satisfying the 132 pattern for every such rising slope, we can store this range (nums[s], nums[i-1])(nums[s],nums[i−1])(acting as (nums[i], nums[j])(nums[i],nums[j])) in, say an intervalsintervals array.
While traversing over the numsnums array to check the rising/falling slopes, whenever we find any rising slope, we can keep adding the endpoint pairs to this intervalsintervals array. At the same time, we can also check if the current element falls in any of the ranges found so far. If so, this element satisfies the 132 criteria for that range.
If no such element is found till the end, we need to return a False value.
"""
def find132pattern(nums):
"""
:param nums: input list
:return: True if there is a 132 pattern False Otherwise
:time : O(n^2)
:space : O(n)
"""
intervals = []
i = 1
s = 0
while i < len(nums):
if nums[i - 1] >= nums[i]:
if s < i - 1:
intervals.append([nums[s], nums[i - 1]])
s = i
for interval in intervals:
if interval[0] < nums[i] < interval[1]:
return True
i += 1
return False
print(find132pattern([3, 1, 4, 2])) |
from tkinter import * # импортировать виджет
widget = Label(None, text='Hello GUI world!') # создать его
widget.pack(expand=YES, fill=BOTH) # разместить
widget.mainloop() # запустить цикл событий |
"всегда выводит 200 - благодаря синхронизации доступа к глобальному ресурсу"
import threading, time
count = 0
def adder(addlock): # совместно используемый объект блокировки
global count
with addlock: # блокировка приобретается/освобождается
count = count + 1 # автоматически
time.sleep(0.5)
with addlock: # в каждый конкретный момент времени
count = count + 1 # только 1 поток может изменить значение переменной
addlock = threading.Lock()
threads = []
for i in range(100):
thread = threading.Thread(target=adder, args=(addlock,))
thread.start()
threads.append(thread)
for thread in threads: thread.join()
print(count) |
"""
отображает изображение с помощью альтернативного объекта из пакета PIL
поддерживает множество форматов изображений; предварительно установите пакет
PIL: поместите его в каталог Lib\site-packages
"""
import os, sys, random
from glob import glob # чтобы получить список файлов по расширению
from tkinter import *
from PIL.ImageTk import PhotoImage # <== использовать альтернативный класс из
# PIL, остальной программный код
# без изменений
imgdir = 'D:/Projects/python/Gifs/'
files = glob(imgdir + '*')
images = [x for x in files]
imgfile = random.choice(images)
if len(sys.argv) > 1:
imgfile = sys.argv[1]
imgpath = os.path.join(imgdir, imgfile)
win = Tk()
win.title(imgfile)
imgobj = PhotoImage(file=imgpath) # теперь поддерживает и JPEG!
imgfile = random.choice(images)
Label(win, image=imgobj).pack()
win.mainloop()
print(imgobj.width(), imgobj.height()) # показать размер в пикселях при выходе |
# проверка состояния флажков, простой способ
from tkinter import *
root = Tk()
states = []
for i in range(10):
var = IntVar()
chk = Checkbutton(root, text=str(i), variable=var)
chk.pack(side=LEFT)
states.append(var)
root.mainloop() # пусть следит библ иотека tkinter
print([var.get() for var in states]) # вывести все состояния при выходе
# (можно также реализовать с помощью
# функции map и lambda-выражение)
|
# 提示输入的三个数以空格隔开,并判断最大的数
string1 = input("请输入三个数字,数字之间用空格隔开:")
client1 = string1.split(" ", string1.count(" "))
print(client1)
if int(client1[0]) > int(client1[1]) and int(client1[0]) > int(client1[2]):
print("您输入的最大数字为:%s" % (client1[0]))
elif int(client1[1]) > int(client1[0]) and int(client1[1]) > int(client1[2]):
print("您输入的最大数字为:%s" % (client1[1]))
else:
print("您输入的最大数字为:%s" % (client1[2]))
# 假如输入的数字超过3个或者个数不随机(可以将字符串列表转化为int数字列表)
client2 = []
for i in client1:
client2.append(int(i))
print(client2)
print(max(client2)) |
# -*- coding:utf-8 -*-
import time
import datetime
localtime = time.localtime(time.time())
print(localtime)
print(time.asctime())
print(time.asctime(time.localtime(time.time())))
print(time.strftime("%Y-%m-%d %H:%M:%S"))
def count():
fs = []
for i in range(1, 4):
def f(j):
def g():
return j*j
return g
r = f(i)
fs.append(r)
return fs
f1 = count()
print(f1)
print(datetime.datetime.now()) |
#!usr/bin/python
# coding=utf-8
'''基于python套接字的半双工通讯实现客户端同服务器的对话(对讲机)'''
import socket
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) #创建socket对象
sock.bind(('',9001)) #创建服务器端口
print('this is server...,I am OK')
sock.listen(60) #设置服务器最大监听数
con,add = sock.accept()
while True:
recvs = con.recv(512).decode() #设置最大接收数量
print('接收到的数据为:%s' %recvs)
if recvs == 'breack':
break
sends = input('请输入要发送的内容"breack"退出:')
con.send(sends.encode())
if sends == 'breack':
break
sock.close() #关闭socket对象
|
#Used for dealing with time
from datetime import datetime, date, time
def now():
#returns the current time as a timestamp
return datetime.timestamp(datetime.now())
def difference(initialTime):
#returns the tifference between the timestamps in minutes in float type
return (datetime.timestamp(datetime.now())-initialTime)/60
#main() is for testing only
def main():
print(now())
if __name__ == "__main__":
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.