blob_id
stringlengths 40
40
| repo_name
stringlengths 6
108
| path
stringlengths 3
244
| length_bytes
int64 36
870k
| score
float64 3.5
5.16
| int_score
int64 4
5
| text
stringlengths 36
870k
|
---|---|---|---|---|---|---|
e61200d2f2eae37f7c8d2f0c115950216b2c9902 | phlalx/algorithms | /leetcode/40.combination-sum-ii.py | 1,712 | 3.5625 | 4 | #
# @lc app=leetcode id=40 lang=python3
#
# [40] Combination Sum II
#
# https://leetcode.com/problems/combination-sum-ii/description/
#
# algorithms
# Medium (43.31%)
# Likes: 1431
# Dislikes: 56
# Total Accepted: 296.5K
# Total Submissions: 642.8K
# Testcase Example: '[10,1,2,7,6,1,5]\n8'
#
# Given a collection of candidate numbers (candidates) and a target number
# (target), find all unique combinations in candidates where the candidate
# numbers sums to target.
#
# Each number in candidates may only be used once in the combination.
#
# Note:
#
#
# All numbers (including target) will be positive integers.
# The solution set must not contain duplicate combinations.
#
#
# Example 1:
#
#
# Input: candidates = [10,1,2,7,6,1,5], target = 8,
# A solution set is:
# [
# [1, 7],
# [1, 2, 5],
# [2, 6],
# [1, 1, 6]
# ]
#
#
# Example 2:
#
#
# Input: candidates = [2,5,2,1,2], target = 5,
# A solution set is:
# [
# [1,2,2],
# [5]
# ]
#
#
#
# TAGS backtrack
# almost identical to combination sum i
# @lc code=start
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
n = len(candidates)
path = []
sols = set()
candidates.sort(reverse=True) # optimization?
def dfs(target, i):
if target == 0 and i == n:
sols.add(tuple(path))
elif i < n:
dfs(target, i+1) # don't use current numbers
c = candidates[i]
if target - c >= 0:
path.append(c)
dfs(target - c, i+1)
path.pop()
dfs(target, 0)
return sols
# @lc code=end
|
931d7cb98196fdd2e04d5b4353b4e758fc4c2d9c | greatabel/PythonRepository | /03Programming in Python 3/1&2Basic_And_DataType/awfulpoetry_strength_ch1answer.py | 951 | 3.671875 | 4 | articles = ['the','a','another','other']
subjects = ['cat','dog','man','woman','boy']
verbs = ['sang','ran','jumped','drank']
adverbials =['loudly','quietly','well','badly']
import random
import sys
def get_input(msg):
while True:
try:
line = input(msg)
return int(line)
except:
# print("unexpected error:",sys.exc_info()[0])
return None
def makepoetry(linecount):
sentence = ''
for i in range(linecount):
# print(i)
sentence = ''
myindex = random.randint(0,len(articles)-1)
sentence += articles[myindex]+' '
myindex = random.randint(0,len(subjects)-1)
sentence += subjects[myindex]+' '
myindex = random.randint(0,len(verbs)-1)
sentence += verbs[myindex]+' '
myindex = random.randint(0,len(adverbials)-1)
sentence += adverbials[myindex]
print(sentence)
while True:
data = get_input("enter a number or Enter to finish:-->")
if data is not None:
makepoetry(data)
else:
makepoetry(5)
break
|
928129ae586811a75b95b7067888aeca52d7daae | jdanray/leetcode | /verticalTraversal.py | 501 | 3.78125 | 4 | # https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/
class Solution(object):
def verticalTraversal(self, root):
if not root:
return []
vertical = {}
stack = [[root, 0, 0]]
while stack:
node, x, y = stack.pop()
if not node:
continue
vertical[x] = vertical.get(x, []) + [(y, node.val)]
stack.append([node.left, x - 1, y + 1])
stack.append([node.right, x + 1, y + 1])
return [[val for y, val in sorted(vertical[x])] for x in sorted(vertical)]
|
184c4fb17400281ad68d7b1d5257dc850e1a1f49 | yinzhiyizhi/Python_Practise | /函数式编程/高阶函数/filter.py | 3,885 | 4.0625 | 4 | # Python内建的filter()函数用于过滤序列。
# 和map()类似,filter()也接收一个函数和一个序列。
# 和map()不同的是,filter()把传入的函数依次作用于每个元素,
# 然后根据返回值是True还是False决定保留还是丢弃该元素。
# 例如,在一个list中,删掉偶数,只保留奇数,可以这么写:
def is_odd(n):
return n%2==1
list(filter(is_odd,[1,2,4,5,6,9,10,15]))
# [1,5,9,15]
# 把一个序列中的空字符串删掉,可以这么写:
def not_empty(s):
return s and s.strip()
list(filter(not_empty,['A','','B',None,'C',' ']))
# ['A','B','C']
# 可见用filter()这个高阶函数,
# 关键在于正确实现一个“筛选”函数。
# 注意到filter()函数返回的是一个Iterator,
# 也就是一个惰性序列,所以要强迫filter()完成计算结果,
# 需要用list()函数获得所有结果并返回list。
# 用filter求素数
# 计算素数的一个方法是埃氏筛法,它的算法理解起来非常简单:
# 首先,列出从2开始的所有自然数,构造一个序列:
# 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...
# 取序列的第一个数2,它一定是素数,
# 然后用2把序列的2的倍数筛掉:
# 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...
# 取新序列的第一个数3,它一定是素数,
# 然后用3把序列的3的倍数筛掉:
# 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...
# 取新序列的第一个数5,然后用5把序列的5的倍数筛掉:
# 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...
# 不断筛下去,就可以得到所有的素数。
# 用Python来实现这个算法,可以先构造一个从3开始的奇数序列:
def _odd_iter():
n=1
while True:
n=n+2
yield n
# 注意这是一个生成器,并且是一个无限序列。
# 然后定义一个筛选函数:
def _not_divisible(n):
return lambda x:x%n>0
# 最后,定义一个生成器,不断返回下一个素数:
def primes():
yield 2
it=_odd_iter() # 初始序列
while True:
n=next(it) # 返回序列的第一个数
yield n
it=filter(_not_divisible(n),it) # 构造新序列
# 这个生成器先返回第一个素数2,然后,
# 利用filter()不断产生筛选后的新的序列。
# 由于primes()也是一个无限序列,
# 所以调用时需要设置一个退出循环的条件:
# 打印1000以内的素数:
for n in primes():
if n<1000:
print(n)
else:
break
# 注意到Iterator是惰性计算的序列,
# 所以我们可以用Python表示“全体自然数”,
# “全体素数”这样的序列,而代码非常简洁。
# 小结
# filter()的作用是从一个序列中筛出符合条件的元素。
# 由于filter()使用了惰性计算,
# 所以只有在取filter()结果的时候,
# 才会真正筛选并每次返回下一个筛出的元素。
# 练习
# 回数是指从左向右读和从右向左读都是一样的数,
# 例如12321,909。请利用filter()筛选出回数:
# def is_palindrome(n):
# pass
# 测试:
# output = filter(is_palindrome, range(1, 1000))
# print('1~1000:', list(output))
# if list(filter(is_palindrome, range(1, 200))) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191]:
# print('测试成功!')
# else:
# print('测试失败!')
def is_palindrome(n):
s=str(n)
if s[0:]==s[::-1]:
return n
# 测试:
output = filter(is_palindrome, range(1, 1000))
print('1~1000:', list(output))
if list(filter(is_palindrome, range(1, 200))) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191]:
print('测试成功!')
else:
print('测试失败!') |
91e52efff48ded70219a0c2a5f028d201c4ee5f2 | ajpiter/PythonProTips | /DeepLearning/Archive/SlopeCalculation.py | 1,257 | 4.125 | 4 | #Slope Calculation Example, with one input and no activation function.
Node1 = Input = 3
Weight = 2
Node2 = Output = 6
PredictedValue = Node2
ActualTargetValue = 10
LearningRate = 0.01
SlopePrediction = Slope of Mean-Squared loss function precdiction
SlopePrediction = 2 * (Predicted Value - Actual Value) = 2*Error
SlopePrediction = 2 *(6 - 10) = 2 * -4
Node1 = Value of the node that feeds into our weight
Node1 = 3
SlopeWeight = Slope for a weight
SlopeWeight = SlopePrediction * Node1
SlopeWeight = 2 * -4 * 3
Slopeweight = -24
NewWeight = Weight -LearningRate *SlopeRate
NewWeight = 2 - 0.01(-24)
#Slope Calculation Example, with two inputs and no activation function
#Code to calucalte the slopes and update the weights
Node1 = 3
Node2 = 4
Weight1 = 1
Weight2 = 2
import numpy as np
weights = np.array([1, 2])
inputdata = np.array([3, 4])
targetvalue = 6
learningrate = 0.01
slopeprediction = (weights * inputdata).sum()
error = slopeprediction - targetvalue
print(error)
gradient = 2 * inputdata * error
gradient
#returns ([30,40})
weightsupdated = weights - learningrate * gradient
predictionupdated = (weightsupdated * inputdata).sum()
errorupdated = predictionupdated - target
print(errorupdated)
#returns -2.5
|
07317312d2ffd9b82a44e473c21aab5bf0940f43 | Jehuty-ML/- | /data structure/100!single link list.py | 3,646 | 3.75 | 4 | '''
模仿c语言的内存精度限制,用链表实现求100阶乘的结果
'''
class Node(object):
"""单链表的结点"""
def __init__(self, item):
# item存放数据元素
self.item = item
# next是下一个节点的标识
self.next = None
class SingleLinkList(object):
"""单链表"""
def __init__(self, item):
self._head = Node(item)
def is_empty(self):
"""判断链表是否为空"""
return self._head is None
def length(self):
"""链表长度"""
cur = self._head
count = 0
while cur is not None:
count += 1
cur = cur.next
return count
def items(self):
cur = self._head
while cur is not None:
yield cur.item
cur = cur.next
def find(self, item):
"""查找元素是否存在"""
return item in list(self.items())
def add(self, item):
"""向链表头部添加元素"""
if not isinstance(item, Node):
item = Node(item)
item.next = self._head
self._head = item
return
def append(self, item):
"""尾部添加元素"""
if not isinstance(item, Node):
item = Node(item)
if self._head is not None:
cur = self._head
while cur.next is not None:
cur = cur.next
cur.next = item
else:
self._head = item
def insert(self, index, item):
"""指定位置插入元素"""
if not isinstance(item, Node):
item = Node(item)
if index <= 0:
self.add(item)
elif index > self.length() - 1:
self.append(item)
else:
cur = self._head
for _ in range(index-1):
cur = cur.next
item.next = cur.next
cur.next = item
def remove(self, item):
if self.find(item):
cur = self._head
pre = None
while cur is not None:
if cur.item == item:
if not pre: #如果第一个节点就是要删除的
self._head = cur.next
else:
pre.next = cur.next
else:
pre = cur
cur = cur.next
else:
'%s is not in single link list' % item
def find(self, item): #item在index
if item in self.items():
index_list = []
index = 0
cur = self._head
for _ in range(self.length()):
if cur.item == item:
index_list.append(index)
cur = cur.next
index += 1
return index_list
def mul(self, value):
addition = 0
cur = self._head
for _ in range(self.length()):
temp = cur.item * value + addition
cur.item = temp % 10
addition = temp // 10
cur = cur.next
while addition:
self.append(addition % 10)
addition //= 10
def reverse(self):
cur = self._head
pre = None
while cur:
cur.next, pre, cur = pre, cur, cur.next
return pre
def __repr__(self):
result = ''
self._head = self.reverse()
# self.reverse()
for i in self.items():
result += str(i)
return result
if __name__ == '__main__':
#阶乘100
result = SingleLinkList(1)
for i in range(1, 100+1):
result.mul(i)
print(result) |
36205f8f4f724fe22e32dc4ca4a9603661c8cde1 | dprestsde/project-euler | /1.py | 351 | 4.1875 | 4 | # If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
# The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
result = 0
i = 1
while 3*i<=1000 or 5*i<=1000:
if 3*i<=1000:
result += (3*i)
if 5*i<=1000:
result += (5*i)
i+=1
print(result)
|
6be1eb13f55085ffc05243d94ef2e67dc84722a8 | WaleedRanaC/Prog-Fund-1 | /Lab 6/CheckPoint3b.py | 333 | 4.15625 | 4 | #write a short program using while loop
#that displays each line of the file
def main():
#open file
infile=open('data.txt','r')
#assign and define line
line=infile.readline()
#while loop
while line !='':
printn(line)
line=infile.readline()
infile.close()
main()
|
dabab3d13b5912664682629aed907c8ec70237bc | szabgab/slides | /python/examples/dictionary/scores.py | 421 | 3.859375 | 4 | scores = {
"Jane" : 30,
"Joe" : 20,
"George" : 30,
"Hellena" : 90,
}
for name in scores.keys():
print(f"{name:8} {scores[name]}")
print('')
for name in sorted(scores.keys()):
print(f"{name:8} {scores[name]}")
print('')
for val in sorted(scores.values()):
print(f"{val:8}")
print('')
for name in sorted(scores.keys(), key=lambda x: scores[x]):
print(f"{name:8} {scores[name]}")
|
5b6e9941152b0950fb29d7422bb72c30e31f2aae | dodekaedro6p14/poesia-python | /thursday.py | 574 | 3.609375 | 4 | from turtle import Screen, Pen
import colorsys
screen = Screen()
screen.title("thursday")
screen.bgcolor("black")
t = Pen()
#pen.speed('fastest')
poesia = 0.0 # rando de colores is 0.0 to 1.0
for i in range(200):
color = colorsys.hsv_to_rgb(poesia, 1, 1) # pen wants RGB
t.pencolor(color)
t.forward(i * 2) # incrementa tamaño
t.right(121) # 120 grados de un tringulo equilatero
poesia += 0.005 # incremento por 1/200
t.hideturtle()
input()
|
4e7e051841fb766dffd059df99a08d0565540263 | brianfurrer/CSE015 | /Lab_08/Lab_8.py | 1,142 | 3.609375 | 4 | import random
import time
def gen_random_list(n):
assert(n>0)
li = [random.randint(0,10*n) for i in range(n)]
return li
if __name__ == '__main__':
l = gen_random_list(10)
l.sort()
print(l)
def linear_search(s,k):
i = 0
n = len(s) - 1
while(i <= n and k != s[i]):
i += 1
if(i <= n):
return -1
def binary_search(s,k):
i = 0
j = len(s)
while i < j:
mid = (i+j)//2
if k > s[mid]:
i = mid + 1
else:
j = mid
if k == s[i]:
result = i
else:
result = -1
return result
print("\n\n")
print("Linear Search Times")
for i in range(9):
li = gen_random_list(10**i)
startTime = time.perf_counter()
linear_search(li, -1)
spentTime = time.perf_counter() - startTime
print("Length = 10^" + str(i + 1))
print(spentTime)
print("\n\n")
print("Binary Search Times")
for i in range(9):
li = gen_random_list(10**i)
startTime = time.perf_counter()
binary_search(li, -1)
spentTime = time.perf_counter() - startTime
print("Length = 10^" + str(i + 1))
print(spentTime) |
63151ec788741a18645abc0be9cfa55492e22a9a | william-yz/show-me-the-code | /0000.py | 521 | 3.625 | 4 | from PIL import Image, ImageDraw, ImageFont
# get an image
base = Image.open('0000.png').convert('RGBA')
# make a blank image for the text, initialized to transparent text color
txt = Image.new('RGBA', base.size, (255,255,255,0))
# get a font
# fnt = ImageFont.truetype('Pillow/Tests/fonts/FreeMono.ttf', 40)
# get a drawing context
d = ImageDraw.Draw(txt)
# draw text, half opacity
d.text((70,0), "1", fill=(255,0,0,255))
# draw text, full opacity
out = Image.alpha_composite(base, txt)
out.save('0000a.png', 'PNG') |
d3c0934742e10645002ba74452aafd9d6eba90c9 | sunshinewxz/leetcode | /78-subsets.py | 775 | 3.59375 | 4 | class Solution(object):
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
# result = [[]]
# for n in nums:
# for r in result[:]:
# temp = r[:]
# temp.append(n)
# result.append(temp)
# print(result)
# return result
# solution 2: dfs
def subsets(self, nums):
result = []
self.dfs(nums, 0, 0, [], result)
return result
def dfs(self, nums, length, index, curr, result):
result.append(curr)
if length == len(nums):
return
for i in range(index, len(nums)):
self.dfs(nums, length+1, i+1, curr+[nums[i]], result)
s = Solution()
print(s.subsets([1, 2, 3]))
|
73efcca981af6efe06eee82b13a4334b57c5e41b | Myduzo/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/models/square.py | 1,787 | 3.75 | 4 | #!/usr/bin/python3
"""The Square"""
from models.rectangle import Rectangle
class Square(Rectangle):
"""class Square that inherits from Rectangle with\
private instance attributes"""
pass
def __init__(self, size, x=0, y=0, id=None):
"""Class contructor"""
super().__init__(size, size, x, y, id)
def __str__(self):
"""method str"""
return "[Square] ({}) {}/{} - {}".format(self.id,
self.x,
self.y,
self.size)
def update(self, *args, **kwargs):
"""public method update"""
if len(args) > 0 and args is not None:
idx = len(args)
if idx >= 1:
self.id = args[0]
if idx >= 2:
self.size = args[1]
if idx >= 3:
self.x = args[2]
if idx >= 4:
self.y = args[3]
else:
self.id = kwargs.get("id", self.id)
self.size = kwargs.get("size", self.size)
self.x = kwargs.get("x", self.x)
self.y = kwargs.get("y", self.y)
def to_dictionary(self):
"""public method to_dictonary"""
return {"id": self.id, "x": self.x, "size": self.size, "y": self.y}
@property
def size(self):
"""Getter for the private size attribute"""
return self.width
@size.setter
def size(self, value):
"""Setter for the private size attribute"""
if not isinstance(value, int):
raise TypeError("width must be an integer")
if value <= 0:
raise ValueError("width must be > 0")
self.width = value
self.height = value
|
55238e02e9c30d3c23dbdf7d8c7b2d32c31fc1b7 | muhfikriw/Praktikum8 | /langkah kerja.py | 1,390 | 3.71875 | 4 | a = [1, 5, 6, 3, 6, 9, 11, 20, 12]
b = [7, 4, 5, 6, 7, 1, 12, 5, 9]
a.insert(3,10)
print("a = ", end="")
print(a)
b.insert(2,15)
print("b = ", end="")
print(b)
#penambahan data terakhir
print("_"*35)
x = len(a)
a.insert(x,4)
print("a = ", end="")
print(a)
l = len(b)
b.insert(l,8)
print("b = ", end="")
print(b)
#sorting ascending
print("_"*35)
a.sort()
print("a = ", end="")
print(a)
b.sort()
print("b = ", end="")
print(b)
#penambahan data c dan d
print("_"*35)
c = a[0:7]
print("c = ", end="")
print(c)
d = b[2:9]
print("d = ", end="")
print(d)
#list e ( c + d)
print("_"*35)
x = 0
e = []
for i in c:
k = c[x] + d[x]
e.append(k)
x += 1
print("e = ", end="")
print(e)
#ubah dari list ke tuple
print("_"*35)
print("Data Tuple = ", end="")
tup = tuple(e)
print(tup)
#sum, min, max
print("_"*35)
print("MIN = ", end="")
print(min(tup))
print("MAX = ", end="")
print(max(tup))
print("JUMLAH SELURUH = ", end="")
print(sum(tup))
#GANTI LIST
#GANTI LIST
#GANTI LIST
#GANTI LIST
print("")
print("_"*35)
myString = ("python adalah bahasa pemrograman yang menyenangkan")
print("python adalah bahasa pemrograman yang menyenangkan")
print("")
print("disusun menggunakan huruf = ", end="")
wkwk = set(myString)
print(wkwk)
print("")
print("_"*35)
wkwkwk = list(wkwk)
wkwkwk.sort()
print(wkwkwk ) |
674c9fa713737486e2835b892e02eda8e90b1360 | elefteroff/chaining_methods_v2 | /chaining_methods.py | 1,190 | 3.703125 | 4 | class User:
def __init__(self, name, email):
self.name = name
self.email = email
self.account_balance = 0
def make_deposit(self, amount):
self.account_balance += amount
return self
def make_withdrawal(self, amount):
self.account_balance -= amount
return self
def display_user_balance(self):
print(f"Name: {self.name}, Balance: {self.account_balance}")
def transfer_money(self, other_user, amount):
self.other_user = other_user
self.amount = amount
self.account_balance -= amount
other_user.account_balance += amount
return self
User1 = User("James Bond", "[email protected]")
User2 = User("John Wick", "[email protected]")
User3 = User("Jack Ryan", "[email protected]")
User1.make_deposit(1000000).make_deposit(2500000).make_withdrawal(750000).display_user_balance()
User2.make_deposit(500000).make_deposit(3000000).make_withdrawal(250000).make_withdrawal(75000).display_user_balance()
User3.make_deposit(100000).make_withdrawal(10000).make_withdrawal(5000).make_withdrawal(7500).display_user_balance()
User1.transfer_money(User3, 500000)
User1.display_user_balance()
User3.display_user_balance() |
103496b50aae26cc6f8313771d0fbaa6bd6ff827 | steveedegbo/learning_python | /Functions/functions.py | 4,512 | 4.125 | 4 | # # # # # #TAKES NAME & GENDER INPUT AND GREETS ACCORDINGLY
# # # # # def greet(name, gender, age):
# # # # # if gender == "male" and age >= 18:
# # # # # print(f'Hello Mr {name}..!')
# # # # # elif gender == "male" and age < 18:
# # # # # print(f'Hello Mst {name}..!')
# # # # # elif gender == "female" and age >= 18:
# # # # # print(f'Hello Mrs {name}..!')
# # # # # else:
# # # # # print(f'Hello Ms {name}..!')
# # # # # # greet("Ade", "female")
# # # # # people = [("bolu", "male", 23), ("ade", "female", 15), ("sholu", "female", 45), ("manny", "male", 33)]
# # # # # for name,gender,age in people:
# # # # # greet(name,gender,age)
# # # # # for name,gender in people:
# # # # # greet(name,gender)
# # # # #DEFINING YOUR OWN PYTHOIN FUNCTION REAL PYTHON READ UP
# # # # #HANGMAN WITH FUNCTIONS IN IT
# # # # name = input("Please enter your name : ")
# # # # print(f"Hi {name}, welcome to Hangman")
# # # # turns = 5
# # # # word = "stephen"
# # # # word_guess = ""
# # # # while turns > 0:
# # # # failed = 0
# # # # for char in word:
# # # # if char in word_guess:
# # # # print(char)
# # # # else:
# # # # print("_")
# # # # failed += 1
# # # # if failed == 0:
# # # # print("You guessed right!")
# # # # break
# # # # guess = input("Please enter your guess : ")
# # # # word_guess += guess
# # # # if guess not in word:
# # # # turns -= 1
# # # # print("You have", turns, "more guesses")
# # # # if turns == 0:
# # # # print("You lost")
# # # # def say_hello(name):
# # # # """THIS FUNCTION IS NICE and this is a docstring"""
# # # # print(f"Hello {name}")
# # # # say_hello('bola')
# # # # def sqrt(number1,number2,power):
# # # # answer = (number1 ** 2 + number2 ** 2) ** (1/power)
# # # # print(answer)
# # # # sqrt(3,4,2)
# # # def sqrt(number):
# # # answer = number ** (1/2)
# # # return answer
# # # def square(number):
# # # answer2 = number ** 2
# # # return answer2
# # # sdf = sqrt(square(5) + square(7))
# # # print(sdf)
# # import datetime
# # # time_now = datetime.datetime.now()
# # # # print(time_now)
# # # # print(time_now.weekday()) #GIVES WEEKDAY IN NUMERALS
# # # print(time_now.strfttime("%a:%H:%M")) #GIVES A FORMATTED STRING REPRESENTATION OF TIME
# # # time_stamp = (time_now.strfttime("%a %H:%M"))
# # def get_timestamp():
# # time_now = datetime.datetime.now()
# # time_stamp = time_now.strftime("%b %d %Y %a %H %M.")
# # print(time_stamp)
# # return time_stamp
# # def number_words(text):
# # count = len(text)
# # print(count)
# # return count
# # def store_memory(memory, time_stamp, count):
# # file = open(f"functions/{time_stamp},{count}.txt", "w")
# # file.write(memory)
# # file.close()
# # return True
# # text = input("Please enter text : ")
# # time_stamp = get_timestamp()
# # count = number_words(text)
# # store_memory(text, time_stamp, count)
# # #OPEN NEW FILE AND WRITE TO IT
# # # file = open("functions/note.txt", "w")
# # # text = input("Please enter text : ")
# # # file.write(text)
# # * is a tuple unpacker * variable positional argument
# ## ** is a dictionary unpacker *variable keyworrd argument
# # def sum_nums(*args):
# # print(args)
# # sum_nums(2,32,3,4,7,8,9,0,4,5)
# def sum_nums(**kwargs):
# print(kwargs)
# sum_nums(x=2,y=3,z=4,q=6,h=23)
#LAMBDA FUNCTION
# numbers = list("12345678")
# mini2 = lambda x: "A" + str(x)
# mapped_result2 = map(mini2, numbers)
# print(list(mapped_result2))
#RECURSION
# def factorial(n):
# if n <= 1:
# return n
# else:
# val = n + factorial(n-1)
# print(val)
# return val
# factorial(3)
# def count_down(num):
# if num == 0:
# return num
# print(num)
# return count_down(num-1)
# count_down(10)
# previous_number = 0
# numbers = 20,60,90,103,109,120
# for i in numbers:
# print(i - previous_number)
# previous_number = i
#with recursion
# previous_number = 0
# numbers = [20,60,90,103,109,120]
# def moving_difference(vals):
# if len(vals) == 1:
# return 0
# else:
# previous = vals.pop(0)
# print(vals[0] - previous)
# return moving_difference(vals)
# moving_difference(numbers) |
3808f700176d80b3051af89fe24bcc584c0ce791 | iambaim/pyEcholab | /echolab2/plotting/qt/QImageViewer/QIVHudText.py | 6,629 | 3.5 | 4 | from PyQt5.QtCore import *
from PyQt5.QtGui import *
class QIVHudText(QObject):
"""
Add text to the scene given the text and position. The function returns
the reference to the QGraphicsItem.
text (string) - The text to add to the scene.
position (QPointF) - The position of the text anchor point.
size (int) - The text size, in point size
font (string) - A string containing the font family to use. Either stick
to the basics with this (i.e. "times", "helvetica") or
consult the QFont docs.
italics (bool) - Set to true to italicise the font.
weight (int) - Set to an integer in the range 0-99. 50 is normal, 75 is bold.
color (list) - A 3 element list or tuple containing the RGB triplet
specifying the color of the text.
alpha (int) - An integer specifying the opacity of the text. 0 is transparent
and 255 is solid.
halign (string) - Set this value to set the horizontal anchor point. Values are:
'left' - Sets the anchor to the left side of the text
'center' - Sets the anchor to the middle of the text
'right' - Sets the anchor to the right side of the text
valign (string) - Set this value to set the vertical anchor point. Values are:
'top' - Sets the anchor to the top of the text
'center' - Sets the anchor to the middle of the text
'bottom' - Sets the anchor to the bottom of the text
"""
def __init__(self, position, text, graphicsview, size=10, font='helvetica',
italics=False, weight=-1, color=[0,0,0], alpha=255, halign='left',
valign='top', normalized=True, parent=None):
super(QIVHudText, self).__init__()
self.__color = color
self.__text = text
self.__font = font
self.__alpha = alpha
self.__size = size
self.__italics = italics
self.__weight = weight
self.__graphicsView = graphicsview
self.__position = position
self.__normalized = normalized
self.__halign = halign
self.__valign = valign
# create the font and brush
self.__font = QFont(font, size, weight, italics)
self.__pen = self.__getPen(self.__color, self.__alpha, '', 1)
self.__backgroundBrush = None
# update the position values
self.__updatePosition()
def setText(self, text):
"""
Set the text.
"""
self.__text = text
self.__updatePosition()
def setBackground(self, color, alpha):
if (color):
self.__backgroundBrush = self.__getBrush(color, alpha)
else:
self.__backgroundBrush = None
def setPosition(self, p1):
"""
Set the text's anchor point. The point must be a QPointF object.
"""
# set the starting point
self.__position = p1
# update the bounding rect
self.__updatePosition()
def setColor(self, color):
"""
Sets the rubberband line color. Color is a 3 element list or tuple containing
the RGB triplet specifying the color of the line.
"""
# change the brush (text) color
self.__color = color
self.__pen.setColor(QColor(color[0], color[1], color[2], self.__alpha))
def setAlpha(self, alpha):
"""
Set the alpha level (transparency) of the text. Valid values
are 0 (transparent) to 255 (solid)
"""
# change the brush (text) alpha
self.__alpha = alpha
self.__pen.setColor(QColor(self.__color[0], self.__color[1], self.__color[2], alpha))
def boundingRect(self):
"""
Returns a QRectF object that defines the bounding box for the text.
"""
return QRectF(self.__boundingRect)
def paint(self, painter):
"""
Simple paint method that draws the text with the supplied painter.
"""
# calculate the text bounding box
self.__updatePosition()
# draw the background if enabled
if (self.__backgroundBrush):
painter.setBrush(self.__backgroundBrush)
painter.drawRect(self.boundingRect())
painter.setBrush(Qt.NoBrush)
# draw the text
painter.setFont(self.__font)
painter.setPen(self.__pen)
painter.drawText(self.position, self.__text)
def __updatePosition(self):
# get the font metrics and calculate text width and height
fontMetrics = QFontMetrics(self.__font)
brWidth = fontMetrics.width(self.__text)
brHeight = fontMetrics.height() + 1
if self.__normalized:
# convert from normalized to viewport coordinates
scenePos = QPointF(self.__graphicsView.viewport().size().width() * self.__position.x(),
self.__graphicsView.viewport().size().height() * self.__position.y())
else:
scenePos = self.__position
# calculate the horizontal position based on alignment
if (self.__halign.lower() == 'center'):
brX = round(scenePos.x() - (brWidth / 2.0))
elif (self.__halign.lower() == 'right'):
brX = round(scenePos.x() - brWidth)
else:
brX = round(scenePos.x())
# calculate the vertical position based on alignment
if (self.__valign.lower() == 'center'):
brY = round(scenePos.y() - (brHeight / 2.0))
elif (self.__valign.lower() == 'bottom'):
brY = round(scenePos.y() - brHeight)
else:
brY = round(scenePos.y())
self.position = QPoint(brX, brY + brHeight - (2 * fontMetrics.descent()))
self.__boundingRect = QRect(brX, brY, brWidth, brHeight)
def __getBrush(self, color, alpha):
brushColor = QColor(color[0], color[1], color[2], alpha)
brush = QBrush(brushColor)
return brush
def __getPen(self, color, alpha, style, width):
# return a pen
penColor = QColor(color[0], color[1], color[2], alpha)
pen = QPen(penColor)
pen.setWidthF(width)
if style.lower() == '-':
pen.setStyle(Qt.DashLine)
elif style.lower() == '.':
pen.setStyle(Qt.DotLine)
else:
pen.setStyle(Qt.SolidLine)
return pen
|
427a00e3ab81f482e87b8f9ade7e62e79922ecb7 | hubduing/my_project | /Curse_2/module2/2.2/date.py | 645 | 3.84375 | 4 | import datetime
def date_vanga():
#получаем дату и кол-во дней
(y, m, d) = [int(n) for n in input().split()]
day_time = int(input())
date = datetime.date(y, m, d) # полученную дату переводим в тип дата
delta = datetime.timedelta(days=day_time) # находим промежуток времени
delta = date + delta
total = 0
#delta = delta.strftime('%Y %-m %-d')
#print(delta.strftime('%Y %m %d'))
d = delta.timetuple()
for i in d:
print(i, end=' ')
total += 1
if total == 3:
break
date_vanga()
# 2000 02 05 |
89f6ba93f1ccb9597cbcffaf3dfd7f2e4e8e3696 | timyu30/legendary-giggle | /Studies/Python_RuneStone/Chapter_1/TimeComparison.py | 1,263 | 3.65625 | 4 | #Comparison of times between dictionary and list access
#%%
import timeit
def find_number_in_list(lst, num):
if num in lst:
return True
else:
return False
short_list = list(range(100))
long_list = list(range(10000000))
#(%) is a Jupyter Magic
%timeit find_number_in_list(short_list, 99)
%timeit find_number_in_list(long_list,9999999)
#slist_time = timeit.timeit(lambda: find_number_in_list(short_list, 99))
#llist_time = timeit.timeit(lambda: find_number_in_list(long_list, 9999999))
short_dict = {x: x*5 for x in range(100)}
long_dict = {x: x*5 for x in range(10000000)}
#sdict_time = timeit.timeit(find_number_in_list(short_dict, 99))
#ldict_time = timeit.timeit(find_number_in_list(long_dict, 9999999))
#print(f"Lookup time change from large to short of list {llist_time/slist_time}.")
#print(f"Lookup time change from large to short of dict {ldict_time/sdict_time}.")
# import time
# d = {'john': 1, 'tim': 2}
# start_time = time.time()
# d['john']
# end_time = time.time()
# print("Time to access dict[0]:", end_time-start_time)
# c = ['john', 'tim']
# start_time = time.time()
# c[0]
# end_time = time.time()
# print("Time to access list[0]:", end_time-start_time)
# %%
|
1f964b0d6faa68feb20eed354c96fe2188d6b4e2 | 3mjay/PY4E | /py4e/every_chapter_exercies/chapter10.py | 1,569 | 4.21875 | 4 | # Exercise 1: Revise a previous program as follows: Read and parse the “From” lines and pull out the addresses from the line. Count the number of messages from each person using a dictionary.
#
# After all the data has been read, print the person with the most commits by creating a list of (count, email) tuples from the dictionary. Then sort the list in reverse order and print out the person who has the most commits.
#
# Sample Line:
# From [email protected] Sat Jan 5 09:14:16 2008
#
# Enter a file name: mbox-short.txt
# [email protected] 5
#
# Enter a file name: mbox.txt
# [email protected] 195
# Exercise 2: This program counts the distribution of the hour of the day for each of the messages. You can pull the hour from the “From” line by finding the time string and then splitting that string into parts using the colon character. Once you have accumulated the counts for each hour, print out the counts, one per line, sorted by hour as shown below.
#
# python timeofday.py
# Enter a file name: mbox-short.txt
# 04 3
# 06 1
# 07 1
# 09 2
# 10 3
# 11 6
# 14 1
# 15 2
# 16 4
# 17 2
# 18 1
# 19 1
# Exercise 3: Write a program that reads a file and prints the letters in decreasing order of frequency. Your program should convert all the input to lower case and only count the letters a-z. Your program should not count spaces, digits, punctuation, or anything other than the letters a-z. Find text samples from several different languages and see how letter frequency varies between languages. Compare your results with the tables at https://wikipedia.org/wiki/Letter_frequencies.
|
37cde5339b4db31fb2159ba0de127648f4b3b01f | Haitham-Darwish/Cryptography | /Cipher by many type/CipherDecryption.py | 6,717 | 4.03125 | 4 | #!/usr/bin/env python3
'''
Decrypt any English word encrypted by Reverse,
Caesar or Transposition cipher
The program idea taken from (python_code_uncoder)
and edited by Haitham Essam
'''
import sys
import os
import time
from detectEnglish import isEnglish
from CaesarCipher import caesar
# we will use ailasing as we have main in our main function
from TranspositionCipherDecryption import main as mainTrans
def main(message, outputFile=''):
'''
Get the decrypted message
Args:
message str:
encrypted message or the file that contain the decrypted message
outputFile str:
The file that we will write the decrypted message in it.
'''
# if True then not entered a file
# if False then entered a file
# then open file and enter the decrypted message in it
flag = True
# Check if entered a file or the actual message
if message.endswith(".txt"):
while True:
try:
with open(message) as file:
message = file.read()
flag = False
if outputFile == '':
outputFile = input('Enter the decryption file name: ')
if __name__=="__main__":
if os.path.exists(outputFile):
print('This will overwrite the file %s. (C)ontinue or (Q)uit?'
% outputFile)
response = input('>>>')
if not response.lower().startswith('c'):
return False
#sys.exit()
break
except FileNotFoundError:
print("This file doesnot exist, please try again ")
message = input("Enter the file name: ")
startTime = time.time()
def write_in_file(message):
'''
Write the decryption in the file
'''
# if get error then the user doesn't enter file name
try:
outputFileObj = open(outputFile,'w')
outputFileObj.write(message)
outputFileObj.close()
except:
pass
LETTERS = '!"#$%&\'()+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ'
#Reverse CIPHER
# Check if encrypted by Reverse Cipher
if isEnglish(message[::-1]):
if(flag):
print("\nThe message is ciphered by Reverse cipher "
+ "and the decryption is %s" % message[::-1] )
else:
write_in_file(message[::-1])
print(f"It took {round(time.time() - startTime, 2)} seconds to decrypt")
return True
#sys.exit()
else:
print("\nThe message is not ciphered by Reverse cipher" )
#Caesar cipher
# Decrypt by checking all possible keys
for key in range(len(LETTERS)):
# Check if encrypted by Caesar Cipher
if(caesar(key, message)[0]):
print("\nThe message is encrypted by caeser cipher")
if(flag):
print(" and the decrypted message is %s and the key is %s"
% (caesar(key, message)[1], key)
+ "\n\nWe have detected the way of ciphering so the"
+ " program will be exited \nQuiting....." )
else:
write_in_file(caesar(key, message)[1])
print(f"It took {round(time.time() - startTime, 2)} "
+ "seconds to decrypt")
return True
#sys.exit(0)
# Trasposition Cipher
# Decrypt by checking all possible keys
for key in range(1, len(LETTERS)):
# Check if encrypted by Trasposition Cipher
if(mainTrans(key, message)[0]):
print("\nThe message is ciphered by "
+ "Trasposition cipher and the key is ", key, end="")
if(flag):
print("and the decryption is %s" % mainTrans(key, message)[1])
else:
# Save it in the file
write_in_file(mainTrans(key, message)[1])
print(f"\nIt took {round(time.time() - startTime, 2)} "
+ "seconds to decrypt")
return True
#sys.exit()
# Product Cipher caesar first
# Decrypt by checking all possible keys
for key in range(1, len(LETTERS)):
# In case if both have different keys
for key2 in range(len(LETTERS)):
# Check if encrypted by Trasposition Cipher
c=caesar(key2, message,word=1,letter=10)[1]
if(mainTrans(key, c)[0]):
print("\nThe message is ciphered by "
+ "Trasposition then Caesar ciphers and there keys are ",
key,key2, end="")
if(flag):
print("and the decryption is %s" % mainTrans(key, c)[1])
else:
# Save it in the file
write_in_file(mainTrans(key, c)[1])
print("\n\nWe have detected the way of ciphering."+
"So, the program will be exit. \nQuiting....." )
print(f"\nIt took {round(time.time() - startTime, 2)} "
+ "seconds to decrypt")
return True
#sys.exit()
# Product Cipher Transposition first
# Decrypt by checking all possible keys
for key in range(len(LETTERS)):
# In case if both have different keys
for key2 in range(1, len(LETTERS)):
# Check if encrypted by Caesar Cipher
c=mainTrans(key2, message,word=1,letter=10)[1]
if(caesar(key, c)[0]):
print("\nThe message is encrypted by Caesar then Trasposition"+
"ciphers and there keys are %s %s"%(key, key2))
if(flag):
print(" and the decrypted message is %s" % (caesar(key, c)[1]))
else:
write_in_file(caesar(key, c)[1])
print("\n\nWe have detected the way of ciphering."+
"So, the program will exit. \nQuiting....." )
print(f"It took {round(time.time() - startTime, 2)} "
+ "seconds to decrypt")
return True
#sys.exit()
if __name__=="__main__":
message = input("Enter the message: ")
main(message)
|
206c069eb650487550ce85d175fc11ec66324464 | mreboland/pythonClasses | /car.py | 10,680 | 4.84375 | 5 | # Working with classes and instances
# Once a Class is written, most of the time spent is with instances created
# with that Class. One of the first tasks we'll want to do is modify the
# attributes associated with a particular instance.
# We can modify the attributes of an instance directly or write methods that
# update attributes in specific ways
class Car:
"""A simple attempt to represent a car"""
# Exact same setup as our Dog example
def __init__(self, make, model, year):
"""Init attributes to describe a car."""
self.make = make
self.model = model
self.year = year
def getDescriptiveName(self):
"""Return a neatly formatted descriptive name."""
longName = f"{self.year} {self.make} {self.model}"
# Return instead of print here, sends the data to the call
return longName.title()
# myNewCar = Car("audi", "a4", 2019)
# print(myNewCar.getDescriptiveName())
# To make the class more interesting, we'll add an attribute that changes over
# time. We'll use a cars mileage to do so.
# Setting a default value for an attribute
class Car:
"""A simple attempt to represent a car"""
def __init__(self, make, model, year):
"""Init attributes to describe a car."""
self.make = make
self.model = model
self.year = year
# When an instance is created, attributes can be defined without being passed in as parameters. They can be defined in the init and are assigned a default value
# Here we create the odometer with a initial value of 0
self.odometerReading = 0
def getDescriptiveName(self):
"""Return a neatly formatted descriptive name."""
longName = f"{self.year} {self.make} {self.model}"
return longName.title()
# We created a method to read the odometer
def readOdometer(self):
"""Print a statement showing the car's mileage."""
print(f"This car has {self.odometerReading} miles on it.")
myNewCar = Car("audi", "a4", 2019)
print(myNewCar.getDescriptiveName())
myNewCar.readOdometer()
# Modifying attribute values
# We can change an attribute's value in three ways:
# Directly, through an instance:
# The simplest way is to modify the value of an attribute through the instance
# We use dot notation to access the attribute odometerReading and we set the value equal to what we want
myNewCar.odometerReading = 23
# Showing the change
myNewCar.readOdometer()
# Modifying an attribute's value through a method
# It can be helpful to have methods that update certain attributes for you.
# Instead of accessing the attribute directly, we pass the new value to a
# method that handles the updating internally
class Car:
"""A simple attempt to represent a car"""
def __init__(self, make, model, year):
"""Init attributes to describe a car."""
self.make = make
self.model = model
self.year = year
self.odometerReading = 0
def getDescriptiveName(self):
"""Return a neatly formatted descriptive name."""
longName = f"{self.year} {self.make} {self.model}"
return longName.title()
def readOdometer(self):
"""Print a statement showing the car's mileage."""
print(f"This car has {self.odometerReading} miles on it.")
# Here we created a method that takes in a mileage parameter and assigns
# it to self.odometerReading which will update the value when we pass
# through an argument
def updateOdometer(self, mileage):
"""Set the odometer reading to the given value"""
"""Reject the change if it attempts to roll the odometer back."""
# We can extent the method to do additional work to prevent rolling
# back the odometer.
if mileage >= self.odometerReading:
self.odometerReading = mileage
else:
print("You can't roll back an odometer!")
myNewCar = Car("audi", "a4", 2019)
print(myNewCar.getDescriptiveName())
# Here we call updateOdometer and give it an argument of 55. This value is
# passed into the method, updateOdometer which updates the odometerReading
# value
myNewCar.updateOdometer(55)
# We then print the odometer to see its new value.
myNewCar.readOdometer()
# Testing the if statement for roll back (mileage is currently 55)
myNewCar.updateOdometer(25)
# Increment an attribute's value through a method
# Sometimes we'll want to increment an attribute's value by a certain amount
# rather than set an entirely new value. Say we buy a used car and put 100
# miles on it between the time we buy it and the time we register it.
class Car:
"""A simple attempt to represent a car"""
def __init__(self, make, model, year):
"""Init attributes to describe a car."""
self.make = make
self.model = model
self.year = year
self.odometerReading = 0
def getDescriptiveName(self):
"""Return a neatly formatted descriptive name."""
longName = f"{self.year} {self.make} {self.model}"
return longName.title()
def readOdometer(self):
"""Print a statement showing the car's mileage."""
print(f"This car has {self.odometerReading} miles on it.")
def updateOdometer(self, mileage):
"""Set the odometer reading to the given value"""
"""Reject the change if it attempts to roll the odometer back."""
if mileage >= self.odometerReading:
self.odometerReading = mileage
else:
print("You can't roll back an odometer!")
# We create a new method that takes in a number of miles and adds this
# value to self.odometerReading
def incrementOdometer(self, miles):
"""Add the given amount to the odometer reading."""
# Doing some self coding to reject negative miles
if miles >= 0:
self.odometerReading += miles
else:
print("You can't have negative miles...")
# We create a used car
myUsedCar = Car("subaru", "outback", 2015)
print(myUsedCar.getDescriptiveName())
# We set its odometer to 23,500 (remember underscores can be used like commas)
# by calling updateOdometer. This is the car's initial mileage.
myUsedCar.updateOdometer(23_500)
myUsedCar.readOdometer()
# After driving it 100 miles we want to add it to our base milage we set above
# so we call incrementOdometer and pass it 100 to update our mileage
myUsedCar.incrementOdometer(100)
myUsedCar.readOdometer()
# Negative miles test
myUsedCar.incrementOdometer(-100)
# Miles stayed the same
myUsedCar.readOdometer()
# Note: You can use methods like this to control how users of your program
# update values such as an odometer reading, but anyone with access to the
# program can set the odometer reading to any value by accessing the attribute
# directly. Effective security takes extreme attention to detail in addition
# to basic checks like those shown here.
# 9-4. Number Served: Start with your program from Exercise 9-1 (page 162).
# Add an attribute called number_served with a default value of 0. Create an
# instance called restaurant from this class. Print the number of customers the
# restaurant has served, and then change this value and print it again.
# Add a method called set_number_served() that lets you set the number
# of customers that have been served. Call this method with a new number and
# print the value again.
# Add a method called increment_number_served() that lets you increment
# the number of customers who’ve been served. Call this method with any number
# you like that could represent how many customers were served in, say, a
# day of business.
class Restaurant:
def __init__(self, restaurantName, cuisineType):
"""Init attr for restaurant name and cuisine"""
self.restaurantName = restaurantName
self.cuisineType = cuisineType
self.numberServed = 0
def describeRestaurant(self):
"""Describing the restaurant"""
print(
f"The restaurant is called {self.restaurantName} and it serves {self.cuisineType.title()}.")
def openRestaurant(self):
"""Simulating opening of restaurant"""
print(f"{self.restaurantName.title()} is now open!")
def setNumberServed(self, customers):
"""Updating the base number of customers served"""
if customers >= 0:
self.numberServed = customers
else:
print("You can't serve a negative amount customers")
def incrementNumberServed(self, served):
"""Adding served customers to base customers served"""
if served >= 0:
self.numberServed += served
else:
print("You can't reduce the amount of customers served!")
restaurant = Restaurant("Japango", "Sushi")
print(restaurant.numberServed)
restaurant.numberServed = 10
print(restaurant.numberServed)
restaurant.setNumberServed(15)
print(restaurant.numberServed)
restaurant.incrementNumberServed(5)
print(restaurant.numberServed)
# 9-5. Login Attempts: Add an attribute called login_attempts to your User
# class from Exercise 9-3 (page 162). Write a method called increment_login
# _attempts() that increments the value of login_attempts by 1. Write another
# method called reset_login_attempts() that resets the value of login_attempts
# to 0.
# Make an instance of the User class and call increment_login_attempts()
# several times. Print the value of login_attempts to make sure it was incremented properly, and then call reset_login_attempts(). Print
# login_attempts again to make sure it was reset to 0.
class User:
def __init__(self, firstName, lastName, age, nationality):
"""Creating a user"""
self.firstName = firstName
self.lastName = lastName
self.age = age
self.nationality = nationality
self.loginAttempts = 0
def describeUser(self):
print(f"\n{self.firstName.title()} {self.lastName.title()}:")
print(f"\tAge: {self.age}")
print(f"\tNationality: {self.nationality.title()}")
def greetUser(self):
print(f"Hello {self.firstName.title()}! How are you today?")
def incrementLoginAttempts(self):
"""Counting the amount of attempts made at logging in"""
self.loginAttempts += 1
def resetLoginAttempts(self):
"""Resetting login attempts"""
self.loginAttempts = 0
userA = User("john", "doe", 55, "canadian")
userA.incrementLoginAttempts()
userA.incrementLoginAttempts()
userA.incrementLoginAttempts()
print(userA.loginAttempts)
userA.resetLoginAttempts()
print(userA.loginAttempts)
|
2d949595e1b4ce666835fe478279dbc6aaeaaf90 | wuyanzhang/Machine-learning | /Logistic/logistic_regression.py | 2,202 | 3.828125 | 4 | import numpy as np
import matplotlib.pyplot as plt
# 函数说明:加载数据集
def loadDataSet():
dataMat = []
labelMat = []
fr = open('testSet.txt')
for line in fr.readlines():
lineArr = line.strip().split()
dataMat.append([1.0, float(lineArr[0]), float(lineArr[1])])
labelMat.append(int(lineArr[2]))
fr.close()
return dataMat, labelMat
def loadDataSet1():
dataMat = []
labelMat = []
fr = open('testSet.txt')
for line in fr.readlines():
line = line.strip().split()
dataMat.append([float(line[0]),float(line[1])])
labelMat.append(int(line[2]))
fr.close()
return dataMat,labelMat
# 函数说明:sigmoid函数
def sigmoid(inx):
return 1.0 / (1 + np.exp(-inx))
# 函数说明:梯度上升算法
def gradAscent(dataMat,labelMat):
dataMat = np.mat(dataMat)
labelMat = np.mat(labelMat).transpose()
m,n = np.shape(dataMat)
alpha = 0.001
maxstep = 500
weights = np.ones([n,1])
for k in range(maxstep):
h = sigmoid(dataMat * weights)
error = labelMat - h
weights = weights + alpha * dataMat.transpose() * error
return weights.getA()
# 函数说明:绘制最优分界线
def plotBestFit(weights):
dataMat, labelMat = loadDataSet1()
dataMat = np.array(dataMat)
num = len(dataMat)
x0 = []
x1 = []
y0 = []
y1 = []
for i in range(num):
if int(labelMat[i]) == 1:
x0.append(dataMat[i][0])
y0.append(dataMat[i][1])
else:
x1.append(dataMat[i][0])
y1.append(dataMat[i][1])
fig = plt.figure()
ax = fig.add_subplot(111) # 1*1网格中的第一个子图(只有一个子图)
ax.scatter(x0, y0, s=20, c='red', marker='s', alpha=.5)
ax.scatter(x1, y1, s=20, c='green', alpha=.5)
x = np.arange(-3.0,3.0,0.1)
y = (-weights[0] - weights[1] * x) / weights[2]
ax.plot(x,y)
plt.title('BestFit')
plt.xlabel('X1')
plt.ylabel('X2')
plt.show()
if __name__ == '__main__':
dataMat,labelMat = loadDataSet()
weights = gradAscent(dataMat,labelMat)
# print(gradAscent(dataMat,labelMat))
plotBestFit(weights)
|
86e953f3b1490caff4ef5e46c892b1eeade465a0 | ibm-5150/Python-HW | /HW-3/task_4.py | 208 | 3.796875 | 4 | string = str(input())
if string.count('a') < 1:
print("False")
elif string.count('a') == 1:
print(string.find('a'))
elif string.count('a') >= 2:
print(string.find('a'), string.rfind('a'))
|
0b2a16e898d30a28d9d0c4127d6c2e4248f9f296 | rbshadow/Python_URI | /Strings/URI_1168.py | 1,009 | 3.546875 | 4 | def math():
loop = int(input())
for i in range(loop):
i_put = input()
count = 0
for j in range(len(i_put)):
if int(i_put[j]) == 1:
count += int(i_put[j]) + 1
elif int(i_put[j]) == 2:
count += int(i_put[j]) + 3
elif int(i_put[j]) == 3:
count += int(i_put[j]) + 2
elif int(i_put[j]) == 4:
count += int(i_put[j]) + 0
elif int(i_put[j]) == 5:
count += int(i_put[j]) + 0
elif int(i_put[j]) == 6:
count += int(i_put[j]) + 0
elif int(i_put[j]) == 7:
count += int(i_put[j]) - 4
elif int(i_put[j]) == 8:
count += int(i_put[j]) - 1
elif int(i_put[j]) == 9:
count += int(i_put[j]) - 3
elif int(i_put[j]) == 0:
count += int(i_put[j]) + 6
print(count, 'leds')
if __name__ == '__main__':
math()
|
0031990e161576f2e9c0ed178cb40f0dd135dd55 | vgomesn/socket-message-listener | /socket-client.py | 1,122 | 3.65625 | 4 | #
# Veronica Gomes
# File: socket-server.py (Python 3)
#
# Used reference code from these sources:
# Jesse Smith, Python Guide for the Total Beginner LiveLessons
# http://www.informit.com/articles/article.aspx?p=2234249
#
# Description:
# Socket client is a client app that will connect to a socket-server running on localhost (configurable) on port 28812 (default)
# And then, it will prompt the user to enter new messages. Each message ends with the user pressing ENTER key
# The user can enter as many messages as they want. When done sending messages, the user can press ENTER (with no message) to exit the program.
#
from socket import *
#HOST = '172.17.0.2'
HOST = '127.0.0.1'
PORT = 28812
BUFSIZE = 1024
ADDR = (HOST, PORT)
clientconn = socket(AF_INET, SOCK_STREAM)
clientconn.connect(ADDR)
print("Connected to socket server. Enter a message. Press ENTER to send. Empty message to exit this client.")
while True:
data = input('Enter message > ')
if not data:
break
clientconn.sendto(data.encode('utf-8'),ADDR)
#data = clientconn.recv(BUFSIZE)
#if not data:
# break
#print(data)
clientconn.close()
|
6b534ff45639843bdeeca9005d40045fac916400 | smspillaz/artificial-intelligence | /artificialintelligence/minimax.py | 8,993 | 4.125 | 4 | # /artificialintelligence/minimax.py
#
# Play a game using the minimax algorithm.
#
# See LICENCE.md for Copyright information
"""Play a game using the minimax algorithm."""
"""
Mancala game v1.0
Lyndon While, 3 April 2014
The program prompts the user for the game size X, then it plays a
game of Mancala between two random players and creates an SVG file
MancalaGameX.svg
that shows the history of the board during the game. Each board is
annotated with the next move made, and the final board is annotated
with the average branching factor during the game.
Software to run the program is available from python.org. Get Python 3.
The size of the displayed boards and the fonts used can be controlled
by changing the variable size below.
The colours used in the display can be controlled by changing the
variable colours.
Please report any bugs on help3001. Unless they're embarrassing ones. :-)
"""
import random
import copy
from collections import namedtuple
import pprint
import colorama
import tabulate
#a board position is a 2x7 list with the stores at the ends
#a player is 0 or 1, and is used to index the board
#a move is a list of indices into a board
#------------------------------------------------------------- This is the display code
size = 5 #controls the board-size and fonts - don't change anything else
side = size * 5
housefont = size * 2
storefont = size * 3
colours = [(0, 0, 0), (255,150,150), (215,215,0)]
# black pink green-yellow
def mkhouse(k, p, x, r):
h = side * (3.4 + k + r // 10 * 9)
v = side * (1.5 - p + r % 10 * 3)
return (colours[p + 1], [(h, v), (h + side, v), (h + side, v + side), (h, v + side), (h, v)],
#text placement and font
(h + side / 2 - len(str(x)) * side / 8, v + 2 * side / 3, str(x), housefont))
def mkstore(p, x, r):
h = side * (9.4 - 7 * p + r // 10 * 9)
v = side * (0.5 + r % 10 * 3)
return (colours[p + 1], [(h, v), (h + side, v), (h + side, v + 2 * side), (h, v + 2 * side), (h, v)],
#text placement and font
(h + side / 2 - len(str(x)) * side / 5, v + 6 * side / 5, str(x), storefont))
def writeColor(c):
(r, g, b) = c
return "".join(["rgb(", str(r), ",", str(g), ",", str(b), ")"])
def writeText(t):
(h, v, z, s) = t
return "".join(["<text x=\"", str(h), "\" y=\"", str(v), "\" font-family=\"Verdana\" font-size=\"",
str(s), "\" fill=\"black\">", z, "</text>\n"])
def writePolygons(f, ps):
for (c, p, t) in ps:
f.write("<polygon points=\"")
for (x, y) in p:
f.write("".join([str(x), ",", str(y), " "]))
f.write("\" style=\"fill:")
f.write(writeColor(c))
f.write(";stroke:")
f.write(writeColor(colours[0]))
f.write(";stroke-width:3\"/>\n")
f.write(writeText(t))
def mancalaDisplay(b, m, r, f):
if r % 2 == 1: t = "green"
else: t = "pink"
if r < 10:
f.write(writeText((size, side * (1.0 + r % 10 * 3), t + "'s", housefont)))
f.write(writeText((size, side * (1.5 + r % 10 * 3), "move", housefont)))
#display the move
f.write(writeText((size + side * (2 + (r - 1) // 10 * 9), side * (3 + (r - 1) % 10 * 3), "".join([str(k + 1) for k in m]), housefont)))
writePolygons(f, [mkhouse(k, p, b[p][5 * p + k * (1 - 2 * p)], r) for p in range(2) for k in range(6)] +
[mkstore( p, b[p][6], r) for p in range(2)])
#------------------------------------------------------------- This is the game mechanics code
def moves(b, p):
#returns a list of legal moves for player p on board b
zs = []
#for each non-empty house on p's side
for m in [h for h in range(6) if b[p][h] > 0]:
#if the final seed will be sown in p's store
if (b[p][m] + m) % 13 == 6:
#copy b, make move m, and check for recursive possibilities
c = copy.deepcopy(b)
move(c, p, [m])
ms = moves(c, p)
if ms == []:
zs += [[m]]
else:
zs += [[m] + n for n in ms]
else:
zs += [[m]]
return zs
def move(b, p, ms):
#make the move ms for player p on board b
for m in ms:
x = b[p][m]
b[p][m] = 0
(capturePossible, z) = sow(b, p, m + 1, 6, x)
#if the last seed was sown in an empty house on p's side, with seeds opposite
if capturePossible and b[p][z] == 1 and b[1 - p][5 - z] > 0:
b[p][6] += b[p][z] + b[1 - p][5 - z]
b[p][z] = 0
b[1 - p][5 - z] = 0
def sow(b, p, m, y, x):
#sow x seeds for player p on board b, starting from house m, with limit y
#the limit is used to exclude the opponent's store
#it returns (possibleCapture, lastHouseSown)
while x > 0:
for z in range(m, min(y + 1, m + x)):
b[p][z] += 1
x -= y + 1 - m
p = 1 - p
m = 0
y = 11 - y
return (y == 5, z)
def render(board):
"""Render the board and print it."""
print tabulate.tabulate(board)
def evaluate(board):
"""Evaluate board for score.
This function is really dumb.
"""
boardScore = sum(board[0]) - sum(board[1])
# Now evalute how many empty houses we have which are next to
# a non-empty house of the opponent
for house_index in range(0, 6):
if board[0][house_index] == 0 and board[1][house_index] != 0:
# Look at all of our available houses and see if we can start
# from any of them to finish in this square.
for i in range(0, 6):
if i + board[0][i] % 13 == house_index:
boardScore += 20
elif board[0][house_index] != 0 and board[1][house_index] == 0:
# Look at all of our available houses and see if we can start
# from any of them to finish in this square.
for i in range(0, 6):
if i + board[1][i] % 13 == house_index:
boardScore -= 20
return boardScore
ScoredMove = namedtuple("AvailableMove", "score move")
PLAYER_MOVE_INDEX = [0, -1]
PLAYER_COLORS = [colorama.Fore.RED, colorama.Fore.GREEN]
def moveScore(nextMove, board, player):
nextBoard = copy.deepcopy(board)
move(nextBoard, player, nextMove)
return evaluate(nextBoard)
def pickMoveForPlayer(player, board, available_moves, scoreFunction):
score_moves = [ScoredMove(score=scoreFunction(m,
board,
player), move=m) for m in available_moves]
score_moves = sorted(score_moves, key=lambda s: s.score)
return (score_moves, score_moves[PLAYER_MOVE_INDEX[player]].move)
def minimax(board, player, depth):
available_moves = moves(board, player)
if depth != 0 and len(available_moves) != 0:
best_move = pickMoveForPlayer(player, board, available_moves, moveScore)[1]
nextBoard = copy.deepcopy(board)
move(nextBoard, player, best_move)
return minimax(nextBoard, 1 - player, depth - 1)
return evaluate(board)
def minimaxScoreFunction(depth):
def minimaxScore(nextMove, board, player):
nextBoard = copy.deepcopy(board)
move(nextBoard, player, nextMove)
return minimax(nextBoard, 1 - player, depth)
return minimaxScore
def mancala(n):
#start with n seeds in each small house
b = [[n] * 6 + [0] for p in [0, 1]]
#open the SVG file
f = open("".join(["MancalaGame", str(n), ".svg"]), 'w')
f.write("<svg xmlns=\"http://www.w3.org/2000/svg\">\n")
mancalaDisplay(b, [], 0, f)
r = 1
current_player = 0
tm = 0
#while both players have seeds in their small houses
while all ([sum(b[p][:6]) > 0 for p in [0, 1]]):
ms = moves(b, current_player)
print colorama.Fore.WHITE
render(b)
if current_player == 0:
score_moves, best_move = pickMoveForPlayer(current_player, b, ms, minimaxScoreFunction(5))
m = best_move
print PLAYER_COLORS[current_player] + pprint.PrettyPrinter().pformat([(i, mv) for i, mv in enumerate(score_moves)])
print PLAYER_COLORS[current_player] + repr(best_move)
else:
print "Chose between \n", pprint.PrettyPrinter().pformat([(i, mv) for i, mv in enumerate(ms)])
choice = 999999999
while choice > len(ms):
choice = int(input("What move? "))
m = ms[choice]
move(b, current_player, m)
mancalaDisplay(b, m, r, f)
r += 1
current_player = 1 - current_player
tm += len(ms)
#move the remaining seeds to the stores
for p in [0, 1]:
for k in [0, 1, 2, 3, 4, 5]:
b[p][6] += b[p][k]
b[p][k] = 0
mancalaDisplay(b, [round(tm / (r - 1), 2)], r, f)
f.write("</svg>\n")
f.close()
def main():
mancala(int(input("What size game? ")))
main() |
cfed77342bcdf960e82f5165771e2b00f7af2c2e | toufeeqahamedns/DataStructures | /Arrays/4 - LeftRotation.py | 728 | 4.1875 | 4 | """
A left rotation operation on an array of size shifts each of
the array's elements 1 unit to the left. For example, if 2 left
rotations are performed on array [1, 2, 3, 4, 5], then the array would become [3, 4, 5, 1, 2].
Given an array of n integers and a number, d, perform d left
rotations on the array. Then print the updated array as a single line of space-separated integers.
"""
import math
import os
import random
import re
import sys
if __name__ == '__main__':
nd = input().split()
n = int(nd[0])
d = int(nd[1])
a = list(map(int, input().rstrip().split()))
mod = d % n
for i in range(0, n):
print(str(a[(mod + i) % n]), end = " ")
|
0e4fd6f7dbff0b15ef6ae5a14cbb90b4b9483d08 | kirubah18/guvi | /codekata/findgcd.py | 136 | 3.609375 | 4 | def gcd(nu1,nu2):
if(nu2==0):
return nu1
else:
return gcd(nu2,nu1%nu2)
nu1,nu2=map(int,input().split())
print(gcd(nu1,nu2))
|
8feaf768ab463736b882b870d33e94e43c7490ed | LBJ-Max/basepython | /多线程/demo1.py | 423 | 3.75 | 4 | # 演示多线程
import threading
import time
def sayEat():
print("吃饭啦")
time.sleep(1)
def main():
t1 = threading.Thread(sayEat())
t2 = threading.Thread(sayEat())
# 查看线程的数量
t1.start()
t2.start()
while True:
print(threading.enumerate())
if len(threading.enumerate()) <=1:
break
time.sleep(1)
if __name__ == '__main__':
main()
|
2ee07e879ce14c14e4883b8ed06a881694971cb1 | gilberto-009199/MyPython | /outros/2020-04-25-2.py | 142 | 3.8125 | 4 |
maior = 0;
while True:
val0 = int(input());
if val0 < 0 :
break;
maior = maior if maior > val0 else val0;
print(maior); |
1c2f3e54868f0f6920d6bfe82342381ea692b297 | MahadiRahman262523/Python_Code_Part-2 | /list comprehension 2.py | 167 | 3.75 | 4 | #list comprehension for filter function
num = [1,2,3,4,5]
#result = list(filter(lambda x : x%2 == 0,num))
result = [x for x in num if x%2 == 0]
print(result) |
9986a6da2816628456e50fd00c7add48dbe737ad | SamEpp/TextMining | /texttmining.py | 4,254 | 3.625 | 4 | import requests
import nltk
import pickle
from bs4 import BeautifulSoup
#Mary_Wade_text = requests.get('http://www.gutenberg.org/cache/epub/43585/pg43585.txt').text
#print(Mildred_Wirt_text)
# Save data to a file (will be part of your data fetching script)
# f = open('Mary_Wade_text.pickle', 'wb')
# pickle.dump(Mary_Wade_text, f)
# f.close()
#Load data from a file (will be part of your data processing script)
def get_pickle(file_name):
input_file = open(file_name, 'rb')
#input_file.seek(0)
reloaded_copy_of_texts = pickle.load(input_file)
reloaded_copy_of_texts = reloaded_copy_of_texts.split("END OF THIS PROJECT GUTENBERG EBOOK")
return reloaded_copy_of_texts[0]
# #soup = BeautifulSoup(Wilkie_Collins_text, 'html.parser')
#print(soup.prettify())
def word_sectioning(s):
""" Takes a string of words returns the first word
s: a string
returns: the first word
>>> word_sectioning("I bat today")
'I'
>>> word_sectioning("I.ban")
'I'
"""
for index in range(0,len(s)):
word_section = s[index]
if word_section == ' ' or word_section == '.' or word_section == ',' or word_section == '?' or word_section == '!' or word_section == ';' or word_section == ':':
# if word_section == ' ':
return s[:index]
return s
def word_finder(s):
""" Takes a string of words returns all of the words. Does not work if the
sentence begings with a "stopper"
s: a string
returns: all of the word
>>> word_sectioning(".I ran back. to the bat.I")
'I', 'ran', 'back', 'to', 'the', 'bat', 'I'
"""
index = 0
word_start_stop_list = []
s = ' ' + s
while index+1 < len(s):
if ((s[index] == ' ' or s[index]== '.' or s[index] == ',' or s[index] == '?' or s[index] == '!' or s[index] == ';' or s[index] == ':')
and (s[index+1] != ' ' and s[index+1] != '.' and s[index+1] != ',' and s[index+1] != '?' and s[index+1] != ' !' and s[index+1] != ';' and s[index+1] != ':')):
full_word = word_sectioning(s[index+1:])
word_start_stop_list.append(full_word)
index = index + len(full_word)
else:
index = index +1
#This words were take from the most common word list on Wikipedia
stopwords = ['a', 'the', 'its', 'over', 'also', 'be', '"', 'to', 'of', 'and', 'in']
stopwords += ['that', 'have', 'it', 'for', 'not', 'on', 'with', 'he', 'as', 'do', 'at']
stopwords += ['this', 'but', 'his', 'by', 'from', 'they', 'we', 'say', 'her', 'she']
stopwords += ['or', 'an', 'will', 'my', 'one', 'all', 'would', 'there', 'their', 'what']
stopwords += ['so', 'up', 'out', 'if', 'about', 'who', 'get', 'which', 'go', 'me', 'when']
stopwords += ['make', 'can', 'like', 'time', 'just', 'him', 'know', 'take', 'people']
stopwords += ['And', 'are', 'said', 'had', 'says', 'you', 'was', 'I', 'is', 'The', 'were']
stopwords += ['has', 'any', 'very', 'am', 'our', 'But', '\r\n', '\r\nAnd', '*', '\r\n\r\n', '\r\nThe']
stopwords += ['[\r\n\r\n[Footnote', '\r\n\r\nHEG', '\r\n\r\nTHEU', '\r\n\r\nTRA',']\r\n\r\n[Footnote']
final_word_list = [word for word in word_start_stop_list if word not in stopwords]
return final_word_list
# return word_start_stop_list
def word_frequency(s):
""" Takes a string of words and using the word_finder program above returns
how many times that word is used
s: a string
returns: number all words are used
>>> word_sectioning(".I ran back. to the bat.I")
'I': 2, 'the': 1, 'to': 1, 'bat': 1, 'ran': 1, 'back': 1
"""
s = word_finder(s)
d = dict()
for c in s:
d[c] = d.get(c, 0) + 1
return d
#Not working because of items? and probably a problem with histogram which word finder was suppose to fix
def most_frequent(s):
histo = word_frequency(s)
my_list = []
for x, f in histo.items():
my_list.append((f, x))
my_list.sort()
sorted_list = []
for f, x in my_list:
sorted_list.append(x)
return sorted_list[-20::]
#print(most_frequent(get_pickle('Wilkie_Collins_text.pickle')))
# reloaded_copy_of_texts = get_pickle('Maria_Stewart_text.pickle')
# print(reloaded_copy_of_texts)
|
9d8ca098e04a4613170ce08a465de31246a103b6 | vsamanvita/APS-2020 | /Graph_cycle_detection.py | 1,019 | 3.828125 | 4 | # Python program to detect cycle in a graph
from collections import defaultdict
class Graph():
def __init__(self,vertices):
self.graph=defaultdict(list)
self.V=vertices
def addEdge(self,u,v):
self.graph[u].append(v)
def isCyclicUtil(self, v, visited, recStack):
visited[v]=True
recStack[v]=True
for neighbour in self.graph[v]:
if visited[neighbour]==False:
if self.isCyclicUtil(neighbour,visited,recStack)==True:
return True
elif recStack[neighbour]==True:
return True
recStack[v]=False
return False
def isCyclic(self):
visited=[False]*self.V
recStack=[False]*self.V
for node in range(self.V):
if visited[node]==False:
if self.isCyclicUtil(node,visited,recStack)==True:
return True
return False
g=Graph(4)
g.addEdge(0,1)
g.addEdge(0,2)
g.addEdge(1,2)
g.addEdge(2,0)
g.addEdge(2,3)
g.addEdge(3,3)
print(g.isCyclic())
g=Graph(3)
g.addEdge(0,1)
g.addEdge(0,2)
print(g.isCyclic()) |
172ee301a4113f9c58f96c9cb30581da2d6a6705 | WOWSCpp/Illumio-Coding-Assignment | /illumio.py | 3,895 | 3.609375 | 4 |
class PortIpRange:
'''
check if port or ip_address is valid
'''
def __init__(self, port_lo, port_hi, ip_lo, ip_hi):
self.port_lo = port_lo
self.port_hi = port_hi
self.ip_lo = ([int(i) for i in ip_lo.split('.')])
self.ip_hi = ([int(i) for i in ip_hi.split('.')])
def port_contains(self, port):
if port >= self.port_lo and port <= self.port_hi:
return True
else:
return False
def ip_contains(self, ip_address):
ip_tuple = ([int(i) for i in ip_address.split('.')])
if ip_tuple >= self.ip_lo and ip_tuple <= self.ip_hi:
return True
else:
return False
class Firewall:
def __init__(self, path):
self.rules = { 'inbound' : {'tcp' : set(), 'udp' : set()},
'outbound' : {'tcp' : set(), 'udp' : set()}
}
file = open(path)
for line in file:
direction, protocol, port, ip = line.split(',')
if direction == 'direction': #If the line is the header of the csv then skip the line
continue
if '-' in port: # If the port is a range
port_lo, port_hi = int(port.split('-')[0]), int(port.split('-')[1])
if '-' in ip: # If the port is a range
ip_lo, ip_hi = ip.split('-')[0], ip.split('-')[1]
else:
ip_lo, ip_hi = ip, ip
else:
port_lo, port_hi = int(port), int(port)
if '-' in ip:
ip_lo, ip_hi = ip.split('-')[0], ip.split('-')[1]
else:
ip_lo, ip_hi = ip, ip
self.rules[direction][protocol].add(PortIpRange(port_lo, port_hi, ip_lo, ip_hi))
file.close()
def accept_packet(self, direction, protocol, port, ip):
try:
for port_ip in self.rules[direction][protocol]:
if port_ip.port_contains(port) and port_ip.ip_contains(ip):
return True
return False
except KeyError: # If KeyError occurs, then return False
return False
if __name__ == '__main__':
fw = Firewall("fw.csv")
try:
assert(fw.accept_packet("inbound", "udp", 53, "192.168.2.1") == True)
assert(fw.accept_packet("outbound", "tcp", 10234, "192.168.10.11") == True)
assert(fw.accept_packet("inbound", "tcp", 81, "192.168.1.2") == False)
assert(fw.accept_packet("inbound", "udp", 24, "52.12.48.92") == False)
assert(fw.accept_packet("inbound", "tcp", 80, "192.168.1.2") == True)
assert(fw.accept_packet("outbound", "tcp", 19999, "192.168.10.11") == True)
assert(fw.accept_packet("inbound", "udp", 53, "192.168.1.1") == True)
assert(fw.accept_packet("outbound", "udp", 999, "52.12.48.92") == False)
assert(fw.accept_packet("inbound", "udp", 53, "192.168.1.0") == False)
assert(fw.accept_packet("inbound", "udp", 53, "192.168.2.5") == True)
assert(fw.accept_packet("inbound", "udp", 53, "192.169.2.5") == False)
assert(fw.accept_packet("outbound", "udp", 53, "192.168.2.5") == False)
assert(fw.accept_packet("inbound", "tcp", 53, "192.168.2.5") == False)
assert(fw.accept_packet("inbound", "tcp", 3000, "192.169.1.2") == True)
assert(fw.accept_packet("inbound", "tcp", 4000, "192.169.2.5") == True)
assert(fw.accept_packet("inbound", "tcp", 4000, "192.169.2.4") == True)
assert(fw.accept_packet("inbound", "tcp", 2999, "192.169.2.4") == False)
print ("all cases passed")
except AssertionError:
print ("AssertionError")
|
26dc64a9744ec2b575d184dfee409a9985b0c181 | jiriVFX/data_structures_and_algorithms | /interview_problems/monarchy.py | 2,132 | 3.96875 | 4 | # Interface design - design a monarchy class and methods
# time complexity - O(n) - number of members of family
# space complexity - O(n) - number of members of family
class Member:
def __init__(self, name, sex):
self.name = name
self.alive = True
self.sex = sex
self.children = []
class Monarchy:
def __init__(self, ruler):
self.ruler = ruler
self.members = {self.ruler.name: self.ruler}
def birth(self, child, parent, sex):
new_member = Member(child, sex)
self.members[new_member.name] = new_member
# add child to the parent's children list
self.members[parent].children.append(new_member)
def death(self, name):
if self.members[name] and self.members[name].alive:
self.members[name].alive = False
def get_succession_order(self):
succession_order = []
# call preorder DFS
self.preorder_dfs(self.ruler, succession_order)
# return the list with successors
return succession_order
def preorder_dfs(self, member, order_list):
# if the member of family is alive and is male (only males were legitimate successors at that time)
if member.alive and member.sex == "male":
# add to succession order list
order_list.append(member.name)
# run DFS on all children
for child in member.children:
self.preorder_dfs(child, order_list)
# test the code --------------------------------------------------------------------------------------------------------
king = Member("Premysl Ottokar I.", "male")
monarchy = Monarchy(king)
monarchy.birth("Vratislav", "Premysl Ottokar I.", "male")
monarchy.birth("Dagmar", "Premysl Ottokar I.", "female")
monarchy.birth("Vaclav I.", "Premysl Ottokar I.", "male")
monarchy.death("Vratislav")
monarchy.birth("Vladislav", "Vaclav I.", "male")
monarchy.birth("Bozena", "Vaclav I.", "female")
monarchy.birth("Anezka", "Vaclav I.", "female")
monarchy.birth("Premysl Ottokar II.", "Vaclav I.", "male")
monarchy.death("Vladislav")
print(monarchy.get_succession_order())
|
3775d73e8a866d70f9365d1d1a8556aaa3873339 | wiecodepython/Exercicios | /Exercicio 2/maarinaabatista/exercicio_semana2.py | 3,562 | 3.59375 | 4 | Python 3.7.1 (v3.7.1:260ec2c36a, Oct 20 2018, 14:57:15) [MSC v.1915 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> #EXERCICIO_SEMANA_2
#QUESTÃO 01
print ("Hello, World!")
Hello, World!
>>> #soma
>>> 3+5
8
>>> 9+12
21
>>> 7+32
39
>>> #decimais
>>> 4.5 + 7.3
11.8
>>> 7.9 + 18.2
26.1
>>> 3.6 + 34.1
37.7
>>> #subtração
>>> 5-2
3
>>> 9-7
2
>>> 15-20
-5
>>> 45-74
-29
>>> #multiplicação
>>> 2 * 5
10
>>> 4 * 9
36
>>> 10 * 10
100
>>> 2 * 2 * 2
8
>>> #divisão
>>> 45 / 5
9.0
>>> 100 / 20
5.0
>>> 9 / 3
3.0
>>> 10 / 3
3.3333333333333335
>>> 2/0
Traceback (most recent call last):
File "<pyshell#24>", line 1, in <module>
2/0
ZeroDivisionError: division by zero
>>> #divisão_inteira
>>> 10 // 3
3
>>> 11 // 2
5
>>> 100 // 6
16
>>> #restodadivisão
>>> 10 % 2
0
>>> 15 % 4
3
>>> 100 % 6
4
>>> #potenciação/exponenciação
>>> 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2
1024
>>> 2 ** 10
1024
>>> 10 ** 3
1000
>>> (10 ** 800 + 9 ** 1000) * 233
407254001651377825050774086265365912933271559572398924650169906751889900030955189004916347478470698880616885512201849445183728845558993514870858509087817789576388584560964682795896403435448681980001360244790530805842737419978616650940647045809688543958807077794866143976192872389017280782837244051514550016751431331392474612723898201318251801288569103581859710953756463227568553903785400053293756105145991925711692828410365978814157929143646138367222515290495329841814490874087309733954914817582614165290441834984054374534909954119315442169415884429645515258867781282214407424938115130906555866837546110340314133204645184212592152733050063403478054121909337278892530383627259086060904403894148963384111173869448637825223750221720739904084905206403076141255284819817001128530851921214720479861908207168928806625713775441834487646542035428141369478170696522098960677314242891140325390964310295889079588950798788612324634050495786532200848059999839607732520233
>>> #raizquadrada
>>> 4 ** 0.5
2.0
>>> import math
>>> math.sqrt(16)
4.0
>>> math.pi
3.141592653589793
>>> #expressõesNuméricas
>>> 3 + 4 * 2
11
>>> 7 + 3 * 6 - 4 ** 2
9
>>> (3 + 4) * 2
14
>>> (8 / 4) ** (5 - 2)
8.0
>>> #notaçãocientifca
>>> 10e6
10000000.0
>>> 1e6
1000000.0
>>> 1e - 5
SyntaxError: invalid syntax
>>> 1e-5
1e-05
>>> 1E6
1000000.0
>>> #comentarios
>>> 3 + 4 #será ldio apenas o calculo
7
>>> 2 < 10
True
>>> 2 > 11
False
>>> 10 > 10
False
>>> 10 >= 10
True
>>> 42 == 25
False
SyntaxError: multiple statements found while compiling a single statement
>>>
>>> #QUESTÃO 2
>>> 10 % 13
10
>>> 10 % 3
1
>>> 13 * 1
13
>>> #QUESTÃO 3
>>> 13 * 1
13
>>> 13 * 2
26
>>> 13 * 3
39
>>> 13 * 4
52
>>> 13 * 5
65
>>> 13 * 6
78
>>> 13 * 7
91
>>> 13 * 8
104
>>> 13 * 9
117
>>> 13 * 10
130
>>> #QUESTÃO 4
>>> #total de semanas
>>> 4 * 4
16
>>> #total de aulas
>>> 2 * 16
32
>>> (75 / 100) * 32
24.0
>>> #aulas que pode faltar
>>> 32 - 24
8
>>> print ("Davinir pode faltar 8 aulas" )
Davinir pode faltar 8 aulas
>>>
>>> #questão 5
>>> import math
>>> math.pi * 2 * 2
12.566370614359172
>>> #questão 6
>>> desl = 65 * 1000
>>> hr = 3 * 3600
>>> minu = 23 * 60
>>> seg = hr + minu + 17
>>> vel = desl / seg
>>> print("A velocidade média é: ", s)
Traceback (most recent call last):
File "<pyshell#36>", line 1, in <module>
print("A velocidade média é: ", s)
NameError: name 's' is not defined
>>> print("A velocidade média é: ", vel)
A velocidade média é: 5.329179306386816
>>> print("A velocidade média é: ", vel ,"m/s")
A velocidade média é: 5.329179306386816 m/s
>>>
|
23836bb7a43deeed06a57cf4af65fea2bc3f95e9 | Cpharles/Python | /CursoEmVideo/Aula_09/ex026 - Primeira e ultima ocorrencia de uma string.py | 594 | 4.03125 | 4 | """Exercício Python 026:
Faça um programa que leia uma frase pelo teclado e mostre quantas vezes aparece a letra "A",
em que posição ela aparece a primeira vez e em que posição ela aparece a última vez."""
frase = str(input('Digite uma frase:_ ')).strip().lower()
import unidecode # esta lib trata string com acentuação
print('A letra "A" aparece ({}) vezes na frase.'.format(unidecode.unidecode(frase).count('a')))
print('A primeira letra "A" aparece na posição:_{}'.format(frase.find('a') + 1))
print('A última letra "A" apareceu na posição:_{}'.format(frase.rfind('a') + 1))
|
162274bec8bd72fead3878c8f6cef83629355cb5 | PPL-IIITA/ppl-assignment-shubham-padia | /q2/boy.py | 642 | 3.625 | 4 | class Boy:
""" Class for boy"""
def __init__(self, name, attractiveness, min_attraction, intelligence, budget, category, single=1, happiness=0):
self.name = name
self.attractiveness = int(attractiveness)
self.intelligence = int(intelligence)
self.budget = int(budget)
self.category = category
self.single = single
self.min_attraction = int(min_attraction)
self.happiness = happiness
def __str__(self):
return str(self.single)
def change_commitment(self):
if self.single:
self.single = 0
else:
self.single = 1
|
5467abc676dc3f44779c4324321339e5f36f4d01 | mimi1987/Python_Script_Mingle_Mangle | /n_factorial_recursion.py | 135 | 3.640625 | 4 | def recursiveCall(n):
# Exit condition
if n == 1:
return 1
# Recursive call of recursiveCall
return n * recursiveCall(n-1)
|
3f0269823041725d11d9b794c67d126c11994c25 | Leadace123/Python-LSystem-Trees | /Tree-Generator/main.py | 2,932 | 3.640625 | 4 | from tkinter import *
import turtle
import random
# Creates Root Window
root = Tk()
root.title('Tree Generator')
root.state('zoomed')
root.config(bg='grey')
w = root.winfo_screenwidth()
h = root.winfo_screenheight()
is_drawing = 0
# Generates Tree
def generate_tree():
global is_drawing
if is_drawing == 0:
clear_scene()
is_drawing = 1
iterate_path()
# Clears any generated Trees
def clear_scene():
tree_turtle.clear()
tree_turtle.hideturtle()
tree_turtle.penup()
tree_turtle.setposition(start_pos)
tree_turtle.setheading(start_heading)
tree_turtle.showturtle()
tree_turtle.pendown()
# Iterates path string
def iterate_path():
cur_string = 'F'
new_string = ""
for each in range(int(entries[0].get())):
for char in cur_string:
if char == "F":
new_string += "FF+[+F-F-F]-[-F+F+F]"
else:
new_string += char
cur_string = new_string
new_string = ""
draw_tree(cur_string)
# Draws tree
def draw_tree(path):
global is_drawing
saved_pos = []
saved_angle = []
for each in path:
if each == "F":
tree_turtle.forward(random.randrange(int(entries[1].get()), int(entries[2].get())))
elif each == "+":
tree_turtle.left(-random.randrange(int(entries[3].get()), int(entries[4].get())))
elif each == "-":
tree_turtle.left(random.randrange(int(entries[3].get()), int(entries[4].get())))
elif each == "[":
saved_pos.append(tree_turtle.pos())
saved_angle.append(tree_turtle.heading())
elif each == "]":
tree_turtle.penup()
tree_turtle.setheading(saved_angle[-1])
del saved_angle[-1]
tree_turtle.setposition(saved_pos[-1])
del saved_pos[-1]
tree_turtle.pendown()
tree_turtle.hideturtle()
is_drawing = 0
# Setup turtle canvas & place turtle close to bottom of screen
canvas = Canvas(root, width=(w-200), height=h)
canvas.grid(row=0, column=2, rowspan=100)
tree_turtle = turtle.RawTurtle(canvas)
tree_turtle.speed(-100)
tree_turtle.hideturtle()
tree_turtle.penup()
tree_turtle.sety(-(h/2) + 100)
tree_turtle.left(90)
tree_turtle.showturtle()
tree_turtle.pendown()
start_pos = tree_turtle.pos()
start_heading = tree_turtle.heading()
# Setup entry fields and buttons
fields = ['Iterations: ', 'Seg Length Low: ', 'Seg Length High: ', 'Turn Angle Low: ', 'Turn Angle High: ']
entry_defaults = [3, 8, 16, 10, 22]
entries = []
for i in range(len(fields)):
lab = Label(root, text=fields[i])
lab.grid(column=0, row=i)
en = Entry(root, width=6)
en.grid(column=1, row=i, padx=10)
en.insert(END, entry_defaults[i])
entries.append(en)
generate = Button(root, font='bold', text='Generate', command=generate_tree)
generate.grid(column=0, row=6, columnspan=2)
root.mainloop()
|
e8ac132d618b3d40ae290d0abdbd738dd090a636 | JuanTorchia/pythonPensamientoComputacional | /rangos.py | 296 | 4.0625 | 4 |
my_range = range(1, 5)
print(type(my_range))
my_range = range(0, 7, 2)
my_other_range = range(0, 8, 2)
print(my_range == my_other_range)
for i in my_range:
print(i)
for i in my_other_range:
print(i)
print(my_range is my_other_range)
for i in range(0, 101, 2):
print(i)
|
2455bfc9cd54424860a1c3ec2455e20d2c48c129 | Joie-Kim/python_ex | /final_exercise/ex9.py | 581 | 3.578125 | 4 | # 9. 평균값 구하기
# sample.txt 파일의 숫자 값을 모두 읽어 총합과 평균 값을 구한 후, 평균 값을 result.txt 파일에 쓰도록 하자.
# (1) 파일 읽기
f = open("./final_exercise/sample.txt", 'r')
list = f.readlines()
f.close()
# (2) 총합과 평균 값 구하기
total = 0
for value in list:
score = int(value)
total += score
avg = total / len(list)
# (3) 평균 값 파일에 쓰기
f = open("./final_exercise/result.txt", 'w')
# f.write(avg) # TypeError : 파일에 쓸 수 있는 데이터는 문자열!
f.write(str(avg))
f.close() |
fe4823fc78f1d7aba084f79ccbc1dde4baccd40a | Siyuan-Liu-233/Python-exercises | /python小练习/017田忌赛马.py | 924 | 3.90625 | 4 | # 这题也是华为面试时候的机试题:
# “ 广义田忌赛马:每匹马都有一个能力指数,齐威王先选马(按能力从大到小排列),田忌后选,马的能力大的一方获胜,若马的能力相同,也是齐威王胜(东道主优势)。”
# 例如:
# 齐威王的马的列表 a = [15,11,9,8,6,5,1]
# 田忌的马的候选表 b = [10,8,7,6,5,3,2]
# 如果你是田忌,如何在劣势很明显的情况下,扭转战局呢?
# 请用python写出解法,输出田忌的对阵列表 c及最终胜败的结果
# 评分
a = [8,15,1,11,6,5,9]
b = [2,8,6,7,5,3,10]
import numpy as np
a,b=np.array(np.sort(a)),np.array(np.sort(b))
x=np.shape(a)[0]
print(a,b)
time=0
print((a-b)>0)
while (((a-b)>0).sum())>=x/2 and time<x:
temp=b[-1-time]
b[0:-1-time],b[-1-time]=b[1:x-time],b[0]
time+=1
if ((a-b)>0).sum()<x/2:
print("获胜方案为:",a,b)
else:
print('无法获胜')
|
5d6afb6166a9ca9b5dd697099b9b571c243674db | BabyNaNaWang/41daysToLearnPython3 | /零基础学习python3.day7.容器集合.py | 2,305 | 3.71875 | 4 | # date:2019-4-17
# author:Ivo Wang
# describition:容器集合、三引号字符串、索引、字符串是不可变的、字符串拼接
# editor for code: vs code
# 容器集合
# 定义:集合(set)是一个无序的不重复元素序列。
# 集合中的元素必须是不可变类型的
# 创建集合的方法有两种:
# 第一种:通过set(value)创建空集合
my_set = set('hello')
print(my_set)
# 第二种:通过{value,value1}方式创建
my_set = {1,2,3,3}
print(my_set)
# 定义不可变集合: [变量名] = frozenset([已创建集合变量])
n_my_set = frozenset(my_set)
print(n_my_set)
# 集合间运算
# 子集判断:< 或 issubset()
my_set1 = {1,2,3,4,5}
my_set2 = {7,8,9,10}
my_set3 = {2,3}
print(my_set3 < my_set1)
print(my_set3 < my_set2)
print(my_set3.issubset(my_set1))
print(my_set3.issubset(my_set2))
# 并集运算:丨 或 union()
my_set1 = {1,2,3,4}
my_set2 = {5,6,7}
print(my_set1 | my_set2)
print(my_set1.union(my_set2))
# 交集:& 或 intersection()
my_set1 = {1,2,3,4}
my_set2 = {3,5,6,7}
print(my_set1 & my_set2)
print(my_set1.intersection(my_set2))
# 差集(所有属于一个集合且不属于另一个集合元素构成的集合):- 或 difference()
my_set1 = {1,2,3,4}
my_set2 = {3,5,6,7}
print(my_set1 - my_set2)
print(my_set1.difference(my_set2))
# 对称差(只属于其中一个集合,而不属于另一个集合的元素组成的集合): ^ 或者 symmetric_difference()
my_set1 = {1,2,3,4}
my_set2 = {3,5,6,7}
print(my_set1 ^ my_set2)
print(my_set1.symmetric_difference(my_set2))
# 集合中添加元素:add
my_set = {1,2,3}
my_set.add(4)
print(my_set)
# 清空集合中的元素:clear
my_set = {1,2,3}
my_set.clear()
print(my_set)
# 复制:copy
my_set = {1,2,3}
n_my_set = my_set.copy()
print(n_my_set)
# 随机删除:pop
my_set = {'h','l','w'}
my_set.pop()
print(my_set)
# 移除:remove,如果删除元素不存在则报KeyError
my_set = {'h','l','w'}
my_set.remove('l')
print(my_set)
# 添加其他集合/列表:update
my_set = {1,2,3}
my_set.update({4,5,6})
print(my_set)
# 还有其他方法,详情参考
# https://www.cnblogs.com/suendanny/p/8597596.html
# 三引号字符串
# 如果字符串需要跨一行以上,可以使用三引号
my_str = '''第一行
第二行
第三行'''
print(my_str) |
04563d005eb2795bd4e09dd83c4731454d948ea4 | panxiao6494/-study | /python-study/while.py | 267 | 4 | 4 | number=7
guess=-1
print('猜字谜游戏')
while guess !=number:
guess=int(input('请输入你猜的数字:'))
if guess==number:
print('恭喜你,猜对了')
elif guess<number:
print('猜的数字小了')
elif guess>number:
print('猜的数字大了--') |
1faeb4b29ce48ce16e2599570a3f3bf395354b8b | oscarepv/Clase-9 | /ejercicio4.1.py | 170 | 3.59375 | 4 | import turtle
def dibujar(x):
t = turtle.Pen()
angulo=360/x
for x in range (1,(x+1)):
t.forward(100)
t.left(angulo)
dibujar(6)
turtle.getscreen()._root.mainloop() |
ea7147ca5b36c804ddcc5c4edd6a925a57436fe1 | nadishs/easycuberoot | /1.croot-bisection.py | 393 | 4.1875 | 4 | #Nadish Shajahan
#Program to find the cube root of a number using bisection method.
#https://github.com/nadishs/
n = input()
high = n
low = 0
eps = 0.0000001
count = 0 # no of steps
mid = (low + high) / 2.0
while abs((mid**3)-n) > eps :
if mid**3 < n:
low = mid
else:
high = mid
mid = (low + high)/2.0
count = count + 1
guess = mid
print "Cube Root of ",n ," : ", guess, " in Time: ",count
|
0ef3cb00a17c65199d6416f1b8e7a74503464854 | chiachichuang/Capstone_ML_DL | /Capstone_Hw1_IO_reviews/PyAdv_02_Args.py | 433 | 3.953125 | 4 | ####################
# PyAdv_S02_Args.py
####################
#
# Program to process script arguments
#
import sys
def show_numbers():
print("From show_numbers: 12345678910 ...")
# this is the main function
def main():
print("Number of arguments ...", len(sys.argv))
for a, b in enumerate(sys.argv):
print(a, b)
# call the function show numbers
show_numbers()
if __name__ == "__main__":
main()
|
38f81a2c500ab92fc80585ac3b79de2407cb207c | odonnell31/python_data_science_basics | /algorithms/strings/unique_characters.py | 837 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Oct 25 12:16:01 2019
@author: Michael ODonnell
"""
# Question
# write an algorithm to determine if a string has all unique characters
def unique_chars(word):
# plan of attack: append each character to a list, if it is not in list already
# create empty list to append new characters to
char_list = []
# loop through the word once
for i in word:
# if character not in char_list, add it to the list
if i not in char_list:
char_list.append(i)
# if character is already in char_list, return False
else:
return(word, "does not have all unique characters")
return(word, "contains all unique characters")
# test the method
for w in ['test', 'multiple', 'words', 'with', 'this', 'function']:
print(unique_chars(w)) |
fc35dc85829511903157c837b3b653a21f6e592c | shalgrim/advent_of_code_2020 | /python/day02_1.py | 651 | 3.796875 | 4 | import re
from file_ops import readlines
LO = 'lo'
HI = 'hi'
LETTER = 'letter'
PWD = 'pwd'
PATTERN = re.compile(
rf'(?P<{LO}>\d+)-(?P<{HI}>\d+)\s+(?P<{LETTER}>[a-z]):\s+(?P<{PWD}>\S+)'
)
def is_valid(groupdict):
lo = int(groupdict[LO])
hi = int(groupdict[HI])
letter = groupdict[LETTER]
password = groupdict[PWD]
return lo <= password.count(letter) <= hi
def count_valid(lines, is_valid_algorithm):
groups = [PATTERN.match(line).groupdict() for line in lines]
return sum(is_valid_algorithm(group) for group in groups)
if __name__ == '__main__':
lines = readlines(2)
print(count_valid(lines, is_valid))
|
0a7a8cac1ef4faa1cd8321d5119f16d800e8a7bc | harut0601/intro-to-Python | /week5/Practical/decorators1.py | 397 | 3.578125 | 4 | def decorator2(func):
def wrapper(*args, **kwargs):
b = func(*args, **kwargs)
c = "!!! Welcome to the party."
print(b + c)
return wrapper
def decorator1(func):
def wrapper(*args, **kwargs):
a = func(*args, **kwargs)
return a.capitalize()
return wrapper
@decorator2
@decorator1
def hi_everyone():
return "HI EVERYONE"
hi_everyone()
|
09ebd1ccdcfc56fff99fe41ac94d57180274d26f | NetworkRanger/python-core | /chapter09/friendsB.py | 1,481 | 3.625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: NetworkRanger
# Date: 2019/8/11 12:28 PM
import cgi
header = 'Content-Type: text/html\n\n'
formhtml = '''
<html>
<head>
<title>Friends CGI Demo (static screen)</title>
</head>
<body>
<h3>Friends list for: <i>NEW USER</i></h3>
<form action="/cgi-bin/friendsA.py">
<b>Enter your Name:</b>
<input type="hidden" name="action" value="edit"
<input type="text" name="person" value="new user" size="15">
<input type="submit">
</form>
</body>
</html>
'''
fradio = '<input type="radio" name="howmany" value="%s" %s> %s\n'
def showForm():
friends = []
for i in (0, 10, 25, 50, 100):
checked = ''
if i == 0:
checked = 'CHECKED'
friends.append(fradio % (str(i), checked, str(i)))
print '%s%s' % (header, formhtml % ''.join(friends))
reshtml = '''
<html>
<head>
<title>Friends CGI Demo</title>
</head>
<body>
<h3>Friends list for: <i>%s</i></h3>
Your name is: <b>%s</b><p>
You have <b>%s</b> friends
</body>
</html>
'''
def doResults(who, howmany):
print header + reshtml % (who, who, howmany)
def process():
form = cgi.FieldStorage()
if 'person' in form:
who = form['person'].value
else:
who = 'NEW USER'
if 'howmay' in form:
howmany = form['howmany'].value
else:
howmany = 0
if 'action' in form:
doResults(who, howmany)
else:
showForm()
if __name__ == '__main__':
process() |
295899eb9199e002ebec71d9b201717bf101d37a | undersfx/python-para-zumbis | /exerc_area.py | 603 | 3.953125 | 4 | '''
Ler tamanho de área de calcular minimo interiro de latas para pinta-la;
Printar o valor total do custo considerando que cada lata;
Tem 18 litros, custa 80 reais e cada litro de tinta pinta 3 metros quadrados.
'''
metros = int(input("M² de área a ser pintada: "))
if metros % 54 != 0:
latas = int(metros / (18 * 3)) + 1
#Se o resto da divisão não for zero
#É preciso uma lata adicional para terminal o perímetro
else:
latas = metros / (18 * 3)
preco = int(latas) * 80
print("Serão necessárias %d latas, totalizando R$%5.2f" %(latas, preco))
|
c6b92a1814677ec16af33d832dcc4674b727a4ee | HTReddy/everyDayUseCodes | /excelToJson.py | 764 | 3.5625 | 4 | import pandas
import pprint
import json
jsonDataFrame = {}
def convertExcelToJson(excelFileName=None, jsonFileName=None):
dataFrame = pandas.read_excel(excelFileName)
pprint.pprint(dataFrame.columns) # All the headings of your excel file, these can become the source for JSON Keys
# Iterate through all the excel sheet headings and store in a dictionary
for everyHeading in dataFrame.columns:
jsonDataFrame[str(everyHeading)] = dataFrame[str(everyHeading)].values.tolist() # Helps extract the contents under a heading
# Dump the dictionary to a JSON
with open(jsonFileName, 'w') as fp:
json.dump(jsonDataFrame, fp)
convertExcelToJson(excelFileName="yourInputExcel.xlsx", jsonFileName="outputJson.json")
|
0b4f27c020a55cf98475c26330e7575291ae6f8a | FjeldMats/Project-Euler | /Python/problem68.py | 3,224 | 3.515625 | 4 | import itertools
class n_gon:
def __init__(self, n):
num_lines = n
self.lines = []
for line in range(num_lines):
self.lines.append([])
for _ in range(3):
self.lines[line].append(0)
def set_with(self, outer, inner):
# put inner nodes in lines
for index, line in enumerate(self.lines):
line[0] = outer[index]
for index, line in enumerate(self.lines):
line[1] = inner[index]
line[2] = inner[(index+1)%len(inner)]
def check_valid(self, p=False):
# check order is correct
# 1. middle node first line equal to last node last line
if self.lines[0][1] != self.lines[-1][-1]:
if p:
print("inner order wrong [1]")
return False
# current line last node equal to next line muiddle node
for i in range(len(self.lines) - 1):
if self.lines[i][-1] != self.lines[i+1][1]:
if p:
print("inner order wrong [2]")
return False
# check all outer nodes are unique
outer_nodes = []
for line in self.lines:
outer_nodes.append(line[0])
if len(outer_nodes) != len(set(outer_nodes)):
if p:
print("found duplicate outer nodes")
return False
# check all lines add up to same sum
sums = []
for line in self.lines:
sums.append(sum(line))
if len(set(sums)) != 1:
if p:
print("sums does not add up to same sum in lines", sums)
return False
return sums[0] # return sum if valid
def __repr__(self):
s = ""
for line in self.lines:
s += str(line) + "\n"
return s
def gen_line(n):
# genereate all possible outer inner inner combinations
# for a given n
N = 2 * n
lsts = list(range(1, N+1))
for lst in itertools.permutations(lsts):
yield list(lst[:n]), list(lst[n:])
def rotate_until_smallest_first(lst):
firsts = [lst[i][0] for i in range(len(lst))]
while lst[0][0] != min(firsts):
lst = lst[1:] + lst[:1]
return lst
def nested_list_to_str(lst):
s = ""
for line in lst:
for node in line:
s += str(node)
return s
if __name__ == "__main__":
n = 5
n_digit = 16
lst = []
seen = set()
for outer, inner in gen_line(n):
g = n_gon(n)
g.set_with(outer, inner)
valid = g.check_valid()
if valid:
s = g.lines
s = rotate_until_smallest_first(s)
str_s = nested_list_to_str(s)
if str_s not in seen:
print(str_s)
seen.add(str_s)
lst.append((valid, s))
lst.sort(key=lambda x: x[0])
for i in lst:
print(i)
if len(seen) != 0:
s = max(map(int,filter(lambda x: len(x) == n_digit, list(seen))))
print(f"maximum {n_digit} digit string for {n}-gon is {s}")
else:
print("no valid solutions")
|
6c100b2ad668b5537d6783054b34ae03c9cc4e00 | pravindra01/DS_And_AlgorithmsPractice | /BInTreeDFS.py | 1,513 | 4.25 | 4 | # Given a binary tree, return the tilt of the whole tree.
# The tilt of a tree node is defined as the absolute difference between the sum of all left subtree node values and the sum of all
# right subtree node values. Null node has tilt 0.
# The tilt of the whole tree is defined as the sum of all nodes' tilt.
# Example:
# Input:
# 1
# / \
# 2 3
# Output: 1
# Explanation:
# Tilt of node 2 : 0
# Tilt of node 3 : 0
# Tilt of node 1 : |2-3| = 1
# Tilt of binary tree : 0 + 0 + 1 = 1
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def __init__(self):
self.tilt = 0
def findTilt(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
leftSum = self._findSumAndTilt(root.left)
rightSum = self._findSumAndTilt(root.right)
return self.tilt + abs(leftSum - rightSum)
def _findSumAndTilt(self, root):
if not root:
return 0
# using recursion
leftSum = self._findSumAndTilt(root.left)
rightSum = self._findSumAndTilt(root.right)
self.tilt += abs(leftSum - rightSum)
return leftSum + rightSum + root.val
if __name__ == "__main__":
test2 = TreeNode(1)
test2.left = TreeNode(2)
test2.right = TreeNode(3)
test = Solution()
print test.findTilt(test2) |
358791111e25574b9e33ffba9a2eed43f04324c2 | vit-shreyansh-kumar/code-droplets | /src/AbstractProperty.py | 397 | 3.734375 | 4 | import abc
class Base(metaclass=abc.ABCMeta):
@property
@abc.abstractmethod
def value(self):
return "To be overridden."
class Implementation(Base):
@property
def value(self):
return "Concrete Implementation."
if __name__ == "__main__":
b = Base()
print("Base.value:", b.value)
i = Implementation()
print("Implementation.value:",i.value) |
c65a1d7183ba13846684af1a80a5c144ba7346ab | kaustubhmali/Python_practice | /Python_basics(Part-2)/reduce.py | 501 | 3.953125 | 4 | import functools
import operator
import itertools
lis = [1, 3, 5, 6, 2, ]
# Sum of all the elements in the list
sum = (functools.reduce(lambda a, b: a + b, lis))
print(sum)
# largest element in the list
largest = (functools.reduce(lambda a, b: a if a > b else b, lis))
print(largest)
# Using operator
sum_ = (functools.reduce(operator.add, lis))
print(sum_)
# multiply
mul_ = (functools.reduce(operator.mul, lis))
print(mul_)
sum1 = (list(itertools.accumulate(lis, lambda a, b: a+b)))
print(sum1) |
87889c37912fe7f9666400c7c70e84cf412ea0c8 | wangxiaolinlin/python | /koujue.py | 145 | 3.546875 | 4 | count = 0
while count <= 9:
row = 1
while row <= count:
print("%d*%d=%d"%(count,row,count*row),end="/t")
row+=1
print("")
count+=1
|
ff9626094d23fa6604d9feddb0e9094312f7db6e | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/bob/1f3b4596b75341c781b0f2a34aca84fa.py | 564 | 4.03125 | 4 | #
# Skeleton file for the Python "Bob" exercise.
#
def hey(what):
# Test if string is empty, has space or tab.
if not what or what.isspace():
return 'Fine. Be that way!'
# Test if string is not empty, has ? mark at the end not uppercase.
elif not what or what[-1] == '?' and not what.isupper():
return 'Sure.'
# Test if string all uppercase or has ! mark at the end and it's uppercase.
elif what[-1] == '!' and what.isupper() or what.isupper():
return 'Whoa, chill out!'
else:
return 'Whatever.'
|
e78ece88c96b93a5a754f6342c2bd704e9bf330f | here0009/LeetCode | /Python/1681_MinimumIncompatibility.py | 4,941 | 4.0625 | 4 | """
You are given an integer array nums and an integer k. You are asked to distribute this array into k subsets of equal size such that there are no two equal elements in the same subset.
A subset's incompatibility is the difference between the maximum and minimum elements in that array.
Return the minimum possible sum of incompatibilities of the k subsets after distributing the array optimally, or return -1 if it is not possible.
A subset is a group integers that appear in the array with no particular order.
Example 1:
Input: nums = [1,2,1,4], k = 2
Output: 4
Explanation: The optimal distribution of subsets is [1,2] and [1,4].
The incompatibility is (2-1) + (4-1) = 4.
Note that [1,1] and [2,4] would result in a smaller sum, but the first subset contains 2 equal elements.
Example 2:
Input: nums = [6,3,8,1,3,1,2,2], k = 4
Output: 6
Explanation: The optimal distribution of subsets is [1,2], [2,3], [6,8], and [1,3].
The incompatibility is (2-1) + (3-2) + (8-6) + (3-1) = 6.
Example 3:
Input: nums = [5,3,3,6,3,3], k = 3
Output: -1
Explanation: It is impossible to distribute nums into 3 subsets where no two elements are equal in the same subset.
Constraints:
1 <= k <= nums.length <= 16
nums.length is divisible by k
1 <= nums[i] <= nums.length
"""
from typing import List
from collections import Counter
import heapq
class Solution:
def minimumIncompatibility(self, nums: List[int], k: int) -> int:
"""
wrong answer
"""
counts = Counter(nums)
len_n = len(nums)
if max(counts.values()) > k:
return -1
lst = [(key, val) for key, val in counts.items()]
heapq.heapify(lst)
group = len_n // k
res = 0
print(lst)
for _ in range(k):
tmp_counts = 0
tmp_lst = []
while tmp_counts < group:
# print(tmp_counts, k)
key, val = heapq.heappop(lst)
tmp_counts += 1
val -= 1
tmp_lst.append((key, val))
print(tmp_lst)
res += tmp_lst[-1][0] - tmp_lst[0][0]
for key, val in tmp_lst:
if val > 0:
heapq.heappush(lst, (key, val))
return res
from typing import List
from collections import Counter
from itertools import combinations
from functools import lru_cache
class Solution:
def minimumIncompatibility(self, nums: List[int], k: int) -> int:
@lru_cache(None)
def dp(status, group):
if group == k:
return 0
avl = []
for i,v in enumerate(status):
if v < counts[keys[i]]:
avl.append(i)
res = float('inf')
for comb in combinations(avl, each_group):
s2 = list(status)
for c in comb:
s2[c] += 1
tmp_lst = sorted(keys[c] for c in comb)
tmp_val = tmp_lst[-1] - tmp_lst[0]
res = min(res, tmp_val + dp(tuple(s2), group + 1))
return res
counts = Counter(nums)
print(counts)
len_n = len(nums)
len_c = len(counts)
each_group = len_n // k
if max(counts.values()) > k:
return -1
keys = list(counts.keys())
return dp(tuple([0] * len_c), 0)
from typing import List
from collections import Counter
from itertools import combinations
from functools import lru_cache
class Solution:
def minimumIncompatibility(self, nums: List[int], k: int) -> int:
@lru_cache(None)
def dp(status):
if status == target:
return 0
avl = [] # store the index of the available keys
for i, v in enumerate(status):
if v < counts[keys[i]]:
avl.append(i)
res = float('inf')
for comb in combinations(avl, each_group): # try all the combinations of the available keys
s2 = list(status)
max_v, min_v = float('-inf'), float('inf')
for c in comb:
s2[c] += 1
max_v = max(max_v, keys[c])
min_v = min(min_v, keys[c])
res = min(res, max_v - min_v + dp(tuple(s2)))
return res
len_n = len(nums)
counts = Counter(nums)
if max(counts.values()) > k:
return -1
target = tuple(counts.values())
keys = list(counts.keys())
len_c = len(counts)
each_group = len_n // k
return dp(tuple([0] * len_c))
S = Solution()
nums = [1,2,1,4]
k = 2
print(S.minimumIncompatibility(nums, k))
nums = [6,3,8,1,3,1,2,2]
k = 4
print(S.minimumIncompatibility(nums, k))
nums = [5,3,3,6,3,3]
k = 3
print(S.minimumIncompatibility(nums, k))
nums = [5,3,2,11,5,8,7,7,6,2,4,5]
k = 12
print(S.minimumIncompatibility(nums, k))
|
374023baa43370bd924fe383b81b4f323d27775c | linminhtoo/algorithms | /greedy/easy/lemonadeChange.py | 801 | 3.640625 | 4 | # https://leetcode.com/problems/lemonade-change/submissions/
from collections import defaultdict
from typing import List
class Solution:
def lemonadeChange(self, bills: List[int]) -> bool:
cash = defaultdict(int)
for b in bills:
if b == 10:
if cash[5] == 0:
return False
cash[5] -= 1
elif b == 20:
# it is critical to give 10 as change first whenever possible
if cash[10] > 0 and cash[5] > 0:
cash[10] -= 1
cash[5] -= 1
elif cash[5] > 2:
cash[5] -= 3
else:
return False
cash[b] += 1
# print(b, cash)
return True |
58f2e33e896485a0efdd0676daf3a2b31a9936d7 | dylanbaghel/python-complete-course | /section_15_lambdas_built_in_functions/11_zip.py | 721 | 4.75 | 5 | # zip() Function
"""
zip():
--> The purpose of zip() is to map the similar index of multiple containers so that they can be used just using as single entity.
"""
"""
zipping
"""
names = ['Abhishek', 'Jonas', 'Kora']
marks = [90, 55, 78]
first_zip = zip(names, marks)
print(list(first_zip))
# initializing lists
name = [ "Manjeet", "Nikhil", "Shambhavi", "Astha" ]
roll_no = [ 4, 1, 3, 2 ]
marks = [ 40, 50, 60, 70 ]
# using zip() to map values
mapped = zip(name, roll_no, marks)
# converting values to print as set
mapped = set(mapped)
# printing resultant values
print (f"The zipped result is : {mapped}")
"""
Unzipping
"""
name, roll_no, marks = zip(*mapped)
print(name)
print(roll_no)
print(marks)
|
5ebcd23fc9a737aed11a2a94cb601f245ef76915 | ipgtzuo/Learn_Python | /demo/minSquenceDiff.py | 544 | 3.5625 | 4 | def minSquenceDiff(list1, list2):
c = list1+list2
c.sort()
n = len(c)
a, b = [], []
for i in range(n):
if sum(a) >= sum(b):
b.append(c[-1])
else:
a.append(c[-1])
c.pop()
if len(a) == n/2:
b += c
break
if len(b) == n/2:
a += c
break
return abs(sum(a)-sum(b)), a, b
if __name__ == '__main__':
a = [1, 2, 6, 12]
b = [6, 20, 8, 9, 10, 16]
print minSquenceDiff(a, b)
|
d15975c7e9d522b1c61dfdfbf7b784841ebe37f7 | beautytasara27/beauty | /driving simulation.py | 1,158 | 3.96875 | 4 | import matplotlib.pylot as plt
Max_Distance = int(input())
Initial_velocity =int(input())
Time_spent =int(input())
Acc =int(input())
Speed_limit=60
Distance_array=[]
Velocity_array=[]
Time_array[]
for i in range(0,Max_distance/10):
Distance_array[i]=i*10
for i in range(0,len(Distance_array)):
Velocity_array[i]= sqrt(2*Acc*i)
for i in range(0,len(Distance_array)):
Time_Array[i]=sqrt(2*Distance_array[i]/Acc)
plt.plot(Time_Array,Distance_Array)
plt.xlabel('time')
plt.ylabel('distance')
for i in Distance_array:
if(Distance_array[len(Distance_array)]>max_Distance):
print("The person reached destination : ", Distance_array[len(Distance_array)])
else:
print("The person did not reach destination:" , Distance_array[len(Distance_array)])
for i in Velocity_array:
if(Velocity_array[len(Velocity_array)]>Speep_limit):
print("The person went over speed limit max speed was : " + Velocity_array[len(Velocity_array)])
else:
print("The person did not go over speed limit max speed was :" + Velocity_array[len(Velocity_array)])
plt.show()
|
3a6c0b29649f6306fe62be6950f0694f0b91bc2e | Igorprof/python_git | /HW_3/6.py | 325 | 4.03125 | 4 | def int_func(word):
# Без использовании функции capitalize
letters = list(word)
letters[0] = letters[0].upper()
cap_word = ''.join(letters)
return cap_word
s = input('Введите строку: ')
new_s = ''
for word in s.split():
new_s += int_func(word) + ' '
print(new_s) |
4465ef7dbeac475e023cbad32537d3683e496ebd | magik2art/DZ_1_python_Mamaev_Pavel | /parcent.py | 528 | 3.8125 | 4 | user_text = int(input("Введите число от 0 до 20 "))
text = ()
i = 0
# for i in range(21): # для проверки
if user_text == 1:
text = user_text, "Процент"
elif user_text == 2 or user_text == 3 or user_text == 4:
text = user_text, "Процента"
else:
text = user_text, "Процентов"
# print(text) # для проверки
# user_text += 1 # для проверки
print("С числом которое вы ввели ваше склонение будет = ", text)
|
a8dfb10c13eaf06e65cc7b419ceb772936537790 | edellle/Python | /lesson_5/task_5.py | 704 | 4.34375 | 4 | # Создать (программно) текстовый файл, записать в него программно набор чисел, разделенных пробелами.
# Программа должна подсчитывать сумму чисел в файле и выводить ее на экран.
with open ('text_5.txt', 'w+') as my_file:
numbers = input ('Введите одно или несколько чисел через пробел: ')
my_file.write(numbers)
my_file.seek(0)
r_numbers = my_file.read()
r_numbers = r_numbers.split(' ')
result = 0
for n in r_numbers:
result += int(n)
print(f'Сумма чисел: {result}')
|
661a04197a4e2d05d61451f10c84f2219fed8fa7 | M0nd4/discopt | /ls/magicsquare/generate_random_square.py | 640 | 4.40625 | 4 | #!/usr/bin/python
import sys
import random
def generate_square(size):
"""Create square of consecutive numbers as test data for magic square"""
nums = size * size
seq = random.sample(list(range(1, nums + 1)), nums)
output = ''
for i in range(nums):
if i > 0:
output += " "
if i > 0 and i % size == 0:
output += '\n'
output += "{0:3}".format(seq[i])
return output
if __name__ == '__main__':
if len(sys.argv) > 1:
size = int(sys.argv[1].strip())
print generate_square(size)
else:
print 'Usage: generate_random_square <int square size>'
|
96bc4214616055bbebb5f5d095f8d9d282bcedb3 | ShuklaShubh89/adventofcode2015 | /3a.py | 639 | 3.65625 | 4 | from collections import defaultdict
def def_value():
return 0
directions = input()
directionlist = list(directions)
coordinates = [0,0]
housevisits = defaultdict(def_value)
for x in directionlist:
if(x == '^'):
coordinates[1]+=1
elif(x == 'v'):
coordinates[1]-=1
elif(x == '>'):
coordinates[0]+=1
elif(x == '<'):
coordinates[0]-=1
#print(str(coordinates))
housevisits[str(coordinates)]+=1
resultcounter=1 #because 0,0 is also a house
for x in list(housevisits.values()):
#print(x)
if (x>=1):
resultcounter+=1
else:
continue
print(resultcounter)
|
8c8d11b6111c82be7e53cb19ff73d76b300d8d6d | Kawser-nerd/CLCDSA | /Source Codes/CodeJamData/15/22/18.py | 1,701 | 3.578125 | 4 | #!/usr/bin/python2.7
import math
f = open('input.txt', 'r')
T = int(f.readline())
def solve_even(r, c, n):
sp = r * c - n
total = 2 * r * c - r - c
if r > c:
t = r
r = c
c = t
if r == 1:
if sp >= c / 2:
return 0
else:
return total - 2 * sp
thres1 = int(math.ceil((r - 2) * (c - 2) / 2.0))
thres2 = int(math.ceil(r * c / 2.0) - 2)
if sp >= math.floor(r * c / 2.0):
return 0
elif sp <= thres1:
return total - 4 * sp
elif sp <= thres2:
return total - 4 * thres1 - 3 * (sp - thres1)
else:
return 2
def solve_odd(r, c, n):
sp = r * c - n
total = 2 * r * c - r - c
if r > c:
t = r
r = c
c = t
if r == 1:
if sp >= math.ceil(c / 2.0):
return 0
else:
return total - 2 * sp
thres1 = int(math.ceil((r - 2) * (c - 2) / 2.0))
thres1_p = int(math.floor((r - 2) * (c - 2) / 2.0))
thres2 = int(math.ceil((r - 2) * (c - 2) / 2.0)) + r + c - 6
thres3 = int(math.ceil((r - 2) * (c - 2) / 2.0)) + r + c - 2
if sp >= math.floor(r * c / 2.0):
return 0
elif sp <= thres1:
return total - 4 * sp
elif sp <= thres2:
return total - 4 * thres1 - 3 * (sp - thres1)
elif sp <= thres3:
return total - 4 * thres1_p - 3 * (sp - thres1_p)
def solve(r, c, n):
if r * c % 2 == 0:
return solve_even(r, c, n)
else:
return solve_odd(r, c, n)
for t in range(T):
(r, c, n) = f.readline().rstrip().split(' ')
r = int(r)
c = int(c)
n = int(n)
print "Case #" + str(t + 1) + ":",
print solve(r, c, n)
|
06d584d7f22583a92088ebcc84ff340707772044 | Zaxcoding/personal-projects | /Project-Euler/Old problems/Problem 12.py | 594 | 3.53125 | 4 | # Problem 12
# What is the value of the first
# triangle number to have over
# five hundred divisors?
#def factors(a): # finds the factors of a
# x = num = 0 # and returns how many to
# while x <= a:
# x += 1
# if a % x == 0:
# num += 1
# return num
def triangle(n):
bestnum = best = 0
b = a = 1
while bestnum <= n:
a += 1
b += a
###
x = num = 0 # and returns how many to
while x <= b:
x += 1
if b % x == 0:
num += 1
###
# print num
if num > bestnum:
bestnum = num
best = b
print "A:", a, "B:", b, "Bestnum:", bestnum, "Best:", best
|
0ae91b5293f8cfe23d006d1333f43c259253223e | kamelzcs/study | /fraction_decimal.py | 766 | 3.890625 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
class Solution:
# @return a string
def fractionToDecimal(self, numerator, denominator):
ans = ""
if numerator * denominator < 0:
ans += "-"
numerator, denominator = abs(numerator), abs(denominator)
ans += str(numerator / denominator)
remain = numerator % denominator
if remain:
ans += "."
cache = {}
while remain:
remain *= 10
if remain in cache:
return "%s(%s)" % (ans[:cache[remain]], ans[cache[remain]:])
cache[remain] = len(ans)
ans += str(remain / denominator)
remain = remain % denominator
return ans
print Solution().fractionToDecimal(1, 2)
print Solution().fractionToDecimal(1, 3)
|
35f5c7214ea123f524eadc1b8953990844b9ee95 | JurgenTas/Programming | /Python/Algorithms & Data Structures/bst.py | 1,229 | 3.828125 | 4 | __author__ = 'J Tas'
class Node:
def __init__(self, key, val):
self.left = None
self.right = None
self.key = key
self.value = val
class BinarySearchTree:
def __init__(self):
self.root = None
def insert(self, node):
self.root = self._insert(self.root, node)
def _insert(self, root, node):
if root is None:
return node
if root.key > node.key:
root.left = self._insert(root.left, node)
else:
root.right = self._insert(root.right, node)
return root
def search(self, key):
return self._search(self.root, key)
def _search(self, node, key):
if node is None:
return None # key not found
if key < node.key:
return self._search(node.left, key)
elif key > node.key:
return self._search(node.right, key)
else:
return node.value # found key
if __name__ == '__main__':
tree = BinarySearchTree()
tree.insert(Node(3, "a"))
tree.insert(Node(7, "d"))
tree.insert(Node(1, "e"))
tree.insert(Node(5, "f"))
tree.insert(Node(6, "f"))
tree.insert(Node(9, "f"))
x = tree.search(9)
|
ba0af78395c0ebf1320cd0303366d37811934771 | SuchismitaDhal/Solutions-dailyInterviewPro | /2020/01-January/01.17.py | 714 | 3.90625 | 4 | # AMAZON
"""
SOLVED -- LEETCODE#405
Given a non-negative integer n, convert the integer to hexadecimal
and return the result as a string.
Hexadecimal is a base 16 representation of a number,
where the digits are 0123456789ABCDEF.
Do not use any builtin base conversion functions like hex.
"""
def to_hex(n):
# Time: O(logn) Space: O(1)
rep = ['0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f']
sol = ""
if n == 0:
return "0"
# for negetive numbers
if n < 0:
n = n + (1 << 32)
while n:
r = n % 16
sol += rep[r]
n = n // 16
return sol[::-1]
print(to_hex(123))
# 7B
|
8712c9be98e00b8190c1d2e84fc1cdd1b0f1575b | UludagUniversitesiYazilim/Basit_Oyunlar | /XoX/XoX_Console.py | 4,676 | 3.65625 | 4 | class XoXMain():
def __init__(self):
self.oyun_tahtasi = [["___","___","___"],
["___","___","___"],
["___","___","___"]]
baslangicYazi="""
XoX oyununa hoşgeldiniz.
Oyun 2 kişiliktir.
1.Oyuncu "X"
2. Oyuncu "O" olucaktır.
Hamlenizi yapmak istediğiniz yeri kordinat siteminde giriniz.
Örnek girdi :
1
2
Örnek Çıktı :
___ ___ ___
_X_ ___ ___
___ ___ ___
Çıkmak için iki değere de 9 giriniz.\n
\t\t\t\t Oyun Tahtası
"""
print(baslangicYazi)
if __name__ == "__main__":
while True:
self.tahtaYazdir()
self.oynamaSırası()
def tahtaYazdir(self):
for i in self.oyun_tahtasi:
print("\t\t\t\t",*i)
def kapat(self):
input()
quit()
def kontrol(self,j1):
orta=self.oyun_tahtasi[1][1]
sag=self.oyun_tahtasi[1][2]
sol=self.oyun_tahtasi[1][0]
üst=self.oyun_tahtasi[0][1]
alt=self.oyun_tahtasi[2][1]
sagUst=self.oyun_tahtasi[0][2]
sagAlt=self.oyun_tahtasi[2][2]
solUst=self.oyun_tahtasi[0][0]
solAlt=self.oyun_tahtasi[2][0]
if j1%2==1:
if solUst=="_X_" and üst=="_X_" and sagUst=="_X_":
print("1. Oyuncu kazandı")
self.kapat()
elif sol=="_X_" and orta=="_X_" and sag=="_X_":
print("1. Oyuncu kazandı")
self.kapat()
elif solAlt=="_X_" and alt=="_X_" and sagAlt=="_X_":
print("1. Oyuncu kazandı")
self.kapat()
elif solUst=="_X_" and sol=="_X_" and solAlt=="_X_":
print("1. Oyuncu kazandı")
self.kapat()
elif üst=="_X_" and orta=="_X_" and alt=="_X_":
print("1. Oyuncu kazandı")
self.kapat()
elif sagUst=="_X_" and sag=="_X_" and sagAlt=="_X_":
print("1. Oyuncu kazandı")
self.kapat()
elif sagUst=="_X_" and orta=="_X_" and solAlt=="_X_":
print("1. Oyuncu kazandı")
self.kapat()
elif solUst=="_X_" and orta=="_X_" and sagAlt=="_X_":
print("1. Oyuncu kazandı")
self.kapat()
else:
j1=j1+1
self.oynamaSırası(j1)
else:
if solUst=="_O_" and üst=="_O_" and sagUst=="_O_":
print("2. Oyuncu kazandı")
self.kapat()
elif sol=="_O_" and orta=="_O_" and sag=="_O_":
print("2. Oyuncu kazandı")
self.kapat()
elif solAlt=="_O_" and alt=="_O_" and sagAlt=="_O_":
print("2. Oyuncu kazandı")
self.kapat()
elif solUst=="_O_" and sol=="_O_" and solAlt=="_O_":
print("2. Oyuncu kazandı")
self.kapat()
elif üst=="_O_" and orta=="_O_" and alt=="_O_":
print("2. Oyuncu kazandı")
self.kapat()
elif sagUst=="_O_" and sag=="_O_" and sagAlt=="_O_":
print("2. Oyuncu kazandı")
self.kapat()
elif sagUst=="_O_" and orta=="_O_" and solAlt=="_O_":
print("2. Oyuncu kazandı")
self.kapat()
elif solUst=="_O_" and orta=="_O_" and sagAlt=="_O_":
print("2. Oyuncu kazandı")
self.kapat()
else:
j1=j1+1
self.oynamaSırası(j1)
def oynamaSırası(self, q=1):
if q%2==1:
print("1.Oyuncu")
else:
print("2.Oyuncu")
x=int(input("x Kordinatını Giriniz: "))
y=int(input("y Kordinatını Giriniz: "))
x=x-1
y=y-1
if x==8 and y==8:
self.kapat()
self.yerlestirme(x,y,q)
def yerlestirme(self,k,l,j):
try:
t=self.oyun_tahtasi[l][k]
if t=="_X_"or t=="_O_":
print("Girdiğiniz yer dolu")
self.oynamaSırası(j)
elif j%2==1:
self.oyun_tahtasi[l][k]="_X_"
self.tahtaYazdir()
else:
self.oyun_tahtasi[l][k]="_O_"
self.tahtaYazdir()
except:
print("1 ve 3 arasında değer giriniz.")
self.oynamaSırası(j)
self.kontrol(j)
j=j+1
XoXMain()
|
14f57e6c8cac248a3d52f5de26297134c8dc2228 | zHigor33/ListasDeExerciciosPython202 | /Estrutura de Repetição/L3E8.py | 343 | 3.734375 | 4 | verifyMedia = True
i = 1
sumOfNumbers = 0
while verifyMedia:
numbers = float(input("Informe o "+str(i)+"° número: "))
sumOfNumbers = sumOfNumbers + numbers
i = i + 1
if i == 6:
verifyMedia = False
avarage = sumOfNumbers / (i - 1)
print("A média dos números é "+str(avarage)+" e a soma é "+str(sumOfNumbers))
|
4972e7ff161e4e64f2031b6fbcd180b2ad54cff4 | xiaofengyvan/GarvinBook | /3.1/random_sampling.py | 392 | 3.53125 | 4 | import random
def RandomSampling(dataMat,number):
try:
slice = random.sample(dataMat, number)
return slice
except:
print 'sample larger than population'
def RepetitionRandomSampling(dataMat,number):
sample=[]
for i in range(number):
sample.append(dataMat[random.randint(0,len(dataMat)-1)])
return sample |
c0e714483ffac20c9bc44572b6f1311eaebb2346 | Th3-C0d3-I3r34k3r/Python_Basics | /34pyexcephandling.py | 1,625 | 4 | 4 | #Python Try Except
# try = this block lets you to test ablock of code for errors
# except = this block lets you to handle errors
# finally = this block lets you to ececute code,regardless of the result of the try=and except blocks
print ()
print (" **************************************")
print (" * Python Python Try-Except *")
print (" **************************************")
print ()
print ()
print (" PYTHON EXCEPTION HANDLING:")
print ("---------------------------")
print ()
try:
print(x)
except:
print("an exception occured")
# print(x) // Produces an error
print ()
print ()
print (" PYTHON MANY EXCEPTION:")
print ("-----------------------")
print ()
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
print ()
print ()
print (" PYTHON ELSE:")
print ("-------------")
print ()
print("else: - A block of code to be executed iof no errors were occured")
try:
print("Helo")
except:
print("Something wqent wrong")
else:
print("Nothing Went wrong")
print ()
print ()
print (" PYTHON FINALLY:")
print ("----------------")
print ()
print("finally: - it will be executed if the try block raises san error or not")
try:
print(x)
except:
print("Something went wrong")
finally:
print("Both try and except executed successfully")
print()
print()
print("AnotherExample:")
print()
try:
f = open("demofile.txt")
f.write("lorumIpsum")
except:
print("Something weent wrong when writing the file")
finally:
f.close()
|
c1b7fb9f359a19693bc1e2d7d979065c7a988ad1 | Windsooon/LeetCode | /Next Greater Element I.py | 755 | 3.640625 | 4 | class Solution:
def nextGreaterElement(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
if not nums1 or not nums2:
return []
dic = {}
stack = []
for i in range(len(nums2)):
while stack and stack[-1] < nums2[i]:
tem = stack.pop()
dic[tem] = nums2[i]
stack.append(nums2[i])
ans = []
for i in range(len(nums1)):
if nums1[i] in dic:
ans.append(dic[nums1[i]])
else:
ans.append(-1)
return ans
nums1 = [2,4]
nums2 = [1,2,3,4]
s = Solution()
print(s.nextGreaterElement(nums1, nums2))
|
9535ae66f72b181e74236016d945a067ca92a8fa | jkerw/Math-Adventures- | /rotTriangle.pyde | 744 | 3.890625 | 4 | def setup():
size(600,600)
rectMode(CENTER)
colorMode(HSB)
t = 0
def draw():
background(255)
global t
translate(width/2,height/2)
for i in range(90):
rotate(radians(360/90))
pushMatrix() #saves the orientation
#goes to circumference of circle
translate(200,0)
#spins each triangle
rotate(radians(t+2*i*360/90))
tri(100)
popMatrix() #return to saved orientation
strokeWeight(2)
stroke(3*i, 255, 255)
t += 0.5
def tri(length):
'''draws an equilateral triangle around center of triangle.'''
noFill()
triangle(0,-length,
-length*sqrt(3)/2, length/2,
length*sqrt(3)/2, length/2)
|
30dfb1be543c648cddd18d6999eefd4f3bf919a6 | Mhmdabed11/CrackingtheCodingInterviewExcercisesTypeScript | /stackOfPlates.py | 2,452 | 3.75 | 4 | class StackNode:
def __init__(self, data):
self.data = data
self.next = None
class Stack:
def __init__(self, data=None):
if(data == None):
self.top = None
self.length = 0
return
self.top = StackNode(data)
self.length = 1
def push(self, data):
if(self.top == None):
self.top = StackNode(data)
self.length = self.length+1
return
else:
item = StackNode(data)
item.next = self.top
self.top = item
self.length = self.length+1
def pop(self):
if(self.top == None):
raise Exception('Stack is empty')
else:
item = self.top
self.top = self.top.next
self.length = self.length-1
return item.data
def peek(self):
if(self.top == None):
raise Exception('Stack is empty')
else:
return self.top.data
def isEmpty(self):
return self.top == None
def getLength(self):
return self.length
class SetOfStacks:
def __init__(self, stackSize):
StackOne = Stack()
self.stackArray = [StackOne]
self.stackSize = stackSize
def push(self, data):
length = len(self.stackArray)
index = length - 1
if(self.stackArray[index].getLength() == self.stackSize):
newStack = Stack()
self.stackArray.append(newStack)
self.stackArray[index+1].push(data)
else:
self.stackArray[index].push(data)
def pop(self):
length = len(self.stackArray)
index = length-1
self.stackArray[index].pop()
if(self.stackArray[index].getLength() == 0):
del self.stackArray[index]
def popAt(self, index):
if(self.stackArray[index]):
self.stackArray[index].pop()
if(self.stackArray[index].getLength() == 0):
del self.stackArray[index]
MySetOfStacks = SetOfStacks(5)
MySetOfStacks.push(1)
MySetOfStacks.push(2)
MySetOfStacks.push(3)
MySetOfStacks.push(4)
MySetOfStacks.push(5)
MySetOfStacks.push(6)
MySetOfStacks.push(7)
MySetOfStacks.push(8)
MySetOfStacks.push(9)
MySetOfStacks.popAt(0)
MySetOfStacks.popAt(0)
MySetOfStacks.popAt(0)
MySetOfStacks.popAt(0)
MySetOfStacks.popAt(0)
MySetOfStacks.popAt(0)
MySetOfStacks.popAt(0)
print(MySetOfStacks.stackArray[0].top.data)
|
925803380192f40a71d2189c2bbd09e7f5fc1ba3 | greenfox-zerda-lasers/matheb | /week-03/day-3/01.py | 621 | 4.125 | 4 | # Create a `Circle` class that takes it's radius as cinstructor parameter
# It should have a `get_circumference` method that returns it's circumference
# It should have a `get_area` method that returns it's area
class Circle():
def __init__(self, radius):
self.radius = radius
def get_circumference(self):
self.circumference = self.radius*2*3.14
circumference = self.circumference
print (circumference)
def get_area(self):
return (self.radius ** 2) * 3.14
#area = self.area
#print(area)
first = Circle(1)
first.get_circumference()
first.get_area()
|
2fe25d827f8af83b2d2790cac7792638b0757668 | eddycaldas/python | /07-Strings-Methods/the-startswith-and-endswith-methods.py | 239 | 4.0625 | 4 |
another_string = 'Los pollitos dicen'
print(another_string.startswith("L"))
print(another_string.startswith("Lo"))
print(another_string.startswith("lo"))
print()
print(another_string.endswith('n'))
print(another_string.endswith('cen'))
|
71c21e274394859f7bad48b59a851bf49f90b9d4 | KataBharat/guvi | /codekata/check_difference_even_or_odd.py | 102 | 3.625 | 4 | a = [int(x) for x in input().split()]
if((abs(a[0]-a[1])%2==0)):
print("even")
else:
print("odd")
|
5f1c459bbe79e013ee973c5aa3524f1c95213c8f | natashagrasso/PARCIAL1 | /punto3.py | 666 | 3.5 | 4 | # Dado un vector con personaje de las películas de la saga de Star Wars resolver las
# siguientes actividades:
# a. Realizar un barrido recursivo del vector.
# b. Realizar una función recursiva que permita determinar si ‘Yoda’ está en el
# vector y en que posición.
personajes = ['hulk' , 'capitan america', 'yoda', 'leia' , 'batman']
def star_wars (personajes, pos):
if(pos < len(personajes) -1):
if (personajes [pos] == 'yoda'): #puntoB
print ('yoda se encuentra en la posicion: ', pos)
return pos
else:
return star_wars(personajes, pos+1)
else:
return -1
print(star_wars(personajes, 0 )) |
f6c1608bbaa69e0294e7dd57f484d4718cce9023 | adikabintang/kolor-di-dinding | /programming/basics/crackingthecodinginterview/trees_and_graphs/tries.py | 2,527 | 3.90625 | 4 | # https://www.geeksforgeeks.org/trie-insert-and-search/
# https://towardsdatascience.com/implementing-a-trie-data-structure-in-python-in-less-than-100-lines-of-code-a877ea23c1a1
class TrieNode:
def __init__(self, ch=None):
self.ch = ch
self.children = []
self.is_end_of_word = False
class Trie:
def __init__(self):
self.root = TrieNode()
def add_a_word(self, word: str):
ptr = self.root
for ch in word:
found = False
# instead of linear search for looking up the children,
# we can use a hashtable for the children
for child in ptr.children:
if ch == child.ch:
ptr = child
found = True
break
if not found:
ptr.children.append(TrieNode(ch))
ptr = ptr.children[-1]
ptr.is_end_of_word = True
def is_prefix_exist(self, prefix):
ptr = self.root
for c in prefix:
found = False
for child in ptr.children:
if c == child.ch:
found = True
ptr = child
break
if not found:
return False
return True
def get_all_str_with_prefix(self, prefix):
ptr = self.root
s = ""
arr = []
for c in prefix:
found = False
for child in ptr.children:
if c == child.ch:
s += c
found = True
ptr = child
break
if not found:
return arr
s = s[:-1]
arr = self.get_all_below_str_dfs(ptr)
for i in range(len(arr)):
arr[i] = s + arr[i]
return arr
def get_all_below_str_dfs(self, root: TrieNode, s=None, arr=None):
if s is None:
s = ""
if arr is None:
arr = []
if root:
s += root.ch
if root.is_end_of_word:
return [s]
for child in root.children:
arr.extend(self.get_all_below_str_dfs(child, s))
return arr
t = Trie()
t.add_a_word("abde")
t.add_a_word("abdf")
t.add_a_word("abg")
t.add_a_word("az")
# print(t.is_prefix_exist("ab"))
# print(t.is_prefix_exist("bc"))
# print(t.is_prefix_exist("ac"))
print(t.get_all_str_with_prefix("ab")) |
7c8f48004afdd70bc557e696495543203c4c37df | inJAJA/Study | /homework/딥러닝 교과서/pandas/pd04_series_append.py | 921 | 3.828125 | 4 | import pandas as pd
fruits = {'banana': 3, 'prange': 2}
series = pd.Series(fruits)
print(series)
# banana 3
# prange 2
# dtype: int64
'''요소 추가'''
# Series에 요소를 추가하려면 해당 요소도 Series형이어야 함
series = series.append(pd.Series([3], index = ['grape']))
print(series)
# banana 3
# prange 2
# grape 3
# dtype: int64
# 문제
index = ['apple', 'orange', 'banana','strawberry','kiwifruit']
data = [10, 5, 8, 12, 3]
series = pd.Series(data, index = index)
print(series)
# apple 10
# orange 5
# banana 8
# strawberry 12
# kiwifruit 3
# dtype: int64
# 추가
pineapple = pd.Series([12], index = ['pineapple'])
print(pineapple)
# pineapple 12
# dtype: int64
series = series.append(pineapple)
print(series)
# apple 10
# orange 5
# banana 8
# strawberry 12
# kiwifruit 3
# pineapple 12
# dtype: int64 |
1859ef43f26404490fad292003d132825c45dbdf | darrencheng0817/AlgorithmLearning | /Python/leetcode/BestMeetingPoint.py | 610 | 3.578125 | 4 | '''
Created on 1.12.2016
@author: Darren
'''
'''
A group of two or more people wants to meet and minimize the total travel distance. You are given a 2D grid of values 0 or 1, where each 1 marks the home of someone in the group. The distance is calculated using Manhattan Distance, where distance(p1, p2) = |p2.x - p1.x| + |p2.y - p1.y|.
For example, given three people living at (0,0), (0,4), and (2,2):
1 - 0 - 0 - 0 - 1
| | | | |
0 - 0 - 0 - 0 - 0
| | | | |
0 - 0 - 1 - 0 - 0
The point (0,2) is an ideal meeting point, as the total travel distance of 2+2+2=6 is minimal. So return 6.
'''
|
a1f47d9cade2c149a42c4db3eb5a6fbe139361e1 | Damian1724/Data-Structure | /MyLinkedList.py | 1,951 | 3.734375 | 4 | /*
Author:Damian Cruz
*/
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class MyLinkedList:
def __init__(self):
self.head = Node()
self.tail = self.head
self.size=0
def enqueue(self, data):
self.size += 1
self.tail.next = Node(data)
self.tail = self.tail.next
def lenght(self):
return self.size
def get(self, index):
if index >= self.size or index < 0:
raise Exception("ERROR: Index out of range")
current = self.head
pos = 0
while pos <= index:
pos += 1
current = current.next
return current.data
def dequeue(self, index):
if index >= self.size or index < 0:
raise Exception("ERROR: Index out of range")
self.size -= 1
current= self.head
pos = 0
while pos <= index:
last_node = current
current = current.next
pos += 1
last_node.next = current.next
def reverse(self):
if self.size >= 2:
output = Node(self.head.data)
while self.head.next is not None:
self.head = self.head.next
aux = output
add_node = Node(self.head.data)
output = add_node
output.next = aux
self.head = output
elif self.size == 0:
raise Exception("The LinkedList is empty")
else:
raise Exception("The LinkedList has just one element")
def get_linked_list(self):
if self.size > 0:
current = self.head.next
lista = []
while current.next is not None:
lista.append(current.data)
current = current.next
lista.append(current.data)
return lista
else:
raise Exception("The LinkedList is empty")
|
6f647f71e356180e141ff1473fa7b21ce0d2f1f1 | mathlot/mathlot | /demo/numerical_physics/bisection.py | 339 | 3.6875 | 4 | '''
Created on 2014.4.17
@author: YT
'''
def fun(x):
return x**2-x-1
def bisection(error_bound=0.05):
a = 1
b = 2
while abs(a-b) >= error_bound:
c = (a+b)/2.
if fun(c)*fun(a) < 0:
b = c
else:
a = b
b = c
print "bisection method: x = %.3f"%b
bisection() |
3b93cf57ba30c768031b9770473d6d8d7632dc94 | billgoo/LeetCode_Solution | /Top Interview Questions/Backtracking/51. N-Queens.py | 3,822 | 3.78125 | 4 | #
# @lc app=leetcode id=51 lang=python3
#
# [51] N-Queens
#
# https://leetcode.com/problems/n-queens/description/
#
# algorithms
# Hard (53.54%)
# Likes: 3935
# Dislikes: 122
# Total Accepted: 294.4K
# Total Submissions: 549.7K
# Testcase Example: '4'
#
# The n-queens puzzle is the problem of placing n queens on an n x n chessboard
# such that no two queens attack each other.
#
# Given an integer n, return all distinct solutions to the n-queens puzzle. You
# may return the answer in any order.
#
# Each solution contains a distinct board configuration of the n-queens'
# placement, where 'Q' and '.' both indicate a queen and an empty space,
# respectively.
#
#
# Example 1:
#
#
# Input: n = 4
# Output: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
# Explanation: There exist two distinct solutions to the 4-queens puzzle as
# shown above
#
#
# Example 2:
#
#
# Input: n = 1
# Output: [["Q"]]
#
#
#
# Constraints:
#
#
# 1 <= n <= 9
#
#
#
# @lc code=start
class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
self.result = []
board = ["." * n for _ in range(n)]
self.backtrack(board, 0)
return self.result
def backtrack(self, board, row):
n = len(board)
if row == n:
self.result.append(board[:])
return
for col in range(n):
if self.isValid(board, row, col):
board[row] = board[row][:col] + "Q" + board[row][col + 1:]
self.backtrack(board, row + 1)
board[row] = board[row][:col] + "." + board[row][col + 1:]
def isValid(self, board, row, col):
n = len(board)
# 验证上方列
for i in range(row):
if board[i][col] == "Q":
return False
# 验证左上
for i, j in zip(range(row - 1, -1, -1), range(col - 1, -1, -1)):
if board[i][j] == "Q":
return False
# 验证右上
for i, j in zip(range(row - 1, -1, -1), range(col + 1, n)):
if board[i][j] == "Q":
return False
return True
# @lc code=end
class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
self.res = []
self.backtrack(["." * n for _ in range(n)], 0, [], [], [])
return self.res
def backtrack(self, board: List[str], row: int, col_set: List[int],
left_set: List[int], right_set: List[int]) -> None:
if row == len(board):
self.res.append(board[:])
for c in range(len(board)):
if not self.isValid(row, c, col_set, left_set, right_set):
continue
# add
board[row] = board[row][:c] + "Q" + board[row][c + 1:]
# col_set.append(c)
# left_set.append(r - c)
# right_set.append(r + c)
# recursion
self.backtrack(board[:], row + 1, col_set[:] + [c],
left_set[:] + [row - c], right_set[:] + [row + c])
# remove
board[row] = board[row][:c] + "." + board[row][c + 1:]
# col_set.pop()
# left_set.pop()
# right_set.pop()
return
def isValid(self, row: int, col: int, col_set: Set[int], left_set: Set[int], right_set: Set[int]) -> bool:
# 从上到下从左到右,row/col 都增大
# 故仅需检查:列上部分、左上、右上
# 列:c in col_set, len = n
# 左上:r - c in left_set, len = n: r - c = (r - 1) - (c - 1)
# 右上:r + c in right_set, len = n: r + c = (r - 1) + (c + 1)
if col in col_set:
return False
if row - col in left_set:
return False
if row + col in right_set:
return False
return True
|
7f82b6f53580bb7ccd8b219f00b97cdef866dae7 | hoyj/ProjectEuler | /12.py | 3,191 | 3.921875 | 4 | '''
Project Euler Problem #12
The sequence of triangle numbers is generated by adding the natural numbers.
ex) the 7th triangle number would be 1 + 2 + 3 + ... + 7 = 28.
The first ten terms would be: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
Let us list the factors of the first seven triangle numbers:
1: 1
3: 1,3
6: 1,2,3,6
10:1,2,5,10
15:1,3,5,15
21:1,3,7,21
28:1,2,4,7,14,28
We can see that 28 is the first triangle number to have over five divisors.
What is the value of the first triangle number to have over five hundred divisors?
'''
from functools import reduce
import operator
from time import time
# Approach:
# find the number of factors in the given triangle number
# -> find prime factorization
# -> add 1 to exponents & multiply the exponents
# how to find prime factorization?
# -> find primes then divide
# Using the prime_number generator from Problem 10...
def isPrime(n):
if n == 1:
return False
elif n in [2, 3]:
return True
for d in range(2, int(pow(n, 1/2)) + 1):
if n % d == 0:
return False
return True
def prime_number_generator():
n = 3
yield 2
yield 3
while True:
n += 2
if isPrime(n):
yield n
def triangle_number_generator():
n = 0
offset = 1
while True:
n += offset
offset += 1
yield n
def primeFactorization(n):
'''
input: n, int
output: list of (a,b) sets
desc: find prime factorization of n
'''
if n == 1: return [(1,1)]
p_gen = prime_number_generator()
pf = []
p = next(p_gen)
while n != 1: # add prime test
exp = 0
while n % p == 0:
exp += 1
n = n // p
if exp != 0:
pf.append((p, exp))
p = next(p_gen)
return pf
def numberOfFactors(pf):
'''
input: prime factorization of n, list of (a,b) sets
output: number of factors, int
desc: exponents + 1 and multiply all exponents to get number of factors
'''
return reduce(operator.mul, [exp+1 for p, exp in pf])
def stringify(pf):
s = ''
for p,exp in pf:
s += str(p) + '^' + str(exp) + ('*' if (p,exp) != pf[-1] else '')
return s
def try1():
gen = triangle_number_generator()
while True:
n = next(gen)
pf = primeFactorization(n)
nf = numberOfFactors(pf)
if nf > 500:
print(n,':', stringify(pf), '# of factors:', nf)
break
def try2():
'''
different approach by 코딩허접
This approach utilizes the fact that factors come in pairs.
'''
number = 1
add = 2
count = 0
while True:
t_number = int(number**0.5)
if t_number == number**0.5:
count+=1
for i in range(1, t_number+1):
if number%i == 0:
count+=2
if count >= 500:
print("%d: %d"%(number, count))
break
number += add
add += 1
count = 0
def timer(f):
start = time()
f()
end = time() - start
print(f, '-- %s seconds --' % round(end, 2))
if __name__ == '__main__':
timer(try1)
timer(try2)
|
74412e044df353a4f7a9efc47a45ed8cab9718de | makrandp/python-practice | /Other/Companies/Amazon/AmazonBlind/FetchItemsToDisplay.py | 2,686 | 4.375 | 4 | '''
An online shopping website contains one to many items on each page. To mimic the logic of the website, a programmer has a list of items and each item has its name, relevance, and price. After sorting the items by (name: 0, relevance: 1, price: 2), the programmer is trying to find out a list of items displayed in a chosen page. Given a list of items, the sort column, the sort order (0: ascending, 1: descending), the number of items to be displayed in each page, and a page number,
write an algorithm to determine the list of item names in the specified page while respecting the item's order (Page number starts at 0).
Input
The input consists of three arguments:
sortParameter: an integer representing the value used for sorting (0 for the name, 1 for relevance, 2 for price)
sortOrder: an integer representing the order of sorting (0 for ascending order and 1 descending order)
itemsPerPage: an integer representing the number of items per page
pageNumber: an integer representing the page number
numOfItems: an integer representing the number of items
items: a map of string as key representing the name and pair of integers as values representing the relevance, price
Output
Return a list of strings representing the item names on the requested page in the order they are displayed.
Constraints
1 <= numOfItems < 10^5
0 <= relevance, price < 10^8
0 <= pageNumber < 10
Note
itemsPerPage is always greater than 0, and is always less than the minimum of numOfItems and 20.
Examples
Example 1:
Input:
sortParameter = 1
sortOrder = 0
itemsPerPage = 2
pageNumber = 1
numOfItems = 3
items = [["item1", 10, 15], ["item2", 3, 4]. ["item3", 17, 8]]
Output: ["item3"]
Explanation:
There are 3 items.
Sort them by relevance(sortParameter = 1) in ascending order items = [["item2", 3, 4], ["item1", 10, 15], ["item3", 17, 8]].
Display up to 2 items on each page.
The page 0 contains 2 item names ["item2", "item1"] and page 1 contains only 1 item name ["item3"].
So, the output is "item3".
'''
class Solution():
def fetchItemsToDisplay(self, sortParam: int, sortOrder: int, itemsPerPage: int, pageNumber: int, items):
# What we are going to do is first just sort everything, then we are going to skip (itemsPerPage)*(pageNumber-1) items
# O(nlogn) time complexity ( from sorting ), and O(n) space complexity (again from sorting).
s = sorted(items, reverse=(True if sortOrder else False), key=lambda t: t[sortParam])
return s[(itemsPerPage)*(pageNumber):(itemsPerPage)*(pageNumber + 1)]
s = Solution()
itemsToDisplay = s.fetchItemsToDisplay(1,0,2,0, [["item1", 10, 15], ["item2", 3, 4], ["item3", 17, 8]])
print(itemsToDisplay) |
40246f84c3ce47b9234f5b0edd7e3db200fbc8ad | ivyson10/CANA | /funcbin.py | 165 | 3.59375 | 4 |
t = int(input())
while (t >= 0 ):
cont = 0
num = int(input())
print(num)
while (num%2 != 0):
if (num%2 == 1):
cont = cont +1
print(cont)
t = t-1
|
234a5e24a91af26c3923ba70f3849b0bb08887ef | 7Aishwarya/HakerRank-Solutions | /Python/alphabet_rangoli.py | 2,000 | 3.890625 | 4 | '''You are given an integer, N. Your task is to print an alphabet rangoli of size N.
(Rangoli is a form of Indian folk art based on creation of patterns.)
Different sizes of alphabet rangoli are shown below:
#size 3
----c----
--c-b-c--
c-b-a-b-c
--c-b-c--
----c----
#size 5
--------e--------
------e-d-e------
----e-d-c-d-e----
--e-d-c-b-c-d-e--
e-d-c-b-a-b-c-d-e
--e-d-c-b-c-d-e--
----e-d-c-d-e----
------e-d-e------
--------e--------
'''
def print_rangoli(size):
# your code goes here
n=size
c=96
dash=n
alpha=n
t=[]
q=0
for i in range(1,n+1):
for j in range(1,(2*dash)-1):
print("-",end='')
for k in range(i):
print(chr(c+alpha),end='')
if(q==1):
print("-",end="")
if(i>1):
t.append(chr(c+alpha))
alpha=alpha-1
t.reverse()
L=len(t)
count=1
for j in range(1,L):
print(t[count],end='')
if(j!=L-1):
print("-",end="")
count+=1
for j in range(((2*dash)-2)):
print("-",end='')
print()
c=96
dash=dash-1
alpha=n
t=[]
q=1
c2=96
dash2=2
alpha2=n
t2=[]
for i in range(n,0,-1):
if(i<n):
print('-',end='')
for j in range(1,(2*dash2)-2):
print("-",end='')
for k in range(i):
print(chr(c2+alpha2),end='')
if(k!=i):
print("-",end='')
t2.append(chr(c2+alpha2))
alpha2=alpha2-1
t2.reverse()
L=len(t2)
count=1
for j in range(1,L):
print(t2[count],end='-')
count+=1
for j in range(1,(2*dash2)-2):
print("-",end='')
print()
c2=96
dash2=dash2+1
alpha2=n
t2=[]
if __name__ == '__main__': |
87912cc5cbcea8b7fdae7a4e9f70f6c81152d436 | Nadaaqrtl/Tugas-Struktur-Data | /R.1.6.py | 192 | 3.921875 | 4 | def squared_odd_sum(n):
sum = 0
for number in range(n):
if number%2 == 0:
continue
sum =sum + number**2
return sum
print(squared_odd_sum(12))
|
925821fcd82a5155babaefe1c3f93f15ff2c47b9 | gffryclrk/ThinkPython2e | /ch12/ex12_10_3.py | 2,150 | 4.3125 | 4 | """
Exercise 3
Two words form a “metathesis pair” if you can transform one into the other by swapping two letters; for example, “converse” and “conserve”. Write a program that finds all of the metathesis pairs in the dictionary. Hint: don’t test all pairs of words, and don’t test all possible swaps. Solution: http://thinkpython2.com/code/metathesis.py. Credit: This exercise is inspired by an example at http://puzzlers.org.
"""
import pdb
import itertools
def anagram_dict(filename):
anagrams = {}
for line in open(filename):
word = line.strip()
key = tuple(sorted(word))
anagram_list = anagrams.get(key, [])
anagram_list.append(word)
anagrams[key] = anagram_list
return anagrams
def check_meta_pair(s1, s2):
"""
This function takes two anagrams and returns a boolean of whether they are metathesis pairs
"""
swaps = []
for t1, t2 in zip(s1, s2):
if t1 is not t2:
swaps.append( (t1, t2) )
if(len(swaps) > 2): return False
return swaps[0][0] is swaps[1][1] and swaps[0][1] is swaps[1][0]
print("Meta pairs converse, conserve: {}".format(check_meta_pair('converse', 'conserve')))
print("Meta pairs tags, stag: {}".format(check_meta_pair('tags', 'stag')))
"""
My approach to this puzzle is to use the list of anagrams from previous exercies
because the metathesis pairs are by definitions anagrams of each other.
So, looping through the sets of anagrams and for each combination of two, finding out if
a pair is a metathesis pair
"""
anagrams = anagram_dict("ch9/words.txt") # This file reference, of course, depends on where you're running this script from
print("{} anagrams found".format(len(anagrams)))
metathesis_pairs = []
for key in anagrams:
anagram_list = anagrams[key]
for pair in itertools.combinations(anagram_list, 2):
if check_meta_pair(pair[0], pair[1]): metathesis_pairs.append( (pair[0], pair[1]) )
print("{} metathesis pairs found!".format(len(metathesis_pairs)))
print("Some examples:")
for index, pair in zip(range(100), metathesis_pairs):
print(pair, end=' ')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.