blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
11b2c589eb9c058b6867419ac7481ed85dc7c9c6 | amytfang/checkers | /board.py | 2,018 | 3.625 | 4 | from piece import Piece
class Board:
def __init__(self):
self._generate_game_board()
def _generate_game_board(self):
grid = []
for row in range(8):
grid.append([])
for col in range(8):
if row <= 2 and (row + col) % 2 != 0:
grid[row].append(Piece('white', (row, col), self))
elif row >= 5 and (row + col) % 2 != 0:
grid[row].append(Piece('red', (row, col), self))
else:
grid[row].append(None)
self.board = grid
def print_board(self):
print(' 0 1 2 3 4 5 6 7')
for idx, row in enumerate(self.board):
display_row = ' '.join([piece.display if piece else '_' for piece in row])
print(str(idx) + " " + display_row)
def move_piece(self, piece, to_pos):
self.board[to_pos[0]][to_pos[1]] = piece
self.board[piece.row][piece.col] = None
if abs(to_pos[0] - piece.row) > 1:
self.remove_jumped_piece(to_pos, piece.pos)
piece.row, piece.col = to_pos
def remove_jumped_piece(self, pos1, pos2):
jumped_row = int((pos1[0] + pos2[0]) / 2)
jumped_col = int((pos1[1] + pos2[1]) / 2)
self.board[jumped_row][jumped_col] = None
def get_pos(self, pos):
return self.board[pos[0]][pos[1]]
def get_valid_moves(self, color):
valid_moves = {}
jump_only = False
for row in range(8):
for col in range(8):
piece = self.get_pos((row,col))
if piece and piece.color == color:
jump, moves = piece.get_valid_moves(jump_only)
if jump and not jump_only:
jump_only = True
valid_moves = {piece.pos: moves}
elif moves:
valid_moves[piece.pos] = moves
return jump_only, valid_moves
|
070bdd3632866f6d636890a882c1c3edb5fd5ba1 | YusufBritton1990/Django_tutorial_backup | /django_project/pagination.py | 635 | 3.546875 | 4 | from django.core.paginator import Paginator
posts = ['1','2','3','4','5']
# this will show two post at a time on the page
p = Paginator(posts, 2)
print(p.num_pages) #return 3 pages
#using page_range will make an interable
for page in p.page_range:
print("page " + str(page)) # return 1,2,3. these are the page numbers
p1 = p.page(1)
print(p1) #return Page 1 of 3
print(p1.number) #return 1
print(p1.object_list) #return list ['1', '2'], showing objects on a page
# Checking to see if there is a prior page
print(p1.has_previous())
# Checking to see if there is a prior page
print(p1.has_next())
print(p1.next_page_number())
|
6fe26b14fa2da6eaf4d3a06b9e23320345d43195 | lwy1471/DesignPattern | /5. Command/command_remotecontrol_simple.py | 1,295 | 3.828125 | 4 | from abc import ABC, abstractmethod
# command interface
class Command(ABC):
@abstractmethod
def execute(self):
pass
# command concrete class
class LightOnCommand(Command):
def __init__(self, light):
self.light = light
def execute(self):
self.light.on()
class LightOffCommand(Command):
def __init__(self, light):
self.light = light
def execute(self):
self.light.off()
# Recieve class
class Light():
def on(self):
print('Light is on')
def off(self):
print('Light is off')
# Invoker class
class RemoteControl():
def __init__(self):
self.slot = []
def setCommand(self, slotNum, command):
self.slot.insert(slotNum, command)
def buttonPressed(self, slotNum):
self.slot[slotNum].execute()
if __name__ == '__main__':
remote = RemoteControl()
remote.setCommand(0, LightOnCommand(Light()))
remote.setCommand(1, LightOffCommand(Light()))
remote.buttonPressed(0)
remote.buttonPressed(1)
print('change button 0->1, 1->0')
remote.setCommand(0, LightOffCommand(Light()))
remote.setCommand(1, LightOnCommand(Light()))
remote.buttonPressed(0)
remote.buttonPressed(1) |
be99040544704fb97b933944f939e17060b8584d | magmarnowak/LPTHW | /ex15.py | 606 | 4.0625 | 4 | from sys import argv
script, filename = argv
txt = open(filename) #creates a file object that later can be read by .read()
print "Here's your file %r:" % filename
print txt.read() # gives the opened a file (the txt file object) a command to \n
#read its contents and prints them
print "Type the filename again:"
file_again=raw_input("> ")
txt_again = open(file_again) #has to be the same file since the path is \n
#only provided in the commandline argument
print txt_again.read()
txt.close()#closes the file
txt_again.close() #wondering if this is needed - it points to the same file as\n
# txt, right?
|
b53183a2c329ea080d4dd00ac321e5f2c5127b1a | boyima/Leetcode | /lc002.py | 1,463 | 3.90625 | 4 | #You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
#
# You may assume the two numbers do not contain any leading zero, except the number 0 itself.
#
# Example:
#
#
#Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
#Output: 7 -> 0 -> 8
#Explanation: 342 + 465 = 807.
#
# Related Topics Linked List Math
#leetcode submit region begin(Prohibit modification and deletion)
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
dummy = ListNode(0)
curNode = dummy
carry = 0
n1 = l1
n2 = l2
while n1 is not None or n2 is not None or carry is not 0:
curSum = 0
if n1 is not None:
curSum += n1.val
n1 = n1.next
if n2 is not None:
curSum += n2.val
n2 = n2.next
curSum += carry
carry = curSum / 10
curNode.next = ListNode(curSum % 10)
curNode = curNode.next
return dummy.next
#leetcode submit region end(Prohibit modification and deletion)
|
26fe738a21d5ddfa8b31ae1bd22b9e72f7f8c51e | oldman1991/learning_python_from_zero | /demo_07.py | 3,024 | 4.125 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# create by oldman
# Date: 2019/01/10
# 面向对象oo
# 定义一个类
# class Car:
#
# #
# def print_info(self):
# print("I am a car")
#
#
# # 实例化一个类的对象
# car = Car()
#
# # 给类对象的属性复制
# car.color = "黑色"
# car.wheel_num = 4
# print(car.color)
# print(car.wheel_num)
# # 调用对象的实例方法
# car.print_info()
import time
class Car2:
# 初始化函数,用来完成一些默认的设置
# 1. __init__方法,在创建对象时默认被调用,不需要手动调用
# 2. __init__方法中,默认有一个参数名字self,如果在创建对象时传递了2个参数,那么
# __init__(self)中self作为第一个参数外还需要两个参数
# 3. __init__方法中的self参数,不需要开发者传递,python的解释器会自动把当前对象引用
# 传递给self
def __init__(self, color, wheel_num):
self.color1 = color
self.wheel_num1 = wheel_num
def do(self):
print(self.color1)
def __str__(self):
return "I am a car"
# 在python中方法名称如果是__XX__()的,那么就有特俗功能,我们俗称“魔法方法”
# 在使用print输出对象的时间,只要自己定义了__str__()方法,
# 那么就会打印从这个函数中return的数据
# car = Car2("黑色", 4)
# car.do()
# print(car)
# print(car.color1)
# print(car.wheel_num1)
class People:
def __init__(self, name):
self.__name = name
def get_name(self):
return self.__name
def set_name(self, name):
if len(name) < 3:
self.__name == "xiaoming"
else:
self.__name = name
# p = People("xiaozhang")
# # print(p.__name) # 错误的写法
# print(p.get_name())
# 如果在属性名前面加了2个下划线'__', 则表明该属性是私有属性,否则为共有属性(方法也是一样的,
# 方法名前面加了2个"__"下划线表示方法是私有的,否则是公有的)
# __del__方法 在删除一个对象时,python解释器也会默认的调用一个方法就是__del__方法
class Animal(object):
# 初始化方法
def __init__(self, name):
print("__init__方法被调用")
self.__name = name
# 析构方法
# 当对象被回收的时候,会自动被调用
def __del__(self):
print("__del__方法被调用")
print("{}对象马上就要被干掉了".format(self.__name))
dog = Animal("京巴狗")
del dog
cat = Animal("波斯猫")
cat2 = cat
cat3 = cat
print("-----马上开始删除cat对象-----")
del cat
print("-----马上开始删除cat2对象-----")
del cat2
print("-----马上开始删除cat3对象-----")
del cat3
print("程序5秒钟后结束")
time.sleep(5)
# 当有一个变量保存了对象的引用时,此对象的引用计数就会加1
# 当使用del删除变量指向的对象时,对象的引用计数会减一
# 当对象的引用计数为0时,会触发垃圾回收
|
321797dc5d3c36ae6e01d2fc9089dbb6f1385159 | kaust-cs249-2020/fernando-zhapa | /chapter3/_391_k_d_composition.py | 619 | 3.90625 | 4 | def printListOfTuples(list):
string = ""
for item in list:
string += '('+item[0]+'|'+item[1]+') '
print (string[:-1])
def k_d_composition(k, d, string):
#returns the k-d composition of the text. k-d composition are pairs of k-mers separated by distance d
composition = []
for i in range(len(string) - (2*k + d) +1):
firstKmer = string[i:i+k]
secondKmer = string[i+k+d:i+2*k+d]
composition.append((firstKmer,secondKmer))
composition.sort()
return composition
if __name__ == "__main__":
printListOfTuples(k_d_composition(3,2,"TAATGGGATGCCATGTT")) |
7b9ce3a73ec0b638d01e9df42cba0186bea37dff | MayurMah/RandomForest-From-Scratch | /decision_tree.py | 5,313 | 3.59375 | 4 | from util import entropy, information_gain, partition_classes
import numpy as np
import ast
class DecisionTree(object):
def __init__(self):
# Initializing the tree as an empty dictionary or list
# self.tree = []
self.tree = {}
# pass
def learn(self, X, y):
"""Train the decision tree (self.tree) using the the sample X and labels y
Args:
X(list of list): features/attributes
y(list): labels
Returns:
Learned RandomForest Model (tree)
"""
# One possible way of implementing the tree:
# Each node in self.tree could be in the form of a dictionary:
# https://docs.python.org/2/library/stdtypes.html#mapping-types-dict
# For example, a non-leaf node with two children can have a 'left' key and a
# 'right' key. We can add more keys which might help in classification
# (eg. split attribute and split value)
max_depth = 10
min_size = max(int(0.01 * len(y)), 1) # 1% of total data
self.tree = self.split(X, y, max_depth, min_size, 1)
def split(self, X, y, max_depth, min_size, depth):
"""Split the tree on the attribute that provides the maximum info gain
Args:
X(list of list): data containing all attributes/features
y(list): labels
max_depth(int): max allowed depth
min_size(int): minimum number of data points needed to be in a node in order to split
depth(int): current depth
Returns:
Updated tree with the split performed
"""
if len(X) <= min_size:
node = {'index': depth, 'split_attribute': -1, 'split_val': self.to_terminal(y), 'left': {}, 'right': {}}
return node
if depth >= max_depth:
node = {'index': depth, 'split_attribute': -1, 'split_val': self.to_terminal(y), 'left': {}, 'right': {}}
return node
# check all columns to find the column to split on
max_info_gain = -1
max_info_gain_col = -1
max_info_gain_col_val = -1
split_type = ''
for i in range(len(X[0])):
# partition X & y based on i
cur_split_type = ''
currentcol = [row[i] for row in X]
isnumeric = True
try:
float(currentcol[0])
except ValueError:
isnumeric = False
if isnumeric:
split_val = np.mean([float(x) for x in currentcol])
cur_split_type = 'continuous'
else:
split_val = max(set(currentcol), key=currentcol.count)
cur_split_type = 'categorical'
# split_attr, split_val decided
X_left, X_right, y_left, y_right = partition_classes(X, y, i, split_val)
# calculate info gain
current_info_gain = information_gain(y, [y_left, y_right])
if max_info_gain < current_info_gain:
max_info_gain = current_info_gain
max_info_gain_col = i
max_info_gain_col_val = split_val
split_type = cur_split_type
left_node = DecisionTree()
right_node = DecisionTree()
node = dict({'index': depth, 'split_attribute': max_info_gain_col, 'split_val': max_info_gain_col_val,
'split_type': split_type, 'left': left_node, 'right': right_node})
self.tree.update(node)
self.tree['left'] = left_node.split(X_left, y_left, max_depth, min_size, depth + 1)
self.tree['right'] = right_node.split(X_right, y_right, max_depth, min_size, depth + 1)
return self.tree
def to_terminal(self, y):
if y.count(0) >= y.count(1):
return 0
else:
return 1
def classify(self, record):
"""Classify the record using self.tree and return the predicted label
Args:
record(list): new data point to be classified
Returns:
Predicted label for the given record (0 or 1)
"""
pred = self.parse_tree(self.tree, record)
return pred
def parse_tree(self, node, X):
"""Recursively parse the tree until the label for the given record is found
Args:
node(tree): current node
X(list): given record
Returns:
Split value of the node
"""
if node['split_attribute'] == -1:
return node['split_val']
if node['split_type'] == 'continuous':
if X[node['split_attribute']] <= node['split_val']:
return self.parse_tree(node['left'], X)
else:
return self.parse_tree(node['right'], X)
if node['split_type'] == 'categorical':
if X[node['split_attribute']] == node['split_val']:
return self.parse_tree(node['left'], X)
else:
return self.parse_tree(node['right'], X)
# Testing code
# d = DecisionTree()
# X = [[3, 'aa', 10],
# [1, 'bb', 22],
# [2, 'cc', 28],
# [5, 'bb', 32],
# [4, 'cc', 32]]
# y = [1,1,0,0,1]
# d.learn(X,y)
# pred = d.classify([5, 'bb', 32])
# print("predicted:")
# print(pred)
|
2d3baf4b0690dd6e7815daf3cd93942dfda48b27 | ultraman-agul/python_demos | /元组列表/findTheBiggest.py | 217 | 4 | 4 | print("How many numbers are there?", end=" ")
n = int(input())
ls = []
for i in range(0, n):
print("Enter a number >>", end=" ")
ls.append(eval(input()))
print("The largest value is %d" % max(ls)) |
a725d3fd7d8db877ee9206551d5fe26c68924cd6 | BaeVic/201819A_cityu_com5507 | /py_codes/05_ds_dic.py | 138 | 4.1875 | 4 | # dictionary
dic1 = {'one':1, 'two':2, 'three':3}
print(dic1)
print(len(dic1)) # how many elements in total in the dictionary (dict1)?
|
3ad6a4ff68af59742ceedd02d8ae1207fa74ba1d | harshildarji/Python-HackerRank | /Sets/Set add().py | 192 | 3.703125 | 4 | # Set .add()
# https://www.hackerrank.com/challenges/py-set-add/problem
n = int(input().strip())
countries = set()
for i in range(n):
countries.add(input().strip())
print(len(countries))
|
ad36a00ddb252a48269726cce87f575e047c7b5a | itnks/Dominos | /Node.py | 3,683 | 4 | 4 | class Node(object):
def __init__(self, data, next):
self.data = data
self.next = next
###########################################
###########################################
class SingleList(object):
head = None
tail = None
def show(self):
print "Showing list data:"
current_node = self.head
while current_node is not None:
print current_node.data, " -> ",
current_node = current_node.next
print None
def append(self, data):
node = Node(data, None)
if self.tail is None:
self.tail = self.head = node
else:
self.head.next = node
self.head = node
def appendH(self, data):
node = Node(data, None)
if self.tail is not None:
self.head = node
else:
while(self.head.next != None):
self.head = self.head.next
self.head = node
# current = self.head
# while current is not None:
# #self.head = self.head.next
# current = current.next
#self.head = node
# self.head.next = self.head #and self.head.next = self.head.next.next
def printHead(self):
print self.head.data
#from random import shuffle
zero = [[0,0],[0,1],[0,2],[0,3],[0,4],[0,5],[0,6]]
one = [[1,1],[1,2],[1,3],[1,4],[1,5],[1,6]]
two = [[2,2],[2,3],[2,4],[2,5],[2,6]]
three = [[3,3],[3,4],[4,5],[3,6]]
four = [[4,4],[4,5],[4,6]]
five = [[5,5],[5,6]]
six = [[6,6]]
deck = []
deck.append(zero)
deck.append(one)
deck.append(two)
deck.append(three)
deck.append(four)
deck.append(five)
deck.append(six)
i = 0
tails = []
for size in deck:
for size0 in size:
# print(size0)
# print(" ")
tails.append(size0)
p1 = []
p2 = []
p3 = []
p4 = []
i1 = 0
i2 = 0
#shuffle(tails)
for x in tails:
if len(p1) != 7:
p1.append(x)
# print("p1: ", x)
tails.remove(x)
elif len(p2) != 7:
p2.append(x)
# print("p2: ", x)
tails.remove(x)
for x in tails:
if len(p3) != 7:
p3.append(x)
# print("p3: ", x)
tails.remove(x)
"""
for x in tails:
while len(p4) != 7:
p4.append(x)
# print("p4: ", x)
tails.remove(x)
"""
s = 0
while len(p4) != 7:
p4.append(tails[s])
tails.remove(tails[s])
s + s+1
"""
print(tails)
print(p1)
print(p2)
print(p3)
print(p4)
"""
def pla(place, p):
lis = []
if len(place) == 0:
place.append(p)
elif place[0][0] == p[0]:
place = [p] + place
elif place[-1][1] == p[1]:
place.append(p)
else:
print("inv")
return place
place = []
pla(place, p1[1])
print(place)
a = [2,3]
b = [0,3]
c = [6,2]
f = [4,6]
pla(place, a)
pla(place, c)
pla(place, f)
print(pla(place, b))
print(place)
##########################
d = SingleList()
#d.append(p1)
#d.append(p2)
#d.append(p3)
#d.append(p4)
def move(index, node):
if node.head is None:
node.append(index)
print("yes")
else:
print("no")
#move(p1[0], d)
"""
d.append(10)
d.append(5)
d.append(15)
d.append(3)
d.show()
d.printHead()
d.appendH(6)
d.printHead()
d.show()
"""
|
986665f3ebde3dddd37e76333dc6c526da120d93 | souvinix/HS | /Ball_test.py | 952 | 3.8125 | 4 | from tkinter import *
from random import *
class Ball:
def __init__(self, canvas, x1, y1, x2, y2):
self.x1 = x1
self.y1 = y1
self.x2 = x2
self.y2 = y2
self.canvas = canvas
self.ball = canvas.create_oval(self.x1, self.y1, self.x2, self.y2, fill="red", tags = 'ball')
def move_ball(self):
deltax = 1
deltay = 1
self.canvas.move(self.ball, deltax, deltay)
self.canvas.after(40, self.move_ball)
def return_ball(self):
#self.canvas.move(self.ball, - 20, -20)
print('Ball')
def Ball_bind(self):
self.canvas.tag_bind('ball', '<Enter>', self.return_ball)
# initialize root Window and canvas
root = Tk()
root.title("Balls")
canvas = Canvas(root, width = 1000, height = 1000)
canvas.pack()
# create two ball objects and animate them
ball1 = Ball(canvas, 10, 10, 30, 30)
ball1.move_ball()
ball1.Ball_bind()
root.mainloop()
|
d53489c13dd78ae42d877aad36bfb98e84d2c04e | SeanFoley123/word_reader | /word_reader2.py | 4,208 | 3.828125 | 4 | class Node(object):
"""This will ONLY work for words that all start with the same letter. It starts checking at the children level, not the grandparent.
You also need to specify if the first letter begins a word.
Also credit goes to http://cbio.ufs.ac.za/live_docs/nbn_tut/trees.html
"""
def __init__(self, value, children=None):
self.value = value
self.children = children
if self.children == None:
self.children = []
def check(self, string_in, index=0): #checks if the next index of the given string is the value of any of self's children. I think this one works.
i = 0 #index of which child you are at
letter_is_word = string_in[0] in ['a', 'i', 'o']
if len(string_in)==1 and letter_is_word: #Depends on the letter: a is a word, e is not.
return True
while True: #as long as you don't have a result, keep checking through the children
if i == len(self.children): #if we've exhausted all the children without returning a true
return False
child = self.children[i]
if child.value == string_in[index+1]: #if the child has the value of the next index of the string: so, if
if index+1 == len(string_in)-1:
return child.is_leaf()
else: #not the end of the string, so go another layer deep
return child.check(string_in, index+1)
i += 1
def display(self, level = 0):
ret = "\t"*level+repr(self.value)+"\n"
for child in self.children:
ret += child.display(level+1)
return ret
def is_leaf(self):
for child in self.children: #is it a standalone word? ex: cartoon is a word. Every word must end in ''
if child.value == '':
return True
return False
def return_children_values(self):
result = []
for child in self.children:
result.append(child.value)
return result
def create_node(word_list, start_letter):
whole_node = Node(start_letter)
added_node = False
for word in word_list:
current_node = whole_node
for i in range(1, len(word)):
for child in current_node.children:
if word[i] == child.value:
current_node = child
added_node = True
break
if not added_node:
new_node = Node(word[i], [])
current_node.children.append(new_node)
current_node = new_node
added_node = False
current_node.children.append(Node(''))
return whole_node
def list_words(word_in):
all_words_file = open('words.txt') #makes a list of words out of the file
all_words = []
for word in all_words_file:
all_words.append(word.strip())
all_words.sort()
end_index = 0 #makes a dictionary of lists of words starting with each letter
list_dict = {}
for letter in ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']:
temp = []
for i in range(end_index, len(all_words)):
if all_words[i][0] != letter:
end_index = i
break
temp.append(all_words[i])
list_dict[letter] = temp
node_dict = {}
for key in list_dict: #turns the dictionary of lists into a dictionary of trees
node_dict[key] = create_node(list_dict[key], key)
words_result = []
for i in range(len(word_in)):
for k in range(i+1, len(word_in)):
if word_in[i:k+1] not in words_result:
result = node_dict[word_in[i]].check(word_in[i:k+1])
if result:
words_result.append(word_in[i:k+1])
for i in range(len(words_result)):
words_result[i] = words_result[i].title()
words_result.sort() #make the list sorted a. by length and b. alphabetically
words_result.sort(key=len, reverse=True)
print
print words_result #prints results and restarts
print
word_input(False)
def word_input(first):
if first:
user_word = raw_input('Enter a word: ')
else:
user_word = raw_input('Enter another word! This is fun!: ')
user_word = user_word.lower()
adjusted_input = []
for letter in user_word:
if letter in ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']:
adjusted_input.append(letter)
adjusted_input = ''.join(adjusted_input)
list_words(adjusted_input)
if __name__ == '__main__':
word_input(True) |
394ca6b951197ef52d366cc693b6ec0d492e5181 | rambler-digital-solutions/aioriak | /aioriak/datatypes/set.py | 2,987 | 3.5625 | 4 | import collections
from aioriak.datatypes.datatype import Datatype
from aioriak.datatypes import TYPES
class Set(collections.Set, Datatype):
'''A convergent datatype representing a Set with observed-remove
semantics. Currently strings are the only supported value type.
Example::
myset.add('barista')
myset.add('roaster')
myset.add('brewer')
Likewise they can simply be removed::
myset.discard('barista')
This datatype also implements the `Set ABC
<https://docs.python.org/2/library/collections.html>`_, meaning it
supports ``len()``, ``in``, and iteration.
'''
type_name = 'set'
_type_error_msg = 'Sets can only be iterables of strings'
def _post_init(self):
self._adds = set()
self._removes = set()
def _default_value(self):
return frozenset()
def add(self, element):
'''
Adds an element to the set.
.. note: You may add elements that already exist in the set.
This may be used as an "assertion" that the element is a
member.
:param element: the element to add
:type element: str
'''
self._check_element(element)
self._adds.add(element)
def discard(self, element):
'''
Removes an element from the set.
.. note: You may remove elements from the set that are not
present, but a context from the server is required.
:param element: the element to remove
:type element: str
'''
self._check_element(element)
self._require_context()
self._removes.add(element)
def to_op(self):
'''
Extracts the modification operation from the set.
:rtype: dict, None
'''
if not self._adds and not self._removes:
return None
changes = {}
if self._adds:
changes['adds'] = list(self._adds)
if self._removes:
changes['removes'] = list(self._removes)
return changes
@Datatype.modified.getter
def modified(self):
'''
Whether this set has staged adds or removes.
'''
return len(self._removes | self._adds) > 0
# collections.Set API, operates only on the immutable version
def __contains__(self, element):
return element in self.value
def __iter__(self):
return iter(self.value)
def __len__(self):
return len(self.value)
def _coerce_value(self, new_value):
return frozenset(new_value)
def _check_type(self, new_value):
if not isinstance(new_value, collections.Iterable):
return False
for element in new_value:
if not isinstance(element, str):
return False
return True
@classmethod
def _check_element(cls, element):
if not isinstance(element, str):
raise TypeError(Set._type_error_msg)
TYPES[Set.type_name] = Set
|
ef6c96d27f6fe639e573985a4dc0a578bde79d6d | Yosha2707/data_structure_algorithm | /asigments_files/dp_2/knapsack.py | 1,487 | 4.125 | 4 | # 0 1 Knapsack - Problem
# Send Feedback
# A thief robbing a store can carry a maximal weight of W into his knapsack. There are N items, and i-th item weigh 'Wi' and the value being 'Vi.' What would be the maximum value V, that the thief can steal?
# Input Format :
# The first line of the input contains an integer value N, which denotes the total number of items.
# The second line of input contains the N number of weights separated by a single space.
# The third line of input contains the N number of values separated by a single space.
# The fourth line of the input contains an integer value W, which denotes the maximum weight the thief can steal.
# Output Format :
# Print the maximum value of V that the thief can steal.
# Constraints :
# 1 <= N <= 20
# 1<= Wi <= 100
# 1 <= Vi <= 100
# Time Limit: 1 sec
# Sample Input 1 :
# 4
# 1 2 4 5
# 5 4 8 6
# 5
# Sample Output 1 :
# 13
# Sample Input 2 :
# 5
# 12 7 11 8 9
# 24 13 23 15 16
# 26
# Sample Output 2 :
# 51
from sys import stdin
def knapsack(weights, values, n, maxWeight) :
pass
def takeInput() :
n = int(stdin.readline().rstrip())
if n == 0 :
return list(), list(), n, 0
weights = list(map(int, stdin.readline().rstrip().split(" ")))
values = list(map(int, stdin.readline().rstrip().split(" ")))
maxWeight = int(stdin.readline().rstrip())
return weights, values, n, maxWeight
#main
weights, values, n, maxWeight = takeInput()
print(knapsack(weights, values, n, maxWeight)) |
f3efb1a19070aef58b0fdc559104a9b7ebcb1f8a | Anjualbin/workdirectory | /Regular exprn/Quantifiers.py | 1,556 | 3.734375 | 4 | # quantifiers
# x='a+' a including group
# x='a*' count including zero number of a
# x='a?' count a as each including zero no of a
# x='a{2}' 2 no of a position
# x='a{2,3}' minimum 2 a and maximum 3 a
# x='^a' check starting with a
# x='a$' check ending with a
# import re
# x='a+' # a in cluding groups, checks for group of a, minmum 1 a should be there
# r="aaab12 456 abdca"
# match=re.finditer(x,r)
# for i in match:
# print(i.start(),i.group())
# import re
# x='a*' # count including zero number of a, check all positions for a,excluding group
# r="aaab12 456 abdca"
# match=re.finditer(x,r)
# for i in match:
# print(i.start(),i.group())
# import re
# x='a?' # count a as each including 0 no of a, check all positions for a
# r="aaab12 456 abdca"
# match=re.finditer(x,r)
# for i in match:
# print(i.start(),i.group())
# import re
# x='a{2}' # 2 nof as together
# r="aaab12 456 abcaaaa"
# match=re.finditer(x,r)
# for i in match:
# print(i.start(),i.group())
# import re
# x='a{1,3}' # checks for maximum then take that else one less than max, then continue till min
# r="aaab12 aaaaa abdcaa"
# match=re.finditer(x,r)
# for i in match:
# print(i.start(),i.group())
# import re
# x='^a' # check starting with a(entire string start with a)
# r="aaab12 456 abdca"
# match=re.finditer(x,r)
# for i in match:
# print(i.start(),i.group())
# import re
# x='a$' # check ending with a(string end with a)
# r="aaab12a 456 abdca"
# match=re.finditer(x,r)
# for i in match:
# print(i.start(),i.group())
|
232cb05114455c02109bfe3d5e9a9d6e4d8dbfce | nigefanshu/mytools | /bitcoin_tools.py | 1,131 | 3.5 | 4 | # 输入难度位计算出目标值、难度值
def compute_target_diff():
# 难度值为1的目标值:
maxcurrenttargettarget = 0x00000000FFFF0000000000000000000000000000000000000000000000000000
nbits = input("输入难度位:")
nbits = int(nbits, 16)
print("难度位十进制:", nbits)
power = (nbits // (16 ** 6) - 3) * 8
base = nbits % (16 ** 6)
currenttarget = base * (2 ** power)
print("目标值十进制:", currenttarget)
currenttarget_hex = hex(currenttarget)
print(
"目标值十六进制:%s 现在%d位数 左侧省略%d个0 " % (currenttarget_hex, len(currenttarget_hex) - 2, 66 - len(currenttarget_hex)))
print("难度值:%.20f" % (maxcurrenttargettarget / currenttarget))
def testblockheader():
blockheader = input("blockheader: ")
blockheader = int(blockheader, 16)
print("难度值: ", 0x00000000FFFF0000000000000000000000000000000000000000000000000000 / blockheader)
def expected_time_block():
diff = input("难度:")
power = input("算力(MH/s):")
time = 10 * int(diff) * 7.185 / int(power)
print(time, "mins")
|
32ea312bd7c1d2095e0105bb59b89607c3847437 | Ksammar/EduPy | /task_4.6.py | 1,279 | 3.828125 | 4 | # -*- coding: utf-8 -*-
# Реализовать два небольших скрипта:
# - итератор, генерирующий целые числа, начиная с указанного;
# - итератор, повторяющий элементы некоторого списка, определённого заранее.
# Подсказка: используйте функцию count() и cycle() модуля itertools.
# Обратите внимание, что создаваемый цикл не должен быть бесконечным.
# Предусмотрите условие его завершения.
# Например, в первом задании выводим целые числа, начиная с 3.
# При достижении числа 10 — завершаем цикл.
# Вторым пунктом необходимо предусмотреть условие, при котором повторение элементов списка прекратится.
from itertools import count, cycle
for i in count(3):
print(i)
if i > 10:
break
my_list = ['red', 'yellow', 'green', 'yellow']
j = 0
for i in cycle(my_list):
print(i)
if i == 'green':
j += 1
if j >= 2:
break
|
f4417fc146577566eec3baf04283c1bc63dabb36 | ckimani/Data-Types | /BinarySearch.py | 597 | 3.890625 | 4 | class BinarySearch(ListComprehension):
'''
Child class BinarySearch
'''
def search(self, item):
self.item=item
dictionary={}
if self.a==0:
return False
else:
dictionary[item]+=1
###########################
class ListComprehension(object):
'''
Implementation of the parent class
'''
list=[]
length=None
def _init_(self, a,b):
self.a=len(list)
self.b = difference
self.lenght.list()
def list(self):
for index, number in enumerate(self.a):
if index< self.length-1:
self.a[index+1]-self.a[index]==1
list.append(number)
return list
|
3be8d98efbfea88518d975e925f86a604d5a48c3 | fernandojampa/Lista-Hibrida | /ListaHibrida.py | 5,471 | 3.734375 | 4 | # Classe que vamos usar para tratar as exceções.
from node import Node
class ListaException(Exception):
def __init__(self, msg):
super().__init__(msg)
# Inicio da classe Lista, para instanciar as listas como objetos.
class Lista:
def __init__(self):
self._vetor = []
self._head = None
@property
def vetor(self):
return self._vetor
@property
def head(self):
return self._head
@vetor.setter
def vetor(self, novo):
self._vetor = novo
@head.setter
def head(self, novo):
self._head = novo
# Método para checar se a lista está vazia.
def estaVazia(self):
if not self._vetor:
return True
else:
return False
# Método para checar o tamanho atual da lista em questão.
def tamanho(self):
print("Total de elementos na lista: ", end='')
return (len(self._vetor))
# Método para consultar o conteúdo de um elemento na lista.
def elemento(self, posicao):
try:
if (self.estaVazia()):
raise ListaException("A lista está vazia!")
cursor = self._head
contador = 1
while(cursor != None):
if(contador == posicao):
return (f'O valor referente ao elemento inserido é: {cursor._carga}')
cursor = cursor._prox
contador += 1
except AttributeError:
raise ListaException(
'Valor inserido não consta como um elemento presente na lista. Por favor, tente novamente inserindo um número em que haja elemento referente na lista.')
# Método para buscar um valor na lista.
def busca(self, valor):
try:
if (self.estaVazia()):
raise ListaException("A lista está vazia!")
cursor = self._head
contador = 1
while(cursor != None):
if(cursor._carga == valor):
return contador
cursor = cursor._prox
contador += 1
except AttributeError:
raise ListaException(
'Valor inserido não consta como um valor presente na lista. Por favor, tente novamente inserindo um número em que haja elemento referente na lista.')
# Método para inserir um valor no início da lista.
def inserir_inicio(self, valor):
no = Node(valor)
if not self._head:
self._head = no
else:
no._prox = self._head
self._head = no
self._vetor.append(no)
# Método para inserir um valor no final da lista.
def inserir_final(self, valor):
no = Node(valor)
if not self._head:
self._head = no
else:
cursor = self._head
while cursor != -1:
if cursor._prox == -1:
cursor._prox = no
break
cursor = cursor._prox
self._vetor.append(no)
# Método para trocar a ordem dos elementos da lista.
def trocar_ordem(self, posicao_elem_1, posicao_elem_2):
try:
if posicao_elem_1 <= 0 or posicao_elem_2 <= 0:
raise ListaException(
"\nPosição inválida. Por favor, insira uma posição presente na lista, maior que zero.")
else:
elem_pos_1 = self._vetor[posicao_elem_1-1]
elem_pos_2 = self._vetor[posicao_elem_2-1]
aux = elem_pos_1._carga
elem_pos_1._carga = elem_pos_2._carga
elem_pos_2._carga = aux
except IndexError:
raise ListaException(
"\nPosição não encontrada. Por favor, insira um valor que esteja presente na lista.")
# Método para imprimir os elementos contidos na lista atual.
def imprimir_lista(self):
self.__str__()
# Método para remover um elemento do início da lista.
def remover_inicio(self):
if (self.estaVazia()):
raise ListaException('Não é possível remover de uma lista vazia')
else:
aux = self._head
self._head = self._head._prox
self._vetor.remove(aux)
# Método para remover um elemento do fim da lista.
def remover_final(self):
if (self.estaVazia()):
raise ListaException('Não é possível remover de uma lista vazia.')
elif len(self._vetor) == 1:
self.remove_todos()
else:
cursor = self._head
while cursor != -1:
# Captura o penultimo elemento
if cursor._prox._prox == -1:
ultimo = cursor._prox
self._vetor.remove(ultimo)
cursor._prox = -1
break
cursor = cursor._prox
# Método para limpar a lista, removendo todos seus elementos.
def remove_todos(self):
self._vetor = []
self._head = None
def __str__(self):
cursor = self._head
if not self._head:
print('[]')
else:
while cursor != -1:
if cursor._prox == -1:
print(f'[{cursor._carga} | -1 ] \n')
else:
print(
f'[{cursor._carga} | {self._vetor.index(cursor._prox)}] ', end='')
cursor = cursor._prox
|
9d64cc55747a9e9c6c3f745c73a7de755ba89359 | MrsKamran/pythonFunctionsDeliverable | /pythonFunctionsDeliverable.py | 997 | 3.765625 | 4 | # def sum_to(num):
# sum = 0
# for i in range(num+1):
# sum = sum + i
# return sum
# print(sum_to(6))
# print(sum_to(10))
# def largest(num_list):
# if len(num_list):
# large = num_list[0]
# for num in num_list:
# if large<num:
# large = num
# return large
# print(largest([1,2,3,4,0]))
# print(largest([10,4,2,231,91, 54]))
# def occurances(word,alphabet):
# count = 0
# for i in range(len(word)):
# if alphabet == word[i]:
# count += 1
# return count
# def occurances(word,alphabet):
# count = 0
# for i in range(0, len(word),len(alphabet)):
# if alphabet in word[i:i+len(alphabet)]:
# count += 1
# return count
# print(occurances('fleep floop','e'))
# print(occurances('fleep floop','p'))
# print(occurances('fleep floop','ee'))
# print(occurances('fleep floop','fe'))
def product(*args):
pro = 1
for num in args:
pro = pro*num
return pro
print(product(-1,4))
print(product(2,5,5))
print(product(4,0.5,5))
|
383677a97d6c15585b51408148284d9e6f4faf21 | etothemanders/Skills1 | /skills1.py | 2,214 | 4.15625 | 4 | # Things you should be able to do.
# Write a function that takes a list and returns a new list with only the odd numbers.
def all_odd(some_list):
new_list = []
for num in some_list:
if num % 2 == 1:
new_list.append(num)
return new_list
# Write a function that takes a list and returns a new list with only the even numbers.
def all_even(some_list):
new_list = []
for num in some_list:
if num % 2 == 0:
new_list.append(num)
return new_list
# Write a function that takes a list of strings and returns a new list with all strings of length 4 or greater.
def long_words(word_list):
new_list = []
for word in word_list:
if len(word) >= 4:
new_list.append(word)
return new_list
# Write a function that finds the smallest element in a list of integers and returns it.
def smallest(some_list):
smallest = sorted(some_list)[0]
return smallest
# Write a function that finds the largest element in a list of integers and returns it.
def largest(some_list):
largest = sorted(some_list)[-1]
return largest
# Write a function that takes a list of numbers and returns a new list of all those numbers divided by two.
def halvesies(some_list):
return map(lambda x: x /2, some_list)
# Write a function that takes a list of words and returns a list of all the lengths of those words.
def word_lengths(word_list):
return map(lambda x: len(x), word_list)
# Write a function (using iteration) that sums all the numbers in a list.
def sum_numbers(numbers):
sum = 0
for num in numbers:
sum += num
return sum
# Write a function that multiplies all the numbers in a list together.
def mult_numbers(numbers):
return reduce(lambda x, y: x*y, numbers)
# Write a function that joins all the strings in a list together (without using the join method) and returns a single string.
def join_strings(string_list):
new_string = ""
for word in string_list:
new_string += word
return new_string
# Write a function that takes a list of integers and returns the average (without using the avg method)
def average(numbers):
return sum_numbers(numbers)/float(len(numbers))
|
ab9bab4760411cbc145718547fa209b7593aa6a7 | a-phillips/ProjectEuler | /P204.py | 1,472 | 3.890625 | 4 | """A Hamming number is a positive number which has no prime factor larger than 5.
So the first few Hamming numbers are 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15.
There are 1105 Hamming numbers not exceeding 10^8.
We will call a positive number a generalised Hamming number of type n, if
it has no prime factor larger than n.
Hence the Hamming numbers are the generalised Hamming numbers of type 5.
How many generalised Hamming numbers of type 100 are there which don't exceed 10^9?
Answer: 2944730
Time: 17.7189998627s
"""
import time
def rec_thru(primes, i, product, limit, count):
n = 0
temp_product = product*(primes[i]**n)
while temp_product <= limit:
if i+1 < len(primes):
count = rec_thru(primes, i+1, temp_product, limit, count)
elif i+1 == len(primes):
count += 1
n += 1
temp_product = product*(primes[i]**n)
return count
def get_primes(limit):
bin_primes = [0]*(limit+1)
primes = []
for i in xrange(2, limit+1):
if bin_primes[i] == 0:
primes.append(i)
elim = i*2
while elim <= limit:
bin_primes[elim] = 1
elim += i
return primes
def run(hamm_type, limit):
t0 = time.time()
primes = get_primes(hamm_type)
result = rec_thru(primes, 0, 1, limit, 0)
print time.time()-t0
print result
if __name__ == '__main__':
run(100, 10**9)
|
e1139675321c700fff279dc5ed11d32585478a69 | freedom-zjw/JPEG_python | /JPEG/tools/Zigzag.py | 1,170 | 3.59375 | 4 | # coding=utf-8
M = 8
def check(i, j):
return i >=0 and j >=0 and i < M and j < M
def zigzag(matrix, Zigzag_order):
"""
zigzag扫描
"""
temp = []
i, j =0, 0
direct = 1 # 0 for 左下, 1 for 右上
temp.append(matrix[0])
for k in range(0, M * M - 1):
if direct == 0:
if check(i+1, j-1): # check是检查是否超出边界
i, j = i+1, j-1
elif check(i+1, j):
i, direct = i+1, 1
elif check(i, j+1):
j, direct = j+1, 1
else:
if check(i-1, j+1):
i, j = i-1, j+1
elif check(i, j+1):
j, direct = j+1, 0
elif check(i+1, j):
i, direct = i+1, 0
if len(Zigzag_order) != M*M: # Zigzag_order[i]表示扫描后的第i个在扫描前的索引。
Zigzag_order.append(i * M + j)
temp.append(matrix[i * M + j])
return temp
def re_zigzag(matrix, Zigzag_order):
"""
使用Zigzag_order恢复扫描前的顺序
"""
temp = list(range(64))
for i in range(64):
temp[Zigzag_order[i]] = matrix[i]
return temp |
e25f7a750223910b8988798415ca8ab5f7e64afc | shuklaumesh/AviStuff | /TablesNew.py | 747 | 4.28125 | 4 | while True:
input_one=input("This is a multiplication/division table whatever number you type it will give u answer.. ")
input_two=input("What is the length of the table? .. ")
getOut = 0
while getOut==0:
input_three=input("Do u want to use multiplication or division ( *or/ )")
var2=1
while var2 < int(input_two)+1:
if input_three == "*":
print(str(input_one) + " * " + str(var2) + " = " + str(int(var2)*int(input_one)))
elif input_three == "/":
print(str(input_one) + " / " + str(var2) + " = " + str(int(input_one)/int(var2)))
else:
print("Invalid Answer")
break
var2 +=1
getOut=1
|
1f0d0327860fbe39f904aab7624c50cf42e67bd8 | li-zeqing/learn_python | /tiantianxiangshang.py | 559 | 3.71875 | 4 | #以1个月为一个周期,连续学习10天能力值不变,从第11天开始至第30天每天能力增长N
#对于不同的N,当连续学习360天后能力值(年终值)是多少
def dayUp(N):
dayup = 1.0
for j in range(12):
for i in range(30):
if i >=10 :
dayup = dayup *(1+N)
else:
pass
return dayup
dayfactor = (0.01,0.02,0.04,0.06,0.08,0.1)
print(len(dayfactor))
for i in range(len(dayfactor)):
print("N=",dayfactor[i])
print("年终值:",dayUp(dayfactor[i]))
|
57b2d795c71ba6c10c4d92d0f92efeff5c7898ca | ziozn/zio | /untitled/函数的定义/公约(倍)数.py | 159 | 3.578125 | 4 | """
函数的定义和使用 - 求最大公约数和最小公倍数
Version: 0.1
Author: 骆昊
Date: 2018-03-05
"""
for x in range(10, 1, -1):
print(x)
|
503bba517b8eaba9653f1fa40eae0dcb699c6c23 | AdityaJ42/Multi-Document-Extractive-Summarization | /modules/shortest.py | 963 | 3.515625 | 4 | class Graph():
def __init__(self, vertices):
self.V = vertices
self.graph = [[0 for column in range(vertices)] for row in range(vertices)]
self.parent = {}
def maxDistance(self, dist, sptSet):
maximum = -1
for v in range(self.V):
if dist[v] >= maximum and sptSet[v] == False:
maximum = dist[v]
max_index = v
return max_index
def getPath(self, parents, src, last):
sentences = [last]
i = last
while i != src:
temp = parents[i]
i = temp
sentences.append(temp)
return sentences[::-1]
def dijkstra(self, src, last):
dist = [-1] * self.V
dist[src] = 0
sptSet = [False] * self.V
for cout in range(self.V):
u = self.maxDistance(dist, sptSet)
sptSet[u] = True
for v in range(self.V):
if self.graph[u][v] > 0 and sptSet[v] == False and dist[v] < dist[u] + self.graph[u][v]:
dist[v] = dist[u] + self.graph[u][v]
self.parent[v] = u
return self.getPath(self.parent, src, last)
|
3329a1f343eb882982ed3feaedf307723320ca03 | ankitbaluni123/GPS-Route-Analyser | /analysis.py | 3,754 | 3.53125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 22 06:53:40 2020
@author: piyush
"""
import time
import pandas as pd
import matplotlib.pyplot as plt
import os
import gpxpy
import math
def gpx_dataframe(file):
"""
Parameters
----------
file : string
path of the gpx file
Returns
-------
df : pd.Dataframe
Dataframe of gpx xml file
"""
gpx_file = open(file, 'r')
gpx = gpxpy.parse(gpx_file)
df = pd.DataFrame(columns=['lat', 'lon', 'ele', 'time'])
for segment in gpx.tracks[0].segments: # all segments
data = segment.points
for point in data:
df = df.append({'lon': point.longitude, 'lat' : point.latitude, 'ele' : point.elevation, 'time' : point.time}, ignore_index=True)
return df
def dis_points(lat1, lon1, lat2, lon2):
"""
Parameters
----------
lat1 : Integer
Latitude of first point
lon1 : Integer
Longitude of first point
lat2 : Integer
Latitude of second point
lon2 : Integer
Longitude of second point
Returns
-------
distance : Integer
distance between two points in kilometers
"""
R = 6373.0
lat1 = math.radians(lat1)
lon1 = math.radians(lon1)
lat2 = math.radians(lat2)
lon2 = math.radians(lon2)
dlon = lon2 - lon1
dlat = lat2 - lat1
a = math.sin(dlat / 2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon / 2)**2
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
distance = R * c
return distance
def dist(file, diff):
"""
Parameters
----------
file : String
The path of the gpx file whose distance needs to be calculated
diff : Integer
The difference between consecutive frames taken into consideration
Returns
-------
exectime : Integer
time required to calculate distance
distance : Integer
route length of gpx file ride
"""
df = gpx_dataframe(file)
distance = 0
i = 0
# Start recording time and calculate distance
start = time.time()
while (i+distance < len(df)):
long1 = df.loc[i]["lon"]
long2 = df.loc[i+diff]["lon"]
lat1 = df.loc[i]["lat"]
lat2 = df.loc[i+diff]["lat"]
distance += dis_points(lat1, long1, lat2, long2)
end = time.time()
exectime = end - start
return exectime, distance
dir = "/home/piyush/IIT Mandi/GPS-Route-Analyser/sample_files"
observations = [2, 4, 6, 8, 16, 32, 64, 128]
times = []
dist_errors = []
actual_dist = []
# Initialise values
for i in range(len(observations)+1):
times.append(0)
dist_errors.append(0)
for i in observations:
start = time.time()
for file in os.listdir(dir):
dist_error +=
end = time.time()
times.append(end-start)
for file in os.listdir(dir):
# Calculate for most accurate case, i.e. diff = 1
tim, dis = dist(dir+"/"+file, 1)
times[0] += tim
t = 1
for i in observations:
obs_time, obs_dist = dist(dir+"/"+file, i)
times[t] += obs_time
dist_error = pow((obs_dist - dis),2)
dist_errors[t] += dist_error
t += 1
observations = [1] + observations
# Plot the Results
plt.figure()
plt.plot(observations, times)
plt.xlabel("Difference between consecutive frames")
plt.ylabel("Time (in seconds)")
plt.title("Computation Time Analysis")
plt.legend()
plt.show()
plt.figure()
plt.plot(observations, dist_errors)
plt.xlabel("Difference between consecutive frames\n(In log scale)")
plt.ylabel("Percentage Error (in %)")
plt.xscale("log")
plt.title("Accuracy Analysis")
plt.legend()
plt.show()
|
ba44a596e83e52ea7d6fdef0f1fa20d417bf0a32 | NickATC/GUI_design | /DataBase/create_test_db.py | 1,530 | 3.9375 | 4 | # Execute this file to create a database. It also adds information for testing purposes.
# Execute only once!
# A file called 'my_database.db' should be created on this same folder
#
# This script doesn't do anything else.
import sqlite3
con_db = sqlite3.connect("my_database.db")
cursor = con_db.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS phone_book \
(id INTEGER PRIMARY KEY AUTOINCREMENT, \
full_name TEXT, \
phone_number TEXT, \
email TEXT, \
notes TEXT)")
# insert data
cursor.execute("INSERT INTO phone_book (full_name, phone_number, email, notes) \
VALUES (?, ?, ?, ?)", ("Nicolas Tautiva", "123-456789", "nicolas_tautiva@mail.com", "Not his real email."))
cursor.execute("INSERT INTO phone_book (full_name, phone_number, email, notes) \
VALUES (?, ?, ?, ?)", ("Pedro Jimenez", "987-654310", "pedro_jimenez@mail.com", "Fake person."))
cursor.execute("INSERT INTO phone_book (full_name, phone_number, email, notes) \
VALUES (?, ?, ?, ?)", ("Juan Perez", "456-789123", "juan_perez@mail.com", "Nothing here"))
cursor.execute("INSERT INTO phone_book (full_name, phone_number, email, notes) \
VALUES (?, ?, ?, ?)", ("Maria Ramirez", "369-258147", "maria_ramirez@mail.com", ""))
# commit transaction
con_db.commit()
# close cursor and connection
cursor.close()
con_db.close()
print("...")
print("Database created")
print("information added successfully!")
|
5739f4f8e83f41a8eff8b548af7999349b6c70ff | abhisheksansanwal/rankwatch17_py_csvbreakdown | /observe raw directory.py | 368 | 3.703125 | 4 | #To work on data analysing us package pandas
import panda as pd
#To read the csv file
pd.read_csv('Testdata.csv'
#The data is merging
frame1=pd.Dataframe ({key:range(5)})
frame1=pd.Data frame ({key:range(5)})'frame1':['a','b','c','d','e']})
frame2=pd.Data frame ({key:range(5)})'frame2':['t','u','v','w','x']})
pd.merge(frame1,frame2,on='key',how='left')
|
d16abdffc0d5cc9519e7ef13ebfc490bed815607 | Abooow/BattleShips | /BattleShips/framework/animation.py | 2,742 | 4.09375 | 4 | ''' This module contains the Animation class
'''
import pygame
import config
import surface_change
class Animation():
''' The base class for an animation, this class can either be instantiated directly or inherited
The Animation class uses a list of images as frames and changes what frame to draw after some time
how to use, example 1:
def load_content(self):
...
anim = Animation(...)
def update(self, delta_time):
...
anim.update(delta_time)
def draw(self):
...
anim.draw(...)
how to use, example 2:
class Missile(Animation):
def __init__(self, ...):
super().__init__(...)
def update(self, delta_time):
super().update(delta_time)
def draw(self):
super().draw(...)
To update the animation: call the update method, otherwise the animation won't animate
To display/draw the animation: call the draw method, otherwise the animation won't be shown
'''
def __init__(self, frames, fps, loop = True, offset = 0):
'''
:param frames (list[surface]): all the frames to be used
:param fps (int): the animation speed (frames per second)
:param loop (bool): allow the animation to loop
:param offset (int): what frame to start animate from
'''
self.frames = frames
self.fps = fps
self.loop = loop
self.done = False
self._frame = offset % len(frames)
self._timer = 0
def update(self, delta_time) -> None:
''' Updates the animation
:param delta_time (int): time since last frame
:returns: NoReturn
:rtype: None
'''
# only update if the animation isn't finished
if not self.done:
# update the timer
self._timer += delta_time
# change frame when time is right
if self._timer >= 1000 / self.fps:
self._timer = 0
self._frame += 1
# restart the animation to frame 0 if loop is True, otherwise mark the animation as done
if self._frame >= len(self.frames):
if self.loop:
self._frame = 0
else:
self.done = True
def draw(self, position) -> None:
''' Draws the animation
:param position (tuple[int,int]): the position to draw the animation
:returns: NoReturn
:rtype: None
'''
if len(self.frames) > 0 and not self.done:
config.window.blit(self.frames[self._frame], position) |
bf475b710f8cce53a37add53eef87726cd5751ec | rhildred/MB215Lab2 | /Iknow2.py | 417 | 3.5 | 4 | class Game:
def __init__(self):
self.__nCurrent = -1
def takeTurn(self, sInput):
if(self.__nCurrent == -1):
self.__nCurrent = 0
return["Welcome to I know you are",
"This is an annoying game you might have played",
"with your sibling."
]
else:
return["I know you are a", sInput, "But what am I?"] |
55982594b465e0e6ef952d909ce808404118cd81 | BilelBouquoyoue/Mads-op | /calcul.py | 9,466 | 3.8125 | 4 | from random import *
class Calcul:
"""
Classe permettant d'appeler les autres classes et de démarrer le jeu
:type resultat_algo = int
:type resultat_utilisateur = int
"""
def __init__(self, tableau_chiffre):
"""
Initialisation du calcul
:param tableau_chiffre: Tableau contenant les chiffres du calcul
"""
self.resultat_algo = tableau_chiffre[0]
self.resultat_utilisateur = 0
def __eq__(self, other):
print("Calcul __eq__ est appelé")
return self.value == other
# Operation entre les 2 premiers chiffres
def calcul_algorithme(self, tableau_chiffre, tableau_operation, tableau_operation_erreur):
"""
Méthode permettant de faire le calcul du jeu
:param tableau_chiffre: Tableau contenant les chiffres du calcul
:param tableau_operation: Tableau contenant les opérations du calcul
:param tableau_operation_erreur: Tableau contenant les 4 opérations
"""
if tableau_operation and tableau_chiffre and tableau_operation_erreur:
self.resultat_utilisateur = tableau_chiffre[0]
if tableau_operation[0] == '/':
if self.resultat_algo % tableau_chiffre[1] == 0:
self.resultat_algo = self.resultat_algo / tableau_chiffre[1]
else:
nouvelle_operation = tableau_operation_erreur[randint(0, 2)]
if nouvelle_operation == '+':
self.resultat_algo = self.resultat_algo + tableau_chiffre[1]
elif nouvelle_operation == '-':
self.resultat_algo = self.resultat_algo - tableau_chiffre[1]
elif nouvelle_operation == '*':
self.resultat_algo = self.resultat_algo * tableau_chiffre[1]
elif tableau_operation[0] == '+':
self.resultat_algo = self.resultat_algo + tableau_chiffre[1]
elif tableau_operation[0] == '-':
self.resultat_algo = self.resultat_algo - tableau_chiffre[1]
elif tableau_operation[0] == '*':
self.resultat_algo = self.resultat_algo * tableau_chiffre[1]
# operation avec le 3eme chiffre
shuffle(tableau_operation)
if tableau_operation[0] == '/':
if self.resultat_algo % tableau_chiffre[2] == 0:
self.resultat_algo = self.resultat_algo / tableau_chiffre[2]
else:
nouvelle_operation = tableau_operation_erreur[randint(0, 2)]
if nouvelle_operation == '+':
self.resultat_algo = self.resultat_algo + tableau_chiffre[2]
elif nouvelle_operation == '-':
self.resultat_algo = self.resultat_algo - tableau_chiffre[2]
elif nouvelle_operation == '*':
self.resultat_algo = self.resultat_algo * tableau_chiffre[2]
elif tableau_operation[0] == '+':
self.resultat_algo = self.resultat_algo + tableau_chiffre[2]
elif tableau_operation[0] == '-':
self.resultat_algo = self.resultat_algo - tableau_chiffre[2]
elif tableau_operation[0] == '*':
self.resultat_algo = self.resultat_algo * tableau_chiffre[2]
# Operation avec le 4eme chiffre
shuffle(tableau_operation)
if tableau_operation[0] == '/':
if self.resultat_algo % tableau_chiffre[3] == 0:
self.resultat_algo = self.resultat_algo / tableau_chiffre[3]
else:
nouvelle_operation = tableau_operation_erreur[randint(0, 2)]
if nouvelle_operation == '+':
self.resultat_algo = self.resultat_algo + tableau_chiffre[3]
elif nouvelle_operation == '-':
self.resultat_algo = self.resultat_algo - tableau_chiffre[3]
elif nouvelle_operation == '*':
self.resultat_algo = self.resultat_algo * tableau_chiffre[3]
elif tableau_operation[0] == '+':
self.resultat_algo = self.resultat_algo + tableau_chiffre[3]
elif tableau_operation[0] == '-':
self.resultat_algo = self.resultat_algo - tableau_chiffre[3]
elif tableau_operation[0] == '*':
self.resultat_algo = self.resultat_algo * tableau_chiffre[3]
@staticmethod
def check_tableau_utilisateur(tableau):
"""
Méthode vérifiant si la valeur entrée est une liste
:param tableau: tableau de valeur
:return:
"""
if type(tableau) == list:
return True
else:
return False
@staticmethod
def check_tableau_taille(tableau):
"""
Méthode vérifiant si le tableau entrée est vide ou non
:param tableau: de valeur
:return:
"""
if not tableau:
return False
else:
return True
def calcul_utilisateur(self, tableau_chiffre, tableau_operation, tableau_operation_erreur):
"""
Méthode permettant de faire le calcul de l'utilisateur
:param tableau_chiffre: tableau de valeur
:param tableau_operation: tableau d'opération
:param tableau_operation_erreur: tableau d'opération sans division
:return:
"""
tableau_chiffre[0] = int(tableau_chiffre[0])
tableau_chiffre[1] = int(tableau_chiffre[1])
tableau_chiffre[2] = int(tableau_chiffre[2])
tableau_chiffre[3] = int(tableau_chiffre[3])
self.resultat_utilisateur = tableau_chiffre[0]
# Operation entre les 2 premiers chiffres
if tableau_operation[0] == '/':
if self.resultat_utilisateur % tableau_chiffre[1] == 0:
self.resultat_utilisateur = self.resultat_utilisateur / tableau_chiffre[1]
else:
nouvelle_operation = tableau_operation_erreur[randint(0, 2)]
if nouvelle_operation == '+':
self.resultat_utilisateur = self.resultat_utilisateur + tableau_chiffre[1]
elif nouvelle_operation == '-':
self.resultat_utilisateur = self.resultat_utilisateur - tableau_chiffre[1]
elif nouvelle_operation == '*':
self.resultat_utilisateur = self.resultat_utilisateur * tableau_chiffre[1]
elif tableau_operation[0] == '+':
self.resultat_utilisateur = self.resultat_utilisateur + tableau_chiffre[1]
elif tableau_operation[0] == '-':
self.resultat_utilisateur = self.resultat_utilisateur - tableau_chiffre[1]
elif tableau_operation[0] == '*':
self.resultat_utilisateur = self.resultat_utilisateur * tableau_chiffre[1]
# operation avec le 3eme chiffre
if tableau_operation[1] == '/':
if self.resultat_utilisateur % tableau_chiffre[2] == 0:
self.resultat_utilisateur = self.resultat_utilisateur / tableau_chiffre[2]
else:
nouvelle_operation = tableau_operation_erreur[randint(0, 2)]
if nouvelle_operation == '+':
self.resultat_utilisateur = self.resultat_utilisateur + tableau_chiffre[2]
elif nouvelle_operation == '-':
self.resultat_utilisateur = self.resultat_utilisateur - tableau_chiffre[2]
elif nouvelle_operation == '*':
self.resultat_utilisateur = self.resultat_utilisateur * tableau_chiffre[2]
elif tableau_operation[1] == '+':
self.resultat_utilisateur = self.resultat_utilisateur + tableau_chiffre[2]
elif tableau_operation[1] == '-':
self.resultat_utilisateur = self.resultat_utilisateur - tableau_chiffre[2]
elif tableau_operation[1] == '*':
self.resultat_utilisateur = self.resultat_utilisateur * tableau_chiffre[2]
# Operation avec le 4eme chiffre
shuffle(tableau_operation)
if tableau_operation[2] == '/':
if self.resultat_utilisateur % tableau_chiffre[3] == 0:
self.resultat_utilisateur = self.resultat_utilisateur / tableau_chiffre[3]
else:
nouvelle_operation = tableau_operation_erreur[randint(0, 2)]
if nouvelle_operation == '+':
self.resultat_utilisateur = self.resultat_utilisateur + tableau_chiffre[3]
elif nouvelle_operation == '-':
self.resultat_utilisateur = self.resultat_utilisateur - tableau_chiffre[3]
elif nouvelle_operation == '*':
self.resultat_utilisateur = self.resultat_utilisateur * tableau_chiffre[3]
elif tableau_operation[2] == '+':
self.resultat_utilisateur = self.resultat_utilisateur + tableau_chiffre[3]
elif tableau_operation[2] == '-':
self.resultat_utilisateur = self.resultat_utilisateur - tableau_chiffre[3]
elif tableau_operation[2] == '*':
self.resultat_utilisateur = self.resultat_utilisateur * tableau_chiffre[3]
|
a3c2dd3f6574e6215d9b9b30cce6e8655582822c | xiez/leetcode | /706*design-hashmap/solution.py | 2,253 | 3.9375 | 4 | class MyHashMap(object):
class Entry:
def __init__(self, key, val, next=None):
self.key = key
self.val = val
self.next = next
def __init__(self):
"""
Initialize your data structure here.
"""
self.size = 7919
self.lst = [None] * self.size
def _hash_key(self, key):
return key % self.size
def put(self, key, value):
"""
value will always be non-negative.
:type key: int
:type value: int
:rtype: None
"""
hash_key = self._hash_key(key)
cur = self.lst[hash_key]
if cur is None:
self.lst[hash_key] = self.Entry(key, value)
return
prev = None
while cur:
if cur.key == key:
cur.val = value
return
prev = cur
cur = cur.next
prev.next = self.Entry(key, value)
def get(self, key):
"""
Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key
:type key: int
:rtype: int
"""
hash_key = self._hash_key(key)
cur = self.lst[hash_key]
if cur is None:
return -1
while cur:
if cur.key == key:
return cur.val
cur = cur.next
return -1
def remove(self, key):
"""
Removes the mapping of the specified value key if this map contains a mapping for the key
:type key: int
:rtype: None
"""
hash_key = self._hash_key(key)
head = self.lst[hash_key]
if head is None:
return
prev = None
while head:
if head.key == key:
if prev is None:
self.lst[hash_key] = head.next
else:
prev.next = head.next
return
else:
prev = head
head = head.next
# Your MyHashMap object will be instantiated and called as such:
# obj = MyHashMap()
# obj.put(key,value)
# param_2 = obj.get(key)
# obj.remove(key)
|
d392c285808d079b423c0214ac1ce6a020bc5dae | jieunin1213/NLP | /nlp_class_day1-master/04_word_count_ex02.py | 456 | 4.0625 | 4 | '''
dict를 여러가지 방법으로 정렬
'''
mydict = {'a':20, 'b':30, 'c':10}
# 값(value)이 가장 큰 거부터 역순으로 정렬
byValues = sorted(mydict.values(), reverse=True)
print( byValues )
# 키를 기준으로 역순 정렬
byKeys = sorted(mydict.keys(), reverse=True)
print( byKeys )
# 값(value)을 역순으로 정렬하되 키를 보여 주기
keysortByValue = sorted(mydict, key=mydict.get, reverse=True)
print( keysortByValue ) |
d9754b7ab5b52ad8dcaad1ca5abe63c638ed4817 | lly102799-git/python-cookbook | /第5章 文件和IO/5.4 读写二进制数据/read_write_binary_data.py | 931 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
@project: python-cookbook
@date: 2020-11-24 15:35
@author: Li Luyao
"""
# 使用open()函数的rb或者wb模式就可以实现对二进制数据的读或写
# Write binary data to file
# with open('somefile.txt', 'xb') as f:
# f.write(b'Hello World!')
# Read the entire file as a single byte string
with open('somefile.txt', 'rb') as f:
data = f.read()
print(data)
# Text string 和 Byte string
t = 'Hello World'
b = b'Hello World'
for c in t:
print(c)
for c in b:
print(c)
# 在二进制文件中进行读取或写入文本内容,请确保进行编码和解码操作
# with open('some_binfile.bin', 'xb') as bf:
# bf.write(b'Hello World')
with open('some_binfile.bin', 'rb') as bf:
data = bf.read()
text = data.decode('utf-8')
print(text)
print(data)
with open('some_binfile.bin', 'wb') as bf:
text = 'Hello World'
bf.write(text.encode('utf-8')) |
29b5060ba13f6239537a2a099aa3acbb3381b8f7 | sorengoyal/python-practice | /sourcewise/leetcode/20-palindromic -substrings/solution.py | 650 | 3.5 | 4 | class Solution:
def countSubstrings(self, s):
"""
:type s: str
:rtype: int
"""
n = len(s)
count = 0
for i in range(0,n):
for j in range(i,n+1):
#print(j,end=' ')
if self.isPalindrome(s[i:j]):
count += 1
return count
def isPalindrome(self,s):
if len(s) == 0:
return False
m = int(len(s)/2)
for i in range(0,m):
if s[i] != s[-1-i]:
return False
return True
if __name__ == '__main__':
sln = Solution()
print(sln.countSubstrings('aabc')) |
bd4b5381f131f6ade1979c259df006d3bb852896 | codeforgirls-sa/python | /unit2/challenge-operators-meal-recommendation.py | 448 | 3.71875 | 4 | hot = True
cold = False
morning = True
evening = False
night = False
soup = False
biscuit = False
cereal = False
pizza = False
if morning:
if cold:
biscuit = True
else:
cereal = True
elif evening:
pizza = True
if cold:
soup = True
elif night:
pizza = True
cereal = True
if cold:
soup = True
print("soup", soup)
print("biscuit", biscuit)
print("cereal", cereal)
print("pizza", pizza)
|
00db2655f9cb4633d6088618cb5e1c1833efd0ff | elabraha/CodingInterviewQuestions | /two_egg_drop.py | 3,405 | 4.28125 | 4 | # If an egg is dropped from above that floor, it will break. If it is dropped
# from that floor or below, it will be completely undamaged and you can drop the
# egg again.
#
# Given two eggs, find the highest floor an egg can be dropped from without
# breaking, with as few drops as possible.
def floor_egg_break(floors):
# This is my first attempt, it just involves going 2 floors at a time:
# drop_point = 0
# for i in range(0, len(floors), 2):
# if floors[i]:
# drop_point = i
# break
# if drop_point >= 1:
# if not floors[drop_point - 1]:
# return drop_point - 1 # returning the floor starting at 0
# else:
# return drop_point
# An equally dumb idea is to go up by half of the floors (50) and then if
# it breaks go up from the first floor to the 50th and if it doesn't
# go up from the 50th to the 100th and where ever it breaks, the floor
# before that is the answer. I think it has the same runtime as the above.
# So a better idea is the make the drop point somewhere between 50 and 2.
# How about we try 10. I'm not sure what the perfect jumps are it would be
# trial and error for me to know because I don't know the math.
# drop_point = 100
# for i in range(10, 100, 10):
# if floors[i]:
# drop_point = i
# break
# for i in range(drop_point - 10, drop_point):
# if floors[i]:
# drop_point = i - 1
# break
# return drop_point
# Maybe there's a certain point at which the division of 100 is not worth
# it going up by 5 is too small worst case is already maybe 24? Going up by
# 20. Worst case is 5 plus the 19 you'll have to go up which is exactly the
# same. As before 24. My current method is 10 plus the 9 that it will take
# to search. the last one. I can do better maybe 15 which does not divide
# evenly so you have about 7 divisions and then one will be shorter but it
# is still not great. In fact it is worse, it's at 20. So maybe smaller is
# better 8. Worst case is 19 maybe 21? Still not any better,
# I did a combo of trial and error plus a hint. what if we tried to even
# out the jumps. There are less on the lower end and high on the higher
# end. I feel like I thought that but since I increased the size of the
# jumps that would be better but it's not becuase than you have to check
# in between the jumps in floors. I was dumb and didn't think to only have
# a high number in the beginning. I just did trial and error to see where
# I should start in terms of the number from 10+9+8+7... Then tried 11,
# 12, 13
jump_height = 14
drop_point = 100
i = jump_height
while i < 100:
if floors[i]:
drop_point = i
break
jump_height-=1
i+=jump_height
for j in range(drop_point - jump_height, drop_point):
if floors[j]:
drop_point = j - 1
break
return drop_point
# Ugh another arithmatic sum series thing n^2 - n all over 2 equals 100.
# solve for n. n is 13 plus some fraction.
def main():
floors = [False for _ in range(0, 48)] # at floor 48 if we are starting at 1
for _ in range(48, 100):
floors.append(True)
print("egg will not break up to floor:", floor_egg_break(floors))
main()
|
2f5191c402c894a161091309a9b8ea7bf9cdd8cb | StephenLingham/MachineLearning | /raymondTitanicForest.py | 2,887 | 3.59375 | 4 | from sklearn.ensemble import RandomForestClassifier
import pandas
from sklearn import tree
import pydotplus
from sklearn.tree import DecisionTreeClassifier
import matplotlib.pyplot as plt
import matplotlib.image as pltimg
import numpy as np
import types
from sklearn import metrics
from sklearn.model_selection import train_test_split
#import csv
df = pandas.read_csv("./train.csv")
# drop non useful columns
df = df.drop(columns=["PassengerId", "Name", "Ticket",
"Fare", "Cabin"])
# drop rows with any empty cells
# https://hackersandslackers.com/pandas-dataframe-drop
df.dropna(
axis=0,
how='any',
thresh=None,
subset=None,
inplace=True
)
# One-hot encode the data using pandas get_dummies
# https://towardsdatascience.com/random-forest-in-python-24d0893d51c0
df = pandas.get_dummies(df)
print(df.head())
print(df.dtypes)
# split data into "features" and "targets" aka "features" and "labels" where Labels are the values we want to predict, and features the variables we use to predict them
# Use numpy to convert label column to array of values
labels = np.array(df['Survived'])
# Remove the label column from the df
df = df.drop('Survived', axis=1)
# Saving list of feature names as numpy array
features = np.array(df)
# use train_test_split to divide the data into train and test data
train_features, test_features, train_labels, test_labels = train_test_split(
features, labels, test_size=0.01, random_state=42)
# check eveything looks right
print('Training Features Shape:', train_features.shape)
print('Training Labels Shape:', train_labels.shape)
print('Testing Features Shape:', test_features.shape)
print('Testing Labels Shape:', test_labels.shape)
# Instantiate model with 1000 decision trees
rf = RandomForestClassifier(n_estimators=1000, random_state=42)
# Train the model on training data
rf.fit(train_features, train_labels)
# generate predictions for the test data based on test features
predictions = rf.predict(test_features)
# just compare length of the test_labels with the length of the predictions to make sure they are they same
print(len(test_labels))
print(len(predictions))
# compare each actual result on the test_label list and the predicted list and populate true or false depending on if the prediction was right
results = []
for i in test_labels:
if test_labels[i] == predictions[i]:
results.append("TRUE")
else:
results.append("FALSE")
print(results)
# create dataframe of our results
dictionaryForDataFrame = {"Predicted Outcome": predictions,
"Actual Outcome": test_labels, "Prediction Successful": results}
resultsDataFrame = pandas.DataFrame(dictionaryForDataFrame)
print(resultsDataFrame)
# looks like it is pretty accurate but is there any wrong results? check if any 'falses'
print("number of falses:", results.count("FALSE"))
|
fb5f9f57ab1079bea1539c5e871c792616df86ee | murlinochka/ICT | /6.py | 114 | 3.515625 | 4 | a = float(input("Cost of a meal: "))
nalog = 0.5
chaev = 0.18
b = (a*nalog) + (a*chaev) + a
print(b)
|
01a77c6668337b65cc340579c2a2f02cca5b8b22 | ru04ru041989/MOOC | /Project_Euler/Q25.py | 507 | 3.59375 | 4 | # 1000-digit Fibonacci number
'''
The Fibonacci sequence is defined by the recurrence relation:
Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.
Hence the first 12 terms will be:
F9 = 34
F10 = 55
F11 = 89
F12 = 144
The 12th term, F12, is the first term to contain three digits.
What is the index of the first term in the Fibonacci sequence to contain 1000 digits?
'''
index = 2
first, second = 1, 1
while second < 10**999:
first, second = second, first+second
index += 1
print(second)
print(index) |
7e584fec705fcae19c979ecd64fc3c487e7f9c70 | bwats2/CSCIE7-Final-Project | /tests/regextest.py | 264 | 4.125 | 4 | import re
def fraction(phrase: str) -> str:
"Return first fraction or blank"
find = '[+-]\d\d*/\d\d*'
match = re.search(find, phrase)
if match:
return match
else:
return ""
print(fraction("This is +1 /3 true and -2/ 3 false")) |
6e9aeecb1e38aae3e1253033b919038d2c02bb95 | angelavuong/python_exercises | /coding_challenges/intro_sorting.py | 401 | 3.921875 | 4 | '''
Name: Intro to Sorting
Input:
V = the value that has to be searched
n = the size of the array
ar = numbers that make up the array
Output:
The index of V in the array
Sample Input:
4
6
1 4 5 7 9 12
Sample Output:
1
'''
V = int(input().strip())
n = int(input().strip())
arr = list(map(int, input().strip().split(' ')))
for i in range(n):
if (arr[i] == V):
print (i)
else: pass
|
86b9c9a2d23767dd6be05f5fc8e969206ba78840 | Lucass96/Python-Faculdade | /Python-LP/Trabalho/Exercicio01.py | 1,493 | 4.125 | 4 | while True: # este while esta servindo para validar se o usuario quer inserir os dados ou nao
dados = input('Inserir dados? 0- Nao 1- Sim ')
if dados in '0': # caso o usuario digite 0, o programa sera encerrado.
print('encerrando programa...')
break
if dados not in '1': # caso o usuario digite qualquer coisa que nao seja o 1, o laco se repete e aparecec uma mensagem de alerta.
print('Digite 1 para SIM ou 0 para NAO')
continue
#Programa principal
nome = input('Nome do aluno: ')
nota = float(input('Nota final: '))
if nota >= 0.0 and nota <= 2.9:
print('O aluno {} tirou a nota {} e se enquandra no conceito E.'.format(nome, nota))
else:
if nota >= 3.0 and nota <= 4.9:
print('O aluno {} tirou a nota {} e se enquandra no conceito D.'.format(nome, nota))
else:
if nota >= 5.0 and nota <= 6.9:
print('O aluno {} tirou a nota {} e se enquandra no conceito C.'.format(nome, nota))
else:
if nota >= 7.0 and nota <= 8.9:
print('O aluno {} tirou a nota {} e se enquandra no conceito B.'.format(nome, nota))
else:
if nota >= 9.0 and nota <= 10.0:
print('O aluno {} tirou a nota {} e se enquandra no conceito A.'.format(nome, nota))
else:
if nota > 10.0:
print('Nota invalida!') |
21e1663fb39b5a47784ddb5a0cadb8bdd9d183ff | eternity6666/university | /CS/2/DataStructure/help_app/code.py | 113 | 3.53125 | 4 | n = input()
s = "void menu();"
print s
for i in range(n):
s = "void code" + str(i + 1) + "();"
print s
|
5f81277878f77ef3f02eb9c971a5314edecd251f | changwei0708/pylearning | /00x1_numpy/02_numpy_array.py | 1,332 | 3.5625 | 4 | # -*- coding: utf-8 -*-
'''
假设一个团队里有5名学员,成绩如下表所示。
1.用NumPy统计下这些人在语文、英语、数学中的平均成绩、最小成绩、最大成绩、方差、标准差。
2.总成绩排序,得出名次进行成绩输出。
'''
import numpy as np
a = np.array([[4,3,2],[2,4,1]])
print(np.sort(a))
print(np.sort(a, axis=None))
print(np.sort(a, axis=0))
print(np.sort(a, axis=1))
print("\npart 6 作业\n")
persontype = np.dtype({
'names':['name', 'chinese','english','math' ],
'formats':['S32', 'i', 'i', 'i']})
peoples = np.array([("ZhangFei",66,65,30),("GuanYu",95,85,98),
("ZhaoYun",93,92,96),("HuangZhong",90,88,77),
("DianWei",80,90,90)],dtype=persontype)
#指定的竖列
name = peoples[:]['name']
chinese = peoples[:]['chinese']
english = peoples[:]['english']
math = peoples[:]['math']
#定义函数用于显示每一排的内容
def show(name,cj):
print('{} | {} | {} | {} | {} | {} '
.format(name,np.mean(cj),np.min(cj),np.max(cj),np.var(cj),np.std(cj)))
print("科目 | 平均成绩 | 最小成绩 | 最大成绩 | 方差 | 标准差")
show("语文", chinese)
show("英语", english)
show("数学", math)
print("排名:")
#用sorted函数进行排序
ranking = sorted(peoples,key=lambda x:x[1]+x[2]+x[3], reverse=True)
print(ranking) |
488c1a45036d087275bb1aaee84a6b9897e42416 | Yanl05/LeetCode | /one_thousand_twenty_five.py | 985 | 3.671875 | 4 | # -*- coding: UTF-8 -*-
"""
# @Time : 2019-06-25 22:53
# @Author : yanlei
# @FileName: one_thousand_twenty_five.py
爱丽丝和鲍勃一起玩游戏,他们轮流行动。爱丽丝先手开局。
最初,黑板上有一个数字 N 。在每个玩家的回合,玩家需要执行以下操作:
选出任一 x,满足 0 < x < N 且 N % x == 0 。
用 N - x 替换黑板上的数字 N 。
"""
class Solution(object):
def divisorGame(self, N):
"""
:type N: int
:rtype: bool
"""
target = [0 for _ in range(N+1)]
target[1] = 0 # alice 抽到1,lose
if N<=1:
return False
else:
target[2] = 1 # alice 抽到2, win
for i in range(3, N+1):
for j in range(1,i//2):
if i%j==0 and target[i-j]==0:
target[i] = 1
break
return target[N]==1
print(Solution().divisorGame(4)) |
68e8783c97600c2f78d1bde98bf8f4b2476b54c7 | Bilibotter/LeetCode | /leetcode4Z字型变换hahaha.py | 520 | 3.515625 | 4 | class Solution:
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
length = len(s)
if numRows == 1 or numRows > length:
return s
List = ['']*numRows
queue = numRows*2-2
for num, word in enumerate(s):
judge = num % queue
if judge >= numRows:
judge = abs(queue-judge)
List[judge] += str(word)
return ''.join(List) |
c7f63de02773b0bb645a6b93d2825f7b4c83c3bf | linsze/scrabble | /scrabble.py | 26,088 | 4.0625 | 4 | """
Author: Lin Sze Khoo
Created on: 21/11/2020
Last modified on: 23/11/2020
Description: This program is a solo terminal scrabble game. Run the program and start playing.
"""
import exception
BOARD = []
DICTIONARY = [] # Stores a list of valid words
SCORES = {} # A map with letters as keys and scores as values
TILES = [] # Tiles to be placed on the board
CELL_WIDTH = 3 # Width of each cell on the board
TILES_COUNT = 7 # Number of tiles to be chosen from in each turn
USED_TILES = 0 # Number of tiles used
BOARD_OCCUPIED_TILES = 0 # Number of tiles occupied on the board
TOTAL_SCORE = 0 # Total score of player
def welcomeMessage():
"""
Prints welcome message and reads from "rules.txt" to print the game rules.
"""
print("GOOD DAY! WELCOME TO THE SCRABBLE GAME!")
print("-" * 50)
print("Here are some rules:")
rulesFile = open("rules.txt")
for line in rulesFile:
print(line.strip())
rulesFile.close()
def initializeBoard(boardSize=5):
"""
Initializes board with a default value of 5.
:param boardSize: The board's size, between 5 and 15, defaults to 5
:type boardSize: int, optional
"""
assert 5 <= boardSize <= 15, "Board size should be between 5 and 15!"
for _ in range(boardSize):
row = []
for _ in range(boardSize):
row.append("")
BOARD.append(row)
def createDictionary():
"""
Reads from "dictionary.txt" and construct a list of valid words.
"""
dictionaryFile = open("dictionary.txt")
for line in dictionaryFile:
line = line.strip()
DICTIONARY.append(line)
dictionaryFile.close()
def createScoreMap():
"""
Reads from "scores.txt" and construct a map with letters as keys and scores as values.
"""
scoreFile = open("scores.txt")
for line in scoreFile:
line = line.strip()
line = line.split(" ")
SCORES[line[0]] = int(line[1])
scoreFile.close()
def createTiles():
"""
Reads from "tiles.txt" and construct a list of tiles.
"""
tilesFile = open("tiles.txt")
for line in tilesFile:
line = line.strip()
TILES.append(line)
tilesFile.close()
def padString(string, c):
"""
Pads left and right of the input string with character c so that the length makes up the cell width.
:param string: String to pad
:param c: Character to pad with
:returns padded string
"""
global CELL_WIDTH
string = str(string)
remaining = CELL_WIDTH - len(string)
remaining = remaining // 2
string = c * remaining + string
remaining = CELL_WIDTH - len(string)
return string + c * remaining
def printBoard():
"""
Prints the board.
"""
print("\nBOARD:")
boardColumnHeader = " |" + "|".join(padString(index + 1, " ") for index in range(len(BOARD))) + "|"
boardSeparator = "--|" + "|".join(padString("", "-") for _ in range(len(BOARD))) + "|"
print(boardColumnHeader)
print(boardSeparator)
for i in range(len(BOARD)):
row = str(i + 1) + " " * (2 - len(str(i))) + "|"
for j in range(len(BOARD)):
row += padString(BOARD[i][j], " ") + "|"
print(row)
print(boardSeparator)
def getCurrentTiles(currentTiles):
"""
Generates tiles for the current move.
Only a maximum of 7 tiles are returned and should consist of the unused tiles from the previous move.
:param currentTiles: List to contain the generated tiles.
"""
global USED_TILES, TILES_COUNT
# Generates a maximum of 7 tiles and uses the previous unused tiles
while len(currentTiles) < TILES_COUNT and USED_TILES < len(TILES):
currentTiles.append(TILES[USED_TILES])
USED_TILES += 1
def printTiles(currentTiles):
"""
Prints tiles for the current turn with their scores.
:param currentTiles: List of tiles to be printed.
"""
tiles = ""
scores = ""
for letter in currentTiles:
tiles += letter + " "
currentScore = SCORES[letter]
if currentScore > 9:
scores += str(currentScore) + " "
else:
scores += str(currentScore) + " "
print("\nTiles : " + tiles)
print("Scores: " + scores + "\n")
def areLettersFromBoard(letterList):
"""
Determines whether the letters already exists in the board.
:param letterList: A list of letters to be checked.
:returns a list of list, each consists of an alphabet with the x and y coordinates on the board,
if all letters exist in the board, false otherwise.
"""
letters = []
# Ensures that the tiles for all the letters are found
foundLetters = [False for _ in range(len(letterList))]
for m in range(len(letterList)):
for i in range(len(BOARD)):
for j in range(len(BOARD)):
if BOARD[i][j] == letterList[m]:
# More than one tile for a letter might exist
if not [letterList[m], i, j] in letters:
foundLetters[m] = True
letters.append([letterList[m], i, j])
if (len(letters) == 0):
return False
else:
try:
foundLetters.index(False)
return False
except ValueError:
return letters
def canBeMadeWithTiles(word, currentTiles):
"""
Determines whether the word can be constructed using the tiles given.
:param word: A word string to be checked.
:param currentTiles: A list of tiles to be checked against.
:returns True if all of the words can be constructed with the given tiles, otherwise
returns a list of tiles to be checked against the board and another with the tiles to be used.
"""
tilesToCompare = currentTiles.copy()
toCheckInBoard = []
tilesToUse = []
for letter in word:
# Looks for letters in the tiles
try:
tilesToCompare.index(letter)
tilesToCompare.remove(letter)
tilesToUse.append(letter)
# Stores letters that are not found to be checked if they exist in the board
except ValueError:
toCheckInBoard.append(letter)
if (len(toCheckInBoard) > 0):
return [toCheckInBoard, tilesToUse]
return True
def wordIsValid(word, currentTiles, firstMove):
"""
Determines whether the input word is valid.
:param word: Valid word with pure alphabets, exists in the dictionary list and \
uses letters from the current tiles or existing ones on the board.
:param currentTiles: Tiles to be used in the current turn.
:param firstMove: Boolean of whether the current turn is the first move.
:returns True if the word only contains letters from the given tiles or existing tiles from the board.
"""
# Word should not contain number, white space or special characters
if not word.isalpha():
return False
# Word should be in the dictionary
try:
DICTIONARY.index(word)
except ValueError:
return False
# Word in the first move should not contain any external tiles.
if firstMove:
if canBeMadeWithTiles(word, currentTiles):
return True
return False
# Following move must use given tiles and at least one existing tile
allLettersFromTiles = canBeMadeWithTiles(word, currentTiles)
# All letters are found in tiles and some from the board.
if (allLettersFromTiles == True):
existingTiles = areLettersFromBoard(word)
# Some letters are not found in tiles but are found from the board.
elif isinstance(allLettersFromTiles, list):
existingTiles = areLettersFromBoard(allLettersFromTiles[0])
if isinstance(existingTiles, list):
return True
return False
def locationValidFormat(loc):
"""
Determines whether the location is in valid format.
Returns a list of [int, int, String] of the split coordinates.
:param loc: Location string with the format of "_:_:H" or "_:_:V".
:returns a list of split location if the input is a valid location.
:raises AssertionError when the coordinates are not numeric or the direction is invalid.
"""
loc = loc.split(":")
assert len(loc) == 3, "Location should be in the form of _:_:H or _:_:V !"
for i in range(len(loc)):
loc[i] = loc[i].strip()
# Checks the coordinates
if i == 0 or i == 1:
if loc[i].isnumeric():
loc[i] = int(loc[i])
else:
raise AssertionError("Location should be numeric!")
# Checks the direction
elif i == 2:
if not (loc[i] == "H" or loc[i] == "V"):
raise AssertionError("Invalid direction!")
return loc
def locationIsValid(loc, word, currentTiles, firstMove):
"""
Determines whether the input location is valid.
Valid location is in the correct format and within the range of the board.
:param loc: Location string to place the word in the board.
:param word: Chosen word string for the current move.
:param currentTiles: List of tiles to be used in the current turn.
:param firstMove: Boolean of whether the current turn is the first move.
:returns True if the location is valid and word is successfully placed into the board.
:raises AssertionError if the location or the word is out of the range of the board.
"""
loc = locationValidFormat(loc)
# Ensures that the coordinates are within the board
assert (0 < loc[0] <= len(BOARD) and 0 < loc[1] <= len(BOARD)), \
"Please select a location within the board!"
# Ensures that the word can fit into the board
assert (loc[2] == "H" and len(word) + loc[1] - 1 <= len(BOARD)) or \
(loc[2] == "V" and len(word) + loc[0] - 1 <= len(BOARD)), \
"The word could not fit into the board!"
# Attempts to place the word into the board
placeTilesOnBoard(loc, word, currentTiles, firstMove)
return True
def placeTilesOnBoard(loc, word, currentTiles, firstMove):
"""
Places tiles of the selected word onto the board.
Reverts and raises exception if the word does not use at least one existing tile.
:param loc: List of selected location.
:param word: Selected word for the current move.
:param currentTiles: List of tiles to be used in the current turn.
:param firstMove: Boolean of whether the current turn is the first move.
:raises TilesError if an existing tile is overwritten, an existing tile is not used,
or when neither an existing nor a given tile is used.
"""
global BOARD_OCCUPIED_TILES
existingTiles = [] # Keeps track of existing tile to avoid counting the scores in
# If word is to be placed horizontally
if loc[2] == "H":
row = loc[0] - 1
startCol = loc[1] - 1
endCol = loc[1] + len(word) - 2
wordIndex = 0
for i in range(startCol, endCol + 1):
# Ensures that no existing tile is overwritten
if (BOARD[row][i] != ""):
if (BOARD[row][i] != word[wordIndex]):
raise exception.TilesError("You must not overwrite existing tiles on the board!")
else:
existingTiles.append(word[wordIndex])
else:
try:
# Removes used tile from the list
currentTiles.remove(word[wordIndex])
BOARD_OCCUPIED_TILES += 1
# The tile exist in the board but is at a different location
except ValueError:
if len(existingTiles) > 0:
# Restore the board into previous state without removing existing tiles
for i in range(startCol, startCol + wordIndex):
if (BOARD[row][i] not in existingTiles):
BOARD[row][i] = ""
BOARD_OCCUPIED_TILES -= 1
else:
existingTiles.remove(BOARD[row][i])
else:
# Restore the board into previous state
for i in range(startCol, startCol + wordIndex):
BOARD[row][i] = ""
BOARD_OCCUPIED_TILES -= 1
raise exception.TilesError("You must only use the existing or given tiles!")
BOARD[row][i] = word[wordIndex]
wordIndex += 1
# Revert if no existing tile is used
if not firstMove and len(existingTiles) == 0:
for i in range(startCol, endCol + 1):
BOARD[row][i] = ""
BOARD_OCCUPIED_TILES -= len(word)
raise exception.TilesError("You must use at least one existing tile!")
# If word is to be placed vertically
elif loc[2] == "V":
col = loc[1] - 1
startRow = loc[0] - 1
endRow = loc[0] + len(word) - 2
wordIndex = 0
for i in range(startRow, endRow + 1):
# Ensures that no existing tile is overwritten
if (BOARD[i][col] != ""):
if (BOARD[i][col] != word[wordIndex]):
raise exception.TilesError("You must not overwrite existing tiles on the board!")
else:
existingTiles.append(word[wordIndex])
else:
try:
# Removes used tile from the list
currentTiles.remove(word[wordIndex])
BOARD_OCCUPIED_TILES += 1
# The tile exist in the board but is at a different location
except ValueError:
if len(existingTiles) > 0:
# Restore the board into previous state without removing existing tiles
for i in range(startRow, startRow + wordIndex):
if (BOARD[i][col] not in existingTiles):
BOARD[i][col] = ""
BOARD_OCCUPIED_TILES -= 1
else:
existingTiles.remove(BOARD[i][col])
else:
# Restore the board into previous state
for i in range(startRow, startRow + wordIndex):
BOARD[i][col] = ""
BOARD_OCCUPIED_TILES -= 1
raise exception.TilesError("You must only use the existing or given tiles!")
# Places letter into the board
BOARD[i][col] = word[wordIndex]
wordIndex += 1
# Revert if no existing tile is used
if not firstMove and len(existingTiles) == 0:
for i in range(startRow, endRow + 1):
BOARD[i][col] = ""
BOARD_OCCUPIED_TILES -= len(word)
raise exception.TilesError("You must use at least one existing tile!")
# Prints the scores for the current turn
printScore(word, existingTiles)
def getCurrentScore(word, existingTiles):
"""
Computes and returns the score of the current move by neglecting the existing tiles used.
:param word: Word string for the current move.
:param existingTiles: A list of existing tiles used.
:returns score for the current word.
"""
score = 0
for letter in word:
# Removes letters that have been accounted for
if letter in existingTiles:
existingTiles.remove(letter)
else:
score += SCORES[letter]
return score
def printScore(word, existingTiles):
"""
Computes and prints the current and total scores.
:param word: Word string for the current move.
:param existingTiles: A list of existing tiles used.
"""
global TOTAL_SCORE
currentScore = getCurrentScore(word, existingTiles)
print("Your score for this move: " + str(currentScore))
TOTAL_SCORE += currentScore
print("Total score: " + str(TOTAL_SCORE))
def getLocationWithBestScore(word, existingTiles, newTiles, firstMove):
"""
Looks for valid location with the highest score to fit the given word into the board.
:param word: A word string to fit into the board.
:param existingTiles: A list of existing tiles on the board which should be used.
:param newTiles: A list of tiles which are supposed to make up the word other than those on the board.
:param firstMove: Boolean of whether the current turn is the first move.
:returns: None if no location is found, otherwise returns a list with location string with its score.
"""
# If current turn is the first move
if firstMove:
if (len(word) <= len(BOARD)):
return ["1:1:H", getCurrentScore(word, [])]
else:
return None
else:
bestScore = 0
bestLocation = ""
usedTiles = []
# Attempt to place word into the board using existing tiles
for letterLoc in existingTiles:
for i in range(len(word)):
if (word[i] == letterLoc[0]):
if (letterLoc[1] - i < 0 and letterLoc[2] - i < 0):
continue
# Attempt to place word horizontally
elif letterLoc[1] - i >= 0 and letterLoc[1] - i + len(word) - 1 < len(BOARD):
wordIndex = 0
for j in range(letterLoc[1] - i, letterLoc[1] - i + len(word)):
# If an existing tile is overwritten
if (BOARD[j][letterLoc[2]] != "" and BOARD[j][letterLoc[2]] != word[wordIndex]):
break
# If an existing tile is used
elif BOARD[j][letterLoc[2]] != "":
usedTiles.append(word[wordIndex])
wordIndex += 1
# If a tile given is used
elif word[wordIndex] in newTiles:
newTiles.remove(word[wordIndex])
wordIndex += 1
# The tile is from the board but at another position
else:
break
# Successful attempt
if wordIndex == len(word):
currentScore = getCurrentScore(word, usedTiles)
if (currentScore > bestScore):
bestScore = currentScore
bestLocation = str(letterLoc[1] - i + 1) + ":" + str(letterLoc[2] + 1) + ":V"
# Attempt to place word vertically
elif letterLoc[2] - i >= 0 and letterLoc[2] - i + len(word) - 1 < len(BOARD):
wordIndex = 0
for j in range(letterLoc[2] - i, letterLoc[2] - i + len(word)):
# If an existing tile is overwritten
if (BOARD[letterLoc[1]][j] != "" and BOARD[letterLoc[1]][j] != word[wordIndex]):
break
# If an existing tile is used
elif BOARD[letterLoc[1]][j] != "":
usedTiles.append(word[wordIndex])
wordIndex += 1
# If a tile given is used
elif word[wordIndex] in newTiles:
wordIndex += 1
# The tile is from the board but at another position
else:
break
# Successful attempt
if wordIndex == len(word):
currentScore = getCurrentScore(word, usedTiles)
if (currentScore > bestScore):
bestScore = currentScore
bestLocation = str(letterLoc[1] + 1) + ":" + str(letterLoc[2] - i + 1) + ":H"
# No valid location is found
if bestScore == 0:
return None
return [bestLocation, bestScore]
def getCurrentBest(currentTiles, firstMove):
"""
Generates move with the maximum score.
:param currentTiles: List of tiles to be used in the current turn.
:param firstMove: Boolean of whether the current turn is the first move.
:returns a list consisting of word with maximum score, the score, and its location in the board.
"""
bestWord = None
bestScore = 0
bestLocation = None
for validWord in DICTIONARY:
# If the current turn is the first move
if firstMove:
# If not all the letters are found from the tiles
if isinstance(canBeMadeWithTiles(validWord, currentTiles), list):
continue
existingTiles = []
newTiles = []
else:
checkedTiles = canBeMadeWithTiles(validWord, currentTiles)
# If all letters are found from the tiles, checks if any letters exist in the board
if (checkedTiles == True):
existingTiles = areLettersFromBoard(validWord)
# If some letters are found from the tiles, checks if those exist in the board
elif isinstance(checkedTiles, list):
existingTiles = areLettersFromBoard(checkedTiles[0])
# If no existing tile is used
if not isinstance(existingTiles, list):
continue
# If all letters are found from the tiles and some from the board
elif (checkedTiles == True):
newTiles = currentTiles.copy()
# If some letters are found from the tiles and the rest are found from the board
else:
newTiles = checkedTiles[1]
# Attempts to get a valid location with the highest score to place the word
locationWithScore = getLocationWithBestScore(validWord, existingTiles, newTiles, firstMove)
if locationWithScore is not None:
if locationWithScore[1] > bestScore:
bestWord = validWord
bestScore = locationWithScore[1]
bestLocation = locationWithScore[0]
return [bestWord, bestScore, bestLocation]
def playGame():
createDictionary()
createScoreMap()
createTiles()
welcomeMessage()
# Prompts for board size
validBoard = False
# Prompts until a valid board size is entered
while not validBoard:
inputBoardSize = input("\nEnter your board size (5 - 15): ")
try:
if (inputBoardSize.isnumeric()):
initializeBoard(int(inputBoardSize))
else:
# Uses default value
initializeBoard()
validBoard = True
# When board size is beyond the range
except AssertionError as message:
print(message)
printBoard()
userInput = ""
quit = False
move = 1
currentTiles = []
getCurrentTiles(currentTiles) # Generates tiles for the current move
# Game ends when player quits or wins the game
while not quit and BOARD_OCCUPIED_TILES < int(inputBoardSize) ** 2:
printTiles(currentTiles)
[bestWord, bestScore, bestLocation] = getCurrentBest(currentTiles, move == 1)
currentTilesCopy = currentTiles.copy()
# No possible move is found
if (bestWord is None):
print("No possible move found!")
break
# Prompts for word
validWord = False
# Prompts until a valid word is entered
while not validWord:
userInput = input("Enter a word: ").upper()
if (userInput == "***"):
quit = True
break
validWord = wordIsValid(userInput, currentTiles, move == 1)
currentWord = userInput
if (not validWord):
print("Invalid word! You must use letters from the tiles!")
# Prompts for location
validLocation = False
# Prompts until a valid location is entered
while validWord and not validLocation:
userInput = input("Enter the location of your word (_:_:H or _:_:V): ").upper()
if (userInput == "***"):
quit = True
break
try:
validLocation = locationIsValid(userInput, currentWord, currentTiles, move == 1)
# Assertion error is raised if requires new location input
except AssertionError as message:
print(message)
# TilesError is raised if requires new word and location input
except exception.TilesError as message:
print(message)
# Restores the tiles that might have been removed
currentTiles = currentTilesCopy
break
# Prints the board if a move is successfully completed
if (validWord and validLocation):
print("Maximum possible score in this move is " + str(bestScore) + " using the word " + bestWord +
" at " + bestLocation)
printBoard()
move += 1
getCurrentTiles(currentTiles)
# If all the tiles are occupied
if BOARD_OCCUPIED_TILES == int(inputBoardSize) ** 2:
print("You won the game!")
break
print("Hope you had fun, do come back again!")
playGame() |
c8124bb38f2db2e434523d5f369ef271c1535d12 | thisistom/checkout | /python/Promos.py | 3,116 | 4.03125 | 4 |
class _PromoEntry(object):
"""
Base class for promotional groupings of items.
"""
def __init__(self, items):
"""
Initializes an instance of the class.
Args:
items (list of Item): The items for this promo.
"""
self._items = items
def cost(self):
raise NotImplementedError("Must be defined in derived class")
def savings(self):
raise NotImplementedError("Must be defined in derived class")
def name(self):
raise NotImplementedError("Must be defined in derived class")
class ThreeForTwoPromo(_PromoEntry):
def __init__(self, item, numPromos=1):
"""
Initializes an instance of the class.
Args:
item (Item): The item for this promo.
numPromos (int): The number of 3-for-2 promos. (Default: 1)
"""
_PromoEntry.__init__(self, [item])
self.__count = numPromos
def cost(self):
"""
Returns:
float. The cost for this promotion.
"""
return 2 * self._items[0].price() * self.__count
def savings(self):
"""
Returns:
float. The savings from this promotion.
"""
return self._items[0].price() * self.__count
def name(self):
"""
Returns:
str. The name of this promotion.
"""
return "%s - 3 for 2" % self._items[0].name()
class CheapestFreePromo(_PromoEntry):
def __init__(self, items):
"""
Initializes an instance of the class.
Args:
items (list of Item): The items for this promo.
Raises:
ValueError: If fewer than three items are provided.
"""
_PromoEntry.__init__(self, items)
if len(items) < 3:
raise ValueError("Not enough items provided")
self._items.sort(key=lambda item: item.price(), reverse=True)
def cost(self):
"""
Returns:
float. The cost for this promotion.
"""
return sum(item.price() for item in self._items[:-1])
def savings(self):
"""
Returns:
float. The savings from this promotion.
"""
return self._items[-1].price()
def name(self):
"""
Returns:
str. The name of this promotion.
"""
return "%s - buy 3 get cheapest free" % self._items[0].promoGroup()
class NoPromo(_PromoEntry):
def __init__(self, item):
"""
Initializes an instance of the class.
Args:
item (Item): The item for this promo.
"""
_PromoEntry.__init__(self, [item])
def cost(self):
"""
Returns:
float. The cost for this promotion.
"""
return sum(item.price() for item in self._items)
def savings(self):
"""
Returns:
float. The savings from this promotion.
"""
return 0.0
def name(self):
"""
Returns:
str. The name of this promotion.
"""
return ""
|
5562886747c8b8d777529894ac51927c9135d90e | peterbat/rubikon | /matrix.py | 8,870 | 3.703125 | 4 | import math
import random as rand
class Matrix:
def __init__(self, a):
if len(a) == 9:
self.data = a
else:
print('ERROR: failed to initialize matrix with wrong dimensional data.')
def lmultiply(self, b):
data2 = [0] * 9
data2[0] = self.data[0] * b.data[0] + self.data[1] * b.data[3] + self.data[2] * b.data[6]
data2[1] = self.data[0] * b.data[1] + self.data[1] * b.data[4] + self.data[2] * b.data[7]
data2[2] = self.data[0] * b.data[2] + self.data[1] * b.data[5] + self.data[2] * b.data[8]
data2[3] = self.data[3] * b.data[0] + self.data[4] * b.data[3] + self.data[5] * b.data[6]
data2[4] = self.data[3] * b.data[1] + self.data[4] * b.data[4] + self.data[5] * b.data[7]
data2[5] = self.data[3] * b.data[2] + self.data[4] * b.data[5] + self.data[5] * b.data[8]
data2[6] = self.data[6] * b.data[0] + self.data[7] * b.data[3] + self.data[8] * b.data[6]
data2[7] = self.data[6] * b.data[1] + self.data[7] * b.data[4] + self.data[8] * b.data[7]
data2[8] = self.data[6] * b.data[2] + self.data[7] * b.data[5] + self.data[8] * b.data[8]
self.data = data2
def operate(self, u, origin = None):
if origin != None:
w = [u[i] - origin[i] for i in range(len(origin))]
else:
w = u
v = [0] * 3
v[0] = self.data[0] * w[0] + self.data[1] * w[1] + self.data[2] * w[2]
v[1] = self.data[3] * w[0] + self.data[4] * w[1] + self.data[5] * w[2]
v[2] = self.data[6] * w[0] + self.data[7] * w[1] + self.data[8] * w[2]
if origin != None:
return [v[i] + origin[i] for i in range(len(origin))]
else:
return v
def list_operate(self, ulist, origin = None):
return [self.operate(u, origin) for u in ulist]
def transpose(self):
data2 = [0] * 9
data2[0] = self.data[0]
data2[1] = self.data[3]
data2[2] = self.data[6]
data2[3] = self.data[1]
data2[4] = self.data[4]
data2[5] = self.data[7]
data2[6] = self.data[2]
data2[7] = self.data[5]
data2[8] = self.data[8]
return Matrix(data2)
def dot(v1, v2):
return v1[0] * v2[0] + v1[1] * v2[1] + v1[2] * v2[2]
def cross(v1, v2):
return [v1[1] * v2[2] - v1[2] * v2[1], \
v1[2] * v2[0] - v1[0] * v2[2], \
v1[0] * v2[1] - v1[1] * v2[0]]
def eye():
return Matrix([1., 0., 0., 0., 1., 0., 0., 0., 1.])
def norm(v):
return math.sqrt(v[0]**2 + v[1]**2 + v[2]**2)
def multiply(m1, m2):
m3 = [0] * 9
m3[0] = m1.data[0] * m2.data[0] + m1.data[1] * m2.data[3] + m1.data[2] * m2.data[6]
m3[1] = m1.data[0] * m2.data[1] + m1.data[1] * m2.data[4] + m1.data[2] * m2.data[7]
m3[2] = m1.data[0] * m2.data[2] + m1.data[1] * m2.data[5] + m1.data[2] * m2.data[8]
m3[3] = m1.data[3] * m2.data[0] + m1.data[4] * m2.data[3] + m1.data[5] * m2.data[6]
m3[4] = m1.data[3] * m2.data[1] + m1.data[4] * m2.data[4] + m1.data[5] * m2.data[7]
m3[5] = m1.data[3] * m2.data[2] + m1.data[4] * m2.data[5] + m1.data[5] * m2.data[8]
m3[6] = m1.data[6] * m2.data[0] + m1.data[7] * m2.data[3] + m1.data[8] * m2.data[6]
m3[7] = m1.data[6] * m2.data[1] + m1.data[7] * m2.data[4] + m1.data[8] * m2.data[7]
m3[8] = m1.data[6] * m2.data[2] + m1.data[7] * m2.data[5] + m1.data[8] * m2.data[8]
return Matrix(m3)
def rotx(theta):
m = [0] * 9
m[0] = 1.
m[1] = 0.
m[2] = 0.
m[3] = 0.
m[4] = math.cos(theta)
m[5] = -math.sin(theta)
m[6] = 0.
m[7] = math.sin(theta)
m[8] = math.cos(theta)
return Matrix(m)
def roty(theta):
m = [0] * 9
m[0] = math.cos(theta)
m[1] = 0.
m[2] = math.sin(theta)
m[3] = 0.
m[4] = 1
m[5] = 0.
m[6] = -math.sin(theta)
m[7] = 0.
m[8] = math.cos(theta)
return Matrix(m)
def rotz(theta):
m = [0] * 9
m[0] = math.cos(theta)
m[1] = -math.sin(theta)
m[2] = 0.
m[3] = math.sin(theta)
m[4] = math.cos(theta)
m[5] = 0.
m[6] = 0.
m[7] = 0.
m[8] = 1.
return Matrix(m)
def rotv(v, theta):
# Rotate v onto the z axis by first rotating it onto the y axis about the z axis,
# then rotating it about the x axis onto the z axis. Perform theta rotation about
# the z axis, and then complete the conjugation.
if abs(v[0]) < 1e-5 and abs(v[1]) < 1e-5:
y_angle = 0.
else:
y_angle = math.acos(dot([v[0], v[1], 0.], [0., 1., 0.]) / math.sqrt(v[0]*v[0] + v[1]*v[1]))
# If we are on the left half plane (x < 0) then we need to rotate by a negative angle to get to
# the positive y axis.
if v[0] < 0:
y_angle = -y_angle
t1 = rotz(y_angle)
t2 = rotx(math.acos(dot(v, [0., 0., 1.]) / math.sqrt(dot(v, v))))
T = multiply(t2, t1)
r = rotz(theta)
return multiply(T.transpose(), multiply(r, T))
def get_axis_from_rot(rot, tol = 1e-9, step = 0.1):
A = Matrix(list(rot.data))
A.data[0] -= 1.0
A.data[4] -= 1.0
A.data[8] -= 1.0
theta, phi = rand.uniform(0.2, 0.5 * math.pi - 0.1), rand.uniform(0.2, 0.5 * math.pi - 0.1)
err = 1.0
steps = 0
while err > tol:
steps += 1
v = [math.sin(theta) * math.cos(phi),\
math.sin(theta) * math.sin(phi),\
math.cos(theta)]
gv_theta = [math.cos(theta) * math.cos(phi),\
math.cos(theta) * math.sin(phi), -math.sin(theta)]
gv_phi = [-math.sin(theta) * math.sin(phi),\
math.sin(theta) * math.cos(phi), 0]
Av = A.operate(v)
g_theta = dot(A.operate(gv_theta), Av)
g_phi = dot(A.operate(gv_phi), Av)
theta = theta - step * g_theta
phi = phi -step * g_phi
err = 0.5 * dot(Av, Av)
return [math.sin(theta) * math.cos(phi),\
math.sin(theta) * math.sin(phi),\
math.cos(theta)]
def get_axis_and_angle_from_rot(rot, tol = 1e-9):
v = get_axis_from_rot(rot, tol = tol)
# make a vector that's perpendicular to v by perturbing a copy of v
# and subtracting the parallel part.
vperp = list(v)
vperp[0] = vperp[0] - 1.0
proj = dot(v, vperp) / math.sqrt(dot(v, v))
vperp[0] = vperp[0] - proj * v[0]
vperp[1] = vperp[1] - proj * v[1]
vperp[2] = vperp[2] - proj * v[2]
# make it into a unit vector.
vperp_norm = math.sqrt(dot(vperp, vperp))
vperp[0] /= vperp_norm
vperp[1] /= vperp_norm
vperp[2] /= vperp_norm
# operate on that vector with rot, and compute the angle between the
# original and the result.
operated = rot.operate(vperp)
crossprod = cross(vperp, operated)
cross_align = dot(crossprod, v)
sign = 1.0 if cross_align >= 0 else -1.0
dot_product = dot(operated, vperp)
if dot_product > 1.0:
dot_product = 1.0
elif dot_product < -1.0:
dot_product = -1.0
angle = sign * math.acos(dot_product)
return v, angle
def translate_point(p, displacement):
return [p[i] + displacement[i] for i in range(len(p))]
def translate_points(points, displacement):
return [translate_point(p, displacement) for p in points]
def test():
print "z rotation of pi/3"
r = rotz(math.pi / 3.)
v = [1., 0., 1.]
w = r.operate(v)
print v
print w
print "y rotation of pi/3"
r = roty(math.pi / 3.)
v = [0., 1., 1.]
w = r.operate(v)
print v
print w
print "x rotation of pi/3"
r = rotx(math.pi / 3.)
v = [1., 1., 0.]
w = r.operate(v)
print v
print w
print "z rotation of -pi/3"
r = rotz(-math.pi / 3.)
v = [1., 0., 1.]
w = r.operate(v)
print v
print w
print "y rotation of -pi/3"
r = roty(-math.pi / 3.)
v = [0., 1., 1.]
w = r.operate(v)
print v
print w
print "x rotation of -pi/3"
r = rotx(-math.pi / 3.)
v = [1., 1., 0.]
w = r.operate(v)
print v
print w
#----
v = [1./math.sqrt(3.), 1./math.sqrt(3.), 1./math.sqrt(3.)]
print "rotation about a vector v = [%f, %f, %f]" % (v[0], v[1], v[2])
w1 = [1., 0., 0.]
r = rotv(v, 2.*math.pi/3.)
w2 = r.operate(w1)
print w1
print w2
print "a second time"
w2 = r.operate(w2)
print w2
print "cross product"
v1 = [1.0, 0.0, 0.0]
v2 = [0.0, 1.0, 0.0]
v3 = cross(v1, v2)
print v1
print v2
print v3
print "find axis of rotation for rot about [1/sqrt(2), 1/sqrt(2), 0] by pi/3"
r = rotv([1. / math.sqrt(2.), 1. / math.sqrt(2.), 0.], math.pi / 3.)
for step in [0.1, 0.2, 0.5, 0.99, 1.0]:
print "using step size: ", step
print get_axis_from_rot(r, step = step)
print "find the angle of rotation for the same rotation"
axis, angle = get_axis_and_angle_from_rot(r)
print "angle: ", angle
print "find axis of rotation for rot about [1/sqrt(3), -1/sqrt(3), 1/sqrt(3)] by pi/2"
r = rotv([1. / math.sqrt(3.), -1. / math.sqrt(3.), 1. / math.sqrt(3.)], math.pi / 2.)
print get_axis_from_rot(r)
axis, angle = get_axis_and_angle_from_rot(r)
print "angle: ", angle
print "find and angle of a slightly off-unitary transformation"
r = Matrix([3.0616169978683826e-16, -1.224646799147353e-16, -1.0, -1.0, 1.83697019872103e-16, -3.0616169978683836e-16, 1.83697019872103e-16, 1.0, -1.224646799147353e-16])
axis, angle = get_axis_and_angle_from_rot(r, tol = 1e-9)
print axis
print "angle: ", angle
if __name__ == '__main__':
test()
|
61132296b1611a80b747186e8e9e5afefee44450 | Jason0221/backup | /HOME/笔记/考试/Python基础考试2-12.16/6.py | 2,561 | 4.25 | 4 | #!/usr/bin/python
#coding=utf-8
'''
6. 编写python程序: 实现一个双向循环链表,封装结点和其他方法。
要求至少实现创建和增删方法,并且要求实现其__getitem__和__setitem__两个魔法方法。
(如果你的__setitem__即可实现链表的插入那么可以不必写额外的插入方法)
'''
class Node(object):
def __init__(self,value,prior=None,next=None):
self.value = value
self.prior = prior
self.next = next
class Linklist(object):
def __init__(self,):
self.head = None
def initlist(self,data):
self.head = Node(0)
p = self.head
for i in data :
node = Node(i)
p.next = node
node.prior = p
p = p.next
p.next = self.head
self.head.prior = p
def show(self):
p =self.head.next
while p !=self.head:
print p.value,
p = p.next
print ""
def insert(self,index,value):
p = self.head
i = 0
while p.next != self.head and i < index:
i += 1
p = p.next
q = Node(value)
p.next.prior = q
q.next = p.next
p.next = q
q.prior =p
def delete(self,index):
p =self.head
i = 0
while p.next != self.head and i< index:
p =p.next
i += 1
p.next = p.next.next
p.next.prior = p
def is_empty(self):
if self.head == None:
print "空列表"
return True
else:
return False
def getitem(self,index):
p = self.head.next
i = 0
while p != self.head and i < index:
p = p.next
i += 1
return p.value
def __getitem__(self,index):
if self.is_empty():
print "Linklist is empty"
return
else:
p = self.head.next
i = 0
while p != self.head and i < index:
p = p.next
i += 1
return p.value
def __setitem__(self,index,value):
self.delete(index)
return self.insert(index,value)
if __name__ == "__main__":
l = Linklist()
print "创建一个双链表:"
l.initlist([1,2,3,5,3,6,8])
l.show()
print '删除下标为2的结点:'
l.delete(2)
l.show()
print "使用魔法方法__getitem__列出下标为1的结点:",l[1]
l.show()
print "使用魔法方法__setitm__修改链表:"
l[1] = 10
l.show()
|
06fc470787100bb4695a18968e85cec9c6384cd2 | rifatmondol/Python-Exercises | /145 - [Listas] Diferença Entre Listas.py | 230 | 3.71875 | 4 | #145 - Write a Python program to get the difference between the two lists.
lista1 = ['Dorgival', 'Cecilia', 'Shiro', 'Kauane']
lista2 = ['Cecilia', 'Kauane', 'John', 'Juliana']
dif = set(lista1).difference(set(lista2))
print(dif) |
21473ff39aff7856d4f000e69b990e3056cafead | hellyab/CompetitiveProgramming | /week-3/largest_rectangle.py | 274 | 3.75 | 4 | def largestRectangle(h):
h.sort()
n = len(h)
max_ = 0
for height in h:
if max_ - (height * n) < 0:
max_ = height * n
n -= 1
print(max_)
largestRectangle([8979, 4570, 6436, 5083, 7780, 3269, 5400, 7579, 2324, 2116]) |
276555d94d3d9de35ea55b46dc39e09948456d0d | LinvernSS/daily_assignments | /week1/day3/day7.py | 2,320 | 3.921875 | 4 | #!/usr/bin/env python
# coding: utf-8
# Lucas Invernizzi Day 7 Assignment
# 1)
# In[143]:
def divisible():
out = []
for i in range(1500,2701):
if i % 7 == 0 and i % 5 == 0:
out += [i]
return out
# In[144]:
print(divisible())
# 2)
# In[145]:
def convertTemp(t):
if t[-1] == 'C':
temp = int((int(t[:-2]) * (9 / 5)) + 32)
print('{} is {} in Fahrenheit'.format(t, str(temp)))
return str(temp) + t[-2:-1] + 'C'
elif t[-1] == 'F':
temp = int((int(t[:-2]) - 32) * (5 / 9))
print('{} is {} in Celcius'.format(t, str(temp)))
return str(temp) + t[-2:-1] + 'F'
else:
print('This is not an accepted temperature unit.')
# In[146]:
convertTemp('60°C')
# In[147]:
convertTemp('45°F')
# 3)
# In[148]:
import random
def guessNum():
genNum = random.randint(1,9)
userNum = int(input('Guess a number between 1 and 9: '))
while userNum != genNum:
userNum = int(input('Wrong number! Guess again: '))
print('Well guessed!')
# In[149]:
guessNum()
# 4)
# In[150]:
def asterisks():
for i in range(1,3):
for j in range(1,6):
out = '* '
if i == 1:
print(out * j)
else:
if 5 - j != 0:
print(out * (5 - j))
# In[151]:
asterisks()
# 6)
# In[152]:
def revWord():
word = input('Enter a word to be reversed: ')
return word[::-1]
# In[153]:
revWord()
# 7)
# In[154]:
def numEvenOdd(data):
numEven = 0
numOdd = 0
for i in data:
if i % 2 == 0:
numEven += 1
else:
numOdd += 1
print('Number of even numbers: {}'.format(numEven))
print('Number of odd numbers: {}'.format(numOdd))
# In[155]:
numEvenOdd([1,2,3,4,5,6,7,8,9])
# 8)
# In[156]:
def printValType(data):
for i, val in zip(range(len(data)), data):
print('Item {} is {} and has the type of {}'.format(i + 1, val, type(val)))
# In[157]:
printValType([1452, 11.23, 1+2j, True, 'w3resource', (0, -1), [5, 12], {"class":'V', "section":'A'}])
# 9)
# In[158]:
def printNums():
for i in range(7):
if i not in [3,6]:
print(str(i) + ' ', end = '')
else:
continue
# In[159]:
printNums()
|
f970e234a0312385121ce671dc042f7bb8eba9c3 | ayannroys/Journal | /s3q3.py | 377 | 3.9375 | 4 | num=list(eval((input("Enter numbers"))))
x = []
N = int(input('enter size of list : '))
for i in range(0, N):
element=int(input('Enter element:'))
x.append(element)
print('Numbers in the list are ')
print(x)
for i in x:
if (i%5==0):
print(i,'is divisable by 5 but not by 7')
elif(i%7==0):
print(i,'is divisable by 7 but not by 5')
|
df0717288696309bad4a704952be2c9e52e485b9 | poo250696/python_training | /lists/exml1.py | 190 | 3.515625 | 4 | a_lists = []
b_lists = [1, 3, 4, 5]
c_lists = ["apple", "bat", "cat"]
d_lists = ['', 1, "string"]
print(a_lists)
print(b_lists[2])
print(c_lists)
for item in d_lists:
print(item)
|
e74a81c3c2aba3de70af51b91ab41efa8d692380 | Bibhuti4086mukhiya/python-practical-first-semester | /lab 4.py | 161 | 4.15625 | 4 | ''''
num=int(input("enter ur number"))
result=1
for i in range(num,0,-1):
result=result*i
print("the factorial of",num,"is",result)
'''
list=[2,3,4,5,6]
|
f1e2465427c61ea8743ca3df75a2184c945a0454 | estebansolo/PythonScripts | /platzi_coding_challenge/03_clock.py | 557 | 4.21875 | 4 | from datetime import timedelta
def seconds_per_hours(hours):
return 60 * 60 * hours
def seconds_per_minutes(minutes):
return 60 * minutes
def main():
hours = int(input("Add hours: "))
minutes = int(input("Add minutes: "))
seconds = seconds_per_hours(hours) + seconds_per_minutes(minutes)
print(f"There are {seconds} seconds in {hours} hours {minutes} minutes")
# Using timedelta
delta = timedelta(hours=hours, minutes=minutes)
print(f"timedelta: {int(delta.total_seconds())}")
if __name__ == "__main__":
main() |
aed6de507e084a6cd97d04abdf5d7206a10e548a | ke1222/PythonZY | /day03_11.py | 170 | 4.03125 | 4 | list1 = []
for i in range(1,8):
for j in range(1,8):
if i != j and sorted([i,j]) not in list1:
list1.append([i,j])
print(list1) |
911b394fd260120b82645732310a9ed1a9996479 | Nv99/Sorting_Algorithm_Visualizer | /Algorithm_visualizer.py | 2,957 | 3.6875 | 4 | from tkinter import *
from tkinter import ttk
import random
from bubblesort import bubble_sort
from quicksort import quick_sort
from mergesort import merge_sort
root=Tk()
root.title('Sorting Algorithm Visualization')
root.maxsize(900,600)
root.config(bg='black')
#variables
selected_alg= StringVar()
data=[]
def drawData(data,colorArray):
canvas.delete('all')
c_height = 380
c_width = 600
x_width = c_width / (len(data)+1)
offset= 30
spacing =10
normalizedData = [i / max(data) for i in data]
for i, height in enumerate(normalizedData):
x0= i* x_width + offset+spacing
y0 = c_height - height * 340
x1=(i+1)* x_width + offset
y1=c_height
canvas.create_rectangle(x0,y0,x1,y1,fill=colorArray[i])
canvas.create_text(x0+2,y0,anchor=SW,text=str(data[i]))
root.update_idletasks()
def Generate():
global data
minVal = int(minEntry.get())
maxVal = int(maxEntry.get())
size= int(sizeEntry.get())
data=[]
for _ in range(size):
data.append(random.randrange(minVal,maxVal+1))
drawData(data,['red' for x in range(len(data))])
def StartAlgorithm():
global data
if not data: return
if algMenu.get()=='Quick sort':
quick_sort(data,0,len(data)-1,drawData,speedScale.get())
elif algMenu.get() == 'Bubble Sort':
bubble_sort(data,drawData,speedScale.get())
elif algMenu.get() == 'Merge Sort':
merge_sort(data ,drawData, speedScale.get())
drawData(data, ['green' for x in range(len(data))])
#base_layout
UI_frame= Frame(root,width=600,height=200,bg='grey')
UI_frame.grid(row=0,column=0,padx=10,pady=5)
canvas= Canvas(root,width=600,height=380,bg='white')
canvas.grid(row=1,column=0,padx=10,pady=5)
#User Interface Area
#Row=0
Label(UI_frame,text="Algorithm: ", bg='grey').grid(row=0,column=0,padx=5,pady=5,sticky=W)
algMenu=ttk.Combobox(UI_frame,textvariable=selected_alg,values=['Bubble Sort','Merge Sort','Quick sort'])
algMenu.grid(row=0,column=1,padx=5,pady=5)
algMenu.current(0)
speedScale = Scale(UI_frame,from_=0.1, to=2.0,length=200,digits=2,resolution=0.2,orient=HORIZONTAL, label="Select Speed [s]")
speedScale.grid(row=0,column=2,padx=5,pady=5)
Button(UI_frame,text="Start",command=StartAlgorithm,bg='red').grid(row=0,column=3,padx=5,pady=5)
#Row=1
sizeEntry = Scale(UI_frame,from_=3, to=25,resolution=1,orient=HORIZONTAL, label="Data Size")
sizeEntry.grid(row=1,column=0,padx=5,pady=5)
minEntry = Scale(UI_frame,from_=0, to=10,resolution=1,orient=HORIZONTAL, label="Min Value")
minEntry.grid(row=1,column=1,padx=5,pady=5)
maxEntry = Scale(UI_frame,from_=10, to=100,resolution=0.1,orient=HORIZONTAL, label="Max Value")
maxEntry.grid(row=1,column=2,padx=5,pady=5)
Button(UI_frame,text="Generate",command=Generate,bg='white').grid(row=1,column=3,padx=5,pady=5)
root.mainloop()
|
ed2da6b57c26cb15b67ffa960cc4d75030f59564 | gabriellaec/desoft-analise-exercicios | /backup/user_058/ch28_2019_08_26_19_24_01_715539.py | 183 | 3.75 | 4 | def velocidade(x):
if x>80:
return "Você foi multado em R$ {0:.2f}".format((x-80)*5)
else:
return "Não foi multado"
x=float(input("Velocidade "))
print(velocidade(x)) |
9a1736519605ac21d2ec7e66d398c4b1d7848cc3 | august-Lee-Yang/Python-Data-Structure-and-Algorithem | /Root_method.py | 1,695 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jul 30 16:20:12 2020
@author: Administrator
"""
def bisection(left,right,tol=1.0e-9,max_iter=100):
if f(left)==0:
return left
if f(right)==0:
return right
if f(left)*f(right)>0:
raise ValueError('No root in the interval')
i=0
if np.abs(f(left)-f(right))<tol and i<max_iter :
middle=(right+left)/2
if f(middle)==0:
return middle
elif f(middle)*f(left)>0:
left=middle
else:
right=middle
i+=1
print('Root is occured at x=%s'%(left+right)/2)
print('Number of iterations:',i)
def newton_method(x0,tol=1.0e-9,max_iter=100):
if f(x0)==0:
return x0
for i in range(max_iter):
x=x0-f(x0)/df(x0)
if np.abs(f(x)-f(x0))<tol:
return x
x0=x
print('Root is occured at x=',x)
print('Number of iterations:',i)
return x
def newton_bisection(left,right,tol=1.0e-9,max_iter=100):
if f(left)==0:
return left
if f(right)==0:
return right
if f(right)*f(left)>0:
raise ValueError('No root')
i=0
if np.abs(f(left)-f(right))<tol and i<max_iter:
x=(left+right)/2
if np.abs(f(x))<tol:
return x
if f(left)*f(x)>0:
left=x
else:
right=x
try:
dx=-f(x)/df(x)
except ZeroDivisionError:dx=right-left
x=x+dx
i+1
print('Root is occured at x=%s'%(left+right)/2)
print('Number of iterations:',i)
|
ce1858f344af9d9611efb488b30974470491d028 | jorenvandeweyer/Python_SudokuSolver | /sudoku.py | 6,559 | 3.5 | 4 | # -*- coding: utf-8 -*-
# @Author: Joren Vandeweyer
# @Date: 2017-07-04 19:18:17
# @Last Modified by: Joren Vandeweyer
# @Last Modified time: 2017-08-07 20:50:25
class Sudoku():
"""docstring for Sudoku"""
def __init__(self):
# self.sudoku = [
# [0,0,0,1,0,4,9,0,0],
# [2,0,3,0,5,7,4,1,0],
# [4,0,0,0,8,2,0,7,0],
# [0,0,4,0,2,0,0,0,1],
# [5,1,0,0,0,0,0,8,6],
# [3,6,0,0,7,1,2,0,0],
# [0,2,0,7,1,0,5,6,4],
# [0,3,5,0,6,8,1,9,2],
# [0,0,6,0,0,5,0,0,0]
# ]
# self.sudoku = [
# [0,0,0,1,0,4,8,0,0],
# [2,0,0,0,0,0,0,0,9],
# [0,0,9,0,0,0,1,0,0],
# [0,2,0,0,8,9,6,0,7],
# [0,7,0,0,1,0,0,3,0],
# [9,0,6,4,7,0,0,8,0],
# [0,0,7,0,0,0,2,0,0],
# [4,0,0,0,0,0,0,0,6],
# [0,0,2,5,0,1,0,0,0]
# ]
# self.sudoku = [
# [9,0,0,4,0,8,0,0,0],
# [0,0,2,0,0,0,1,0,0],
# [3,0,0,0,0,0,0,0,9],
# [1,0,5,2,3,0,0,6,0],
# [0,3,0,0,8,0,0,7,0],
# [0,9,0,0,6,5,3,0,1],
# [5,0,0,0,0,0,0,0,8],
# [0,0,9,0,0,0,5,0,0],
# [0,0,0,8,0,2,0,0,6]
# ]
self.sudoku = [
[0,0,0,0,0,0,0,0,0],
[2,7,8,0,0,0,1,6,9],
[0,0,0,2,0,9,0,0,0],
[0,3,7,0,5,0,8,4,0],
[0,0,0,0,0,0,0,0,0],
[0,5,1,0,6,0,7,3,0],
[0,0,0,4,0,7,0,0,0],
[5,9,4,0,0,0,3,7,6],
[0,0,0,0,0,0,0,0,0]
]
self.solve()
def printSudoku(self):
for row in self.sudoku:
print(row)
def solve(self):
for i in range(0,9):
for j in range(0,9):
if self.sudoku[i][j] == 0:
pos = possibilities(self.sudoku, i, j)
if len(pos) == 1:
self.sudoku[i][j] = pos[0]
else:
self.sudoku[i][j] = pos
elif type(self.sudoku[i][j]) == list:
if singlePossibility(self.sudoku, i, j):
pass
elif lookForInvisibleLines(self.sudoku, i, j):
pass
else:
removePossibilities(self.sudoku, i, j)
continue
else:
if self.complete():
self.printSudoku()
print("[+] COMPLETE")
return
else:
self.printSudoku()
print("--")
self.solve()
def complete(self):
for i in range(0,9):
for j in range(0,9):
if self.sudoku[i][j] == 0 or type(self.sudoku[i][j]) == list:
return False
else:
return True
def possibilities(matrix, row, column):
pos = list(range(1, 10))
pos = rowPossibilities(matrix, row, pos)
pos = columnPossibilities(matrix, column, pos)
pos = blockPossibilities(matrix, row, column, pos)
return pos
def rowPossibilities(matrix, row, numbers):
for i in numbers[:]:
if i in matrix[row]:
numbers.remove(i)
else:
return numbers
def columnPossibilities(matrix, column, numbers):
matrix = [[row[i] for row in matrix] for i in range(9)]
for i in numbers[:]:
if i in matrix[column]:
numbers.remove(i)
else:
return numbers
def blockPossibilities(matrix, row, column, numbers):
blockRow = createBlockRange(row // 3)
blockColumn = createBlockRange(column // 3)
current = []
for i in blockRow:
for j in blockColumn:
if matrix[i][j] != 0:
current.append(matrix[i][j])
for i in numbers[:]:
if i in current:
numbers.remove(i)
else:
return numbers
def removePossibilities(matrix, row, column):
value = matrix[row][column]
removeRowPossibilities(matrix, row, value)
removeColumnPossibilities(matrix, column, value)
removeBlockPossibilities(matrix, row, column, value)
def removeRowPossibilities(matrix, row, value):
for column in range(0,9):
cleanUpList(matrix, row, column, value)
def removeColumnPossibilities(matrix, column, value):
for row in range(0,9):
cleanUpList(matrix, row, column, value)
def removeBlockPossibilities(matrix, row, column, value):
blockRow = createBlockRange(row // 3)
blockColumn = createBlockRange(column // 3)
for i in blockRow:
for j in blockColumn:
cleanUpList(matrix, i, j, value)
def cleanUpList(matrix, row, column, value):
l = matrix[row][column]
if type(l) == list:
if value in l :
l.remove(value)
if len(l) == 1:
matrix[row][column] = l[0]
removePossibilities(matrix, row, column)
def createBlockRange(current):
return range(current * 3, current * 3 + 3)
def lookForInvisibleLines(matrix, row, column):
for value in matrix[row][column]:
lookForHorizontalLine(matrix, row, column, value)
lookForVerticalLine(matrix, row, column, value)
else: return False
def lookForHorizontalLine(matrix, row, column, value):
blockRow = createBlockRange(row // 3)
blockColumn = createBlockRange(column // 3)
for i in blockRow:
if i == row:
continue
for j in blockColumn:
if type(matrix[i][j]) == list:
if value in matrix[i][j]:
return
elif matrix[i][j] == value:
return
for j in range(0,9):
if j in blockColumn:
continue
else:
cleanUpList(matrix, row, j, value)
def lookForVerticalLine(matrix, row, column, value):
blockRow = createBlockRange(row // 3)
blockColumn = createBlockRange(column // 3)
for j in blockColumn:
if j == column:
continue
for i in blockRow:
if type(matrix[i][j]) == list:
if value in matrix[i][j]:
return
elif matrix[i][j] == value:
return
for i in range(0,9):
if i in blockRow:
continue
else:
cleanUpList(matrix, i, column, value)
def singlePossibility(matrix, row, column):
for value in matrix[row][column]:
if singleRowPossibility(matrix, row, column, value):
matrix[row][column] = value
removePossibilities(matrix, row, column)
return True
elif singleColumnPossibility(matrix, row, column, value):
matrix[row][column] = value
removePossibilities(matrix, row, column)
return True
elif singleBlockPossibility(matrix, row, column, value):
matrix[row][column] = value
removePossibilities(matrix, row, column)
return True
else:
return False
def singleRowPossibility(matrix, row, column, value):
for j in range(0,9):
if j == column:
continue
if type(matrix[row][j]) == list:
if value in matrix[row][j]:
return False
elif value == matrix[row][j]:
return False
else:
return True
def singleColumnPossibility(matrix, row, column, value):
for i in range(0,9):
if i == row:
continue
if type(matrix[i][column]) == list:
if value in matrix[i][column]:
return False
elif value == matrix[i][column]:
return False
else:
return True
def singleBlockPossibility(matrix, row, column, value):
blockRow = createBlockRange(row // 3)
blockColumn = createBlockRange(column // 3)
for i in blockRow:
for j in blockColumn:
if i == row and j == column:
continue
if type(matrix[row][column]) == list:
if value in matrix[row][column]:
return False
elif value == matrix[i][j]:
return False
else:
return True
sudoku = Sudoku()
|
66e7a0529336367d58fa6cb0c7d1601ed2202b27 | devanand73/learnpython | /function.py | 457 | 4.03125 | 4 | #function id defined by key word def and can accept parameters and they return value to the caller using keyword return inside the function.
##code after return keyword don't get executed as function exits once it encounter return statement
print("function to cube a number")
def cube(num):
result=num*num*num
return result
print(result)
value=input("enter a number to be qubed: ")
num=int(value)
print(num)
result=cube(num)
print(result)
|
cd82e115337943c8ee6d510d4a421e784cf793e2 | Pramod-Shrinivas/Project-Euler | /Python/007-3.py | 1,168 | 3.984375 | 4 | #!/usr/bin/python
'''
Purpose: https://projecteuler.net/problem=7
Sieve of Erasthonese Algorithm used.
Using enumerate() function.
Usage: enumerate(thing), where thing is either an iterator or a sequence, returns a iterator
that will return (0, thing[0]), (1, thing[1]), (2, thing[2]), and so forth
Here we consider a list called primes of size 130000 which contains either true or false
depending on whether the corresponding value is prime or not. Initialise primes list to true.
primes[0] and primes[1] are set to none. cause 0 and 1 are not primes.
On iterating we find primes[2] is true. Hence set all multiples of 2 to false and so on.
We just look at 10001st item in the list primes having value true.
@author:Pramod S
'''
def main():
primes = [True] * 130000
primes[0],primes[1] = [None] * 2
count =0
for index,value in enumerate(primes):
if value is True:
primes[index*2::index] = [False] * ((129999//index) - 1)
count+=1
if count == 10001:
print("Result {0}".format(index))
break
if __name__ == "__main__":
main()
|
20d99281a37dcceee1243942ed94be1d8538d458 | joshmalek/leetcode-solutions | /DynamicProgramming/BuyAndSellStock.py | 311 | 3.65625 | 4 | # Link: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
def maxProfit(self, prices: List[int]) -> int:
max_profit = 0
for k in range(len(prices)-1,0,-1):
if(min(prices[0:k]) < prices[k]):
max_profit = max(max_profit,prices[k] - min(prices[0:k]))
return max_profit |
de3f84f5258cef30c7c1b00ccfb90fb343d34b94 | pyoumg/computational_thinking_hw | /s5/5-3.py | 196 | 3.640625 | 4 | a = 3.141592
b = 1000
c = 'Python'
print("a:{}, b:{:>7d}, c:{:9s}".format(a,b,c))
print("a:{:>+8.4f}, b:{}, c:{:>13s}".format(a,b,c))
print("a:{:>8.3f}, b:{:,}, c:{}".format(a,b,c))
|
acd30ee73ba84f6949268933863ed2ae3cc4a575 | qademo2015/CodeSamples | /Python/003_reverse_words_in_string.py | 856 | 4.53125 | 5 | ######################################################################
# this file contains different implementations of reverse words
# in string without reversing their order
######################################################################
# this method does not change original string
def reverse_words_1(string):
init_arr = string.split()
final_arr = []
for x in init_arr:
final_arr.append(x[::-1])
return ' '.join(final_arr)
# this method does not change original string
def reverse_words_2(string):
arr = string.split()
for index, item in enumerate(arr):
arr[index] = item[::-1]
return ' '.join(arr)
def main():
string = 'Please reverse all words in this string'
print(string)
print(reverse_words_1(string))
print(reverse_words_2(string))
if __name__ == '__main__':
main()
|
335688028b62f7f3aefeee310f225f0066ea590d | Shaashwat05/Predictive_speech | /text.py | 765 | 3.5625 | 4 | import speech_recognition as sr
import pyttsx3
from pydub import AudioSegment
r = sr.Recognizer()
#audio_file = AudioSegment.from_wav('output.wav')
while(1):
try:
with sr.Microphone() as source2:
r.adjust_for_ambient_noise(source2, duration=2)
audio2 = r.listen(source2)
Mytext = r.recognize_google(audio2)
Mytext = Mytext.lower()
print("Did you say" + Mytext)
except sr.RequestError as e:
print("Could not request results; {0}".format(e))
except sr.UnknownValueError:
print("unknown error occured")
'''with sr.AudioFile(audio_file) as source:
audio = r.record(source)
Mytext = r.recognize_google(audio)
print(Mytext)'''
|
3e83ee55746f071268c510fa0c1be9b19c605e41 | gmt710/leetcode_python | /high/2_sortList.py | 1,813 | 3.84375 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def sortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
# https://blog.csdn.net/qq_34364995/article/details/80994110
# 先将链表递归由中间分成两个链表,然后在将这两个链表作比较,得到一个排序链表
# 即不断将由中点分成的两个链表进行排序
# ******** | ^
# **** **** | |
# ** ** ** ** | |
# * * * * * * * * V |
if head is None or head.next is None:
return head
mid = self.get_mid(head)
left = head
right = mid.next
mid.next = None
# 次数递归
return self.merge(self.sortList(left), self.sortList(right))
def merge(self, p, q):
# 按小大顺序合并两个链表
tmp = ListNode(0)
cur = tmp
while p and q:
if p.val < q.val:
cur.next = p
p = p.next
else:
cur.next = q
q = q.next
cur = cur.next
if p:
cur.next = p
else:
cur.next = q
return tmp.next
def get_mid(self, head):
# 链接中作者使用的是快慢指针,快指针走完全程时,慢指针才走了一半距离
if head is None:
return None
fast = slow = head
while fast.next and fast.next.next:
fast = fast.next.next
slow = slow.next
return slow
|
ac54a80869c640e1f07dbc364b7f000c2cb24b0d | pinobatch/little-things-nes | /rgb121/tools/bitbuilder.py | 6,272 | 3.890625 | 4 | #!/usr/bin/env python3
"""
"""
from __future__ import with_statement, print_function
def log2(i):
return int(i).bit_length() - 1
class BitBuilder(object):
def __init__(self):
self.data = bytearray()
self.nbits = 0 # number of bits left in the last byte
def append(self, value, length=1):
"""Append a bit string."""
assert(value < 1 << length)
while length > 0:
if self.nbits == 0:
self.nbits = 8
self.data.append(0)
lToAdd = min(length, self.nbits)
bitsToAdd = (value >> (length - lToAdd))
length -= lToAdd
self.nbits -= lToAdd
bitsToAdd = (bitsToAdd << self.nbits) & 0xFF
self.data[-1] = self.data[-1] | bitsToAdd
def appendRemainder(self, value, divisor):
"""Append a number from 0 to divisor - 1.
This writes small numbers with floor(log2(divisor)) bits and large
numbers with ceil(log2(divisor)) bits.
"""
nBits = log2(divisor)
# 2 to the power of (1 + nBits)
cutoff = (2 << nBits) - divisor
if value >= cutoff:
nBits += 1
value += cutoff
self.append(value, nBits)
def appendGamma(self, value, divisor=1):
"""Add a nonnegative integer in the exp-Golomb code.
Universal codes are a class of prefix codes over the integers that
are optimal for variables with a power-law distribution. Peter Elias
developed the "gamma code" in 1975, and it has become commonly used
in data compression. First write one fewer 0 bits than there are
binary digits in the number, then write the number. For example:
1 -> 1
2 -> 010
3 -> 011
4 -> 00100
...
21 -> 000010101
This function modifies the gamma code slightly by encoding value + 1
so that zero has a code.
The exp-Golomb code is a generalization of Peter Elias' gamma code to
support flatter power law distributions. The code for n with divisor
M is the gamma code for (n // M) + 1 followed by the remainder code
for n % M. To write plain gamma codes, use M = 1.
"""
if divisor > 1:
remainder = value % divisor
value = value // divisor
value += 1
length = log2(value)
self.append(0, length)
self.append(value, length + 1)
if divisor > 1:
self.appendRemainder(remainder, divisor)
def appendGolomb(self, value, divisor=1):
"""Add a nonnegative integer in the Golomb code.
The Golomb code is intended for a geometric distribution, such as
run-length encoding a Bernoulli random variable. It has a parameter
M related to the variable's expected value. The Golomb code for n
with divisor M is the unary code for n // M followed by the remainder
code for n % M.
Rice codes are Golomb codes where the divisor is a power of 2, and
the unary code is the Golomb code with a divisor of 1.
"""
if divisor > 1:
remainder = value % divisor
value = value // divisor
self.append(1, value + 1)
if divisor > 1:
self.appendRemainder(remainder, divisor)
def __bytes__(self):
return bytes(self.data)
def __len__(self):
return len(self.data) * 8 - self.nbits
@classmethod
def test(cls):
testcases = [
(cls.append, 0, 0, b''),
(cls.append, 123456789, 0, None),
(cls.append, 1, 1, b'\x80'),
(cls.append, 1, 2, b'\xA0'),
(cls.append, 3, 4, b'\xA6'),
(cls.append, 513, 10, b'\xA7\x00\x80'), # with 7 bits left
(cls.appendRemainder, 5, 10, b'\xA7\x00\xD0'),
(cls.appendRemainder, 6, 10, b'\xA7\x00\xDC'), # with 0 bits left
(cls.appendGolomb, 14, 9, b'\xA7\x00\xDC\x68'),
]
bits = BitBuilder()
if bytes(bits) != b'':
print("fail create")
for i, testcase in enumerate(testcases):
(appendFunc, value, length, result) = testcase
try:
appendFunc(bits, value, length)
should = bytes(bits)
except AssertionError:
should = None
if should != result:
print("BitBuilder.test: line", i, "failed.")
print(''.join("%02x" % x for x in bits.data))
return False
return True
def remainderlen(value, divisor):
nBits = log2(divisor)
cutoff = (2 << nBits) - divisor
if value >= cutoff:
nBits += 1
return nBits
def gammalen(value, divisor=1):
return 1 + 2*log2((value // divisor) + 1) + remainderlen(value % divisor, divisor)
def golomblen(value, divisor=1):
return 1 + value // divisor + remainderlen(value % divisor, divisor)
def biterator(data):
"""Return an iterator over the bits in a sequence of 8-bit integers."""
for byte in data:
for bit in range(8):
byte = (byte << 1)
yield (byte >> 8) & 1
byte = byte & 0xFF
class Biterator(object):
def __init__(self, data):
self.data = iter(data)
self.bitsLeft = 0
def __iter__(self):
return self
def read(self, count=1):
accum = 0
while count > 0:
if self.bitsLeft == 0:
self.bits = next(self.data)
self.bitsLeft = 8
bitsToAdd = min(self.bitsLeft, count)
self.bits <<= bitsToAdd
accum = (accum << bitsToAdd) | (self.bits >> 8)
self.bits &= 0x00FF
self.bitsLeft -= bitsToAdd
count -= bitsToAdd
return accum
__next__ = read
@classmethod
def test(cls):
src = Biterator([0xBA,0xDA,0x55,0x52,0xA9,0x0E])
print("%x" % src.read(12),)
print("%x mother shut your mouth" % src.read(12))
print("zero is", next(src))
print("%x is donkey" % src.read(12))
print("one thirty five is", src.read(10))
print("zero is", next(src))
try:
next(src)
except StopIteration:
print("stopped as expected")
else:
print("didn't stop.")
if __name__=='__main__':
print("Testing BitBuilder")
BitBuilder.test()
print("Testing Biterator")
Biterator.test()
|
4eb506aafc70283bb2e38cd8fc96dda63600e330 | HollyMccoy/InCollege | /menus/Languages.py | 1,025 | 3.921875 | 4 | # Menu commands for the "Languages" submenu
# Path: Main menu / important links / privacy policy / guest controls / languages
import globals
def ShowMenu():
"""Present the user with a menu of guest control settings."""
while True:
selection = input(
"\n" + "-- Languages --: " + '\n\n' \
+ f"Current language: {globals.currentAccount.language}" + '\n\n' \
+ "[1] English" + '\n' \
+ "[2] Spanish" + '\n' \
+ f"[{globals.goBack.upper()}] Return to the previous menu" + '\n\n')
selection = selection.lower()
if (selection == "1"): # Set the language to English
globals.currentAccount.language = "English"
globals.updateAccounts()
elif (selection == "2"): # Set the language to Spanish
globals.currentAccount.language = "Spanish"
globals.updateAccounts()
elif (selection == globals.goBack): # Return to the previous menu
return
|
7b3b51d1eae737d1be879db113210be7332d8b7b | tnotstar/talgostar | /competitive/codefights/arcade/intro/level-1/03_checkPalindrome/checkPalindrome.py | 777 | 3.640625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
def checkPalindrome(inputString):
los = len(inputString)
for i in range(los // 2):
if inputString[i] != inputString[-(i+1)]:
return False
return True
if __name__ == "__main__":
assert checkPalindrome("aabaa"), "Test #1"
assert not checkPalindrome("abac"), "Test #2"
assert checkPalindrome("a"), "Test #3"
assert not checkPalindrome("az"), "Test #4"
assert checkPalindrome("abacaba"), "Test #5"
assert checkPalindrome("z"), "Test #6"
assert not checkPalindrome("aaabaaaa"), "Test #7"
assert not checkPalindrome("zzzazzazz"), "Test #8"
assert checkPalindrome("hlbeeykoqqqqokyeeblh"), "Test #9"
assert checkPalindrome("hlbeeykoqqqokyeeblh"), "Test #10"
# EOF |
5de0b354def226b5dfc61489e7ad29bf3baed479 | zxy199803/fluent_python_exercise | /part2-数据结构/chapter3-字典和集合/3.4映射的弹性键查询.py | 1,769 | 3.71875 | 4 | """
某个键在映射里不存在时候希望能取到一个默认值
collections.defaultdict
背后是
特殊方法__missing__,所有映射类型都可以选择去支持
d.__getitem__(k) 让字典d用d[k]的形式返回键k对应的值
d.__missing__(k) 当__getitem__找不到对应的键时调用该方法
dict.keys()的返回值是视图,再其中查找元素很快
"""
# StrKeyDict0在查询的时候把非字符串的键转换为字符串
class StrKeyDict0(dict): # 继承自dict
def __missing__(self, key):
if isinstance(key, str): # isinstance判断一个对象是否是一个已知的类型。
# 若无该测试,遇到str(k)不存在时,无限递归(self[str(key)]调用__getitem__,srt(k)不存在,调用了__missing__)。
raise KeyError(key) # 如果找不到的键本身是字符串,抛出异常。
return self[str(key)] # 找不到的键不是字符串,转换成字符串再查找。调用了__getitem__
def get(self, key, default=None):
try:
return self[key] # 把查找工作用self[key]的形式委托给__getitem__,失败前可以用__missing__
except KeyError: # 如果抛出KeyError,说明__missing__也失败
return default
def __contains__(self, key): # k in dict 时调用该方法
return key in self.keys() or str(key) in self.keys() # 先按传入键的原本值查找,失败再转换成字符串查找
# 用k in my_dict检查键是否存在会导致__contains__被递归调用
d = StrKeyDict0([('2', 'two'), ('4', 'four')])
print(d['2'])
print(d[4]) # 支持非字符串的查询
# print(d[1])
print(d.get('2'))
print(d.get(4))
print(d.get(1, 'N/A'))
print(2 in d)
print(1 in d)
print('two' in d)
|
c73d0a7e87d0d8fa6b8904916f37113bfc6b3f4e | imanahmedy29/hello-world | /collatz.py | 402 | 4.15625 | 4 |
numb=int(input("Enter a number: "))
def collatz(numb):
print(numb)
while numb>1:
if numb%2==0:
numb=numb//2
print(numb)
else:
numb=(numb*3)+1
print(numb)
collatz(numb)
ques=input("Would you like to input another number? ")
while ques=="yes":
numb=int(input("Enter a number: "))
collatz(numb)
ques=input("Enter yes if you like to input another number: ")
|
aa328384d9bfa0f72b97d27a58c0e49a021b4380 | Omardyab/data-structures-and-algorithms-python | /python/code_challenges/Merge_Sort/merge_sort.py | 778 | 3.96875 | 4 |
def merge_sort(unsorted_list):
if len(unsorted_list) > 1:
mid = len(unsorted_list)//2
L = unsorted_list[:mid]
R = unsorted_list[mid:]
print(L)
print(R)
merge_sort(L)
merge_sort(R)
merge(L,R,unsorted_list)
def merge(L,R,unsorted_list):
i,j,k =0,0,0
while i < len(L) and j < len(R):
if L[i] <= R[j]:
unsorted_list[k] = L[i]
i += 1
else:
unsorted_list[k] = R[j]
j += 1
k += 1
if i == len(L):
for num in R[j:]:
unsorted_list[k] = num
k += 1
else:
for num in L[i:]:
unsorted_list[k] = num
k += 1
mylist=[20, 18, 12, 8, 5, -2]
merge_sort(mylist)
print(mylist)
|
e9eeed6edcd206f5fe70cab7743f8dd09a29e389 | jimbobsweeney/HDipPythonScripts | /unix-commands/head.py | 2,538 | 3.5625 | 4 | #!/usr/bin/python
def main():
# Import argparse and add all the arguments. Also import 'exit' to exit if there
# is an error.
import argparse
from sys import exit
parser = argparse.ArgumentParser()
parser.add_argument("files", nargs="+", help="Enter the file path on which to run the command.")
parser.add_argument("-v","--verbose", action = "store_true", help = "Always print headers giving file names.")
parser.add_argument("-q","--quiet","--silent", action = "store_true", help = "Never print headers giving file names.")
parser.add_argument("-n","--lines", action = "store", help = "Print the first N lines of the file(s).")
parser.add_argument("-c","--bytes", action = "store", help = "Print the first N bytes of the file(s).")
args = parser.parse_args()
# Filenames can be either given all the time (verbose), none of the time (quiet)
# or if there's more than one file (normal).
if args.verbose:
filenames = "verbose"
elif args.quiet:
filenames = "quiet"
else:
filenames = "normal"
# Files are scanned by lines or by bytes, with the number of each able to be
# customised by passing the appropriate flag.
# Error handling included for if a non-integer is passed to the -n or -c flags.
if args.lines:
scan_type = "lines"
try:
numLines = int(args.lines)
except ValueError:
print "Illegal argument: must be an integer."
exit()
elif args.bytes:
try:
scan_type = "bytes"
numBytes = int(args.bytes)
except ValueError:
print "Illegal argument: must be an integer."
exit()
else:
scan_type = "lines"
numLines = 10
# The text from each of the files is put into a list within a dictionary.
# By doing this, only one line of the file is in memory at a time.
text = {}
for file in args.files:
this_file = open(file)
text[file] = []
if scan_type == "bytes":
byte = 0
while byte < numBytes:
text[file].append(this_file.readline(numBytes-1))
byte = this_file.tell()
else:
line = 0
while line < numLines:
text[file].append(this_file.readline())
line += 1
this_file.close()
# Calls the decorate_filenames function at the start of each file, then
# prints the relevant lines.
for file in args.files:
decorate_filenames(filenames, file, args)
for line in text[file]:
print line,
print "\n",
# Puts the filename in where appropriate.
def decorate_filenames(filenames, file, args):
if filenames == "verbose" or (filenames == "normal" and len(args.files) > 1):
print "==> %s <==" % file
if __name__ == '__main__':
main() |
204680d695c3d64ef43f711978941b302c1e4814 | fifajan/py-stuff | /algorithms/sorting/merge_sort.py | 1,773 | 3.671875 | 4 | #! /usr/bin/python
# to test it run:
# $ ./merge_sort.py array.txt
# tests:
# Array state Time (array is 10^4 integers text file)
# ---------------------------
# random 0.2 s
# inverted 0.1 s
from sys import argv
from collections import deque
def sort(arr):
'''
Merge Sort implementation.
'''
mid = len(arr) / 2
if not mid:
return arr
l, r = arr[:mid], arr[mid:]
l, r = sort(l), sort(r)
return merge(l, r)
def merge(l, r):
'''
This merge func works exactly as it should.
'''
res = []
i = j = 0
l_l = len(l)
r_l = len(r)
while i < l_l and j < r_l:
if l[i] < r[j]:
res.append(l[i])
i += 1
else:
res.append(r[j])
j += 1
return res + l[i:] + r[j:]
def merge_list_pop(l, r):
'''
This merge func looks good but works significantly slower than it should.
10 time slower than merge on only 200K int sorting.
'''
res = []
lr_min = lambda: l.pop(0) if l[0] < r[0] else r.pop(0)
while l and r:
res.append(lr_min())
return res + l + r
def merge_deque_pop(l, r):
'''
Looks quite good too and uses deque but works a bit slower than it should.
1.5 time slower than merge on 2M int sorting.
'''
l_q, r_q = deque(l), deque(r)
res = []
lr_min = lambda: l_q.popleft() if l_q[0] < r_q[0] else r_q.popleft()
while l_q and r_q:
res.append(lr_min())
return res + list(l_q) + list(r_q)
if __name__ == '__main__':
array1 = [int(line) for line in file(argv[1])]
array2 = array1[:]
print '- Does this algorithm work correctly? (checking it now...)'
print '- ' + ('Yes!' if sort(array1) == sorted(array2) else 'Nope!')
|
dfad4102b24c3c4f22633f232d6159d77f89047b | akweiss/cfd-simulations | /code/step-4-nonlinear-convection-2D.py | 2,776 | 3.734375 | 4 | """
STEP FOUR: Nonlinear convection in two dimensions.
In this step we want to solve 2D nonlinear convection, which is represented
by these corresponding PDEs:
du/dt + u * du/dx + v * du/dy = 0
dv/dt + u * dv/dx + v * dv/dy = 0
We can discretize and solve these in a similar fashion to step three and get:
u^(n+1)_(i,j) = u(^n)_(i,j) - u_(i,j) * ((del * t) / (del * x)) * (u(^n)_(i,j) - u(^n)_(i-1,j))
- v(^n)_(i,j) * ((del * t) / (del * y)) * (u(^n)_(i,j) - u(^n)_(i,j-1))
v^(n+1)_(i,j) = v(^n)_(i,j) - u_(i,j) * ((del * t) / (del * x)) * (u(^n)_(i,j) - u(^n)_(i-1,j))
- v(^n)_(i,j) * ((del * t) / (del * y)) * (u(^n)_(i,j) - u(^n)_(i,j-1))
Here, our initial conditions are:
u, v = { 2 for x, y in (0.5, 1) x (0.5, 1)
{ 1 everywhere else
And our boundary conditions are:
u = 1
v = 1 for x = 0, 2 and y = 0,2
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import time, sys
from mpl_toolkits.mplot3d import Axes3D
# Variable declarations
nx = 101
ny = 101
nt = 100
c = 1
dx = 2 / (nx - 1)
dy = 2 / (ny - 1)
sigma = .2
dt = sigma * dx
x = np.linspace(0, 2, nx)
y = np.linspace(0, 2, ny)
u = np.ones((ny, nx))
un = np.ones((ny, nx))
v = np.ones((ny, nx))
vn = np.ones((ny, nx))
# Assign initial conditions
u[int(.5 / dy):int(1 / dy + 1),int(.5 / dx):int(1 / dx + 1)] = 2
v[int(.5 / dy):int(1 / dy + 1),int(.5 / dx):int(1 / dx + 1)] = 2
# Plot initial conditions
fig = plt.figure(figsize=(11, 7), dpi=100)
ax = fig.gca(projection='3d')
X, Y = np.meshgrid(x, y)
surf = ax.plot_surface(X, Y, u, cmap=cm.plasma)
# Implement our solutions for u^(n+1)_(i,j) and v^(n+1)_(i,j) using array operations.
for n in range(nt + 1):
un = u.copy()
vn = v.copy()
u[1:, 1:] = (un[1:, 1:] - (un[1:, 1:] * c * dt / dx * (un[1:, 1:] - un[1:, :-1]))
- vn[1:, 1:] * c * dt / dy * (un[1:, 1:] - un[:-1, 1:]))
v[1:, 1:] = (vn[1:, 1:] - (un[1:, 1:] * c * dt / dx * (vn[1:, 1:] - vn[1:, :-1]))
- vn[1:, 1:] * c * dt / dy * (vn[1:, 1:] - vn[:-1, 1:]))
u[0, :] = 1
u[-1, :] = 1
u[:, 0] = 1
u[:, -1] = 1
v[0, :] = 1
v[-1, :] = 1
v[:, 0] = 1
v[:, -1] = 1
# Plot the PDEs
fig = plt.figure(figsize=(11, 7), dpi=100)
ax = fig.gca(projection='3d')
surf2 = ax.plot_surface(X, Y, u, cmap=cm.plasma)
ax.set_xlabel('$x$')
ax.set_zlabel('$u$')
ax.set_ylabel('$y$')
ax.text2D(0.35, 0.95, "2D Non-Linear Convection at t=10 for u Velocity", transform=ax.transAxes)
fig = plt.figure(figsize=(11, 7), dpi=100)
ax = fig.gca(projection='3d')
surf3 = ax.plot_surface(X, Y, v, cmap=cm.plasma)
ax.set_xlabel('$x$')
ax.set_zlabel('$v$')
ax.set_ylabel('$y$')
ax.text2D(0.35, 0.95, "2D Non-Linear Convection at t=10 for v Velocity", transform=ax.transAxes)
plt.show()
|
6a15fe90cb5845b16e2700cf6b6a6d3fdecec245 | CodeFreezers/DSA-GFG | /Recursion/Palindrome/Python/main.py | 276 | 3.8125 | 4 | #1
def CheckPalindrome(s):
return helperCheck(s, 0, len(s) - 1)
def helperCheck(s, start, end):
if start >= end:
return True;
return (s[start] == s[end]) and helperCheck(s, start + 1, end - 1)
print(CheckPalindrome("abbcdba"))
print(CheckPalindrome("abbcbba"))
|
0d9ff2ed63aa009b75a283b0a80b0ba0e2a0096b | bobbyplubell/EulerProblems | /p27.py | 694 | 3.765625 | 4 | import bobmath
def primes_quad(a, b):
primes = 0
n = 0
num = (n * n) + (a * n) + b
while bobmath.is_prime(num):
primes += 1
num = (n * n) + (a * n) + b
n += 1
return primes
if __name__ == "__main__":
most_primes = 0
a_most = 0
b_most = 0
for a in xrange(-1001, 1001):
for b in xrange(-1001, 1001):
primes = primes_quad(a,b)
if primes > most_primes:
print("New Largest: " + str(primes) + " a: "\
+ str(a) + " b: " + str(b))
most_primes = primes
a_most = a
b_most = b
print(str(a_most) + " " + str(b_most))
print(a_most*b_most)
|
a2b56664e8038821f440a7ad4ec59d3fdd8edf22 | RayHuo/MyBlog | /python/IfElse.py | 546 | 4.0625 | 4 | a = input("First : ")
b = input("Second : ")
# if-elif-else
# remeber the ":" at the end of the condition
if a == b :
print "first is equal to second!"
elif a < b :
print "first is less than second!"
else :
print "first is larger than second!"
# python has no switch
if a + b < 10 and a * b < 20 :
print "%d + %d < 10, and %d * %d < 20" % (a, b, a, b)
elif a + b < 10 or a * b < 20 :
if not (a + b < 10) :
print "%d * %d < 20" % (a, b)
else :
print "%d + %d < 10" % (a, b)
else :
print "Nothing" |
8c0c6ea1dc5850d9d46c246e36900f437eef9c99 | kenchoi523/data_structures | /cs260_hw5/heap.py | 2,489 | 3.984375 | 4 | class Heap:
def __init__(self):
self.heap = []
self.last = 0
def __str__(self):
return str(self.heap)
def makenull(self):
self.heap = []
self.last = 0
def insert(self, x):
self.heap.append(x)
self.last += 1
if self.last == 2:
if self.heap[1] < self.heap[0]:
self.swap(0, 1)
elif self.last >= 3:
self.upheap(self.last)
def parent(self, i):
return (i-1)//2
def left(self, i):
return (i+1)*2 - 1
def right(self, i):
return (i+1)*2
def swap(self, a, b):
temp = self.heap[a]
self.heap[a] = self.heap[b]
self.heap[b] = temp
def upheap(self, i):
while i // 2 > 0:
if self.heap[i - 1] < self.heap[(i // 2) - 1]:
self.swap(((i // 2) - 1), (i - 1))
i = i // 2
def downheap(self, i):
while (i * 2) + 2 < self.last:
if self.left(i) is not None or self.right(i) is not None:
if self.heap[self.left(i)] < self.heap[self.right(i)]:
temp = self.left(i)
else:
temp = self.right(i)
if self.heap[i] > self.heap[temp]:
self.swap(temp, i)
i = temp
def inorder(self, i):
if i < self.last:
if self.left(i) is not None:
self.inorder(self.left(i))
if self.heap[i] is not None:
print(str(self.heap[i]), end=" ")
if self.right(i) is not None:
self.inorder(self.right(i))
def preorder(self, i):
if i < self.last:
if self.heap[i] is not None:
print(str(self.heap[i]), end=" ")
if self.left(i) is not None:
self.preorder(self.left(i))
if self.right(i) is not None:
self.preorder(self.right(i))
def postorder(self, i):
if i < self.last:
if self.left(i) is not None:
self.postorder(self.left(i))
if self.right(i) is not None:
self.postorder(self.right(i))
if self.heap[i] is not None:
print(str(self.heap[i]), end=" ")
def min(self):
return self.heap[0]
def deletemin(self):
self.swap(0, self.last-1)
result = self.heap.pop(self.last-1)
self.last -= 1
self.downheap(0)
return result
|
63c39b2cb47c1d363e95eaa1d9e5e0c046b46d85 | UjeanPoloz/python_hw | /homework_13.py | 693 | 3.96875 | 4 | catheter_a = int(input('Введите длину катета А:\n'))
catheter_b = int(input('Введите длину катета B:\n'))
def triangle_square_and_perimeter(a, b):
square = 1/2 * a * b
c = (a**2 + b**2)**0.5
perimeter = a + b + c
return square, perimeter
def print_answer(number):
if number - int(number) == 0:
print('Площадь треугольника равна: %d' % number)
else:
print('Площадь треугольника равна: %.3f' % number)
answer_square, answer_perimeter = triangle_square_and_perimeter(catheter_a, catheter_b)
print('-'*40)
print_answer(answer_square)
print_answer(answer_perimeter)
|
5db0c9d61f67946dabac5edb0705d26901b173cd | blueclowd/leetCode | /python/1424-Diagonal_traverse_II.py | 722 | 3.796875 | 4 | '''
Description:
Given a list of lists of integers, nums, return all elements of nums in diagonal order as shown in the below images.
'''
class Solution:
def findDiagonalOrder(self, nums: List[List[int]]) -> List[int]:
table = {}
for row_idx in range(len(nums)):
for col_idx in range(len(nums[row_idx])):
if row_idx + col_idx in table:
table[row_idx + col_idx].append(nums[row_idx][col_idx])
else:
table[row_idx + col_idx] = [nums[row_idx][col_idx]]
output = []
for _, values in sorted(table.items(), key=lambda item: item[0]):
output += list(reversed(values))
return output |
344ebfe82f4c7935d980e01b72b3ee0021775b2b | uncleLonli/homework | /second.py | 543 | 4.28125 | 4 | # coding=utf-8
"""Домашнее задание
Написать функцию find_multiples
Принимает два аргумента число и лимит
Возвращает таблицу умножения этого числа до лимита (включительно)
Например find_multiples(5, 25) вернет [5, 10, 15, 20, 25]
"""
def find_multiples(integer, limit):
list_multiples = []
for i in range(1, limit // integer + 1):
list_multiples.append(integer * i)
return list_multiples
|
74e54697962a450bc4653e9a8c2f405a78a65ebe | Allamaris0/Python | /petlecwiczenia.py | 797 | 3.671875 | 4 | for i in range(1,8):
if i==5:
print("Znalazłem " + str(i) + "!")
continue
print(i)
a = list(range(1,9))
print("Moja lista",a)
for x in a:
if x==5:
break
print(x)
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
b=0
while b<20:
b+=1
if b%3==0:
print(b)
continue
z=1
while z<=21:
print(z)
z += 5
print("------------------")
n=10
while n>=0:
print(n)
n-=1
print("---------------")
choose_letter=input("wpisz n lub c: ")
if choose_letter == "n" or "c":
print("Dziękuję!")
else:
print("wpisałeś niepoprawną literę")
print("----------------")
suma = 0
for x in range(5):
print("Wprowadź wartość")
x1 = int(input())
suma += x1
print("Suma wartości:", str(suma))
|
a8da2413e4d0e4a31098328cb55a59322b1a4b67 | BJV-git/leetcode | /string/valid_palindrome.py | 577 | 3.65625 | 4 | # logic: rather checking at each level, can simply check teh middle ones
# learned: we can just compare from the point, where the unnecessary is to be avoided
import time
x = time.time()
def del_1_palindorme(s):
slen=len(s)
i=0
j=slen-1
while i<j:
if s[i]==s[j]:
i+=1
j-=1
else:
break
if i>=j:
return True
return s[i+1:j+1]==s[i+1:j+1][::-1] or s[i:j]==s[i:j][::-1] # to consider the jth element also and on to the other hand also
print(del_1_palindorme("deeee"))
print(time.time() - x) |
58bc8e6c85215fc3c9bbc36f405db5fb9f3de6a7 | Forif-PythonClass/Assignments | /Sangjin/HW2/2-4.py | 90 | 3.75 | 4 | sum_list=[1,2,-20]
sum=0
for i in range (0,3):
sum=sum+sum_list[i]
print("sum: ",sum)
|
c8f1a1f0224007e1cbaa9fd26119792fee5cda43 | haoccheng/pegasus | /coding_interview/edit_distance.py | 1,569 | 3.828125 | 4 | # Implement a function that finds the edit distance of two input strings.
# 3 edit operations.
# insert, delete, substitution.
# saturday : sunday -> 3
# saturday : sturday -> 1
# sturday : surday -> 1
# surday : sunday -> 1
# Dynamic programming.
# Table format to keep some sort of states/scores/memory.
# How to initialize/kick start some cells in the table.
# What is the iterative direction to fill the rest of the cells.
def build_scores(input1, input2):
scores = []
for i in range(len(input1)+1):
row = []
for j in range(len(input2)+1):
row.append(None)
scores.append(row)
return scores
def init_scores(scores):
for i in range(len(scores)):
scores[i][0] = i
for i in range(len(scores[0])):
scores[0][i] = i
def iterate_scores(scores, input1, input2):
for i in range(1, len(scores)):
for j in range(1, len(scores[i])):
#
s1 = 0
if (input1[i-1] == input2[j-1]): # match; and choose to match.
s1 = scores[i-1][j-1]
else: # mismatch; choose to substitute.
s1 = scores[i-1][j-1] + 1
s2 = scores[i-1][j] + 1 # choose to delete/addition.
s3 = scores[i][j-1] + 1
scores[i][j] = min([s1, s2, s3])
def print_scores(scores):
print '==================='
for i in range(len(scores)):
print scores[i]
def edit(input1, input2):
scores = build_scores(input1, input2)
init_scores(scores)
iterate_scores(scores, input1, input2)
print_scores(scores)
edit('saturday', 'sunday')
edit('saturday', 'sturday')
edit('sturday', 'surday')
edit('surday', 'sunday')
|
5b4bd18358fe2e2d485aaf70ab34578ee0077737 | nazarov-yuriy/contests | /yrrgpbqr/p0636/__init__.py | 1,458 | 3.65625 | 4 | import unittest
from typing import List
class Solution:
def exclusiveTime(self, n: int, logs: List[str]) -> List[int]:
res = [0] * (n+1)
stack = [-1]
start = 0
for i, event in enumerate(logs):
func, action, time = event.split(":")
func = int(func)
time = int(time)
if action == "start":
res[stack[-1]] += time - start
stack.append(func)
start = time
else:
res[stack[-1]] += time + 1 - start
stack.pop()
start = time + 1
return res[:-1]
class Test(unittest.TestCase):
def test(self):
n = 2
logs = ["0:start:0", "1:start:2", "1:end:5", "0:end:6"]
self.assertEqual(Solution().exclusiveTime(n , logs), [3, 4])
n = 1
logs = ["0:start:0", "0:start:2", "0:end:5", "0:start:6", "0:end:6", "0:end:7"]
self.assertEqual(Solution().exclusiveTime(n, logs), [8])
n = 2
logs = ["0:start:0","0:start:2","0:end:5","1:start:6","1:end:6","0:end:7"]
self.assertEqual(Solution().exclusiveTime(n, logs), [7, 1])
n = 2
logs = ["0:start:0", "0:start:2", "0:end:5", "1:start:7", "1:end:7", "0:end:8"]
self.assertEqual(Solution().exclusiveTime(n, logs), [8, 1])
n = 1
logs = ["0:start:0","0:end:0"]
self.assertEqual(Solution().exclusiveTime(n, logs), [1])
|
42565a4d2c42ee11cc990817234d11c580bf68ae | OATOMO/study | /python/project_py/2048/atomDraw.py | 2,506 | 4 | 4 | #!/usr/bin/python
#coding=utf-8
import math
class Point(object):
def __init__(self,x,y):
self.x = x;
self.y = y;
def __sub__(self,other):
return Point(self.x-other.x,self.y-other.y)
def __add__(self,other):
return Point(self.x+other.x,self.y+other.y)
@property
def xy(self):
return (self.x,self.y)
def __str__(self):
return "x={0},y={1}".format(self.x,self.y)
def __repr__(self):
return str(self,xy)
@staticmethod
def dist(a,b):
return math.sqrt((a.x-b.x)**2 + (a.y-b.y)**2)
from abc import ABCMeta,abstractmethod
#基类多边形
class Polygon(object):
#用来生成抽象基础类的元类,由她生成的类可以被直接继承
__metaclass__ = ABCMeta
def __init__(self,points_list,**Kwargs):
# **Kwargs是一个关键字参数,它是一个字典
for point in points_list:
assert isinstance(point,Point),"input must be Point type"
self.points = points_list[:]
self.points.append(points_list[0])#使矩形闭合
#获得关键字的键值
self.color=Kwargs.get('color','#000000')
#遍历一个多边行的所有点
def drawPoints(self):
points_xy = []
for point in self.points:
points_xy.append(point.xy)
print points_xy
return tuple(points_xy)
@abstractmethod
def area(self):
raise("not implement")
def __lt__(self,other):
assert isinstance(other,Polygon)
return self.area<other.area
#子类矩形
class RectAngle(Polygon):
def __init__(self,startPoint,w,h,**Kwargs):
self._w = w
self._h = h
Polygon.__init__(self,[startPoint,startPoint+Point(w,0),startPoint+Point(w,h),startPoint+Point(0,h)],**Kwargs)
def area(self):
return self._w * self._h
#子类圆形
class CircleAngle(Polygon):
def __init__(self,center_xy,r,accuracy,**Kwargs):
self.center_xy = center_xy
self.r = r
self.accuracy = accuracy
self.points_xy = []
for i in range(accuracy):
jiao = float(i)/accuracy*2*math.pi
x1 = center_xy.x + r*math.cos(jiao)
y1 = center_xy.y + r*math.sin(jiao)
self.point = Point(x1,y1);
self.points_xy.append(self.point)
self.points_xy.append(self.points_xy[0])
Polygon.__init__(self,self.points_xy,**Kwargs)
def area(self):
return 2*self.r*math.pi
|
8eb7aa289e24758589fa8d53fe0c275910297fd3 | xilixjd/leetcode | /Tree/107. Binary Tree Level Order Traversal II (easy).py | 1,836 | 4.09375 | 4 | '''
Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its bottom-up level order traversal as:
[
[15,7],
[9,20],
[3]
]
'''
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class ReSolution(object):
def levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
def dfs(root, height, array):
if root is None:
return
while len(array) <= height:
array.append([])
array[height].append(root.val)
dfs(root.left, height + 1, array)
dfs(root.right, height + 1, array)
array = []
dfs(root, 0, array)
return array[::-1]
root = TreeNode(3)
root.left = TreeNode(2)
root.right = TreeNode(4)
root.left.right = TreeNode(6)
root.left.right.right = TreeNode(8)
re = ReSolution()
print re.levelOrderBottom(root)
class Solution(object):
def levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
array = []
if root is None:
return array
queue = [root]
while len(queue) != 0:
alist = []
for q in queue:
alist.append(q.val)
array.append(alist)
queue2 = queue
queue = []
for q in queue2:
if q.left:
queue.append(q.left)
if q.right:
queue.append(q.right)
return array[::-1] |
d209291021d84876cc8e1fba2c4ac606510cecb7 | wxhheian/hpip | /ch5/ex5_1.py | 652 | 3.734375 | 4 | # cars = ['audi','bmw','subaru','toyata']
#
# for car in cars:
# if car == 'bmw':
# print(car.upper())
# else:
# print(car.title())
#
# car = 'Audi'
# print(car == 'audi')
#
# requested_topping = 'mushrooms'
# if requested_topping != 'anchovies':
# print('Hold the anchovies!')
#and or
#检查特定值是否在列表中
requested_toppings = ['mushrooms','onions','pipeapple']
print('mushrooms' in requested_toppings)
#检查特定值是否不包含在列表中
banned_users = ['andrew','carolina','david']
user = 'marie'
if user not in banned_users:
print(user.title() + ", you can post a response if you wish.")
|
ca94c4e27aaa425b0481ca39707ff3ac6e49154a | graycarl/algorithms_c | /chapter2/insertsort.py | 492 | 3.59375 | 4 | #!/usr/bin/env python
def read_in(filename):
f = file(filename, 'r')
nums = []
for s in f: nums.append(int(s))
return nums
def write_out(filename, nums):
strs = [ str(n) for n in nums]
file(filename, 'w').write("\n".join(strs))
return
def ins_sort(nums):
length = len(nums)
for i in range(1, length-1):
key = nums[i]
j = i-1
while j >= 0 and key < nums[j]:
nums[j+1] = nums[j]
j = j-1
nums[j+1] = key
nums = read_in("data")
ins_sort(nums)
write_out("result", nums)
|
3bcfa78c189ee5d5db328b1e464bc3dfd2e8276b | Collinbarlow98/Assignments | /Calculate/FizzBuzz.py | 446 | 4.03125 | 4 | fizz = "Fizz"
buzz = "Buzz"
no_fizz_buzz = "Where is FizzBuzz?"
def ask_user_input():
greet = "Hello please enter an integer!"
print(greet)
def fizz_buzz():
number = int(input("Number: "))
if (number % 3 == 0 and number % 5 == 0):
print(fizz + buzz)
elif (number % 5 == 0):
print(buzz)
elif (number % 3 == 0):
print(fizz)
else:
print(no_fizz_buzz)
return fizz_buzz()
fizz_buzz()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.