blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
eb5f1b59e77387e5915d12a6d608658a7a0cd796 | alexvatti/interview-skills | /test-python-skills/pandas/learn-explore/ex_pandas_05.py | 846 | 3.96875 | 4 | #pandas leaning
#converting data frame to series
#behaviour or methods
#exercise 05: delete a columns of mentioned column names using drop menthod
import sys
sys.path.append('/usr/lib/python3.4')
sys.path.append('/usr/lib/python3.4/plat-x86_64-linux-gnu')
sys.path.append('/usr/lib/python3.4/lib-dynload')
sys.path.append('/usr/local/lib/python3.4/dist-packages')
sys.path.append('/usr/lib/python3/dist-packages')
import pandas as pd
col =['city', 'colors_Reported', 'shape_Reported', 'state', 'time']
movies = pd.read_csv("http://bit.ly/uforeports")
print(type(movies))
print(movies.columns)
movies.columns = col
print(movies.columns)
print(movies.dtypes)
movies.drop("colors_Reported",axis=1,inplace=True)
print(movies.columns)
print(movies.head())
movies.drop(['city','state'],axis=1,inplace=True)
print(movies.columns)
print(movies.head())
|
77aba8b4395e090cf55d4d34bf53b54885c9617b | chenjunyuan1996/Java-Practice | /day67/findNumberIn2DArray.py | 1,270 | 3.640625 | 4 | # 暴力遍历
# class Solution:
# def findNumberIn2DArray(self, matrix: List[List[int]], target: int) -> bool:
# for row in matrix:
# if target in row:
# return True
# return False
# 从左下方开始搜索
class Solution:
def findNumberIn2DArray(self, matrix: List[List[int]], target: int) -> bool:
if not matrix or not matrix[0]: return False
rows, cols = len(matrix), len(matrix[0])
n, m = rows - 1, 0
while n >= 0 and m < cols:
if matrix[n][m] == target:
return True
elif matrix[n][m] > target:
n -= 1
elif matrix[n][m] < target:
m += 1
return False
# 剪枝, 从右上开始搜索
# class Solution:
# def findNumberIn2DArray(self, matrix: List[List[int]], target: int) -> bool:
# if not matrix or not matrix[0]: return False
# rows, cols = len(matrix), len(matrix[0])
# n, m = 0, cols - 1
# while n < rows and m >=0:
# if matrix[n][m] == target:
# return True
# elif matrix[n][m] > target:
# m -= 1
# elif matrix[n][m] < target:
# n += 1
# return False
|
16f325d116645341c3e81cb87f3ccf392603918a | RaffaeleFiorillo/Challanges | /flatten_arguments.py | 1,169 | 4.4375 | 4 | # This function takes all the arguments passed and returns them in a list
# al the elements contained in arrays and sub-arrays passed as arguments are extracted and just the values inside them
# are passed into the list that will be returned
def flatten(*args):
unchecked = True # checks if arguments were changed in the last iteration of the following while loop
while unchecked:
arguments = [] # This is the list were all the values that are not lists go
unchecked = False # variable is set to False so that the loop can finish
for arg in args:
if type(arg) == list: # checks if the current value of the arguments is a list
for a in arg: # if it is a list, it iterates between his elements and puts them into the argument list
arguments.append(a)
unchecked = True # if a list is found, all the unpacked elements must be checked too
else:
arguments.append(arg)
args = arguments[:] # the value of args is updated for the next iteration
return arguments
print(flatten(['hello',2,['text',[4,5]]],[[]],'[list]')) # test case
|
ea409a5a1e3c5e13bba5ea89a27ea460bcc9a039 | UzairJ99/PythonLeetCode | /N-aryTreePostOrderTraversal.py | 642 | 3.75 | 4 | class Node:
def __init__(self, val, children):
self.val = val
self.children = children
class Solution:
def postorder(self, root):
nodes = [root]
#return values
output = []
if root is None:
return None
#DFS
while len(nodes) > 0:
node = nodes.pop()
#place this value into our return list
output.append(node.val)
#add the children
nodes += node.children
#reverse our output list which makes it postorder traversal
output = output[::-1]
return output |
5e6e6aeda0cc96624c037853ecbb55d50f811182 | Yucheng7713/CodingPracticeByYuch | /Medium/529_mineSweeper.py | 1,865 | 3.8125 | 4 | class Solution:
# Check the number of adjacent mines around the given position
def checkAdjacentMines(self, row, col, board):
mine_count = 0
for i, j in (row + 1, col), (row + 1, col + 1), (row + 1, col - 1), (row, col + 1), (row, col - 1), (row - 1, col - 1), (row - 1, col + 1), (row - 1, col):
if i >= 0 and i < len(board) and j >= 0 and j < len(board[0]):
if board[i][j] == 'M':
mine_count += 1
return mine_count
def reveal(self, row, col, board):
# Stop recursion
if row < 0 or row >= len(board) or col < 0 or col >= len(board[0]) or board[row][col] != 'E':
return
# Check if there is any adjacent mine existed
n = self.checkAdjacentMines(row, col, board)
if n > 0:
# If there is, update the entry to digit
board[row][col] = str(n)
else:
# If there isn't, update the entry to 'B' and keep recursion
board[row][col] = 'B'
self.reveal(row + 1, col, board)
self.reveal(row - 1, col, board)
self.reveal(row, col + 1, board)
self.reveal(row, col - 1, board)
self.reveal(row + 1, col + 1, board)
self.reveal(row + 1, col - 1, board)
self.reveal(row - 1, col + 1, board)
self.reveal(row - 1, col - 1, board)
def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]:
clicked = board[click[0]][click[1]]
if clicked == 'M':
board[click[0]][click[1]] = 'X'
else:
self.reveal(click[0], click[1], board)
return board
board = [['E', 'E', 'E', 'E', 'E'],
['E', 'E', 'M', 'E', 'E'],
['E', 'E', 'E', 'E', 'E'],
['E', 'E', 'E', 'E', 'E']]
click = [3, 0]
print(Solution().updateBoard(board, click)) |
0cdffa91d0ff4230d6c4b3f921132e7bf8401f53 | Rkozik/gitlab-change-log-generator | /venv/lib/python3.7/site-packages/GitReleaseNotesGenerator-0.1-py3.7.egg/GitReleaseNotesGenerator/translations/translation.py | 831 | 3.78125 | 4 | from abc import ABCMeta, abstractmethod
class Translation:
__metaclass__ = ABCMeta
def __init__(self, phrase: str):
self.phrase = phrase
@abstractmethod
def verify(self) -> bool:
"""
Determines whether or not the translation is necessary.
:return:
"""
pass
@abstractmethod
def translate(self):
"""
Transforms a foreign phrase into a native phrase.
:return:
"""
pass
def apply(self):
"""
Preforms the translation if it needs to happen.
:return:
"""
return self.translate() if self.verify() else self.phrase
@abstractmethod
def __regex(self, phrase: str):
"""
Regular expressions used in content parsing
:return:
"""
pass
|
cf333c57a2bae842197a4a4c3cc7a3e31c1430b3 | llanoxdewa/python | /pythonEXCEPTION/latihan.py | 341 | 3.875 | 4 |
try:
print('masukan angka bilangan bulat positif')
angka = int(input('\n>>'))
if angka < 0:
raise ValueError('input harus bilangan bulat positif')
else:
print(angka)
except ValueError as e:
while(angka < 0):
print(e)
angka = int(input('\n>>'))
else:
print(angka)
|
230eecd75ad0246d33f240779fc36823803cb32e | DaphneKouts/NCWIT | /rock paper scissors.py | 870 | 3.765625 | 4 | #Daphne Koutsoukos
def RPS():
import random
choices = ["rock","paper","scissors"]
computerChoice = random.choice(choices)
player = raw_input("Pick rock, paper, or scissors: ")
if player == computerChoice:
return "Tie"
elif computerChoice == "rock" and player == "paper":
return "You win, computer chose rock"
elif computerChoice == "rock" and player == "scissors":
return "Computer wins, computer chose rock"
elif computerChoice == "scissors" and player == "rock":
return "You win, computer chose scissors"
elif computerChoice == "scissors" and player == "paper":
return "Computer wins, computer chose scissors"
elif computerChoice == "paper" and player == "rock":
return "Computer wins, computer chose paper"
else:
return "You win, computer chose paper"
|
02f4b56542cd66922351a660c2d07e25dc012ff0 | HoseungJang/py-HxD | /src/modules/byte.py | 144 | 3.59375 | 4 | def reverseBytes(byte):
reversedBytes = ''
for i in range(8, 0, -2):
reversedBytes += byte[i-2:i]
return reversedBytes |
2ba7dafa404a7d8f8bc71e004953cde395ce618c | zhenglaizhang/da-quest | /survey.py | 1,509 | 3.625 | 4 | import csv
import pprint
data_path = "./survey.csv"
def run():
male_set = {'male', 'm'}
female_set = {'female', 'f'}
# value is list with 2 elements, 1st element is result of female, 2nd element is the result of male's
result = {}
with open(data_path, newline='') as csv_file:
rows = csv.reader(csv_file)
for i, row in enumerate(rows):
if i == 0:
continue
if i % 50 == 0:
print("processing row {}".format(i))
# raw data
gender_val = row[2]
country_val = row[3]
# cleaning
gender_val = gender_val.lower().replace(' ', '')
country_val = country_val.lower()
if country_val not in result:
result[country_val] = [0, 0]
if gender_val in female_set:
result[country_val][0] += 1
elif gender_val in male_set:
result[country_val][1] += 1
else:
# noise data
# pass
print("unknown gender_val: {}", gender_val)
pprint.pprint(result)
with open('survey_result1.csv', 'w', newline='', encoding='utf-8') as csv_file:
writer = csv.writer(csv_file, delimiter=',')
writer.writerow(['Country', 'Male', 'Female'])
for k, v in list(result.items()):
writer.writerow([k, v[0], v[1]])
if __name__ == '__main__':
run()
|
1c2b1aab4fd8981d73c56f3e6bf8a2bf81e003fa | Minkov/python-fundamentals-sept-2019 | /dicts/3_statistics.py | 1,048 | 3.65625 | 4 | def read_until_command(end_command):
lines = []
while True:
line = input()
if line == end_command:
break
lines.append(line)
return lines
def print_quantities(quantities_dict):
print('Products in stock:')
for (product, quantity) in quantities_dict.items():
print(f'- {product}: {quantity}')
print(f'Total Products: {len(quantities_dict)}')
print(f'Total Quantity: {sum(quantities_dict.values())}')
def get_products_quantities_dict(lines):
quantities_dict = {}
for line in lines:
(product, quantity_str) = line.split(': ')
if product not in quantities_dict:
quantities_dict[product] = 0
quantities_dict[product] += int(quantity_str)
return quantities_dict
def solve(lines):
quantities_dict = get_products_quantities_dict(lines)
print_quantities(quantities_dict)
lines = read_until_command('statistics')
# lines = ['bread: 4', 'cheese: 2', 'ham: 1', 'bread: 1']
solve(lines)
|
b28ca9045d61e9a5f4ade4f0e0d193b773ab19d6 | ngladkoff/2019FDI | /while.py | 178 | 3.875 | 4 | mayor = 0
numero = 0
indice = 0
while indice < 10:
numero = int(input("nro:"))
if numero > mayor:
mayor= numero
indice = indice + 1
print("mayor: ", mayor)
|
5f31bed7df6fcd2cc5cdc5bc737ca4b5acc35b7d | taitujing123/my_leetcode | /047_permuteUnique.py | 1,089 | 3.859375 | 4 | """
给定一个可包含重复数字的序列,返回所有不重复的全排列。
示例:
输入: [1,1,2]
输出:
[
[1,1,2],
[1,2,1],
[2,1,1]
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/permutations-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
class Solution(object):
def permuteUnique(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
if len(num) == 0:
return res
self.permute(res, num, 0)
return res
def permute(self, res, num, index):
if index == len(num):
res.append(list(num))
return
appeared = set()
for i in range(index, len(num)):
if num[i] in appeared:
continue
appeared.add(num[i])
num[i], num[index] = num[index], num[i]
self.permute(res, num, index + 1)
num[i], num[index] = num[index], num[i] |
2f022869374b48c916c97916530dbf5c5d4011ac | martinyangcp/learning-python | /03CHAPTER_Random,If,While,For/practice1-3.py | 215 | 3.53125 | 4 | import random
first=random.randint(1,100)
second=random.randint(1,100)
answer=int(input(str(first)+"-"+str(second)+"="))
if answer == first-second :
print("맞았습니다.")
else:
print("틀렸습니다.")
|
81ac33dff34b158a13d8e046e6f6619dca7a5e98 | DoggLow/SoloLearnPython | /OOP/oop1.py | 4,091 | 4.65625 | 5 | #Object Oriented Programming
#############################################################
#############################################################
#############################################################
######## Examples from solo Learn #######
class Animal:
def __init__(self, name, color):
self.name = name
self.color = color
class Cat(Animal):
def purr(self):
print("Purr...")
class Dog(Animal):
def bark(self):
print("Woof!")
fido = Dog("Fido", "brown")
print(fido.color)
fido.bark()
class A:
def firstMethod(self):
print("A method")
class B(A):
def secondMethod(self):
print("B method")
class C(B):
def thirdMethod(self):
print("C method")
ctest = C()
ctest.firstMethod()
ctest.secondMethod()
ctest.thirdMethod()
## Magic Methods ##
#
#Magic methods are special methods which have double underscores at the beginning and end of their names.
#They are also known as dunders.
#So far, the only one we have encountered is __init__, but there are several others.
#They are used to create functionality that can't be represented as a normal method.
#
#One common use of them is operator overloading.
#This means defining operators for custom classes that allow operators such as + and * to be used on them.
#An example magic method is __add__ for +.
#class Vector2D:
# def __init__(self, x, y):
# self.x = x
# self.y = y
# def __add__(self, other):
# return Vector2D(self.x + other.x, self.y + other.y)
#
#first = Vector2D(5, 7)
#second = Vector2D(3, 9)
#result = first + second
#print(result.x)
#print(result.y)
#
#Magic Methods
#
#More magic methods for common operators:
#__sub__ for -
#__mul__ for *
#__truediv__ for /
#__floordiv__ for //
#__mod__ for %
#__pow__ for **
#__and__ for &
#__xor__ for ^
#__or__ for |
#
#The expression x + y is translated into x.__add__(y).
#However, if x hasn't implemented __add__, and x and y are of different types, then y.__radd__(x) is called.
#There are equivalent r methods for all magic methods just mentioned.Magic Methods
#
#More magic methods for common operators:
#__sub__ for -
#__mul__ for *
#__truediv__ for /
#__floordiv__ for //
#__mod__ for %
#__pow__ for **
#__and__ for &
#__xor__ for ^
#__or__ for |
#
#The expression x + y is translated into x.__add__(y).
#However, if x hasn't implemented __add__, and x and y are of different types, then y.__radd__(x) is called.
#There are equivalent r methods for all magic methods just mentioned.
#############################################################
#############################################################
#############################################################
class MyAnimal: #Class = object
def __init__(self, color, legs): # most important method of a class, always include it
self.color = color
self.legs = legs
def setColor(color):
self.color = color
def speak():
print("I am an animal, I don't speak")
self.lang = None
class Feline(MyAnimal):
specie = "feline"
def __init__(self,name,theType):
self.name = name
self.theType = theType
self.legs =4
def color(self,color):
super.setColor(color)
def speak(self):
print("All cats purr!")
self.lang = "purr"
def speak(self,lang):
self.lang = lang
print(lang)
simba = Feline("Simba","Lion")
simba.color("yellow")
print(simba.color)
simba.speak()
simba.speak("roar")
class Vehicle:
def information(self):
"""
Speed = how fast the vehicle goes
wheels = number of wheels
fuel = How much fuel per hour it consumes
"""
def __init__(self):
speed = 100
wheels = 4
fuel = 40
wings = False
def __init__(self,speed, wheels, wings, fuel):
self.speed = speed
self.wheels = wheels
self.wings = wings
def maxdistance():
maxdistance = (speed/fuel)
class Plane(Vehicle):
def fly(self):
print("The plane is flying")
jet = Plane()
jet.wings = True
print (jet.fly())
|
d406142d698fc9eb3f95ef5243013da10a4f1a0e | IreneArapogiorgi/Algo-Assignments | /network_destruction/network_destruction.py | 8,672 | 3.9375 | 4 | from collections import deque
import argparse
# Extract file's nodes in list
def extract_nodes(file):
# Open and read given file
with open(file, 'r') as file:
# Extract file's lines & each line's nodes in list
lines = [line.strip('\n') for line in file.readlines()]
nodes = [node.split(" ") for node in lines]
return nodes
# Create graph
def create_graph(nodes):
graph = {}
for node in nodes:
if int(node[0]) not in graph:
graph[int(node[0])] = []
if int(node[1]) not in graph:
graph[int(node[1])] = []
graph[int(node[0])].append(int(node[1]))
graph[int(node[1])].append(int(node[0]))
return graph
# Calculate each node's degree
def find_degree(graph):
degree = []
for key, adjacencylist in sorted(graph.items()):
degree.append(len(adjacencylist))
return degree
# Immunize network based on the degree of each node
def immunize_by_degree(graph, degree, num_nodes):
# Initialize removed_nodes list which stores nodes removed & their degree
removed_nodes = []
for i in range(num_nodes):
max_degree = max(degree)
# Find & remove node with maximum degree
#
# In case of multiple nodes having the maximum degree, remove the smallest one
# To achieve that, we iterate the sorted graph
for key, adjacencylist in sorted(graph.items()):
if degree[key-1] == max_degree:
# Store removed node in variable removed
removed = key
# Set removed node to have no neighbors
graph[key] = []
# Set removed node's degree to -1 which could not be found in list degree
degree[key-1] = -1
break
# Delete removed node from adjacencylists when found & decrease degree when needed
for key, adjacencylist in sorted(graph.items()):
if removed in adjacencylist:
degree[key-1] -= 1
adjacencylist.remove(removed)
# List removed_nodes stores all nodes removed from graph and their degree
removed_nodes.append([removed, max_degree])
return removed_nodes
# Before we go into immunizing the network based on the collective influence (ci) of each node,
# we need to implement the following functions: find_path_length(), ball_sum(), affected_nodes() & calculate_ci()
# Find the minimum path length starting from each node until we reach node i of the graph
#
# Function is based on BFS algorithm
def find_path_length(graph, size, i):
# Initialize path_length list which stores the minimum distance between each node of the graph and given node i
path_length = [0] * size
# Find path length for each node of the graph
#
# n corresponds to each node of the graph
# range(size) is equal to the total number of nodes in graph
for n in range(size):
# Initialize visited & inqueue lists
visited = [False] * size
inqueue = [False] * size
# Initialize dist list which stores the distance between the starting node n and each neighbor
dist = [0] * size
# Create a new queue with deque() function
q = deque()
# Queue named q stores nodes we visit
#
# We append n+1 because graph's nodes start with 1, 2, ... while variable n with 0, 1, ... but corresponds to 1, 2, ...
q.append(n+1)
inqueue[n] = True
while q:
c = q.pop()
inqueue[c-1] = False
visited[c-1] = True
# While loop stops when we reach node i passed as a parameter
#
# path_length[n] is the minimum distance between node n and i
if c == i:
path_length[n] = dist[i-1]
break
for neighbor in graph[c]:
if not visited[neighbor-1] and not inqueue[neighbor-1]:
q.appendleft(neighbor)
inqueue[neighbor-1] = True
# Each time we visit a node's neighbor, we set or update the neighbor's path length by adding 1 to its predecessor's
if dist[neighbor-1] == 0 or dist[neighbor-1] > dist[c-1] + 1:
dist[neighbor-1] = dist[c-1] + 1
return path_length
# Find the sum of (kj-1) for each j with path length equal to r
#
# Disclaimer: kj is equal to degree[j]
def ball_sum(graph, degree, i, r):
ball_sum = 0
# Find path length starting from each node until we reach node i+1
#
# We pass i+1 because graph's nodes start with 1, 2, ... while variable i with 0, 1, ... but corresponds to 1, 2, ...
path_length = find_path_length(graph, len(degree), i+1)
for j, length in enumerate(path_length):
if length == r:
ball_sum += degree[j] - 1
return ball_sum
# Find nodes affected from removing key i
#
# Affected nodes have path length equal to or less than r+1 passed in function as parameter r
def affected_nodes(graph, size, i, r):
affected = []
# Find path length starting from each node until we reach node i, which is the removed one
path_length = find_path_length(graph, size, i)
for j, length in enumerate(path_length):
if length <= r + 1:
affected.append(j)
return affected
# Calculate collective influence of given node
def calculate_ci(graph, degree, node, r):
# For removed nodes, whose degree[i] == -1, set ci to -1
if degree[node] == -1:
return -1
else:
return (degree[node] - 1) * ball_sum(graph, degree, node, r)
# Immunize network based on the collective influence (ci) of each node
def immunize_by_ci(graph, degree, r, num_nodes):
# Initialize removed_nodes list which stores nodes removed & their ci
removed_nodes = []
# Initialize ci list which stores each node's collective influence
ci = [0] * len(graph)
# Calculate collective influence of graph's nodes
for node in range(len(ci)):
ci[node] = calculate_ci(graph, degree, node, r)
for i in range(num_nodes):
max_ci = max(ci)
# Find & remove node with maximum ci
#
# In case of multiple nodes having the maximum ci, we remove the smallest one
# To achieve that, we iterate the sorted graph
for key, adjacencylist in sorted(graph.items()):
if ci[key-1] == max_ci:
# Store removed node in variable removed
removed = key
# Set removed node to have no neighbors
graph[key] = []
# Set removed node's degree to -1 which could not be found in list degree
degree[key-1] = -1
break
# Delete removed node from adjacencylists when found & decrease degree when needed
for key, adjacencylist in sorted(graph.items()):
if removed in adjacencylist:
degree[key-1] -= 1
adjacencylist.remove(removed)
# Update collective influence of affected nodes
for node in affected_nodes(graph, len(degree), removed, r):
ci[node] = calculate_ci(graph, degree, node, r)
# List removed_nodes stores all nodes removed from graph and their ci
removed_nodes.append([removed, max_ci])
return removed_nodes
# Main function
def main():
# Retrieve arguments passed on command line
#
# Optional argument -c means that we immunize the network by degree
# Optional argument -r means that we immunize the network by collective influence
#
# Argument num_nodes stores the number of nodes to be removed
# Argument input_file stores nodes' links
parser = argparse.ArgumentParser()
parser.add_argument("-c", "--degree", action='store_true', help="immunize by degree")
parser.add_argument("-r", "--radius", type=int, help="radius")
parser.add_argument("num_nodes", type=int, help="nodes to be removed")
parser.add_argument("input_file", help="nodes' links")
args = parser.parse_args()
nodes = extract_nodes(args.input_file)
graph = create_graph(nodes)
degree = find_degree(graph)
# Immunize the network based on the given arguments
if args.degree:
removed_nodes = immunize_by_degree(graph, degree, args.num_nodes)
else:
removed_nodes = immunize_by_ci(graph, degree, args.radius, args.num_nodes)
# Print both nodes removed & their degree/ci
for node in removed_nodes:
print(*node)
if __name__ == "__main__":
main() |
665b594e9b30d6ebbea1396a12aebaf80a5d8d3f | Wuskysong/python01_- | /python_one_learn/day08/review.py | 753 | 4 | 4 | """
day07 复习
能力提升for for
# 结论:外层循环执行一次,内层循环执行多次。
外层控制行,内层控制列.
for r in range(2):# 0 1
for c in range(3):#012 012
pass
函数
定义:功能,使用一个名称,包装多个语句。
语法:
做
def 名字(形参):
函数体
用
名字(实参)
"""
list01 = [23,34,4,6]
for r in range(len(list01) - 1):
# 作比较
for c in range(r + 1, len(list01)):
# list01[2] list01[c]
if list01[r] > list01[c]:
list01[r], list01[c] = list01[c], list01[r]
|
b4d7e23bfec4147b71206b46c698252cd9953cd2 | 1525125249/NEUQ-ACM-Solution | /week2/韩涵/8.1.py | 489 | 4.0625 | 4 | def hanoi(a, b, c, d): # a,b,c分别为一,二,三根柱子
if d > 1: # 当 d = 1时就只有一个圆盘,不需要在进行递归
hanoi(a, c, b, d - 1) # 将n-1个圆盘从a移动到b
print(a + "->" + c)
if d > 1: # 同理
hanoi(b, a, c, d - 1) # 将n-1个圆盘从b移动到c
def week2_1():
n = int(input(""))
name = [input(""), input(""), input("")]
hanoi(name[0], name[1], name[2], n)
if __name__ == '__main__':
week2_1()
|
66905904ca38359746a769b2657aaff55bdce3e6 | rishinkaku/Software-University---Software-Engineering | /Python Fundamentals/Basic Syntax, Conditional Statements and Loops/09. Easter Cozonacs/9. Easter Cozonacs.py | 3,441 | 4 | 4 | budget = float(input())
flour = float(input())
eggs = flour*0.75
milk = flour+0.25*flour
cozonac = eggs+flour+milk*0.25
cozonac_counter = 0
colored_eggs = 0
while True:
if budget < cozonac:
break
cozonac_counter += 1
colored_eggs += 3
budget -= cozonac
if cozonac_counter % 3 == 0:
colored_eggs -= cozonac_counter-2
price = cozonac*cozonac_counter
print(f"You made {cozonac_counter} cozonacs! Now you have {colored_eggs} eggs and {budget:.2f}BGN left.")
"""
Since it’s Easter you have decided to make some cozonacs and exchange them for eggs.
Create a program that calculates how much cozonacs you can make with the budget you have. First,
you will receive your budget. Then, you will receive the price for 1 kg flour. Here is the recipe for one cozonac:
Eggs
1 pack
Flour
1 kg
Milk
0.250 l
The price for 1 pack of eggs is 75% of the price for 1 kg flour.
The price for 1l milk is 25% more than price for 1 kg flour. Notice,
that you need 0.250l milk for one cozonac and the calculated price is for 1l.
Start cooking the cozonacs and keep making them until you have enough budget. Keep in mind that:
For every cozonac that you make, you will receive 3 colored eggs.
For every 3rd cozonac that you make, you will lose some of your colored eggs after you have
received the usual 3 colored eggs for your cozonac. The count of eggs you will lose is calculated
when you subtract 2 from your current count of cozonacs – ({currentCozonacsCount} – 2)
In the end, print the cozonacs you made, the eggs you have gathered and the money you have left,
formatted to the 2nd decimal place, in the following format:
"You made {countOfCozonacs} cozonacs! Now you have {coloredEggs} eggs and {moneyLeft}BGN left."
Input / Constraints
On the 1st line you will receive the budget – a real number in the range_shot [0.0…100000.0]
On the 2nd line you will receive the price for 1 kg flour – a real number in the range_shot [0.0…100000.0]
The input will always be in the right format.
You will always have a remaining budget.
There will not be a case in which the eggs become a negative count.
Output
In the end print the count of cozonacs you have made, the colored eggs you have gathered and the money
formatted to the 2nd decimal place in the format described above.
Examples
Input
Output
20.50
1.25
You made 7 cozonacs! Now you have 16 eggs and 2.45BGN left.
Comments
We start by calculating the price for a pack of eggs, which is 75% of the price for 1 kg floor,
which in this case is 1.25. The pack of eggs price is 0.9375. The price for 1l milk is 25% more
than the price for 1kg floor and in this case it is – 1.5625, but we need the price for 0.250ml, which is - 0.390625.
The total price for one cozonac is:
1.25 + 0.9375 + 0.390625 = 2.578125.
And we start subtracting the price for a single cozonac from the budget, and for each cozonac we receive 3 eggs.
So after the first subtraction we will have 17.921875 budget, 1 cozonac and 3 eggs. After the second - 15.34375 budget,
6 eggs, and on the third - 12.765625 budget and 9 eggs and since it’s the third, we need to subtract the lost eggs,
which will be 3 – 2 = 1, so we subtract 1 from 9 and our eggs become 8. We continue subtracting money from the budget
until the money aren't enough for us to make a cozonac. In the end we have 2.45BGN left.
15.75
1.4
You made 5 cozonacs! Now you have 14 eggs and 1.31BGN left.
"""
|
d4ed738bb0d1edb3f8f566a54c8ed92c0ebdb0dc | MarkMarkos2308/homework2 | /basich6 — копия.py | 2,371 | 3.578125 | 4 | import os
# a = open(r'C:\Users\User\Desktop\basiq py\fruits.txt', 'a')
# a.write(' apple, orange.')
# a.close()
# a = open(r'C:\Users\User\Desktop\basiq py\fruits.txt', 'r')
# print(a.read())
# v = open(r'C:\Users\User\Desktop\basiq py\5strings.txt', 'r')
# a = v.readline()
# b = v.readline()
# c = v.readline()
# d = v.readline()
# e = v.readline()
# print(a + b + c + d + e)
# a = open(r"C:\Users\User\Desktop\basiq py\pr3.txt", 'r')
# v = ''
# for word in a:
# if v < word:
# v = word
# print(v)
# a = open(r'C:\Users\User\Desktop\basiq py\groupnames.txt', 'r')
# a = a.read()
#
# a = a.split(' ')
#
# for word in a:
# print(len(word) * (word + ' '))
# new_names = ['Ани', 'Армен', 'Арен', 'Аргишти', 'Арсен', 'Алик', 'Анаит', 'Анна']
# for name in new_names:
# fg = name
# if os.path.exists(name):
# print('true')
# else:
# print("foals")
# s = 'D d D D D d D D F G g g g H h j'
# for x in s:
# print(x.isupper())
# v = "Homework 6Deadline: 28 AUG, 20:00 Problem 1Create a file manually with some text in it like 'My favourite
# fruits " \ "are:'.Then write a program to append the file with the fruits that you love. Problem 2Create a file
# that has 5 or " \ "more lines of text.Write a program to store each line in a variable. Problem 3Find the longest
# word in the file " \ "pr3.txt. Problem 4Create a list of names of all our group members.Loop over the list and
# create files (filename = " \ "name).Each file should contain the name of a person repeated as many times as the
# characters of the name.for " \ "example: file -> Ani.txt text - > Ani Ani
# AniAni is " \ "repeated 3 times as it has 3 characters. Problem 5After writing Problem 4 write a function that gets
# this list " \ "and checks if files with these names exist. If a file exists return True, otherwise False.'new_names
# = ['Ani', " \ "'Armen', 'Aren', 'Argishti', 'Arsen', 'Alik', 'Anahit', 'Anna']' Problem 6Write a function that gets
# a file path " \ "and calculates how many upper case letters are in the text.Hint: use isupper() method. Problem 7 (
# OPTIONAL)Write " \ "a program to show the frequency(how many times a word appears in the text) of each word. Hint:
# set() " a = len(v) c = v.replace("Problem", "") b = a - len(c) n = b / len("problem") print(n)
|
d38426b8d29185d9bdb1314e23baefe3d4386a1c | ronnicohen/Project-Euler | /17. Number letter counts .py | 765 | 3.59375 | 4 | # https://projecteuler.net/problem=17
# If the numbers 1 to 5 are written out in words: one, two, three, four,
# five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
#
# If all the numbers from 1 to 1000 (one thousand) inclusive were written out
# in words, how many letters would be used?
#
#
# NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and
# forty-two) contains 23 letters and 115 (one hundred and fifteen) contains
# 20 letters. The use of "and" when writing out numbers is in compliance with
# British usage.
from num2words import num2words
big_word = ''
for j in xrange(1, 1001):
in_words = str(num2words(j))
for i in in_words:
if (i != ' ') and (i != ',') and (i != '-'):
big_word += i
print len(big_word)
|
ad6d6d941ee26149e0ac0e4346c81fa81dc683b1 | VX5lG/Programming-1-2 | /9.1.2.py | 303 | 4.03125 | 4 | # axel
# period 4
# 11/13/2015
# 9.1.1
# takes 2 numbers from user
num1 = int(input("Give me a number: "))
num2 = int(input("Give me another number: "))
if num1 > num2:
print ("The number %d is larger than %d" %(num1, num2))
else:
print ("The number %d is larger than %d" %(num2, num1))
|
1b3f8e5c457881c8558a4bfbe48a79796c84059a | VictorLi5611/Mark-Calculator | /Mark Calculator/main.py | 1,182 | 3.75 | 4 | import markCalc
USER = input("Please enter your name:\n").upper()
COURSE_CODE = input("Please enter your course code:\n").upper()
ALL_MARKS = markCalc.getMarks("marks.csv")
data = []
find = {}
VALID_INPUT = [1,2,3,4]
def main():
for eval in ALL_MARKS:
currentMarks = eval.split(",")
item, weight = currentMarks.pop(0).upper(), float(currentMarks.pop(0))
total = markCalc.weightedAverage(currentMarks, weight)
avg = markCalc.average(currentMarks)
temp = [item, weight, avg, total]
find[item] = [weight,avg,total]
data.append(temp)
while True:
inpt = int(input("SEE CURRENT PROGRESS PRESS 1, CALCULATE WHAT YOU NEED TO PASS PRESS 2, QUIT PRESS 3:\n"))
if inpt not in VALID_INPUT:
print("You entered an incorrect input, please try again.")
else:
if inpt == 1:
markCalc.markBreakdown(data,USER,COURSE_CODE)
elif inpt == 2:
markCalc.passingMark(data,COURSE_CODE)
elif inpt == 3:
quit()
if __name__ == "__main__":
main()
|
adfea2c44cceee4e0be9a2dad248ba1103e6397c | YazdKotwal-creator/C101 | /phone_book.py | 3,359 | 3.8125 | 4 | #------------------------------
# functions and definitions
#------------------------------
import os
phone_book ={} #dictonary containing your phonbook
def cleer_screen(confirm=True): # function to clear screen between menu selections
if confirm == True: # do i want the user to press enter before clearing or not defaulted to true
spacer()
cont = raw_input("press enter to continue")
os.system('cls' if os.name == 'nt' else 'clear')
def spacer(): # just adding 2 lines of nothing :)
print " "
print " "
def print_menu(): # print ouy main menu
spacer()
print " #############################################"
print " # phone book v0.1 #"
print " #############################################"
print " # 1. add Person/number #"
print " # 2. del Person/number #"
print " # 3. find number #"
print " # 4. List all numbers #"
print " # s. Save phone book #"
print " # l. Load phone book #"
print " # q Quit #"
print " #############################################"
spacer()
def add_number(): # add number to phone_book var
spacer()
name = raw_input("enter name: ")
number = raw_input("enter number: ")
phone_book[name] = number
cleer_screen(False)
def del_number(): # del a entry from the phonebook
spacer()
name = raw_input("enter name to delete: ")
print "are you sure you want to delete " + name
yesno = raw_input("y/n: ")
if yesno == "y" or yesno == "Y": # just a safty to make sure you want do del the name you entered
try: # had to put this in a try except so the program would not crash if user enter a name thats not in the book
print "deleting " + name + " - " + phone_book[name]
del phone_book[name]
except:
print "name not found"
cleer_screen()
def find_number(): # find a number by name
spacer()
name = raw_input("enter name: ")
try: # had to use try exept in case some one enters a name thats not in the dictonary
print name + " " + phone_book[name]
cleer_screen()
except :
print "that name is not in the phone book"
cleer_screen()
def list_numbers(): # list all names and numbers in the phone book
spacer()
print "number - name"
for x,y in enumerate(sorted(phone_book)):
print phone_book[y] + " - " + y
cleer_screen()
def save_book(): #save the array to a file
file = open('phone-book.dat' , 'w+')
for (id, item) in phone_book.items():
#print id, item
file.write(str(id) + '-' + str(item) + '\n')
def load_book(): #open the phone-book.dat
try:
file = open('phone-book.dat' , 'r+')
for line in file:
tmpInput = line.split('-')
tmpInput2 = tmpInput[1].split()
phone_book[tmpInput[0]] = tmpInput2[0]
except:
print "there is no saved phonebook"
cleer_screen()
#------------------------------
# application
#------------------------------
cleer_screen(False)
while True : # main while loop
print_menu()
input = raw_input("make your selection ")
cleer_screen(False)
if input == "1":
add_number()
if input == "2":
del_number()
if input == "3":
find_number()
if input == "4":
list_numbers()
if input == "s":
save_book()
if input == "l":
load_book()
if input.strip() == 'Q' or input.strip() == 'q' :
print "Bye !"
break
|
33cca381fa759473ca7627e82fc62c05fdd616fe | LavenderIris/CS-3A---OO-in-Python | /finalunittest.py | 2,959 | 3.71875 | 4 | # Priscilla Chung Finder
# Final Unit test
# CS 3A
# unit tests for various states of my tic tac toe board
import unittest
import pygame, sys
from lib import *
class Test_libpy(unittest.TestCase):
def test_check_not_game_over(self):
"""
Unit test to check when in-game
:return:
"""
pygame.init()
board = Board(grid_size=3, box_size=100, border=50, line_width=10)
surface_size = board.surface.get_height()
board.process_click_ingame(surface_size/2, surface_size/2)
ans = False
self.assertEqual(board.game_over, ans)
def test_check_gameover(self):
"""
Unit test to check when gameover.
:return:
"""
pygame.init()
board = Board(grid_size=3, box_size=100, border=50, line_width=10)
surface_size = board.surface.get_height()
# sets the board for gameover state
board.process_click(surface_size/2, surface_size/2)
board.process_click(surface_size/2, surface_size * 0.7)
board.process_click(surface_size * 0.7, surface_size/2)
board.process_click(surface_size/3, surface_size * 0.7)
board.process_click(surface_size * 0.3, surface_size/2)
ans = True
self.assertEqual(board.game_over, ans)
def test_check_player_1_wins(self):
"""
Unit test to check when player 1 wins.
:return:
"""
pygame.init()
board = Board(grid_size=3, box_size=100, border=50, line_width=10)
surface_size = board.surface.get_height()
# sets the board for gameover state
board.process_click(surface_size/2, surface_size/2)
board.process_click(surface_size/2, surface_size * 0.7)
board.process_click(surface_size * 0.7, surface_size/2)
board.process_click(surface_size/3, surface_size * 0.7)
board.process_click(surface_size * 0.3, surface_size/2)
ans = 1
self.assertEqual(board.check_for_winner(), ans)
def test_check_player_2_wins(self):
"""
Unit test to check when player 2 wins
:return:
"""
pygame.init()
board = Board(grid_size=3, box_size=100, border=50, line_width=10)
surface_size = board.surface.get_height()
# sets the board for gameover state
board.process_click(surface_size * 0.3, surface_size * 0.5)
board.process_click(surface_size * 0.7, surface_size * 0.3)
board.process_click(surface_size * 0.5, surface_size * 0.5)
board.process_click(surface_size * 0.7, surface_size * 0.5)
board.process_click(surface_size * 0.3, surface_size * 0.7)
board.process_click(surface_size * 0.7, surface_size * 0.7)
ans = 2
self.assertEqual(board.check_for_winner(), ans)
if __name__ == "__main__":
unittest.main()
# OUTPUT
# ....
# ----------------------------------------------------------------------
# Ran 4 tests in 0.973s
#
# OK
|
06d8fbc13b67b432bb4844e8464207d89f3f893d | bulatnig/textsolutions | /cracking/arrays/1.7.py | 924 | 3.8125 | 4 | def rotate(matrix: list[list[int]]) -> list[list[int]]:
size = len(matrix)
if size < 2:
return matrix
circle_count = size // 2
for i in range(0, circle_count):
for j in range(0, size - 1 - i * 2):
tmp = matrix[i][i + j]
matrix[i][i + j] = matrix[size - 1 - i - j][i]
matrix[size - 1 - i - j][i] = matrix[size - 1 - i][size - 1 - i - j]
matrix[size - 1 - i][size - 1 - i - j] = matrix[i + j][size - 1 - i]
matrix[i + j][size - 1 - i] = tmp
return matrix
print(rotate([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]))
print(rotate([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]]))
print(rotate([[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25]]))
|
45c47da33101e64ddb9f24cbd643ff38b3d8bb53 | nycowboy04/PythonProjects | /Python-Django-Course-Udemy/warcardgame.py | 3,845 | 4.40625 | 4 | #####################################
### WELCOME TO YOUR OOP PROJECT #####
#####################################
# For this project you will be using OOP to create a card game. This card game will
# be the card game "War" for two players, you an the computer. If you don't know
# how to play "War" here are the basic rules:
#
# The deck is divided evenly, with each player receiving 26 cards, dealt one at a time,
# face down. Anyone may deal first. Each player places his stack of cards face down,
# in front of him.
#
# The Play:
#
# Each player turns up a card at the same time and the player with the higher card
# takes both cards and puts them, face down, on the bottom of his stack.
#
# If the cards are the same rank, it is War. Each player turns up three cards face
# down and one card face up. The player with the higher cards takes both piles
# (six cards). If the turned-up cards are again the same rank, each player places
# another card face down and turns another card face up. The player with the
# higher card takes all 10 cards, and so on.
#
# There are some more variations on this but we will keep it simple for now.
# Ignore "double" wars
#
# https://en.wikipedia.org/wiki/War_(card_game)
from random import shuffle
# Two useful variables for creating Cards.
class Deck():
"""
This is the Deck Class. This object will create a deck of cards to initiate
play. You can then use this Deck list of cards to split in half and give to
the players. It will use SUITE and RANKS to create the deck. It should also
have a method for splitting/cutting the deck in half and Shuffling the deck.
"""
SUIT = 'H D S C'.split()
RANKS = '2 3 4 5 6 7 8 9 10 J Q K A'.split()
def __init__(self):
deck=[]
def createDeck(self):
for item in SUIT:
for card in RANKS:
deck+="".join(item,card)
return deck
def shuffling(self):
deck=shuffle(deck)
return deck
def split(self, player):
if player=='player1':
player.hand=deck[::2]
else:
player.hand=deck[1::2]
return player.hand
class Hand(Deck):
'''
This is the Hand class. Each player has a Hand, and can add or remove
cards from that hand. There should be an add and remove card method here.
'''
def __init__(self):
hand=self.hand
def play_card(self):
card=hand.pop(0)
return card
def add_card(self, cards):
for item in cards:
hand.append(item)
return hand.append(cards)
class Player(Hand):
"""
This is the Player class, which takes in a name and an instance of a Hand
class object. The Payer can then play cards and check if they still have cards.
"""
def __init__(self, name):
name=self.name
def check_hand(self):
if len(Player.hand)==0:
print("You have lost the game, {}".format(Player.name))
######################
#### GAME PLAY #######
######################
P1Card=[]
P2Card=[]
def round(P1, P2):
P1Card=P1.play_card()
P2Card=P2.play_card()
if P1Card > P2Card:
P1.add_card(P1Card)
P1.add_card(P2Card)
elif P1Card == P2Card:
war(Player1, Player2)
else:
P2.add_card(P1Card)
P2.add_card(P2Card)
def war(P1,P2):
p1down=[]
p2down=[]
for i in range(3):
p1down.append(P1.play_card())
p2down.append(P2.play_card())
P1Card=P1.play_card()
P2Card=P2.play_card()
print("Welcome to War, let's begin...")
p1=input("Player 1, please enter your name")
Player1=Player(p1)
p2=input("Player 2, please enter your name")
Player2=Player(p2)
deck=Deck()
deck.shuffling()
Player1.hand=split('player1')
Player2.hand=split('player2')
# Use the 3 classes along with some logic to play a game of war!
|
feff434c255c51e4813a1f51090ad23891c10961 | junaid238/class_files | /python files/conditional_statements.py | 787 | 3.671875 | 4 | # conditional statements
# ----------------------
# exec stops at wrong stmt
# if else
# condition --> t / f
# if T --> stmt1
# else F --> may or maynot stmt2
# condition1
# if T --> stmt1
# elif F --> condition2
# else --> T --> stmt2
# --> F --> stmt3
# if elif else
# if elif elif elif else
# nested condition statements
# ---------------------------
# if
# if
# if
# else
# else
# else
# Syntax:
# -------
# C CPP Java
# if(condition){
# tstmt
# }
# else{
# fstmt
# }
# Python
# ------
# if condition :
# tstmt
# else:
# fstmt
# if (condition) :
# tstmt
# else:
# fstmt
# a = 11
# if a==10:
# print("right")
# elif a==11:
# print("hai")
# else:
# print("wrong")
# b = 101
# if (b==10):
# pass
# else:
# print("wrong")
|
f62dc7f236fe5e2bc563d8f8a5aa7278f3a9df12 | dicao425/algorithmExercise | /LeetCode/diameterOfBinaryTree.py | 877 | 3.859375 | 4 | #!/usr/bin/python
import sys
#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 diameterOfBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.result = 0
self.dfs(root)
return self.result
def dfs(self, node):
if not node:
return 0
l = self.dfs(node.left)
r = self.dfs(node.right)
self.result = max(self.result, l + r)
return max(l, r) + 1
def main():
aa = Solution()
t = TreeNode(1)
t.left = TreeNode(2)
t.right = TreeNode(3)
t.left.left = TreeNode(4)
t.left.right = TreeNode(5)
print aa.diameterOfBinaryTree(t)
return 0
if __name__ == "__main__":
sys.exit(main())
|
f1de0a6818a8112eb9d7577e78b6ca6dcad200c8 | mistrydarshan99/Leetcode-3 | /interviews/linked_list/146_LRU_cache.py | 4,610 | 3.703125 | 4 | """
146. LRU Cache
Hard
1983
61
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.
get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
put(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
Follow up:
Could you do both operations in O(1) time complexity?
Example:
LRUCache cache = new LRUCache( 2 /* capacity */ );
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // returns 1
cache.put(3, 3); // evicts key 2
cache.get(2); // returns -1 (not found)
cache.put(4, 4); // evicts key 1
cache.get(1); // returns -1 (not found)
cache.get(3); // returns 3
cache.get(4); // returns 4
“”“
"""
The solution is:
1. Doulbe Linked List + Dict
2. always add an item to the end of the linked list
3. The dict will store: 1)key 2)address for that particular node at linked list
REASON for 2. always PUT an item to the end of the linked list:
- head: older nodes - least recenlty used
- tail: recently used (get or put) nodes
- always add newly PUT and newly GET node at the end of the linked list, so when we need to evict/eleminate certain element from the head, we alwasy evict / eliminate the least recently used node which are those closer to the head of the linked list.
所以,当我们GET一个node时,我们需要把它从原来的linked list里_remove 和 _add到linked list的尾部. 这样的话,我们就知道它最近被提取过,不会被删掉。
当我们需要PUT一个node时,我们需要考虑两点:
1)这个node是否已存在现在的Linked List里:查看dict
2)现在的capacity 够不够: 查看len(dict)
(如果这个节点已经存在在现在的链接里:那么不用担心capacity不够,因为肯定会删掉一个再加如新的;
但是这个节点没有存在在现在的链接里:那么的话,新增加的节点有可能导致exceed capacity.)
1-如果node没有存在:
· 加到现在dict
. 添加到现在的linkdlist的尾部
1-如果node已经存在:
- 从现有的 Linked list 里删除
- 更新字典里的value
"""
class Node(object):
def __init__(self, key, val):
self.key = key
self.val = val
self.prev = None
self.next = None
class LRUCache:
def __init__(self, capacity):
"""
:type capacity: int
"""
self.cap = capacity
self.cache = {}
self.head = Node(0, 0)
self.tail = Node(0, 0)
self.head.next = self.tail
self.tail.prev = self.head
def get(self, key):
"""
:type key: int
:rtype: int
# if key not in dict: return -1
# if key in dict:
# remove it
# add it again at the end of tail
"""
if key not in self.cache:
return -1
node = self.cache[key]
self._remove(node)
self._add(node)
# self.dprint()
return node.val
def put(self, key, value):
"""
:type key: int
:type value: int
:rtype: void
# if key already in cache:
# del it from linked list
# del it from dict
# if at capacity:
# remove the node pointed by the head (head.next)
# remove that node from dec
# add the new (key, val)
"""
if key in self.cache:
self._remove(self.cache[key])
elif len(self.cache) == self.cap:
print("overload")
old_node = self.head.next
self._remove(old_node)
del self.cache[old_node.key]
new_node = Node(key, value)
self._add(new_node)
self.cache[key] = new_node
# self.dprint()
def _add(self, node):
p = self.tail.prev
p.next = node
node.prev = p
node.next = self.tail
self.tail.prev = node
def _remove(self, node):
"""
remove the node by:
connect the node.previous with the node.next
"""
p = node.prev
p.next = node.next
node.next.prev = p
# def dprint(self):
# node = self.head
# print("new list")
# while node:
# print(node.val)
# node = node.next
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)
|
7113031649c14bed12c30817c66d1c1007d98f02 | junfengP/Python_ver_of_algorithm | /data_structure/binary_search_tree/binary_search_tree.py | 3,423 | 3.90625 | 4 | #!/usr/bin/python3
class BinaryTreeNode:
def __init__(self, key, st_info=None, left=None, right=None, p=None):
self.key = key
self.left = left
self.right = right
self.p = p
self.st_info = st_info # 卫星数据
def __repr__(self):
return str(self.key)
class BST:
def __init__(self):
self.nil = BinaryTreeNode(key=None)
self.root = self.nil
def get_root(self):
return self.root
def inorder_tree_walk(self, x):
if x != self.nil:
self.inorder_tree_walk(x.left)
print(x)
self.inorder_tree_walk(x.right)
def tree_search(self, x, k):
if x == self.nil or k == x.key:
return x
if k < x.key:
return self.tree_search(x.left, k)
else:
return self.tree_search(x.right, k)
def iterative_tree_search(self, x, k):
while x != self.nil and k != x.key:
if k < x.key:
x = x.left
else:
x = x.right
return x
def tree_minimum(self, x):
while x.left != self.nil:
x = x.left
return x
def tree_maximum(self, x):
while x.right != self.nil:
x = x.right
return x
def tree_successor(self, x):
if x.right != self.nil:
return self.tree_minimum(x.right)
y = x.p
while y != self.nil and x == y.right:
x = y
y = y.p
return y
def tree_predecessor(self, x):
if x.left != self.nil:
return self.tree_maximum(x.left)
y = x.p
while y != self.nil and x == y.left:
x = y
y = y.p
return y
def tree_insert(self, z):
if not isinstance(z, BinaryTreeNode):
z = BinaryTreeNode(z)
y = self.nil
x = self.root
while x != self.nil:
y = x
if z.key < x.key:
x = x.left
else:
x = x.right
z.p = y
if y == self.nil:
self.root = z
elif z.key < y.key:
y.left = z
else:
y.right = z
z.left = self.nil
z.right = self.nil
def transplant(self, u, v):
if u.p == self.nil:
self.root = v
elif u == u.p.left:
u.p.left = v
else:
u.p.right = v
if v == self.nil:
v.p = u.p
def tree_delete(self, z):
if z.left == self.nil:
self.transplant(z, z.right)
elif z.right == self.nil:
self.transplant(z, z.left)
else:
y = self.tree_minimum(z.right)
if y.p != z:
self.transplant(y, y.right)
y.right = z.right
y.right.p = y
self.transplant(z, y)
y.left = z.left
y.left.p = y
if __name__ == '__main__':
bst = BST()
for i in range(10, 1, -1):
bst.tree_insert(i)
print("树的最小值", bst.tree_minimum(bst.get_root()))
print("树的最大值", bst.tree_maximum(bst.get_root()))
print("删除节点4")
bst.tree_delete(bst.tree_search(bst.get_root(), 4))
print("节点5的前驱", bst.tree_predecessor(bst.tree_search(bst.get_root(), 5)))
print("节点5的后继", bst.tree_successor(bst.tree_search(bst.get_root(), 5)))
|
37aedfaba8cab86d7bf0a07a471ad417f503092a | chrisotto6/cps313 | /Week1/Exercise6.py | 698 | 4.375 | 4 | # Chris Otto
# Week 1 - Program Exercise 6
# CPS313
# Read the purchase amount from the user, calculates the state and country tax
# returning that information to the user
purchase = float(input('Enter the purchase amount: '))
# Calculate the taxes and tax totals based on input
stateTax = purchase * 0.05
countyTax = purchase * 0.025
totalTax = stateTax + countyTax
# Find out the end price of the purchase after tax
finalPurchase = purchase + totalTax
# Display information to the user
print('Original Amount of Purchase: ', purchase)
print('State Sales Tax: ', stateTax)
print('Country Sales Tax: ', countyTax)
print('Total Sales Tax: ', totalTax)
print('Final Purchase Price: ', finalPurchase) |
31315c731014f1d44da5b436814f92cc9d92e0af | ggoma5879/p1_201110081 | /w3MAIN(2).py | 336 | 3.65625 | 4 |
# coding: utf-8
# In[5]:
tmp = raw_input("What do you want to know F or C")
# In[6]:
if (tmp== 'F'):
tmp1= float(raw_input("#C?"))
tmp1 = tmp1 * (1.8) + 32
elif (tmp=='C'):
tmp1= float(raw_input("#F?"))
tmp1 = (tmp1-32)*5/9
else :
print ("Error")
print "Temperature is ", tmp1, tmp
# In[ ]:
wn.exitonclick
|
415cdca5a3a569c68a5e7bc8cdba405ab4d0f361 | y471n/algorithms-n-ds | /ds/stack-balanced-symbols.py | 828 | 4.125 | 4 | from stack import Stack
OPENING_SYMBOLS = "([{"
CLOSING_SYMBOLS = ")]}"
def matching_closing_symbol(opening_symbol, closing_symbol):
return OPENING_SYMBOLS.index(opening_symbol) == CLOSING_SYMBOLS.index(closing_symbol)
def paranthesis_check(symbols):
balanced, s = True, Stack()
for symbol in symbols:
if symbol in OPENING_SYMBOLS:
s.push(symbol)
else:
if s.is_empty():
balanced = False
break
if matching_closing_symbol(s.peek(), symbol):
s.pop()
continue
balanced = False
break
if not s.is_empty():
balanced = False
return balanced
if __name__ == "__main__":
symbols = input()
is_balanced = paranthesis_check(symbols)
print(is_balanced)
|
827149e17f5fbb558b0665346cccfb9fed1987aa | Cendra123/Improved-K-Means-By-Optimizing-initial-cluster | /density_tweet.py | 547 | 3.890625 | 4 | import math
import pandas as pd
import sys
# Example points in 3-dimensional space...
# x = (5, 6, 7,1)
# y = (8, 9, 9,4)
df = pd.read_excel('TF-IDF_01.xlsx')
print(df)
sys.exit()
# print(type(x))
# print(df.ix[1][:])
for i in range(5):
for j in range(i,5):
distance = math.sqrt(sum([(a - b) ** 2 for a, b in zip(df.ix[i][:], df.ix[j][:])]))
print("Euclidean distance from ",i," to ",j,": ",distance)
# distance = math.sqrt(sum([(a - b) ** 2 for a, b in zip(x, y)]))
# print("Euclidean distance from x to y: ",distance) |
f76ba420e87097d40b1a95dfee81e83423b9bf6d | GSvensk/OpenKattis | /LowDifficulty/sumkindofproblem.py | 205 | 3.59375 | 4 |
p = int(input())
for i in range(0, p):
arr = input().split()
a = int(arr[1])
plusone = int((a**2 + a)/2)
print("{} {} {} {}".format(arr[0], plusone, 2*plusone - int(arr[1]), 2*plusone)) |
dec165f77ff183f4d2ca1ed9d93c3cfb2b3c665d | WangDooo/Effective-Python-Specific-Ways-to-Better | /Learning/Unit_1-用Pythonic方式来思考/learn_1.py | 4,072 | 3.9375 | 4 | #================================================================
# 4. 用辅助函数来取代复杂的表达式
#----------------------------------------------------------------
# 少写那些复杂且难以理解的单行表达式 不利于维护
#----------------------------------------------------------------
#================================================================
# 7. 用列表推导(list comprehension)来取代map、filter
#----------------------------------------------------------------
# a = [1,2,3,4,5,6,7,8,9,10]
# squares_list = [x**2 for x in a] # list comprehension
# print(squares_list)
# # 若使用map 就要创建lambda函数
# squares_map = list(map(lambda x: x**2, a)) # map 复杂
# print(squares_map)
# even_squares_list = [x**2 for x in a if x % 2 == 0]
# print(even_squares_list)
# # 若使用map 就要创建lambda函数 和filter筛选
# alt = list(map(lambda x:x**2, filter(lambda x:x%2==0, a))) # map+filter 复杂
# print(alt)
# # 字典(dict)与集(set)也有和列表类似的推导机制
# chile_ranks = {'ghost':1, 'haha':2, 'xixi':3}
# rank_dict = {rank: name for name,rank in chile_ranks.items()}
# print(rank_dict)
# chile_len_set = {len(name) for name in rank_dict.values()}
# print(chile_len_set)
#----------------------------------------------------------------
#================================================================
# 8. 不要使用含有两个以上表达式的列表推导
#----------------------------------------------------------------
#----------------------------------------------------------------
#================================================================
# 9. 用生成器表达式来改写数据量较大的列表推导
#----------------------------------------------------------------
# 数据大,列表推导占内存多
# 生成器表达式所返回的迭代器 可以逐次输出值 避免内存用量问题
#----------------------------------------------------------------
# it = (len(x) for x in open('my_file.txt'))
# # for i in it:
# # print(i)
# roots = ((x,x**0.5) for x in it)
# print(next(roots))
#================================================================
# 10. 尽量用enumerate取代range
#----------------------------------------------------------------
# # enumerate函数 可以把各种迭代器包装成生成器 以便稍后产生输出值
# # 生成器没词产生一对输出值 前者表示循环下标 后者表示从迭代器中获取到的下一个序列元素
# color_list = ['red','green','yellow','blue']
# for i, color in enumerate(color_list): # 默认从0开始计数
# print('%d:%s' % (i+1, color))
# for i, color in enumerate(color_list, 1):
# print('%d:%s' % (i, color))
#----------------------------------------------------------------
#================================================================
# 11. 用zip函数同时遍历两个迭代器
#----------------------------------------------------------------
# zip函数可以把两个或两个以上的迭代器封装为生成器, 有一个耗尽就停止
# names = ["AAAAAAAAAAAA","BBBB","CC"]
# letters = [len(n) for n in names]
# max_letters = 0
# for name, count in zip(names, letters):
# if count > max_letters:
# longest_name = name
# max_letters = count
# print(longest_name)
#----------------------------------------------------------------
#================================================================
# 12. 不要在for和while循环后面写else块
#----------------------------------------------------------------
#----------------------------------------------------------------
#================================================================
# 13. 合理利用 try/except/else/finally结构中的每个快的代码
#----------------------------------------------------------------
# else块 如果try块没有发生异常,那么就执行else块
# else块 可以用来缩减try块中的代码量,把没有发生异常时要执行的语句与try/except代码隔开
#----------------------------------------------------------------
|
336ed99a857ec182f58861518197d7168af52757 | Aasthaengg/IBMdataset | /Python_codes/p02379/s959588510.py | 126 | 3.515625 | 4 | x1, y1, x2, y2 = map(float, input().split())
distance = ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** (1 / 2)
print(f"{distance:.5f}")
|
151fd7221f09f255b627331742894a9c52be571d | xov17/151lab1 | /testing_pickle/io_pickle.py | 779 | 3.734375 | 4 | import pickle
import hashlib
# The name of the file where we will store the object
shoplistfile = 'shoplist.data'
# The list of things to buy
shoplist = {'apple', 'mango', 'carrot'}
print 'shoplist:'
print(hashlib.md5(shoplist).hexdigest())
# Write to the file
f = open(shoplistfile, 'wb')
print 'f before dumping'
print(hashlib.md5(f).hexdigest())
# Dump the object to a file
pickle.dump(shoplist, f)
print 'f after dumping'
print(hashlib.md5(f).hexdigest())
f.close()
# Destroy the shoplist variable
del shoplist
# Read back from the storage
f = open(shoplistfile, 'rb')
print 'f after opening again'
print(hashlib.md5(f).hexdigest())
# Load the object from the file
storedlist = pickle.load(f)
print 'storedlist:'
print(hashlib.md5(storedlist).hexdigest())
print storedlist |
9997b9a6081529c8b8a3d13ec235f6c7dcbce608 | Rahulk990/TSP_Using_AI | /Others/City_Manager.py | 1,009 | 3.9375 | 4 | from typing import List
from Others.City import City
# Storing the cities data
cities: List[City] = []
distances: List[List[float]] = []
# Adding cities to the list
def addCity(city: City) -> None:
cities.append(city)
# Get a particular city
def getCity(index: int) -> City:
return cities[index]
# Get the total number of cities
def getLength() -> int:
return len(cities)
# Pre-Calculate distances between each pair of cities
def calculateDistances() -> None:
for start in cities:
distances_from_start = []
for end in cities:
xDiff = abs(start.getCity()[0] - end.getCity()[0])
yDiff = abs(start.getCity()[1] - end.getCity()[1])
distances_from_start.append((xDiff**2 + yDiff**2)**0.5)
distances.append(distances_from_start)
# Get distance between two cities
def getDistance(index_a: int, index_b: int) -> float:
return distances[index_a][index_b]
# Clearing the data
def clear():
cities.clear()
distances.clear()
|
3cff364a8b62eb39176e0941aefc42e40b560962 | zeumoweb/scaffold | /hello.py | 98 | 4 | 4 | def add(x, y):
return x + y
result = add(3, 6)
print(f"this is the sum of 3 and 6: {result}") |
a8ed504ae58b32c4a83c239fefad7af87904f48d | jtlai0921/MP31909_Example | /MP31909_Example/範例/RPi/EX2_9.py | 310 | 3.53125 | 4 | # Homework 2-9
import property as P
tc = P.house('apartment', 5600000, 'tclin','taichung')
money = P.deposit('money', 100000, 'taiwanBank')
stock = P.stock('tpower', 5, 20000)
total = [tc, money, stock]
sum = 0
for i in total:
sum = sum + i.getValue();
print("Total value of properties : {0}".format(sum))
|
6ff52cbc86b3fd7b395bf31e2d0495c05a4bdf3e | heart-bool/study-doc | /python-100-day/day07/map_demo.py | 755 | 4.3125 | 4 | """
字典:类似于java中的map。属于可变的容器,以键值对形式存储数据,可以存储任何对象。
"""
def main():
# 定义map
map1 = {1: 'a', 2: 'b', 3: 'c'}
print(map1)
# 以建取值
print(map1[1])
print(map1.get(2))
# 获取不存在的key,可以指定默认值,不指定时则返回None
print(map1.get(4))
print(map1.get(4, 'd'))
# 添加
# map1.update('4'= 'd')
# print(map1.items())
# 更新
map1[2] = 'D'
print(map1)
# 遍历
for key in map1:
print(key, ':', map1[key])
# 删除指定key元素
map1.pop(1)
print(map1)
# 删除最后一个元素
map1.popitem()
print(map1)
if __name__ == '__main__':
main()
|
dee76b56bec46ab1be23fba323ebe981ec43683f | CodeMuz/adventofcode | /day16/part1.py | 720 | 3.53125 | 4 | #!/usr/bin/python
output = {
'children': 3,
'cats': 7,
'samoyeds': 2,
'pomeranians': 3,
'akitas': 0,
'vizslas': 0,
'goldfish': 5,
'trees': 3,
'cars': 2,
'perfumes': 1
}
with open("input.txt") as f:
content = f.readlines()
def isMatch(prop):
for v in prop:
if prop[v] != output[v]:
return False
return True
for line in content:
lineArray = line.replace(",", "").replace(":", "").replace("\n", "").split(' ')
number = lineArray[1]
prop = {}
prop[lineArray[2]] = int(lineArray[3])
prop[lineArray[4]] = int(lineArray[5])
prop[lineArray[6]] = int(lineArray[7])
if isMatch(prop):
print number
print isMatch(prop) |
843ced7043f1897419c7c3c865654b108b89be74 | nato4ka1987/lesson5 | /part5.py | 683 | 3.90625 | 4 | '''
Создать (программно) текстовый файл, записать в него программно
набор чисел, разделенных пробелами. Программа должна
подсчитывать сумму чисел в файле и выводить ее на экран.
'''
FILENAME = "task5.txt"
NUMBERS = "12 7 87 935 0 32 71"
summ = 0
try:
with open(FILENAME, 'w') as fhs:
fhs.write(NUMBERS)
with open(FILENAME, 'r') as fhd:
data = fhd.read()
for item in data.split():
summ += float(item)
except IOError as e:
print(e)
except ValueError:
print("Error")
print(summ)
|
ed92627c5285eb87f82fa8aa4fd0012f5f765958 | kmayur9/vending-machine-console-app | /test.py | 3,118 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Mar 22 23:45:43 2021
@author: Amritbaan-0001
"""
import unittest
from vendingMachine import Product, Denomination, Cart
class TestSum(unittest.TestCase):
def setUp(self):
self.product = Product()
self.denomination = Denomination()
self.cart = Cart()
# self.vending_machine = VendingMachine()
# Product test cases
def test_add_product(self):
"""
Test that it is adding product
"""
self.product.add_product("Coke",5)
self.assertEqual(len(self.product.all_products), 1)
self.assertEqual(self.product.all_products[0].name, "Coke")
def test_remove_product(self):
self.product.add_product("Coke",5)
self.assertEqual(len(self.product.all_products), 1)
self.product.remove_product("Coke")
self.assertEqual(len(self.product.all_products), 0)
def test_reset(self):
self.product.add_product("Coke",5)
self.product.add_product("Lays",50)
self.assertEqual(len(self.product.all_products), 2)
self.product.reset()
self.assertEqual(len(self.product.all_products), 0)
#Denomination test case
def test_add_denomination(self):
"""
Test that it is adding product
"""
self.denomination.add_denomination(5)
self.assertEqual(len(self.denomination.all_denomination), 1)
self.assertEqual(self.denomination.all_denomination[0], 5)
def test_remove_denomination(self):
self.denomination.add_denomination(9)
self.assertEqual(len(self.denomination.all_denomination), 1)
self.denomination.remove_denomination(9)
self.assertEqual(len(self.denomination.all_denomination), 0)
def test_reset_denomination(self):
self.denomination.add_denomination(9)
self.denomination.add_denomination(99)
self.assertEqual(len(self.denomination.all_denomination), 2)
self.denomination.reset()
self.assertEqual(len(self.denomination.all_denomination), 0)
def test_add_to_cart(self):
prod = Product()
prod.name = "Pepsi"
prod.price = 55
self.cart.add_to_cart(prod)
self.assertEqual(self.cart.prod[0].name, "Pepsi")
self.assertEqual(len(self.cart.prod), 1)
self.assertEqual(self.cart.prod[0].price, 55)
self.assertEqual(self.cart.cart_value, 55)
def test_edit_cart(self):
prod = Product()
prod.name = "Pepsi"
prod.price = 55
self.cart.add_to_cart(prod)
self.assertEqual(self.cart.prod[0].name, "Pepsi")
self.assertEqual(len(self.cart.prod), 1)
self.cart.edit_order(prod.name)
self.assertEqual(len(self.cart.prod), 0)
self.assertEqual(self.cart.cart_value, 0)
if __name__ == '__main__':
unittest.main()
|
200e4dac548d5bbfe918c5cdc99c7cab5a950c87 | RufusKingori/Palindrome | /acronyms.py | 304 | 4.375 | 4 | #This program generates acronyms from a number of words entered.
words = input("Enter the words or the sentence to output the acronym:\n")
word_by_word = words.split()
print(word_by_word)
acronym = ""
for i in word_by_word:
acronym += i[0]
print("The acronym of '{}' is '{}'".format(words,acronym)) |
2d71944996405b47887add37ffc325831463c80b | ramyasutraye/Guvi_Python | /set9/81.py | 192 | 3.921875 | 4 | a=int(input("Enter kabali clan's members:"))
b=int(input("Enter the opponent clan's members:"))
if a<b:
print(b-a)
else:
print("Kabali's ninja number is never greater than his opponent.")
|
3136c450e0c8e2d2981e01277cc8fc5a2c0b38ea | miguel-alv1/cs321 | /Othello/othelloPlayers.py | 9,641 | 3.984375 | 4 | import othelloBoard
import math
from typing import Tuple, Optional
from collections import namedtuple
'''You should modify the chooseMove code for the ComputerPlayer
class. You should also modify the heuristic function, which should
return a number indicating the value of that board position (the
bigger the better). We will use your heuristic function when running
the tournament between players.
Feel free to add additional methods or functions.'''
class HumanPlayer:
'''Interactive player: prompts the user to make a move.'''
def __init__(self,name,color):
self.name = name
self.color = color
def chooseMove(self,board):
while True:
try:
move = eval('(' + input(self.name + \
': enter row, column (or type "0,0" if no legal move): ') \
+ ')')
if len(move)==2 and type(move[0])==int and \
type(move[1])==int and (move[0] in range(1,9) and \
move[1] in range(1,9) or move==(0,0)):
break
print('Illegal entry, try again.')
except Exception:
print('Illegal entry, try again.')
if move==(0,0):
return None
else:
return move
# https://courses.cs.washington.edu/courses/cse573/04au/Project/mini1/RUSSIA/Final_Paper.pdf
# We used the above paper as a reference for heuristics
def heuristic(board) -> int:
# Linearly combine our two heuristic functions to get a total heuristic value
return cornersCaptured(board) + mobilityScore(board)
def cornersCaptured(board):
# Return a score from -100 to 100 based on corners captured
max_corners = 0
min_corners = 0
if board.array[1][1] != 0:
if board.array[1][1] < 0:
max_corners += 1
else:
min_corners += 1
if board.array[1][8] != 0:
if board.array[1][8] < 0:
max_corners += 1
else:
min_corners += 1
if board.array[8][1] != 0:
if board.array[8][1] < 0:
max_corners += 1
else:
min_corners += 1
if board.array[8][8] != 0:
if board.array[8][8] < 0:
max_corners += 1
else:
min_corners += 1
if (max_corners + min_corners) != 0:
return 100*(max_corners - min_corners)/(max_corners + min_corners)
else:
return 0
def mobilityScore(board) -> int:
# Return a score of -100 to 100 bast on the relative amount of possible
# moves for the max and min players
max_score = len(legalMoves(board, othelloBoard.black))
min_score = len(legalMoves(board, othelloBoard.white))
if max_score + min_score != 0:
return 100*(max_score - min_score)/(max_score + min_score)
else:
return 0
def legalMoves(board,color):
moves = []
for i in range(1,othelloBoard.size-1):
for j in range(1,othelloBoard.size-1):
bcopy = board.makeMove(i,j,color)
if bcopy != None:
moves.append((i,j))
return moves
class ComputerPlayer:
'''Computer player: chooseMove is where the action is.'''
def __init__(self,name,color,heuristic,plies) -> None:
self.name = name
self.color = color
self.heuristic = heuristic
self.plies = plies
# chooseMove should return a tuple that looks like:
# (row of move, column of move, number of times heuristic was called)
# We will be using the third piece of information to assist with grading.
def chooseMove(self,board) -> Optional[Tuple[int,int,int]]:
'''This very silly player just returns the first legal move
that it finds.'''
numHeuristicCalls = 0
def maxValue(board, plies) -> Tuple[int,Tuple[int,int]]:
if plies == 0:
nonlocal numHeuristicCalls
numHeuristicCalls += 1
return (heuristic(board), None)
else:
moves = legalMoves(board, othelloBoard.black)
if len(moves) == 0:
return (board.scores()[0], None)
else:
best = -math.inf
best_move = None
for move in moves:
#tuple (best, move)
next_min = minValue(board.makeMove(move[0], move[1], othelloBoard.black), plies - 1)
if best < next_min[0]:
best = next_min[0]
best_move = move
return (best, best_move)
def minValue(board, plies) -> Tuple[int,Tuple[int,int]]:
if plies == 0:
#allow access to numHeuristic calls in parent function
nonlocal numHeuristicCalls
numHeuristicCalls += 1
return (heuristic(board), None)
else:
moves = legalMoves(board, othelloBoard.white)
if len(moves) == 0:
return (board.scores()[0], None)
else:
best = math.inf
best_move = None
for move in moves:
next_max = maxValue(board.makeMove(move[0], move[1], othelloBoard.white), plies - 1)
if best > next_max[0]:
best = next_max[0]
best_move = move
return (best, best_move)
if self.color == othelloBoard.white:
best_move = minValue(board, self.plies)[1]
if best_move:
return (best_move[0], best_move[1], numHeuristicCalls)
else:
# None is considered a pass
return None
else:
best_move = maxValue(board, self.plies)[1]
if best_move:
return (best_move[0], best_move[1], numHeuristicCalls)
else:
return None
class ComputerPlayerPruning:
'''Computer player (with pruning): chooseMove is where the action is.'''
def __init__(self,name,color,heuristic,plies) -> None:
self.name = name
self.color = color
self.heuristic = heuristic
self.plies = plies
# chooseMove should return a tuple that looks like:
# (row of move, column of move, number of times heuristic was called)
# We will be using the third piece of information to assist with grading.
def chooseMove(self,board) -> Optional[Tuple[int,int,int]]:
'''This very silly player just returns the first legal move
that it finds.'''
numHeuristicCalls = 0
# using named tuple as suggested by Dave
moveReturned = namedtuple("moveReturned", ["val", "move"])
def maxValue(board, plies, alpha, beta) -> Tuple[int,Tuple[int,int]]:
if plies == 0:
nonlocal numHeuristicCalls
numHeuristicCalls += 1
return moveReturned(heuristic(board), None)
else:
moves = legalMoves(board, othelloBoard.black)
if len(moves) == 0:
return moveReturned(board.scores()[0], None)
else:
best = -math.inf
best_move = None
for move in moves:
#tuple (best, move)
next_min = minValue(board.makeMove(move[0], move[1], othelloBoard.black), plies - 1, alpha, beta)
if best < next_min.val:
best = next_min.val
best_move = move
alpha = max(alpha, best)
if best >= beta:
return moveReturned(best, best_move)
return moveReturned(best, best_move)
def minValue(board, plies, alpha, beta) -> Tuple[int,Tuple[int,int]]:
if plies == 0:
#allow access to numHeuristic calls in parent function
nonlocal numHeuristicCalls
numHeuristicCalls += 1
return moveReturned(heuristic(board), None)
else:
moves = legalMoves(board, othelloBoard.white)
if len(moves) == 0:
return moveReturned(board.scores()[1], None)
else:
best = math.inf
best_move = None
for move in moves:
next_max = maxValue(board.makeMove(move[0], move[1], othelloBoard.white), plies - 1, alpha, beta)
if best > next_max.val:
best = next_max.val
best_move = move
beta = min(beta, best)
if best <= alpha:
return moveReturned(best, best_move)
return moveReturned(best, best_move)
if self.color == othelloBoard.white:
best_move = minValue(board, self.plies, -math.inf, math.inf).move
if best_move:
return (best_move[0], best_move[1], numHeuristicCalls)
else:
# None is considered a pass
return None
else:
best_move = maxValue(board, self.plies, -math.inf, math.inf).move
if best_move:
return (best_move[0], best_move[1], numHeuristicCalls)
else:
return None |
952e6c19fcd944bc48f180786c6fce0247f9d0c4 | ctc316/algorithm-python | /Lintcode/Ladder_all_G_OA/1627. Word Segmentation.py | 553 | 3.84375 | 4 | class Solution:
"""
@param s: the string
@param k: the k
@return: the answer
"""
def wordSegmentation(self, s, k):
res = []
i = 0
words = s.split(" ")
n = len(words)
while i < n:
line = words[i]
j = i + 1
while j < n:
if len(line) + len(words[j]) < k:
line += " " + words[j]
j += 1
else:
break
res.append(line)
i = j
return res |
caffa5d0aabc9ebb2a3cd4525fb32200c94081db | kaiix/algo | /kaiix/other/majority_element.py | 753 | 3.765625 | 4 | # https://leetcode.com/problems/majority-element/
def majorityElement2(nums):
counter = {}
for n in nums:
if n in counter:
counter[n] += 1
else:
counter[n] = 1
return max(counter, key=lambda x: counter[x])
# http://www.cs.utexas.edu/~moore/best-ideas/mjrty/index.html
def majorityElement(nums):
count = 0
candidate = None
for i in nums:
if count == 0:
candidate = i
count += 1
else:
if i == candidate:
count += 1
else:
count -= 1
if count > len(nums)/2+1:
break
return candidate
if __name__ == '__main__':
print majorityElement([2, 1, 3, 2, 2, 3])
|
97ab0f8bfa2f39543d0c4eaf7b6dee0e6d49243c | TARMAH/HACKER-RANK | /Interview Preparation Kit/Search/Pairs.py | 588 | 3.578125 | 4 |
# Complete the pairs function below.
def pairs(k, arr):
LIST = {}
count = 0
for element in arr:
if element in LIST:
count+=1
else:
LIST[element] = 1
if element+k in LIST:
count+=1
else:
LIST[element+k] = 1
return count
if __name__ == '__main__':
nk = input().split()
n = int(nk[0])
k = int(nk[1])
arr = list(map(int, input().rstrip().split()))
result = pairs(k, arr)
print(result)
|
d5d9d102c989082062539aa29fb60de9541b0c9a | UWPCE-PythonCert-ClassRepos/Wi2018-Online | /students/ChrisH/lesson04/file_lab_copy_file.py | 2,544 | 3.6875 | 4 | #!/usr/bin/env python3
# -----------------------------------------------------------
# file_lab_copy_file.py
# demonstrates basic file copying, using binary mode
# without using shutil, or the OS copy command
# -----------------------------------------------------------
import os
def check_file(fname, oper):
"""
Takes a file name and operation in the form 'w' or 'r'. Determines if the file exists
and prompts the user for confirmation action if needed.
:param fname: a file name & path
:param oper: 'w' if the file is to be written to, 'r' if it is to be read from
:return: False - if file not found(r) or user does not want to overwrite(w). True otherwise.
"""
if oper == 'r' and not os.path.isfile(fname):
print('Could not find file: {}'.format(fname))
return False
elif oper == 'w' and os.path.isfile(fname):
while True:
ans = input('File "{}" already exists, overwrite (Y/n):'.format(fname))
if ans == '' or ans.lower() == 'y':
break
else:
return False
return True
def bin_copyfile(file_in, file_out):
"""
Copies a file from file_in to file_out in 50 byte chunks. Returns bytes written, or False if
file checks fail.
:param file_in: file to read
:param file_out: file to write
:return: bytes written or False if unable to perform operation
"""
if not (check_file(file_in, 'r') and check_file(file_out, 'w')):
return False
total_bytes = 0
with open(file_in, 'rb') as file_in: # method removes need to have a file.close operation
with open(file_out, 'wb') as file_out:
while True:
buffer = file_in.read(50) # read file in 50 byte chunks
total_bytes += file_out.write(buffer)
if len(buffer) < 50 or buffer == '': # buffer will be empty at end of file, or have <50 bytes
break
return total_bytes
if __name__ == "__main__":
# tests for file read/write ability
assert check_file('shark.jpg','r') == True
assert check_file('sk.jpg','r') == False
assert check_file('shark_out.jpg', 'w') == True
assert check_file('sk.jpg', 'w') == True
# File copy tests.
files = [ ('./shark.jpg', './shark_out.jpg'), ('./hobbes_markov.txt', './hobbes_markov_out.txt')]
for file in files:
print("Copy file '{}' to '{}'".format(*file))
print("Bytes written: {:d}".format(bin_copyfile(*file)))
|
bf4d21e79b9d4dbaa39e394ad0b9739feb97e811 | abikg71/python37 | /CS1030/CS1030HWQ1.py | 2,838 | 3.921875 | 4 | '''
Abinet Kenore
CS1030 HW#6
Due for July 27, 2018
Instruction
Write a Python program named SalesTransaction.
This program should ask the user to enter the price
and name of purchased item. The program should then
compute the state and county sales tax. Assume the state sales tax
is 4 percent and the county sales tax is 2 percent.
The program should display the item name, price of the item,
the state sales tax, the county sales tax, the total sales tax,
and the total of the sale (which is the sum of the amount of
purchase plus the total sales tax).
Hint: Use the value 0.02 to represent 2 percent, and 0.04 to represent 4 percent.
'''
def main():
#Display program header
print("Well Come to this Store")
print("-----------------------------")
print("How many Items did you purchase")
choose = 0
while choose != 3:
print("Choose from the Options below")
print("1. One item only \n" "2. More than One item \n"
"3. To Exit the system \n")
choose = int(input())
if choose != 0:
if choose == 1:
sales_one_transaction()
elif choose == 2:
sales_more_transactions()
elif choose ==3:
print("You exit the System")
else:
print("The program will now exit\m"
"Have Good Day")
print("The program will now exit!")
def sales_one_transaction():
print()
print("Okay you purcchased only one item")
items = str(input("Enter the purchased Item name"))
price = float(input("Enter the price of purchased Item"))
tol_price = price
state_tax = 0.04 * price # states sales tax
county_tax = 0.02 * price #county sales tax
tol_tax = 0.06 *price
print("-" *50)
print("-" *50)
print("the item name ",items + "\nprice of the item ", price,
"\n the state sales tax " ,state_tax, "\n the county sales tax"
,county_tax, "\nthe total sales tax " , tol_tax,
"\nthe total of the sales price is " , tol_price)
print()
def sales_more_transactions():
#This def will need improvement and design change
print()
items_list = str(input("enter the list of items you bought" .split(",")))
print("You have purchased: " ,items_list)
pricess = input(("Please entner Student score list separated by ,"))
pricess= [int(x) for x in pricess.split(',')]
sum = 0
for number in pricess:
sum += number
state_tax = 0.04 * sum # states sales tax
county_tax = 0.02 * sum #county sales tax
tol_tax = 0.06 * sum
print("Total Amt paid is: ", sum)
print("the state sales tax " ,state_tax)
print("the county sales tax " ,county_tax)
print("the total sales tax " , tol_tax)
print("the total of the sales price is " , sum)
print()
main()
|
8242c6a6a72e232564359d65d9b56708d580ebc8 | hvaldez24/EDXnotes | /squares.py | 371 | 3.84375 | 4 | from functions import square
for i in range(10):
print(f"The square of {i} is {square(i)}")
#running this function ny itself will results in an Exception:
#Traceback (most recent call last):
#File "D:\Desktop\EDX Courses\EDXnotes\squares.py", line 2, in <module>
#print(f"The square of {i} is {square(i)}")
#NameError: name 'square' is not defined |
584195a64a494a2cdc12d089df7225c8d1c68f5f | logan-lach/Algos | /contains_dup.py | 949 | 3.53125 | 4 | def romanToInt( s: str) -> int:
roman = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000
}
value = 0
for i in range(len(s)):
if i < len(s) - 1 and s[i] == 'I':
if s[i + 1] == 'V':
value += 4
continue
elif s[i + 1] == 'X':
value += 9
continue
elif i < len(s) - 1 and s[i] == 'X':
if s[i + 1] == 'L':
value += 40
continue
elif s[i + 1] == 'C':
value += 90
continue
elif i < len(s) - 1 and s[i] == 'C':
if s[i + 1] == 'D':
value += 400
continue
elif s[i + 1] == 'M':
value += 900
continue
value += roman[s[i]]
return value
print(romanToInt('IV'))
|
4d6b0d9732e9c57342ad2773e4f237b9f7f3bb64 | JustSayHelloWorld/python-coding-marathon | /sprint_03_[Functions]/Task_5.py | 1,670 | 4.59375 | 5 | """Create decorator logger. The decorator should print to the console information about function's name and all its arguments separated with ',' for the function decorated with logger.
Create function concat with any numbers of any arguments which concatenates arguments and apply logger decorator for this function.
For example
print(concat(2, 3)) display
Executing of function concat with arguments 2, 3...
23
print(concat('hello', 2)) display
Executing of function concat with arguments hello, 2...
hello2
print(concat (first = 'one', second = 'two')) display
Executing of function concat with arguments one, two...
onetwo"""
def logger(func):
def wrapper(*args, **kwargs):
func_arguments = []
if len(args) > 0:
for each in args:
func_arguments.append(each)
if len(kwargs) > 0:
for each in kwargs:
func_arguments.append(kwargs[each])
function = func(*args, **kwargs)
print(f"Executing of function {func.__name__} with arguments", end=" ")
for i in range(len(func_arguments)):
if i < len(func_arguments) - 1:
print(func_arguments[i], end=", ")
else:
print(func_arguments[i], end="")
print("...")
return function
return wrapper
@logger
def sum(a, b):
return a + b
@logger
def print_arg(arg):
print(arg)
@logger
def concat(*args, **kwargs):
concated = ""
if len(args) > 0:
for each in args:
concated += str(each)
if len(kwargs) > 0:
for each in kwargs:
concated += str(kwargs[each])
return concated |
4d9595caa0e4b145990cfb230ab79a7d71044ede | aishwarya9879/python-learnings | /temp.py | 1,145 | 4.125 | 4 | #declare a method for even numbers
#declaring for loop with range from (0,25) even numbers
# if condition num==num%2 is 0
#print if above condition is True
#call above method in order to execute printing even numbers
def evennumbers():
for evennumber in range(0,25):
if 0==evennumber%2:
print("all even numbers",evennumber)
evennumbers()
#Indentation
# What is Indentation?
# Indentation is to make statements belong to a method or if condition or loops
# How to delcare indentation?
# Use a tab right after next line in the same column and start the line of instruction. So, that the
#instruction belongs to above line loop/method/ifcondition.
# What are advantages of indentation in PYTHON?
# In programming like C, Java, C++ ..developers use { , } (curly braces) to start a method and end a method or to
#start a if condition, end if condition or to start a loop(while,dowhile, for) or end the loop.
# But, here in python we will give indentation....instead of CURLY braces..So python executor will identify
# if the instrctions belong to method/loop/if conditions......
|
6acd8d45823d2f2215481537206147401e40dc0a | Iso-luo/python-assignment | /practice/Lab2/HWs.py | 2,944 | 4.25 | 4 | # -*- coding: utf-8 -*-
# !/usr/bin/env python
# @Time: 2020-05-06 6:18 p.m.
"""
Q1. Write a function called estimate_pi that uses this formula
to compute and return an estimate of π.
It should use a while loop to compute terms of the summation
until the last term is smaller than 1e- 15 (which is Python notation for 10−15).
You can check the result by comparing it to math.pi.
"""
from math import sqrt, pow, factorial, pi, exp, e
def estimate_pi():
a = 2 * sqrt(2) / 9801
k = 0
x = 0
y = 0.1 # Assign a number which bigger than 0 for y randomly!!!
while y > 1e-15:
y = factorial(4 * k) * (1103 + 26390 * k) / (pow(factorial(k), 4) * pow(396, (4 * k)))
x += y
k += 1
result = 1 / (a * x)
return result
# print(estimate_pi())
"""
Q2. Write a function that takes a string as an argument
and displays the letters backward, one per line.
"""
# method 1
def reverse_word(s):
s = list(s)
new_letter = []
for i in range(len(s)):
new_letter.append(s[-i - 1])
return "".join(new_letter)
# print(reverse_word("abcd"))
# print(reverse_word("abcdefg"))
# method2
def reverse_word2(s):
letter = []
[letter.append(i) for i in s[::-1]] # [::-1] traverse from back to front
return "".join(letter)
# print(reverse_word2("abcdf"))
"""
Q3. There is a string method called count. Read the documentation of this method
and write an invocation that counts the number of a(s)’ in 'banana'.
"""
def invocation():
s = "banana"
num = s.count("a", 0, len(s))
return num
# print(invocation())
"""
Q4. A step size of -1 goes through the word backwards,
so the slice [::-1] generates a reversed string.
Use this idiom to write a one-line version of is_palindrome from lab 1.
"""
def is_palindrome(s):
new_list = []
[new_list.append(i) for i in s[::-1]]
new_word = "".join(new_list)
if new_word == s: # the values of two strings are equal but addresses values are different
return True
return False
# print(is_palindrome("abcacba"))
# print(is_palindrome("redivider"))
"""
Q5
Write a function called has_no_e that returns True if the given word doesnt have the letter “e” in it.
Modify your program from the previous section to
print only the words that have no “e”
and compute the percentage of the words in the list have no “e.”
"""
# def has_no_e(word):
# if "e" not in word:
# return True
# return False
def has_no_e(word):
return not ("e" in word)
# print(has_no_e("word"))
def judge():
count = 0
total = 0
word_list = []
with open("/Users/a123/Desktop/words.txt", "r") as file:
for i in file:
if "e" not in i:
count += 1
word_list.append(i[:-1])
total += 1
print(("the percentage of having no 'e': {:.2%}".format(count / total)), "\n", "\n".join(word_list))
print(judge())
|
d94cce2031d0b2a40974911b37fb1124af34bf96 | KodairaTomonori/NLP100knock2015 | /Python/01set/part02.py | 215 | 3.53125 | 4 | #coding: UTF-8
#文字列の連結
if __name__ == "__main__":
sample1 = u"パトカー"
sample2 = u"タクシー"
ans = u""
for i in range(0, len(sample1) ):
ans += sample1[i] + sample2[i]
print ans |
e9d5e16418061d1aa6a011511e4a0ec98376b320 | cassiobotaro/rivendell | /cv/rectangles.py | 757 | 3.78125 | 4 | # Module to draw rectangles in the image
import cv2
image = cv2.imread('lena.jpg')
# Creates a blue rectangle over the entire width of the image
image[30:50, :] = (255, 0, 0)
# Creates a red square
image[100:150, 50:100] = (0, 0, 255)
# Created a yellow rectangle all over the image height
image[:, 200:220] = (0, 255, 255)
# Creates a green rectangle from line 150 to 300 on columns 250 to 350
image[150:301, 250:351] = (0, 255, 0)
# Creates a cyan square from line 300 to 400 on columns 50 to 150
image[300:401, 50:251] = (255, 255, 0)
# Creates a white square
image[250:350, 300:400] = (255, 255, 255)
# Creates a black rectangle
image[70:100, 300: 450] = (0, 0, 0)
cv2.imshow('Altered image', image)
cv2.imwrite('rectangles.jpg', image)
cv2.waitKey(0)
|
1bfff77bf672a02fc2aff007142f40dc139587c7 | ParsaYadollahi/leetcode | /remove_duplicates_from_unsorted_LL.py | 1,114 | 3.828125 | 4 | '''
Remove duplicates from an unsorted linked list - CTCI #2.1
'''
class LinkedList:
def __init__(self):
self.head = None
class Node:
def __init__(self, val=None):
self.val = val
self.next = None
class Solution:
def remove_duplicates_from_LL(self, head):
first_node = head
dic = {}
prev = head
dic.setdefault(head.val, 1)
head = head.next
while (head != None):
# print(head.val)
if (head.val not in dic):
dic.setdefault(head.val, 1)
prev = head
head = head.next
else:
prev.next = head.next
head = head.next
def print_ll(self, head):
while (head != None):
print(head.val)
head = head.next
ll = LinkedList()
ll.head = Node(1)
n2 = Node(3)
n3 = Node(2)
n4 = Node(4)
n5 = Node(3)
n6 = Node(4)
n7 = Node(5)
ll.head.next = n2
n2.next = n3
n3.next = n4
n4.next = n5
n5.next = n6
n6.next = n7
s = Solution()
s.remove_duplicates_from_LL(ll.head)
s.print_ll(ll.head)
|
4dfcb6338fcf18c103a6a72bf207d8dc76f7a7bc | thebazman1998/School-Projects | /Grade 10/Unit 1/Bp_U1_Assignment7/Bp_U1_Assignment7_V1.py | 491 | 3.984375 | 4 | def compare( x, y ):
if x < y:
print x, "is less than", y
elif x > y:
print x, "is greater than", y
else:
print x, "and", y, "are equal"
def isVowel( character ):
if character == "a" or "e" or "i" or "o" or "u" or "A" or "E" or "I" or "O" or "U":
print character, "is a vowel"
elif character == "y" or "Y":
print character, "is sometimes a vowel"
else:
print character, "is a consonant"
isVowel("i") |
3051f773171c91cf8ed231c931073aba8c2c1fcf | ffiiccuuss/torouterui | /torouterui/netif.py | 14,488 | 3.59375 | 4 | """
Helper functions for working with network interfaces and network configuration
(including WiFi).
"""
import os
import augeas
from torouterui import app
from util import *
def parse_ip(ifname):
"""
Calls the ``ip`` command and parse the output to collect current status
information about a given network interface (specified by ifname argument).
Returns a dictionary, notably always including a 'state' string value.
If the interface can not be found at all, raises a KeyError.
Example ``ip link show`` string:
2: eth0: <BROADCAST,MULTICAST> mtu 1500 qdisc pfifo_fast state DOWN mode DEFAULT qlen 1000
link/ether 00:12:34:56:78:90 brd ff:ff:ff:ff:ff:ff
"""
d = dict()
ipinfo = cli_read_lines('ip addr show %s' % ifname)
if 0 == len(ipinfo):
raise KeyError('No such interface: ' + ifname)
iplinkl = ipinfo[0].split()
d['ifname'] = iplinkl[1][:-1]
val_indexes = {'mtu': 3, 'qdisc': 5, 'state': 7, 'mode': 9, 'qlen': 11}
for k, v in val_indexes.iteritems():
if len(iplinkl) > v and iplinkl[v] == k:
d[k] = iplinkl[v+1]
if 'LOWER_UP' in iplinkl[2][1:-1].split(","):
d['state'] = "RUNNING"
elif 'NO-CARRIER' in iplinkl[2][1:-1].split(","):
d['state'] = "DISCONNECTED"
d['ipv4addrs'] = list()
d['ipv6addrs'] = list()
for l in ipinfo[1:]:
# iterate through the address lines
l = l.split()
if l[0] == "link/ether":
d['mac'] = l[1]
elif l[0] == "inet":
d['ipv4addrs'].append(dict(
addr=l[1].split('/')[0],
prefix=int(l[1].split('/')[1]),
mask=prefix_to_ipv4_mask(int(l[1].split('/')[1])),
scope=l[5]))
elif l[0] == "inet6":
d['ipv6addrs'].append(dict(
addr=l[1].split('/')[0],
prefix=int(l[1].split('/')[1]),
scope=l[3]))
return d
def parse_iw(ifname):
"""
Calls the ``iw`` command and parse the output to collect current status
information about a given network interface (specified by ifname argument).
Returns a dictionary, notably always including a 'radio_state' string
value.
If the interface can not be found at all, raises a KeyError.
Example `iw dev wlan0 link` string (sic):
Connected to c0:25:06:51:22:9b (on wlan0)
SSID: fleischfressendepflanze
freq: 2427
RX: 73744193 bytes (456838 packets)
TX: 3269174 bytes (19709 packets)
signal: -44 dBm
tx bitrate: 72.2 MBit/s MCS 7 short GI
bss flags:
dtim period: 0
beacon int: 100
"""
d = dict()
iwinfo = cli_read_lines('iw dev %s link' % ifname)
if 0 == len(iwinfo):
raise KeyError('No such interface: ' + ifname)
if iwinfo[0].strip() == "Not connected.":
d['radio_state'] = "disabled"
return d
else:
d['radio_state'] = "enabled"
for l in iwinfo:
l = l.strip()
if l.startswith("SSID:"):
d['ssid'] = l[6:].strip()
elif l.startswith("freq:"):
d['freq'] = "%sMHz" % l.split()[-1].strip()
elif l.startswith("signal:"):
d['signal_dbm'] = l.split()[1]
elif l.startswith("tx bitrate:"):
d['signal_throughput'] = ' '.join(l.split()[2:4])
return d
def parse_uaputl():
"""
Calls the ``uaputl`` command and parses the output to collect current
status information about a DreamPlug WiFi uap device.
Returns a dictionary, notably always including a 'state' string value.
Example `uaputl sys_config` string (sic):
AP settings:
SSID = torproject
Basic Rates = 0x82 0x84 0x8b 0x96
Non-Basic Rates = 0xc 0x12 0x18 0x24 0x30 0x48 0x60 0x6c
AP MAC address = 00:66:66:66:66:66
Beacon period = 100
DTIM period = 1
Tx power = 13 dBm
SSID broadcast = enabled
Preamble type = short
Rx antenna = A
Tx antenna = A
Radio = on
Firmware = handles intra-BSS packets
RTS threshold = 2347
Fragmentation threshold = 2346
Tx data rate = auto
STA ageout timer = 1800
WEP KEY_0 = 00 00 00 00 00
Default WEP Key = 0
WEP KEY_1 = 00 00 00 00 00
WEP KEY_2 = 00 00 00 00 00
WEP KEY_3 = 00 00 00 00 00
AUTHMODE = Open authentication
Filter Mode = Filter table is disabled
PROTOCOL = No security
Max Station Number = 8
Retry Limit = 7
Channel = 6
Channel Select Mode = Manual
Channels List = 1 2 3 4 5 6 7 8 9 10 11
MCBC data rate = auto
Group re-key time = 86400 second
KeyMgmt = PSK
PairwiseCipher = None
GroupCipher = None
WPA passphrase = None
802.11D setting:
State = disabled
Dot11d = country code is not set.
Bad address
ERR:UAP_POWER_MODE is not supported by uap0
"""
d = dict()
uapinfo = cli_read_lines('uaputl sys_config')
if 0 == len(uapinfo):
raise Exception('problem reading uaputl configuration')
for l in uapinfo:
l = l.strip()
if l.startswith("Radio ="):
d['radio_state'] = l[8:].strip()
if l.startswith("AUTHMODE ="):
d['auth_mode'] = l[10:].strip()
if l.startswith("SSID ="):
d['ssid'] = l[7:].strip()
if l.startswith("SSID broadcast ="):
d['ssid_broadcast'] = l[17:].strip()
elif l.startswith("Channel ="):
d['channel'] = l[10:].strip()
elif l.startswith("Tx power ="):
d['tx_power'] = l[11:].strip()
elif l.startswith("Tx data rate ="):
d['data_rate'] = l[15:].strip()
if d['radio_state'] == 'on':
d['state'] = "ENABLED"
return d
def read_augeas_ifinfo(ifname):
d = dict()
aug = augeas.Augeas(flags=augeas.Augeas.NO_MODL_AUTOLOAD)
aug.set("/augeas/load/Interfaces/lens", "Interfaces.lns")
aug.set("/augeas/load/Interfaces/incl", "/etc/network/interfaces")
aug.load()
for iface in aug.match("/files/etc/network/interfaces/iface"):
if aug.get(iface) == ifname:
if aug.get(iface + "/family") == 'inet':
d['ipv4method'] = aug.get(iface + "/method")
if d['ipv4method'] == 'manual':
d['ipv4method'] = 'disabled'
d['ipv4addr'] = aug.get(iface + "/address")
d['ipv4netmask'] = aug.get(iface + "/netmask")
d['ipv4gateway'] = aug.get(iface + "/gateway")
d['ipv4mtu'] = aug.get(iface + "/mtu")
d['ipv4mac'] = aug.get(iface + "/hwaddress")
elif aug.get(iface + "/family") == 'inet6':
# handle ipv6 stuff
pass
aug.close()
return d
aug.close()
return None
def write_augeas_ifinfo(ifname, settings, method='disabled'):
d = dict()
aug = augeas.Augeas(flags=augeas.Augeas.NO_MODL_AUTOLOAD)
aug.set("/augeas/load/Interfaces/lens", "Interfaces.lns")
aug.set("/augeas/load/Interfaces/incl", "/etc/network/interfaces")
aug.load()
path = None
for iface in aug.match("/files/etc/network/interfaces/iface"):
if aug.get(iface) == ifname and aug.get(iface + "/family") == 'inet':
path = iface
if not path:
# insert iface
if len(aug.match("/files/etc/network/interfaces/iface")) == 0:
# no interfaces at all, insert wherever
path = "/files/etc/network/interfaces/iface"
aug.set(path, ifname)
else:
aug.insert("/files/etc/network/interfaces/iface", "iface",
before=False)
path = aug.match("/files/etc/network/interfaces/iface")[-1]
aug.set(path, ifname)
assert path, "require path to be set"
aug.set(path + "/family", 'inet')
if method == 'disabled':
aug.set(path + "/method", 'manual')
aug.remove(path + "/address")
aug.remove(path + "/netmask")
aug.remove(path + "/gateway")
elif method == 'dhcp':
aug.set(path + "/method", 'dhcp')
aug.remove(path + "/address")
aug.remove(path + "/netmask")
aug.remove(path + "/gateway")
elif method == 'static':
aug.set(path + "/method", 'static')
aug.set(path + "/address", str(settings['ipv4addr']))
aug.set(path + "/netmask", str(settings['ipv4netmask']))
if settings.has_key('ipv4gateway'):
aug.set(path + "/gateway", str(settings['ipv4gateway']))
else:
raise ValueError("unrecognized network interface method: " + method)
print "committing with augeas..."
aug.save()
print "augeas errors: %s" % aug.get("/augeas/error")
aug.close()
def read_augeas_dnsmasq(interface):
"""
interface arg should be one of lan or wifi
"""
d = dict()
aug = augeas.Augeas(flags=augeas.Augeas.NO_MODL_AUTOLOAD)
aug.set("/augeas/load/Interfaces/lens", "Dnsmasq.lns")
aug.set("/augeas/load/Interfaces/incl", "/etc/dnsmasq.d/%s" % interface)
aug.load()
dhcp_range = aug.get("/files/etc/dnsmasq.d/%s/dhcp-range" % interface)
if dhcp_range and len(dhcp_range.split(',')) == 4:
d['dhcpbase'] = dhcp_range.split(',')[0]
d['dhcptop'] = dhcp_range.split(',')[1]
d['dhcpnetmask'] = dhcp_range.split(',')[2]
d['dhcptime'] = dhcp_range.split(',')[3]
aug.close()
return d
def write_augeas_dnsmasq(interface, form):
"""
interface arg should be one of lan or wifi
"""
aug = augeas.Augeas(flags=augeas.Augeas.NO_MODL_AUTOLOAD)
aug.set("/augeas/load/Interfaces/lens", "Dnsmasq.lns")
aug.set("/augeas/load/Interfaces/incl", "/etc/dnsmasq.d/%s" % interface)
aug.load()
dhcp_range = ','.join([form['dhcpbase'],
form['dhcptop'],
form['dhcpnetmask'],
form['dhcptime']])
print dhcp_range
aug.set("/files/etc/dnsmasq.d/%s/dhcp-range" % interface, str(dhcp_range))
print "committing with augeas..."
aug.save()
print "augeas errors: %s" % aug.get("/augeas/error")
aug.close()
return
def get_wan_status(ifname=None):
if not ifname:
# grab configuration at run time, not earlier
ifname = app.config['WAN_IF']
d = dict()
try:
d.update(parse_ip(ifname))
except KeyError:
return None
return d
def get_lan_status(ifname=None):
if not ifname:
# grab configuration at run time, not earlier
ifname = app.config['LAN_IF']
d = dict()
try:
d.update(parse_ip(ifname))
except KeyError:
return None
return d
def get_wifi_status(ifname=None):
if not ifname:
# grab configuration at run time, not earlier
ifname = app.config['WIFI_IF']
d = dict()
try:
d.update(parse_ip(ifname))
except KeyError, ke:
return None
if ifname.startswith('wlan'):
d.update(parse_iw(ifname))
else:
d.update(parse_uaputl())
return d
def get_wan_settings(ifname=None):
if not ifname:
# grab configuration at run time, not earlier
ifname = app.config['WAN_IF']
return read_augeas_ifinfo(ifname)
def save_wan_settings(form, ifname=None):
if not ifname:
# grab configuration at run time, not earlier
ifname = app.config['WAN_IF']
write_augeas_ifinfo(ifname, method=form['ipv4method'], settings=form)
if form['ipv4method'] == 'disabled':
print "ifdown..."
os.system("ifdown %s" % ifname)
else:
print "ifup..."
os.system("ifdown %s" % ifname)
os.system("ifup %s &" % ifname)
def get_lan_settings(ifname=None):
if not ifname:
# grab configuration at run time, not earlier
ifname = app.config['LAN_IF']
d = read_augeas_ifinfo(ifname)
d['ipv4enable'] = bool(d['ipv4method'] != 'manual') and 'true'
d.update(read_augeas_dnsmasq('lan'))
return d
def save_lan_settings(form, ifname=None):
if not ifname:
# grab configuration at run time, not earlier
ifname = app.config['LAN_IF']
if form.get('ipv4enable') != 'true':
write_augeas_ifinfo(ifname, method='disabled', settings=form)
print "ifdown..."
os.system("ifdown %s" % ifname)
else:
write_augeas_ifinfo(ifname, method='static', settings=form)
print "ifup..."
os.system("ifdown %s" % ifname)
os.system("ifup %s &" % ifname)
write_augeas_dnsmasq('lan', form)
os.system("/etc/init.d/dnsmasq reload &")
def get_wifi_settings(ifname=None):
if not ifname:
# grab configuration at run time, not earlier
ifname = app.config['WIFI_IF']
d = dict()
ifinfo = read_augeas_ifinfo(ifname)
print "ifinfo: %s" % ifinfo
if ifinfo:
d.update(ifinfo)
d.update(read_augeas_dnsmasq('wifi'))
return d
def save_wifi_settings(ifname=None):
if not ifname:
# grab configuration at run time, not earlier
ifname = app.config['WIFI_IF']
# TODO: need to go in to deep interfaces action here...
if form.get('wifienable') != 'true':
write_augeas_ifinfo(ifname, method='disabled', settings=form)
print "ifdown..."
os.system("ifdown %s" % ifname)
else:
write_augeas_ifinfo(ifname, method='static', settings=form)
print "ifup..."
os.system("ifdown %s" % ifname)
os.system("ifup %s &" % ifname)
write_augeas_dnsmasq('wifi', form)
os.system("/etc/init.d/dnsmasq reload &")
pass
def is_valid_ipv4(s):
# TODO: this is a hack
l = s.split('.')
if not len(l) == 4:
return False
try:
l = map(int, l)
except ValueError:
return False
if l[0] > 255 or l[1] > 255 or l[2] > 255 or l[3] > 255:
return False
if l[0] == 0 or l[3] == 0:
return False
return True
def is_valid_ipv4mask(s):
# TODO: this is a hack
l = s.split('.')
if not len(l) == 4:
return False
try:
l = map(int, l)
except ValueError:
return False
if l[0] > 255 or l[1] > 255 or l[2] > 255 or l[3] > 255:
return False
return True
|
705042d8008f6639f73e0f8c17cc1f52026002b7 | Ran-oops/python | /1python基础/01 Python基础/09/tuple2.py | 679 | 4.3125 | 4 | #序列操作
'''
#加法
tuple1 = ('王泽东','王泽西','王泽南','王泽北')
tuple2 = ('王泽左','王泽右','王泽前','王泽后')
result = tuple1 + tuple2
print(result)
#乘法
tuple1 = ('男学生','女学生')
result = tuple1 * 5
print(result)
#索引
tuple1 = ('西施','貂蝉','王昭君','杨玉环')
print(tuple1[2])
'''
#分片
tuple1 = ('吕布','许褚','典韦','关羽','张飞','赵云')
print(tuple1[2:5])
print(tuple1[:5])
print(tuple1[2:])
print(tuple1[:])
print(tuple1[1::2])
#成员检测
tuple1 = ('小鸡','小鸭','小鹅','小鸟')
result = '小鸡' in tuple1
print(result)
result = '小鸭鸭' not in tuple1
print(result)
|
c7f898f5a88bae4bae31478182410bb32992cbf1 | varshakohirkar/python-learning | /strings.py | 236 | 3.75 | 4 | shoppinglist="milk,carrots,apples,eggs,water"
p=shoppinglist[2]
print(p)
shoppinglist1=["milk","carrots","apples","eggs","water"]
s=shoppinglist1[3]
print(s)
shoppinglist1[3]="chocolates"
print(shoppinglist1)
print(shoppinglist1[4])
|
853ab80a3b0b6b2b581f5c5acd4fec9b0939f7c2 | RajParab/100DaysOfAlgo | /Day 75/BinToInt.py | 310 | 3.625 | 4 | #Question - https://leetcode.com/problems/convert-binary-number-in-a-linked-list-to-integer
class Solution:
def getDecimalValue(self, head: ListNode) -> int:
num=''
while head:
num+=str(head.val)
head=head.next
ans=int(num,2)
return ans |
923444d720920c19754debbaf4257583677990cf | chloechao/coursera | /2048/merge.py | 780 | 4.03125 | 4 | #!/usr/bin/python
def merge(line):
"""
Function that merges a single row or column in 2048.
"""
new_line = []
#removed all zero item
new_line += [ item for item in line if item != 0 ]
#replaced with a tile of twice the value
index = 0
while index < len(new_line)-1:
if new_line[index] == new_line[index+1]:
new_line[index] = int(new_line[index]) * 2
new_line.pop(index+1)
index += 1
#appended zero to the new list
new_line += [ 0 for i in range(len(new_line),len(line)) ]
return new_line
list0=[2, 0, 2, 4]
list1=[0, 0, 2, 2]
list2=[2, 2, 0, 0]
list3=[2, 2, 2, 2, 2]
list4=[8, 16, 16, 8]
print merge(list0)
print merge(list1)
print merge(list2)
print merge(list3)
print merge(list4)
|
60e01f4b137b1f8846237936669ed643fee588e6 | jpmacveigh/WCS-AROME-PYTHON | /distanceOrthodromique.py | 1,165 | 3.828125 | 4 | import math
def distanceOrthodromique (rlonb,rlatb,rlonc,rlatc):
'''
c J.P. Mac Veigh le 27/2/88
c Calcul de la distance (m) orthodromique entre deux points B et C de la surface
c de la terre définis par leur latitude et longitude.
c On résoud le triangle sphérique formé par les deux points et le pôle
c nord et dont on connait deux côtés (les compléments des latitudes
c des deux points) et l'angle compris (la différence des longitudes des
c deux points).
c Référence: Cours d'Astronomie
c H. Andoyer
c première partie, troisième édition, page 24
c Librairie Scientifique J. Hermann, 1923.
*/'''
if rlonb==rlonc and rlatb==rlatc : return 0.
r=6366.2031 # rayon de la terre en km
pi=math.pi
a=(rlonc-rlonb)*(pi/180)
rc=(pi/2)-(rlatb*pi/180)
rb=(pi/2)-(rlatc*pi/180)
x=math.cos(rb)*math.cos(rc)+math.sin(rb)*math.sin(rc)*math.cos(a)
if x>1. : x=1.
elif x<-1.: x=-1.
ra=math.acos(x)
d=ra*r
return 1000.*abs(d) # retour en mètres
#print (distanceOrthodromique(0.,0.,1.,0.)) |
4f2c2666e1bf10b1323ac55c5f431e258b391929 | momentum-cohort-2019-09/examples-mystery-word | /mystery_word_test.py | 3,021 | 3.546875 | 4 | import mystery_word as m
def test_display_word_uppercase():
assert m.display_word(word="FEATHEREDGED",
guesses=['F', 'D']) == "F _ _ _ _ _ _ _ D _ _ D"
assert m.display_word(word="CAT", guesses=['C']) == "C _ _"
def test_display_word_lowercase():
assert m.display_word(word="featheredged",
guesses=['f', 'd']) == "F _ _ _ _ _ _ _ D _ _ D"
def test_display_word_mixedcase():
assert m.display_word(word="featheredged",
guesses=['F', 'D']) == "F _ _ _ _ _ _ _ D _ _ D"
def test_display_word_all_guesses():
assert m.display_word(word="CAT", guesses=['C', 'A', 'T']) == "C A T"
def test_is_valid_letter_good_input():
assert m.is_valid_letter("c")
assert m.is_valid_letter("Z")
def test_is_valid_letter_multiple_letters():
assert not m.is_valid_letter("cn")
def test_is_valid_letter_empty_string():
assert not m.is_valid_letter("")
def test_is_valid_letter_with_nonletters():
assert not m.is_valid_letter("1")
assert not m.is_valid_letter('!')
def test_has_been_guessed():
assert m.has_been_guessed("A",
correct_guesses=["A", "T"],
incorrect_guesses=["D"])
assert m.has_been_guessed("A",
correct_guesses=["T"],
incorrect_guesses=["A", "D"])
def test_has_been_guessed_false():
assert not m.has_been_guessed(
"A", correct_guesses=["T", "Z"], incorrect_guesses=["D"])
def test_game_can_be_made():
game = m.Game(word="beluga")
assert game.word == "beluga"
assert len(game.correct_guesses) == 0
assert len(game.incorrect_guesses) == 0
def test_game_is_not_over_if_no_guesses():
game = m.Game(word="beluga")
assert not game.is_game_over()
def test_game_over_from_incorrect_guesses():
game = m.Game(word="beluga")
game.incorrect_guesses = ["c", "d", "f", "h", "i", "j", "k", "m"]
assert game.is_game_over()
game.incorrect_guesses.append("z")
assert game.is_game_over()
def test_game_over_from_correct_guesses():
game = m.Game(word="beluga")
game.correct_guesses = ["b", "e", "l", "u", "g", "a"]
assert game.is_game_over()
def test_have_all_letters_been_guessed_true():
game = m.Game(word="beluga")
game.correct_guesses = ["b", "e", "l", "u", "g", "a"]
assert game.have_all_letters_been_guessed()
def test_add_guess_adds_correct_guess():
game = m.Game(word="beluga")
game.add_guess("b")
assert len(game.correct_guesses) == 1
assert len(game.incorrect_guesses) == 0
def test_add_guess_adds_correct_guess_case_insensitive():
game = m.Game(word="beluga")
game.add_guess("B")
assert len(game.correct_guesses) == 1
assert len(game.incorrect_guesses) == 0
def test_add_guess_adds_incorrect_guess():
game = m.Game(word="beluga")
game.add_guess("d")
assert len(game.correct_guesses) == 0
assert len(game.incorrect_guesses) == 1
|
67bc7687e6b5534794bb6430e64126ce1782c71e | Tedigom/Alghorithm_practice | /180222_Q01.py | 1,031 | 3.765625 | 4 | # -*- coding: utf-8 -*-
# python3 180222_Q01.py
'''
1. map() 함수
map(f, iterable)은 함수 (f)와 반복 가능한(iterable) 자료형을 입력받는다.map은 입력받은
자료형의 각 요소가 함수 f에 의해 수행된 결과를 묶어서 리턴하는 함수이다.
def two_times(numberList):
result = [ ]
for number in numberList:
result.append(number*2)
return result
result = two_times([1, 2, 3, 4])
print(result)
이와 같은 형태의 코드를
def two_times(x): return x*2
list(map(two_times,[1,2,3,4]))
형태로 바꿀 수 있다.
2. split() 함수
a = "I have a dog"
a.split() # ['I','have','a','dog']
형태로 나누어준다.
b = "1:2:3:4"
b.split(':') #['1','2','3','4']
'''
'''
문제 : 두 수 A와 B를 입력받은 다음, A+B를 출력하는 프로그램을 작성하시오.
'''
# a = input("a 를 입력하세요")
# b = input("b 를 입력하세요")
# print(int(a)+int(b))
# 를 아래와 같이 변형할 수 있다.
a,b = map(int, input().split())
print(a+b)
|
d79fe96ed14a061ff081367f9228760233ac5476 | litsdm/Tweet-Generator | /challenges/anagram_generator.py | 392 | 3.78125 | 4 | from itertools import permutations
import sys
import dictionary_words
def generate_anagrams():
word = sys.argv[1]
perms = [''.join(p) for p in permutations(word)]
possible_words = set(perms)
dict_words = dictionary_words.read_words()
all_words = set(dict_words)
return possible_words & all_words
if __name__ == '__main__':
print ' '.join(generate_anagrams())
|
468f51c8e283b1cb9b8da17ede79d2f66a159344 | Jcazub/AutomateTheBoringStuffProjects | /commaCode.py | 336 | 3.78125 | 4 |
def convertToSentence(passedList):
sentence = ""
for i in range(len(passedList)):
if i == len(passedList) - 1:
sentence += "and " + str(passedList[i])
else:
sentence += str(passedList[i]) + ", "
return sentence
print(convertToSentence(['spam','eggs','bacon', 'orange juice'])) |
1e2ca5e17317be0b6bd953da01b8c6b43bd77003 | jsebastiansalazar7/ai-algorithms | /Tree.py | 2,028 | 4.03125 | 4 | __author__ = 'Juan Sebastian Salazar Aguirre'
## TREE STRUCTURE
## Definition of the class Nodo
class Nodo:
## Define constructor of the class
## It receives a data to store on a node and optionally a list of children
def __init__(self, datos, hijos = None):
self.datos = datos
self.hijos = None
self.padre = None
self.coste = None
self.setHijos(hijos)
## Define method to set children
## Assigns a list of children to the node
def setHijos(self, hijos):
self.hijos = hijos
if self.hijos != None:
for h in self.hijos:
h.padre = self
## Define method to get children
## Returns a list with the children of the node
def getHijos(self):
return self.hijos
## Define method to get the father
## Returns the parent node
def getFather(self):
return self.padre
## Define method to set father
## Assigns the parent node of the current node
def setPadre(self, padre):
self.padre = padre
## Define method to set data
## Assigns a data to the current node
def setDatos(self, datos):
self.datos = datos
## Define method to get data
## Return the stored data of the node
def getDatos(self):
return self.datos
## Define method to set cost
## Define a weight for the node in the tree
def setCoste(self, coste):
self.coste = coste
## Define method to get cost
## Return the weight of the node in the tree
def getCoste(self):
return self.coste
## Define method
def igual(self, nodo):
if self.getDatos() == nodo.getDatos():
return True
else:
return False
## Define method
def isListed(self, listaNodos):
Listed = False
for n in listaNodos:
if self.igual(n):
Listed = True
return Listed
## Define method
def __str__(self):
return str(self.getDatos())
|
5d56344089c054ad6e29e661dcee5dfde4ba4532 | nishizumi-lab/sample | /python/basic/time/datetime/date_year.py | 224 | 3.875 | 4 | # -*- coding: utf-8 -*-
import datetime as dt
def main():
date = dt.datetime(2017, 1, 1, 0, 0)
for i in range(365):
print(date)
date += dt.timedelta(days=1)
if __name__=='__main__':
main()
|
3617c7182fae78b685925265137b0f6afe6bfee3 | IrinaAg/training_projects_python | /lesson_004/02_global_color.py | 2,897 | 3.875 | 4 | # -*- coding: utf-8 -*-
import simple_draw as sd
# Добавить цвет в функции рисования геом. фигур. из упр lesson_004/01_shapes.py
# (код функций скопировать сюда и изменить)
# Запросить у пользователя цвет фигуры посредством выбора из существующих:
# вывести список всех цветов с номерами и ждать ввода номера желаемого цвета.
# Потом нарисовать все фигуры этим цветом
# Пригодятся функции
# sd.get_point()
# sd.line()
# sd.get_vector()
# и константы COLOR_RED, COLOR_ORANGE, COLOR_YELLOW, COLOR_GREEN, COLOR_CYAN, COLOR_BLUE, COLOR_PURPLE
# Результат решения см lesson_004/results/exercise_02_global_color.jpg
def draw_figure(point, angle, start_angle, length):
for angle in range(0, 360 - angle, angle):
v = sd.get_vector(start_point=point, angle=angle + start_angle, length=length, width=3)
v.draw(color=color)
point = v.end_point
sd.line(start_point=point, end_point=point_0, color=color, width=3)
def triangle(point, start_angle, length=100):
draw_figure(point=point, angle=120, start_angle=start_angle, length=length)
def square(point, start_angle, length=100):
draw_figure(point=point, angle=90, start_angle=start_angle, length=length)
def pentagon(point, start_angle, length=100):
draw_figure(point=point, angle=72, start_angle=start_angle, length=length)
def hexagon(point, start_angle, length=100):
draw_figure(point=point, angle=60, start_angle=start_angle, length=length)
colors = {
'0': {'color_name': 'red', 'sd_name': sd.COLOR_RED},
'1': {'color_name': 'orange', 'sd_name': sd.COLOR_ORANGE},
'2': {'color_name': 'yellow', 'sd_name': sd.COLOR_YELLOW},
'3': {'color_name': 'green', 'sd_name': sd.COLOR_GREEN},
'4': {'color_name': 'cyan', 'sd_name': sd.COLOR_CYAN},
'5': {'color_name': 'blue', 'sd_name': sd.COLOR_BLUE},
'6': {'color_name': 'purple', 'sd_name': sd.COLOR_PURPLE}
}
print('Возможные цвета:')
for code, val in colors.items():
print(code, ':', val['color_name'])
while True:
user_input = input('Введите желаемый цвет >')
if user_input in colors:
color = colors[user_input]['sd_name']
break
else:
print("Вы ввели некорректный номер")
point_0 = sd.get_point(150, 130)
triangle(point=point_0, start_angle=25, length=100)
point_0 = sd.get_point(400, 130)
square(point=point_0, start_angle=25, length=100)
point_0 = sd.get_point(150, 350)
pentagon(point=point_0, start_angle=25, length=100)
point_0 = sd.get_point(450, 350)
hexagon(point=point_0, start_angle=25, length=100)
sd.pause()
#зачет! |
ec962a698c6b15d86f086a502ff5a660fcd27730 | sagardhumal26/PythonCodes | /MergeSort.py | 980 | 4.0625 | 4 |
def merge_list(left,right):
result = []
left_idx,right_idx=0,0
while left_idx<len(left) and right_idx<len(right):
if left[left_idx]<right[right_idx]:
result.append(left[left_idx])
left_idx+=1
else:
result.append(right[right_idx])
right_idx+=1
if left:
result.extend(left[left_idx:])
if right:
result.extend(right[right_idx:])
return result
def mergeSort(arr):
if len(arr)<=1:
return arr
mid=len(arr)//2
left = arr[:mid]
right = arr[mid:]
left=mergeSort(left)
right=mergeSort(right)
return merge_list(left,right)
def printList(arr):
for item in arr:
print(item,end=" ")
print()
if __name__=='__main__':
arr = [12, 11, 13, 5, 6, 7]
print ("Given array is", end="\n")
printList(arr)
arr=mergeSort(arr)
print("Sorted array is: ", end="\n")
printList(arr)
|
8a118f2782af6a484675c1fe883f7a210b2f7448 | ethanmad/c4cs-f16-rpn | /test_rpn.py | 702 | 3.546875 | 4 | import unittest
import rpn
class TestBasics(unittest.TestCase):
def test_add(self):
result = rpn.calculate("1 1 +")
self.assertEqual(2, result)
def test_subtract(self):
result = rpn.calculate("5 3 -")
self.assertEqual(2, result)
def test_multiply(self):
result = rpn.calculate("7 -5 *")
self.assertEqual(-35, result)
def test_divide(self):
result = rpn.calculate("39 13 /")
self.assertEqual(3, result)
def test_power(self):
result = rpn.calculate("2 7 ^")
self.assertEqual(128, result)
def test_toomanythings(self):
with self.assertRaises(TypeError):
rpn.calculate("1 2 3 +")
|
cbec9f9d8b94ef82f2484159c36e91da2df0bf92 | bedros-bzdigian/intro-to-python | /week 4/homework/problem2.py | 192 | 3.71875 | 4 | d = {"name":"Armen","age":15,"grades":[10,8,8,4,6,7]}
v = 0
for x in (d["grades"]):
v = v + x
v = v / 6
if v > 7:
print ("Good job! " )
else:
print ("you need to work more ") |
96be5b29676937dd5edcf3b9ca96c412d65a1578 | jonhusen/learning-python | /pluralsight/phonebook_unittest/test_phonebook.py | 1,516 | 3.90625 | 4 | import unittest
from .phonebook import PhoneBook
class PhoneBookTest(unittest.TestCase):
def setUp(self) -> None:
self.phonebook = PhoneBook()
def test_lookup_by_name(self):
self.phonebook.add("Bob", "12345")
number = self.phonebook.lookup("Bob")
self.assertEqual("12345", number)
def test_missing_name(self):
with self.assertRaises(KeyError):
self.phonebook.lookup("missing")
def test_empty_phonebook_is_consistent(self):
self.assertTrue(self.phonebook.is_consistent())
def test_is_consistent_with_different_entries(self):
self.phonebook.add("Bob", "12345")
self.phonebook.add("Anna", "012345")
self.assertTrue(self.phonebook.is_consistent())
def test_inconsistent_with_duplicate_entries(self):
self.phonebook.add("Bob", "12345")
self.phonebook.add("Sue", "12345")
self.assertFalse(self.phonebook.is_consistent())
def test_inconsistent_with_duplicate_prefix(self):
self.phonebook.add("Bob", "12345")
self.phonebook.add("Sue", "123")
self.assertFalse(self.phonebook.is_consistent())
def test_phonebook_adds_names_and_numbers(self):
# Example of where two asserts might be reasonable in a test
# This tests the add method for correct insertion of name and number
self.phonebook.add("Sue", "123343")
self.assertIn("Sue", self.phonebook.get_names())
self.assertIn("123343", self.phonebook.get_numbers())
|
175d335184d8ea162218a9687988bdaa003a15e2 | ArchAngelEU/training- | /class.py | 799 | 3.6875 | 4 | import statistics
class Student:
# To access class variables need to use the instance .self or the class itself .Student
email_prefix = ['@uel.ac.uk', '@uel.admin.uk']
# Init method for a class
def __init__(self, first, last, grades):
self.first = first
self.last = last
self.grades = grades
self.email = f'{first}{last}{self.email_prefix[1]} '
self.average = f' Average Grade for {first} {last} {sum(grades) // len(grades)}%'
full_name = lambda self : f'{self.first} {self.last}'
student_1 = Student('Joe','Jacques', [145, 66, 77,88])
# Calling a call method full_name()
print(Student.full_name(student_1))
print(student_1.email)
print(student_1.average) |
adc34481d81237296fae4c7a9a0316136e293153 | Aasthaengg/IBMdataset | /Python_codes/p02771/s807871419.py | 119 | 3.53125 | 4 | # coding: utf-8
# Your code here!
A=set(map(int,input().split()))
if len(A)==2:
print("Yes")
else:
print("No") |
2e9962def83ce4ae9642bfdb25bac711bb12e352 | lichangg/myleet | /titles/6. Z 字形变换.py | 429 | 3.703125 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows < 2:return s
res = ['' for _ in range(numRows)]
idx, flag = 0, -1
for string in s:
res[idx] += string
if idx == 0 or idx == numRows-1:flag = -flag
idx +=flag
return ''.join(res)
a=Solution().convert('PAYPALISHIRING', 3)
print(a) |
39fc26a5af186b4e554d2ac0c64ae5c0b6621418 | gschen/sctu-ds-2020 | /1906101119-祝源/day0303课后作业/test01.py | 405 | 3.8125 | 4 | # 1.创建Person类,属性有姓名、年龄、性别,创建方法personInfo,打印这个人的信息
class Person():
def __init__(self,name,age,sex):
self.name = name
self.age = age
self.sex = sex
def personInfo(self):
print('姓名:%s 年龄:%s 性别:%s' %(self.name,self.age,self.sex))
student1 = Person('祝源','18','男')
student1.personInfo()
|
1bdefd2d9df70e413b493cdcb9ccdb9466d81864 | cassyhyy/ml_assignment_1B | /multiAgents.py | 12,722 | 4.09375 | 4 | from util import manhattanDistance
from game import Directions
import random, util
from game import Agent
class ReflexAgent(Agent):
"""
A reflex agent chooses an action at each choice point by examining
its alternatives via a state evaluation function.
The code below is provided as a guide. You are welcome to change
it in any way you see fit, so long as you don't touch our method
headers.
"""
def getAction(self, gameState):
"""
You do not need to change this method, but you're welcome to.
getAction chooses among the best options according to the evaluation function.
Just like in the previous project, getAction takes a GameState and returns
some Directions.X for some X in the set {North, South, West, East, Stop}
"""
# Collect legal moves and successor states
legalMoves = gameState.getLegalActions()
# Choose one of the best actions
scores = [self.evaluationFunction(gameState, action) for action in legalMoves]
bestScore = max(scores)
bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore]
chosenIndex = random.choice(bestIndices) # Pick randomly among the best
"Add more of your code here if you want to"
return legalMoves[chosenIndex]
def evaluationFunction(self, currentGameState, action):
"""
Design a better evaluation function here.
The evaluation function takes in the current and proposed successor
GameStates (pacman.py) and returns a number, where higher numbers are better.
The code below extracts some useful information from the state, like the
remaining food (newFood) and Pacman position after moving (newPos).
newScaredTimes holds the number of moves that each ghost will remain
scared because of Pacman having eaten a power pellet.
Print out these variables to see what you're getting, then combine them
to create a masterful evaluation function.
"""
# Useful information you can extract from a GameState (pacman.py)
prevFood = currentGameState.getFood()
successorGameState = currentGameState.generatePacmanSuccessor(action)
newPos = successorGameState.getPacmanPosition() #(x,y)
newFood = successorGameState.getFood() #foodGrid
newGhostStates = successorGameState.getGhostStates() #game.AgentState
newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates]
"*** YOUR CODE HERE ***"
maxNum = newFood.width + newFood.height
minGhostDistance = maxNum # 离鬼的最小距离
eatGhostChance = 0 # 吃掉鬼的机会
# 获取pacman距最近鬼的距离
for state in newGhostStates:
ghostDistance = manhattanDistance(newPos, state.getPosition())
# if ghostDistance < minGhostDistance and state.scaredTimer:
# minGhostDistance = ghostDistance
if state.scaredTimer - ghostDistance > eatGhostChance:
eatGhostChance = state.scaredTimer - ghostDistance
# 当不能吃掉鬼时,才计算与鬼的距离
elif ghostDistance < minGhostDistance:
minGhostDistance = ghostDistance
# 获取pacman距最近食物的距离
foodPosition = newFood.asList()
minFoodDistance = 0
if len(foodPosition) > 0:
minFoodDistance = min([manhattanDistance(newPos,p) for p in foodPosition])
# pacman离鬼、食物最近距离要+1才做倒数处理,因为可能被除数=0
result = successorGameState.getScore() - 1.0/(minGhostDistance+1) + 1.0/(minFoodDistance+1) + eatGhostChance
return result
def scoreEvaluationFunction(currentGameState):
"""
This default evaluation function just returns the score of the state.
The score is the same one displayed in the Pacman GUI.
This evaluation function is meant for use with adversarial search agents
(not reflex agents).
"""
return currentGameState.getScore()
class MultiAgentSearchAgent(Agent):
"""
This class provides some common elements to all of your
multi-agent searchers. Any methods defined here will be available
to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent.
You *do not* need to make any changes here, but you can if you want to
add functionality to all your adversarial search agents. Please do not
remove anything, however.
Note: this is an abstract class: one that should not be instantiated. It's
only partially specified, and designed to be extended. Agent (game.py)
is another abstract class.
"""
def __init__(self, evalFn = 'scoreEvaluationFunction', depth = '2'):
self.index = 0 # Pacman is always agent index 0
self.evaluationFunction = util.lookup(evalFn, globals())
self.depth = int(depth)
class MinimaxAgent(MultiAgentSearchAgent):
"""
Your minimax agent (question 2)
"""
def getAction(self, gameState):
"""
Returns the minimax action from the current gameState using self.depth
and self.evaluationFunction.
Here are some method calls that might be useful when implementing minimax.
gameState.getLegalActions(agentIndex):
Returns a list of legal actions for an agent
agentIndex=0 means Pacman, ghosts are >= 1
gameState.generateSuccessor(agentIndex, action):
Returns the successor game state after an agent takes an action
gameState.getNumAgents():
Returns the total number of agents in the game
gameState.isWin():
Returns whether or not the game state is a winning state
gameState.isLose():
Returns whether or not the game state is a losing state
"""
"*** YOUR CODE HERE ***"
return self.minimax(gameState, 0)[0]
util.raiseNotDefined()
# minimax的递归,返回(action, bestScore)
def minimax(self, gameState, depth):
agentNum = gameState.getNumAgents()
# 当遍历深度足够或者游戏结束时,返回(None,当前分数)
if depth == agentNum * self.depth or gameState.isWin() or gameState.isLose():
return (None, self.evaluationFunction(gameState))
# 记录变量
agentIndex = depth % agentNum
legalMoves = gameState.getLegalActions(agentIndex)
scores = []
for action in legalMoves:
newState = gameState.generateSuccessor(agentIndex, action)
scores.append(self.minimax(newState, depth+1)[1])
# 依据agentIndex记录bestScores,当agent为pacman时取scores的最大值,为ghost时取最小值
if agentIndex == 0:
bestScore = max(scores)
else:
bestScore = min(scores)
bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore]
chosenIndex = random.choice(bestIndices) # Pick randomly among the best
return (legalMoves[chosenIndex], bestScore)
class AlphaBetaAgent(MultiAgentSearchAgent):
"""
Your minimax agent with alpha-beta pruning (question 3)
"""
def getAction(self, gameState):
"""
Returns the minimax action using self.depth and self.evaluationFunction
"""
"*** YOUR CODE HERE ***"
return self.minimax(gameState, 0, -9999, 9999)[0]
util.raiseNotDefined()
# minimax的递归,返回(action, bestScore, aplha, beta)
def minimax(self, gameState, depth, alpha, beta):
agentNum = gameState.getNumAgents()
# 当遍历深度足够或者游戏结束时,返回(None,当前分数)
if depth == agentNum * self.depth or gameState.isWin() or gameState.isLose():
return (None, self.evaluationFunction(gameState))
# 记录变量
agentIndex = depth % agentNum
legalMoves = gameState.getLegalActions(agentIndex)
minScore = 9999
maxScore = -9999
for action in legalMoves:
newState = gameState.generateSuccessor(agentIndex, action)
value = self.minimax(newState, depth + 1, alpha, beta)[1]
if agentIndex == 0:
# find max: 判断v>beta?
if value >= maxScore:
maxScore = value
chooseAction = action
if value > beta:
return (chooseAction, maxScore)
# max结点:确定alpha
alpha = max(alpha, maxScore)
else:
# find min: 判断v<alpha?
if value <= minScore:
minScore = value
chooseAction = action
if value < alpha:
return (chooseAction, minScore)
# min结点:确定beta
beta = min(beta, minScore)
# 依据agentIndex记录bestScore,当agent为pacman时取max,为ghost时取min
if agentIndex == 0:
bestScore = maxScore
else:
bestScore = minScore
return (chooseAction, bestScore)
class ExpectimaxAgent(MultiAgentSearchAgent):
"""
Your expectimax agent (question 4)
"""
def getAction(self, gameState):
"""
Returns the expectimax action using self.depth and self.evaluationFunction
All ghosts should be modeled as choosing uniformly at random from their
legal moves.
"""
"*** YOUR CODE HERE ***"
return self.expectimax(gameState, 0)[0]
util.raiseNotDefined()
# expectimax的递归,返回(action, bestScore)
def expectimax(self, gameState, depth):
agentNum = gameState.getNumAgents()
# 当遍历深度足够或者游戏结束时,返回(None,当前分数)
if depth == agentNum * self.depth or gameState.isWin() or gameState.isLose():
return (None, self.evaluationFunction(gameState))
# 记录变量
agentIndex = depth % agentNum
legalMoves = gameState.getLegalActions(agentIndex)
probability = 1.0 / len(legalMoves)
scores = []
averageScore = 0
for action in legalMoves:
newState = gameState.generateSuccessor(agentIndex, action)
if agentIndex == 0:
scores.append(self.expectimax(newState, depth + 1)[1])
else:
averageScore += probability * self.expectimax(newState, depth + 1)[1]
# 当前agent为ghost时,返回averageScore;为pacman时返回最大分数
if agentIndex != 0:
return (None, averageScore)
bestScore = max(scores)
bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore]
chosenIndex = random.choice(bestIndices) # Pick randomly among the best
return (legalMoves[chosenIndex], bestScore)
def betterEvaluationFunction(currentGameState):
"""
Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable
evaluation function (question 5).
DESCRIPTION: <write something here so we know what you did>
"""
"*** YOUR CODE HERE ***"
# 同第一题思路差不多
pacmanPos = currentGameState.getPacmanPosition()
ghostStates = currentGameState.getGhostStates()
food = currentGameState.getFood()
maxNum = food.width + food.height
minGhostDistance = maxNum # 离鬼的最小距离
eatGhostChance = 0 # 吃掉鬼的机会
# 获取pacman距最近鬼的距离
for state in ghostStates:
ghostDistance = manhattanDistance(pacmanPos, state.getPosition())
# if ghostDistance < minGhostDistance and state.scaredTimer:
# minGhostDistance = ghostDistance
if state.scaredTimer - ghostDistance > eatGhostChance:
eatGhostChance = state.scaredTimer - ghostDistance
# 当不能吃掉鬼时,才计算与鬼的距离
elif ghostDistance < minGhostDistance:
minGhostDistance = ghostDistance
# 获取pacman距最近食物的距离
foodPosition = food.asList()
minFoodDistance = 0
if len(foodPosition) > 0:
minFoodDistance = min([manhattanDistance(pacmanPos, p) for p in foodPosition])
# pacman离鬼、食物最近距离要+1才做倒数处理,因为可能被除数=0
result = currentGameState.getScore() - 1.0 / (minGhostDistance + 1) + 1.0 / (minFoodDistance + 1) + eatGhostChance
return result
util.raiseNotDefined()
# Abbreviation
better = betterEvaluationFunction
|
72d6923d900726e37d88714cb1451064867ecf59 | bala4rtraining/python_programming | /python-programming-workshop/pythondatastructures/for/filetolist.py | 163 | 3.75 | 4 |
List = []
with open("words.txt") as f:
for line in f:
for word in line.split():
List.append(word) # add only first word
List[::-1]
print(List)
|
310e2e04c81636cbb26d717172136c27b4d1b53d | lumaherr/python_fundamentals | /17_generators/17_01_generators.py | 256 | 4.21875 | 4 | '''
Demonstrate how to create a generator object. Print the object to the console to see what you get.
Then iterate over the generator object and print out each item.
'''
gen = (i for i in range(1,500) if i%3 == 0 and i%5 != 0)
for i in gen:
print(i) |
69e8c5200f6d36cf31a255c8a61e5c71da1efd58 | dongheelee1/LeetCode | /9_palindrome_number.py | 1,457 | 4.25 | 4 | '''
9. Palindrome Number
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example 1:
Input: 121
Output: true
Example 2:
Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Follow up:
Coud you solve it without converting the integer to a string?
'''
class Solution:
def isPalindrome(self, x: int) -> bool:
'''
TIME COMPLEXITY:
Used a single for loop, which means a O(n) time complexity
IDEA:
if x is negative, return False (reversing -121 is 121- ==> not a palindrome)
if x is positive,
str_format = str(x)
get right most digit of x (updated in every loop)
look at each char from left to right in str_format
if right digit != int(str_format[i]):
return False
return True
'''
if x < 0:
return False
else:
str_format = str(x)
for i in range(0, len(str_format) // 2):
digit = x % 10
x = x // 10
if digit != int(str_format[i]):
return False
return True
|
be5c1a03bcdcdcd3082db877a323a6ac3602ea78 | rydovoi50/python_projekt | /lesson05/home_work/hw05_hard.py | 4,521 | 3.515625 | 4 | # Задание-1:
# Доработайте реализацию программы из примера examples/5_with_args.py,
# добавив реализацию следующих команд (переданных в качестве аргументов):
# cp <file_name> - создает копию указанного файла
# rm <file_name> - удаляет указанный файл (запросить подтверждение операции)
# cd <full_path or relative_path> - меняет текущую директорию на указанную
# ls - отображение полного пути текущей директории
# путь считать абсолютным (full_path) -
# в Linux начинается с /, в Windows с имени диска,
# все остальные пути считать относительными.
import os
import sys
print('sys.argv = ', sys.argv)
def print_help():
print("help - получение справки")
print("mkdir <dir_name> - создание директории")
print("rmdir <dir_name> - удаление директории")
print("срdir <dir_name> - перейти в директорию")
print("listdir - список файлов в директории")
print("copy_file <file> - копирование заданного файла")
print("del <file> - удаление заданного файла")
print("getcwd - отображает путь дирректории")
def make_dir():
if not dir_name:
print("Необходимо указать имя директории вторым параметром")
return
dir_path = os.path.join(os.getcwd(), dir_name)
try:
os.mkdir(dir_path)
print('директория {} создана'.format(dir_name))
except FileExistsError:
print('директория {} уже существует'.format(dir_name))
def rm_dir():
if not dir_name:
print('Необходимо указать имя директории вторым параметром')
return
try:
os.rmdir(dir_name)
print('Директория {} удалена'.format(dir_name))
except FileNotFoundError:
print('директории {} не существует'.format(dir_name))
def ch_dir():
if not dir_name:
print('Необходимо указать имя директории вторым параметром')
return
os.chdir(dir_name)
# dir_name = os.getcwd()
print('Успешно перешли в {}'.format(dir_name))
def ls():
print(os.listdir(os.getcwd()))
def copy():
if not file:
print('Необходимо указать имя файла вторым параметром')
return
with open(file, 'r', encoding='UTF-8') as file_1:
h = file_1.read()
with open('new' + file, 'w', encoding='UTF-8') as file_2:
file_2.write(h)
print('Файл удачно скопирован')
def cwd():
print(os.getcwd())
def delet():
if not file:
print('Необходимо указать имя директории вторым параметром')
return
user = input('Вы точно хотите удалит файл {}, y/n: '.format(file))
if user == 'y':
os.remove(file)
print('Файл {} успешно удален'.format(file))
do = {
"help": print_help,
"mkdir": make_dir,
"rmdir": rm_dir,
"chdir": ch_dir,
"listdir": ls,
"copy_file": copy,
"getcwd": cwd,
"del": delet
}
try:
file = sys.argv[2]
except IndexError:
file = None
try:
dir_name = sys.argv[2]
except IndexError:
dir_name = None
try:
key = sys.argv[1]
except IndexError:
key = None
if key:
if do.get(key):
do[key]()
else:
print("Задан неверный ключ")
print("Укажите ключ help для получения справки")
while True:
print('Введите команду')
key = input()
# Важно! Все операции должны выполняться в той директории, в который вы находитесь.
# Исходной директорией считать ту, в которой был запущен скрипт.
# P.S. По возможности, сделайте кросс-платформенную реализацию.
|
e2549ea8c7e81e539a36feddc0129e8191683ac7 | krnets/codewars-practice | /7kyu/Char Code Calculation/kata.py | 324 | 3.59375 | 4 | def calc(x):
total1 = [int(t) for c in x for t in str(ord(c))]
total2 = [1 if t == 7 else t for t in total1]
return sum(total1) - sum(total2)
q = calc("ABC") # 6
q
q = calc("abcdef") # 6
q
q = calc("ifkhchlhfd") # 6
q
q = calc("aaaaaddddr") # 30
q
q = calc("jfmgklf8hglbe") # 6
q
q = calc("jaam") # 12
q
|
dbbf5a5e4e3a6bf440ab5cdc6ad861eb624f7064 | sazzadrupak/python_exercise | /dict/contact.py | 1,109 | 4.1875 | 4 | # TIE-02100 Johdatus ohjelmointiin
# TIE-02106 Introduction to Programming
# Task: contacts, program code template
def main():
contacts = {"Tom": {"name": "Tom Techie",
"phone": "040 123546",
"email": "tom@tut.fi",
"skype": "tom_92_"},
"Mike": {"name": "Mike Mechanic",
"phone": "050 123546",
"email": "mike@tut.fi",
"skype": "-Mike-M-"},
"Archie": {"name": "Archie Architect",
"phone": "050 987654",
"email": "archie@tut.fi"}}
contact = input("Enter the name of the contact: ")
field = input("Enter the field name you're searching for: ")
if not contacts.get(contact):
print("No contact information for {}".format(contact))
elif contacts[contact]['name'] and not contacts[contact].get(field):
print("No {} for {}".format(field, contacts[contact]['name']))
else:
print('{}, {}: {}'.format(contacts[contact]['name'], field, contacts[contact][field]))
main()
|
6ba06d9c1cda0ca0bc2e4df21ea65d7d34910f72 | chakravarthi-giduthuri/DSA | /Stacks/Stacks.py | 1,645 | 4.1875 | 4 | # there are two ways to implement stacks
# using array
# using linked list
#implement using array method
from sys import maxsize
def createStack():
stack = []
return stack
def isEmpty(stack):
return len(stack) == 0
def push(stack, item):
stack.append(item)
print(item+'pushed to stack')
def pop(stack):
if isEmpty(stack):
return str(-maxsize-1)
return stack.pop()
def peek(stack):
if isEmpty(stack):
return str(-maxsize-1)
return stack[len(stack)-1]
if __name__ == '__main__':
stack = createStack()
push(stack, str(10))
push(stack, str(20))
push(stack, str(30))
print(peek(stack),'is peek')
print(pop(stack),'pop from stack')
#implement using linked list method
class StackNode:
def __init__(self,data):
self.data = data
self.next = None
class Stack:
def __init__(self):
self.root = None
def isEmpty(self):
return True if self.root is None else False
def push(self,data):
newNode = StackNode(data)
newNode.next = self.root
self.root = newNode
print('push stack ',data)
def pop(self):
if self.isEmpty():
return float('-inf')
temp = self.root
self.root = self.root.next
popped = temp.data
return popped
def peek(self):
if self.isEmpty():
return float('-inf')
return self.root.data
if __name__ == '__main__':
stack = Stack()
stack.push(10)
stack.push(20)
stack.push(30)
print('popped from stack',stack.pop())
print('top element is ',stack.peek())
|
c68e6980ee2f2c70d02c44400a850538c6469479 | AlienWu2019/Alien-s-Code | /爬虫/《精通python网络爬虫》/正则表达式/原子/普通字符作为原子.py | 138 | 3.5 | 4 | import re
pattern = "yue" #普通字符作为原子
string = "http://yum.iqianyue.com"
result1 = re.search(pattern,string)
print(result1) |
87f13c0055e310220cc09a3041e897bc14334548 | kateblolo/advent_of_code_2020 | /day18/day18.py | 2,222 | 3.5625 | 4 | with open("input_day18.txt", "r") as myfile:
input = myfile.read().split("\n")
# PART2 -- adds parenthesis around "+" elements
def add_priority(line):
line2 = line[:]
appended = 0
nxt_app = []
for c in range(len(line)):
if nxt_app:
if c+appended == min(nxt_app):
appended += 1
nxt_app.remove(min(nxt_app))
if line[c] == "+":
cpt = 0
c2 = c-1+appended
while not line2[c2].isnumeric() or cpt != 0:
if line2[c2] == ")":
cpt += 1
elif line2[c2] == "(":
cpt -=1
if cpt == 0:
break
c2 -= 1
line2 = line2[:c2] + "(" + line2[c2:]
appended += 1
c2 = c+1+appended
while not line2[c2].isnumeric() or cpt != 0:
if line2[c2] == "(":
cpt += 1
elif line2[c2] == ")":
cpt -=1
if cpt == 0:
break
c2 += 1
line2 = line2[:c2+1] + ")" + line2[c2+1:]
nxt_app = [i+2 for i in nxt_app]
nxt_app.append(c2+1)
return line2
def solve_line(line):
line = line.replace(" ", "")
##PART2 v
line = add_priority(line)
##PART2 ^
res = [0]
cpt = 0
operation = ["+"]
for i in range(len(line)):
if line[i] == "(":
cpt += 1
res.append(0)
operation.append("+")
elif line[i] == ")":
cpt -= 1
if operation[cpt] == "+":
res[cpt] += res[cpt+1]
else:
res[cpt] *= res[cpt+1]
res = res[:cpt+1]
operation = operation[:cpt+1]
elif line[i] == "+":
operation[cpt] = "+"
elif line[i] == "*":
operation[cpt] = "*"
elif line[i].isnumeric():
if operation[cpt] == "+": res[cpt] += int(line[i])
else: res[cpt] *= int(line[i])
return res[0]
def solve(input):
res = 0
for i in input:
res += solve_line(i)
return res
print(solve(input)) |
5e477f8f3339035e4fd8fd0f2c559fc225016708 | suhyeonjin/HomeWork | /lab1/embedded_pyGame/Crash_Of_Block.py | 4,324 | 3.75 | 4 | #coding:utf-8
# refer : https://github.com/attojeon/BricksWithPython
# draw ball
# draw ball & moving it
# bounce ball
# draw bar
# control bar
# draw block
# check collision block & ball
# veiw score
import pygame, sys, math, random
from pygame.locals import *
BLACK = ( 0, 0, 0)
WHITE = (255,255,255)
RED = (255, 0, 0)
GREEN = ( 0,255, 0)
BLUE = ( 0, 0,255)
width = 640
height = 480
radius = 10
bx = width / 2
by = height / 2
dx = 1
dy = 1
tAngle = 45
px = 0
py = 440
p_vel = 10
p_width = 80
p_height = 10
bricks_cols = 3
bricks_rows = 7
brickWidth = 75
brickHeight = 20
brickPadding = 10
brickOffsetTop = 40
brickOffsetLeft = 30
score = 1000
keys = [False, False]
bricks = []
pygame.init()
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('Crash_Of_Block')
# font
fontObj = pygame.font.SysFont('Courier', 20)
def bricksInit():
global bricks_cols, bricks_rows, brickWidth, brickHeight, brickPadding, brickOffsetTop, brickOffsetLeft
for r in range(bricks_rows):
for c in range(bricks_cols):
state = 1
x = brickOffsetLeft + r*(brickPadding + brickWidth)
y = brickOffsetTop + c*(brickPadding + brickHeight)
oneBrick = [x, y, state]
bricks.append(oneBrick)
print(bricks)
def drawBricks():
global bricks_cols, bricks_rows, brickWidth, brickHeight, brickPadding, brickOffsetTop, brickOffsetLeft
for b in bricks:
if b[2] == 1 :
pygame.draw.rect(screen, GREEN, (b[0], b[1],brickWidth, brickHeight))
def drawbar(x, y):
pygame.draw.rect(screen, WHITE, (px, py, p_width, p_height))
def drawball(x, y, r):
pygame.draw.circle(screen, WHITE, (int(x), int(y)), r, 0)
def updateObject():
global bx, by, dx, dy, px, py, p_width, p_height, p_vel, tAngle
bx += dx
#by += dy
by += int( round( math.tan(math.radians(tAngle)) * dx ) ) * -1
#print "%r %r" % (bx, by)
if bx > width or bx < 0:
dx = dx * (-1)
tAngle = 180 - tAngle
if by > height or by < 0:
#dy = dy * (-1)
tAngle = 180 - tAngle
if keys[0] == True:
px -= p_vel
if keys[1] == True:
px += p_vel
if px < 0:
px = 0
if px + p_width > 640:
px = width - p_width
def collideCheck():
global bx, by, dx, dy, px, py, p_width, p_height, p_vel
global bricks_cols, bricks_rows, brickWidth, brickHeight, brickPadding, brickOffsetTop, brickOffsetLeft, tAngle
global score
# Collision Check - ball & paddle
if bx > px and bx < px + p_width and by > py:
#dx *= -1
#dy *= -1
tAngle = 180 - tAngle + random.randint(-20, 20)
# check the block collision
for b in bricks:
if bx > b[0] and bx < b[0]+brickWidth and by > b[1] and by < b[1]+brickHeight and b[2] == 1: #state == 1일 때에만 체크
b[2] = 0
#dy *= -1
tAngle = 180 - tAngle
score += 100
def drawScore(screen, scoreView):
scoreView = fontObj.render(str(score), True, WHITE, BLACK)
scoreRect = scoreView.get_rect()
scoreRect.topleft = (10, 10)
screen.blit(scoreView, scoreRect)
def scoreInit():
global fontObj, score
score = 1000
fontObj = pygame.font.SysFont('Courier', 20)
scoreView = fontObj.render('10000000', True, WHITE, BLACK)
#scoreRect = scoreView.get_rect()
#scoreRect.center = (200, 50)
return scoreView
def main():
bricksInit()
scoreView = scoreInit()
while True:
screen.fill(BLACK)
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == K_LEFT:
keys[0] = True
elif event.key == K_RIGHT:
keys[1] = True
if event.type == pygame.KEYUP:
if event.key == K_LEFT:
keys[0] = False
elif event.key == K_RIGHT:
keys[1] = False
updateObject()
collideCheck()
drawBricks()
drawball(bx, by, radius)
drawbar(px, py)
drawScore(screen, scoreView)
pygame.display.update()
if __name__ == '__main__':
main()
|
3753be8264bcd374f59e5b0d930729e0646e76f7 | Invalid-coder/Data-Structures-and-algorithms | /Graphs/Unweighted_graphs/Tasks/eolymp(2470).py | 723 | 3.671875 | 4 | #https://www.e-olymp.com/uk/submissions/7687618
class Graph:
def __init__(self, matrix):
self.adjacentMatrix = matrix
def isNotOriented(self):
n = len(self.adjacentMatrix)
for i in range(n):
for j in range(n):
if i == j and self.adjacentMatrix[i][j] == 1:
return False
if self.adjacentMatrix[i][j] != self.adjacentMatrix[j][i]:
return False
return True
if __name__ == '__main__':
n = int(input())
matrix = []
for i in range(n):
row = list(map(int, input().split()))
matrix.append(row)
graph = Graph(matrix)
print("YES" if graph.isNotOriented() else "NO")
|
984ea002455f8a531f068ccb1bcbb1313c85b91e | V-Plum/ITEA | /lesson_10/l10_ex1.py | 367 | 3.671875 | 4 | def symbols_add(f):
def wrapped(text):
if text[1] != '"':
text = '"' + text
if text.strip()[-1] != '"':
text = text + '"'
return text
@symbols_add
def text_input():
text = input("Print some text: ")
return text
def main():
text = text_input()
print(text)
if __name__ == '__main__':
main()
|
6a51a70544dd65eb693cfb3a730aede532407d56 | hemal507/python | /longest_substr_without_repeation.py | 716 | 3.921875 | 4 | '''
given string find the longest substring without repeating characters
'''
def len_str(inp_str) :
prev,return_str = '',''
for i in inp_str :
if i not in return_str :
return_str += i
else :
if len(prev) < len(return_str) :
prev = return_str
return_str = i
return len(prev), prev
import unittest
class TestSubStrLen(unittest.TestCase) :
def test_string1(self) :
self.assertEqual(len_str('abcabcbb'),(3,'abc'))
print('Test case 1 passed')
def test_string2(self) :
self.assertEqual(len_str('bbbbbb'),(1,'b'))
print('Test case 2 passed')
def test_string3(self) :
self.assertEqual(len_str('pwwkew'),(3,'wke'))
print('Test case 3 passed')
if __name__ == '__main__' :
unittest.main()
|
2cffde581c6844428a5ae74296045184d05167f4 | xfbs/euler | /src/002-even-fibonacci-numbers/python/solver.py | 208 | 4.09375 | 4 | import fibonacci
def even_fibonacci(m):
cur = 0
fib = fibonacci.nth(cur)
while fib < m:
yield fib
cur += 3
fib = fibonacci.nth(cur)
def solve(m):
return sum(even_fibonacci(m))
|
01cb764ae39ef3b189881681e9b7d35a00fd5b1a | de-centralized-systems/sssmp | /src/GF256.py | 3,405 | 3.8125 | 4 | from typing import Sequence, Union
def add(a: int, b: int) -> int:
"""Implements addition of `a` and b` in GF256.
Added here for reference only. Addition may typically be inlined for better performance.
"""
return a ^ b
def _multiply(a: int, b: int) -> int:
"""Implements multiplication of `a` times `b` in GF256, i.e.,
multiplication modulo the AES irreducible polynomial `x**8 + x**4 + x**3 + x + 1`.
"""
IRREDUCIBLE_POLYNOMIAL = 0b100011011
product = 0
while b > 0:
# add (xor operation) `a` to the product if the last bit of `b` == 1
product ^= a * (b & 1)
# shift `a` one bit to the left
# and perform a modulo reduction if there is an overflow after shifting (a >> 8 == 1)
a <<= 1
a ^= (a >> 8) * IRREDUCIBLE_POLYNOMIAL
# move the next highest bit of `b` bit shifting it down
b >>= 1
return product
def multiply(a: int, b: int) -> int:
"""Implements multiplication of `a` times `b` in GF256, i.e.,
multiplication modulo the AES irreducible polynomial `x**8 + x**4 + x**3 + x + 1`.
Faster implementation using a pregenerated lookup table (64KB in size).
"""
return MULTIPLICATION_TABLE[(a << 8) | b]
def inverse(e: int) -> int:
"""Implements finding the inverse of an GF256 element `e` via a lookup table."""
if e == 0:
raise ValueError("Zero has no inverse element!")
return INVERSE_LOOKUP_TABLE[e]
def init_multiplication_table() -> bytes:
"""Initializes the lookup table (256*256 elements) for quickly multiplying elements in GF256.
The product `a * b` is computed by accessing the lookup table at index `(a << 8) | b`.
"""
return bytes(0 if (i == 0 or j == 0) else _multiply(i, j) for i in range(256) for j in range(256))
def init_inverse_lookup_table() -> bytes:
"""Initializes the lookup table (256 elements) for quickly finding inverse elements in GF256."""
table = [0] * 256
for e in range(1, 256):
for i in range(e, 256):
if multiply(e, i) == 1:
table[e] = i
table[i] = e
return bytes(table)
MULTIPLICATION_TABLE: bytes = init_multiplication_table()
INVERSE_LOOKUP_TABLE: bytes = init_inverse_lookup_table()
class Polynomial:
""" Holds the coefficients of a polynomial in GF256 and provides a function to evaluate the polynomial.
Example usage: f = Polynomial([17, 124, 33]
f(10) ==> 56
"""
def __init__(self, coefficients: Union[bytes, Sequence[int]]) -> None:
self.coefficients = coefficients
def __call__(self, x: int) -> int:
"""Evaluates this `t+1`-degree polynomial for the given input `x` in GF256.
f(x) = c[0] + c[1] x + c[2] x^2 + ... + c[t-1] x^{t-1}
"""
c = self.coefficients
t = len(c)
if t == 0:
return 0
# Initialize the result with the first coeffcient c[0].
result = c[0]
# Add terms c[1] x + ... + c[t-2] x^{t-2} to `result`.
# `xk` is a helper variable holding the value value x^k.
xk = x
for k in range(1, t - 1):
result ^= multiply(c[k], xk)
xk = multiply(xk, x)
# Add the last term c[t-1] to `result` (ensure t[0] is not added twice).
if t - 1 > 0:
result ^= multiply(c[t - 1], xk)
return result
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.