blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
ac54a80869c640e1f07dbc364b7f000c2cb24b0d | pinobatch/little-things-nes | /rgb121/tools/bitbuilder.py | 6,272 | 3.890625 | 4 | #!/usr/bin/env python3
"""
"""
from __future__ import with_statement, print_function
def log2(i):
return int(i).bit_length() - 1
class BitBuilder(object):
def __init__(self):
self.data = bytearray()
self.nbits = 0 # number of bits left in the last byte
def append(self, value, length=1):
"""Append a bit string."""
assert(value < 1 << length)
while length > 0:
if self.nbits == 0:
self.nbits = 8
self.data.append(0)
lToAdd = min(length, self.nbits)
bitsToAdd = (value >> (length - lToAdd))
length -= lToAdd
self.nbits -= lToAdd
bitsToAdd = (bitsToAdd << self.nbits) & 0xFF
self.data[-1] = self.data[-1] | bitsToAdd
def appendRemainder(self, value, divisor):
"""Append a number from 0 to divisor - 1.
This writes small numbers with floor(log2(divisor)) bits and large
numbers with ceil(log2(divisor)) bits.
"""
nBits = log2(divisor)
# 2 to the power of (1 + nBits)
cutoff = (2 << nBits) - divisor
if value >= cutoff:
nBits += 1
value += cutoff
self.append(value, nBits)
def appendGamma(self, value, divisor=1):
"""Add a nonnegative integer in the exp-Golomb code.
Universal codes are a class of prefix codes over the integers that
are optimal for variables with a power-law distribution. Peter Elias
developed the "gamma code" in 1975, and it has become commonly used
in data compression. First write one fewer 0 bits than there are
binary digits in the number, then write the number. For example:
1 -> 1
2 -> 010
3 -> 011
4 -> 00100
...
21 -> 000010101
This function modifies the gamma code slightly by encoding value + 1
so that zero has a code.
The exp-Golomb code is a generalization of Peter Elias' gamma code to
support flatter power law distributions. The code for n with divisor
M is the gamma code for (n // M) + 1 followed by the remainder code
for n % M. To write plain gamma codes, use M = 1.
"""
if divisor > 1:
remainder = value % divisor
value = value // divisor
value += 1
length = log2(value)
self.append(0, length)
self.append(value, length + 1)
if divisor > 1:
self.appendRemainder(remainder, divisor)
def appendGolomb(self, value, divisor=1):
"""Add a nonnegative integer in the Golomb code.
The Golomb code is intended for a geometric distribution, such as
run-length encoding a Bernoulli random variable. It has a parameter
M related to the variable's expected value. The Golomb code for n
with divisor M is the unary code for n // M followed by the remainder
code for n % M.
Rice codes are Golomb codes where the divisor is a power of 2, and
the unary code is the Golomb code with a divisor of 1.
"""
if divisor > 1:
remainder = value % divisor
value = value // divisor
self.append(1, value + 1)
if divisor > 1:
self.appendRemainder(remainder, divisor)
def __bytes__(self):
return bytes(self.data)
def __len__(self):
return len(self.data) * 8 - self.nbits
@classmethod
def test(cls):
testcases = [
(cls.append, 0, 0, b''),
(cls.append, 123456789, 0, None),
(cls.append, 1, 1, b'\x80'),
(cls.append, 1, 2, b'\xA0'),
(cls.append, 3, 4, b'\xA6'),
(cls.append, 513, 10, b'\xA7\x00\x80'), # with 7 bits left
(cls.appendRemainder, 5, 10, b'\xA7\x00\xD0'),
(cls.appendRemainder, 6, 10, b'\xA7\x00\xDC'), # with 0 bits left
(cls.appendGolomb, 14, 9, b'\xA7\x00\xDC\x68'),
]
bits = BitBuilder()
if bytes(bits) != b'':
print("fail create")
for i, testcase in enumerate(testcases):
(appendFunc, value, length, result) = testcase
try:
appendFunc(bits, value, length)
should = bytes(bits)
except AssertionError:
should = None
if should != result:
print("BitBuilder.test: line", i, "failed.")
print(''.join("%02x" % x for x in bits.data))
return False
return True
def remainderlen(value, divisor):
nBits = log2(divisor)
cutoff = (2 << nBits) - divisor
if value >= cutoff:
nBits += 1
return nBits
def gammalen(value, divisor=1):
return 1 + 2*log2((value // divisor) + 1) + remainderlen(value % divisor, divisor)
def golomblen(value, divisor=1):
return 1 + value // divisor + remainderlen(value % divisor, divisor)
def biterator(data):
"""Return an iterator over the bits in a sequence of 8-bit integers."""
for byte in data:
for bit in range(8):
byte = (byte << 1)
yield (byte >> 8) & 1
byte = byte & 0xFF
class Biterator(object):
def __init__(self, data):
self.data = iter(data)
self.bitsLeft = 0
def __iter__(self):
return self
def read(self, count=1):
accum = 0
while count > 0:
if self.bitsLeft == 0:
self.bits = next(self.data)
self.bitsLeft = 8
bitsToAdd = min(self.bitsLeft, count)
self.bits <<= bitsToAdd
accum = (accum << bitsToAdd) | (self.bits >> 8)
self.bits &= 0x00FF
self.bitsLeft -= bitsToAdd
count -= bitsToAdd
return accum
__next__ = read
@classmethod
def test(cls):
src = Biterator([0xBA,0xDA,0x55,0x52,0xA9,0x0E])
print("%x" % src.read(12),)
print("%x mother shut your mouth" % src.read(12))
print("zero is", next(src))
print("%x is donkey" % src.read(12))
print("one thirty five is", src.read(10))
print("zero is", next(src))
try:
next(src)
except StopIteration:
print("stopped as expected")
else:
print("didn't stop.")
if __name__=='__main__':
print("Testing BitBuilder")
BitBuilder.test()
print("Testing Biterator")
Biterator.test()
|
5bc1f0ccb1d818d5350e1f986ab7ac973ae727cb | whirlkick/assignment8 | /jj1745/investment.py | 936 | 3.5625 | 4 | '''
Created on Nov 7, 2015
@author: jj1745
'''
import numpy as np
class instrument(object):
'''
Create the object of an investment instrument
the instrument is determined by how many shares the investor holds.
the value of each investment is then computed accordingly
'''
def __init__(self, num_shares):
'''
Constructor
'''
self.num_shares = num_shares #number of shares to buy
self.position_value = 1000 / self.num_shares #the value of each investment
def generateOneDay(self):
'''
simulate the outcome of one day of investment
'''
cumu_ret = 0
for s in range(self.num_shares):
r = np.random.rand()
if r <= 0.51:
cumu_ret = cumu_ret + 2 * self.position_value #if the coin is head, then my position value doubles
return cumu_ret
|
1d3e70307afeea8a02f453d066aaf6e2f61de560 | chaosWsF/Python-Practice | /leetcode/1022_sum_of_root_to_leaf_binary_numbers.py | 1,574 | 4.09375 | 4 | """
You are given the root of a binary tree where each node has a value 0 or 1. Each root-to-leaf path
represents a binary number starting with the most significant bit. For example, if the path is
0 -> 1 -> 1 -> 0 -> 1, then this could represent 01101 in binary, which is 13.
For all leaves in the tree, consider the numbers represented by the path from the root to that leaf.
Return the sum of these numbers. The answer is guaranteed to fit in a 32-bits integer.
Example 1:
https://assets.leetcode.com/uploads/2019/04/04/sum-of-root-to-leaf-binary-numbers.png
Input: root = [1,0,1,0,1,0,1]
Output: 22
Explanation: (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22
Example 2:
Input: root = [0]
Output: 0
Example 3:
Input: root = [1]
Output: 1
Example 4:
Input: root = [1,1]
Output: 3
Constraints:
1. The number of nodes in the tree is in the range [1, 1000].
2. Node.val is 0 or 1.
"""
class TreeNode:
"""Definition for a binary tree node."""
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def sumRootToLeaf(self, root: TreeNode) -> int:
def preorder(tree: TreeNode, res: int) -> int:
if not tree:
return 0
res += res + tree.val
if not (tree.left or tree.right):
return res
else:
return preorder(tree.left, res) + preorder(tree.right, res)
return preorder(root, 0)
|
ceca8d13c0bd8d92960d375ac5f5f335f053e2bf | dengyings/biji | /NLP/双向最大匹配法.py | 1,799 | 3.640625 | 4 |
#正向最大匹配法
class MM(object):
def __init__(self):
self.max_size = 3
def cut(self, text):
result=[]
index=0
text_len = len(text)
dic = ['研究','研究生','生命','命','的','起源']
while text_len > index:
for size in range(self.max_size+index,index,-1):
piece = text[index:size]
if piece in dic:
index = size-1
break
index += 1
result.append(piece)
return result
# 逆向最大匹配
class RMM(object):
def __init__(self):
self.max_size = 3
def cut(self, text):
result = []
index = len(text)
dic = ['研究', '研究生', '生命', '命', '的', '起源']
while index > 0:
for size in range(index - self.max_size, index):
piece = text[size:index]
if piece in dic:
index = size + 1
break
index -= 1
result.append(piece)
result.reverse()
return result
if __name__ == '__main__':
text = '研究生命的起源'
count1 = 0
count2 = 0
First = MM()
Second = RMM()
a = First.cut(text)
b = Second.cut(text)
print("正向最大匹配结果",a)
print("反向最大匹配结果",b)
if a == b:
print(a)
lena = len(a)
lenb = len(b)
if lena == lenb:
for DY1 in a:
if len(DY1) == 5:
count1 = count1 + 1
for DY2 in b:
if len(DY2) == 5:
count2 = count2 + 1
if count1 > count2:
print(b)
else:
print(a)
if lena > lenb:
print(b)
if lena < lenb:
print(a)
|
6380ddde36cf959db9188f3d029ef8b5b52dc4a5 | Fateeeeee/demo | /join函数合并字符串.py | 380 | 3.734375 | 4 | '''
1、join()函数
语法: 'sep'.join(seq)
参数说明
sep:分隔符。可以为空
seq:要连接的元素序列、字符串、元组、字典
上面的语法即:以sep作为分隔符,将seq所有的元素合并成一个新的字符串
'''
test = ["I", "Like", "Python"]
print(test)
print("".join(test)) # 表示分隔符为空合并字符串数组为一个字符串 |
458276d2efba99f4f4b051151d0b2a0682ae07e1 | mshekhar/random-algs | /epi_solutions/arrays/insert-delete-getrandom-o1.py | 2,058 | 3.84375 | 4 | import random
class RandomizedSet(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.ele_as_list = []
self.ele_idx_map = {}
def insert(self, val):
"""
Inserts a value to the set. Returns true if the set did not already contain the specified element.
:type val: int
:rtype: bool
"""
if val in self.ele_idx_map:
return False
self.ele_as_list.append(val)
self.ele_idx_map[val] = len(self.ele_as_list) - 1
return True
def remove(self, val):
"""
Removes a value from the set. Returns true if the set contained the specified element.
:type val: int
:rtype: bool
"""
if val not in self.ele_idx_map:
return False
ele_counter = self.ele_idx_map.pop(val)
if ele_counter == len(self.ele_as_list) - 1:
self.ele_as_list.pop()
else:
self.ele_as_list[ele_counter] = self.ele_as_list.pop()
self.ele_idx_map[self.ele_as_list[ele_counter]] = ele_counter
return True
def getRandom(self):
"""
Get a random element from the set.
:rtype: int
"""
return self.ele_as_list[random.randint(0, len(self.ele_as_list) - 1)]
@classmethod
def generic_runner(cls, oper, val, expected):
obj = RandomizedSet()
c = 1
for op, v in zip(oper[1:], val[1:]):
res = getattr(obj, op)(*v)
print op, v, expected[c], res, expected[c] == res
c += 1
null = None
true = True
false = False
print RandomizedSet.generic_runner(
["RandomizedSet", "insert", "remove", "insert", "getRandom", "remove", "insert", "getRandom"],
[[], [1], [2], [2], [], [1], [2], []],
[null, true, false, true, 2, true, false, 2])
# Your RandomizedSet object will be instantiated and called as such:
# obj = RandomizedSet()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom()
|
25175b36f6928f869f97a079e6d2ed1669c12174 | sanashahin2225/ProjectEuler | /projectEuler6.py | 695 | 3.765625 | 4 | # The sum of the squares of the first ten natural numbers is,
# (1^2 + 2^2 + 3^2 + ... 10^2) = 385
# The square of the sum of the first ten natural numbers is,
# (1+2+3+ ... 10)^2 = 55^2 = 3025
# Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is .
# 3025 - 385 = 2640
# Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
def defiiferenceSum(n):
d = 1
a = 1
S = (2 * a + (n - 1) * d) * int(n/2)
sq = int((n * (n+1)* (2 * n + 1))/6)
return((S ** 2) - sq)
print(defiiferenceSum(100)) |
e4bd91eaa4af430568e24bbaac488ab98e2dd503 | eselyavka/python | /reducer.py | 573 | 3.515625 | 4 | #!/usr/bin/env python
import sys
def reducer():
(iterator, max_duration) = (None, -sys.maxint)
for line in sys.stdin:
(year, duration) = line.strip().split(';')
if iterator and iterator != year:
print "%s\t%s" % (iterator, max_duration)
(iterator, max_duration) = (year, int(duration))
else:
(iterator, max_duration) = (year, max(max_duration, int(duration)))
if iterator:
print "%s\t%s" % (iterator,max_duration)
def main():
reducer()
if __name__=='__main__':
main()
|
08c2424b1e0a4d16d234ce30af4ca21cc877e626 | DevangSharma/D-Encryptor | /D-Encrypter main.py | 393 | 3.625 | 4 | from functions import *
print("Welcome! to D-Encryptor \nHere you can encode a message for someone else end at the other end one can decrypt "
"it as well")
n = input("Press Enter to continue \n")
test_input(n, "")
print(" 1 : Encryption \n 2 : Decryption")
task = int(input("Please select your task : "))
test_input_range(task, 1, 2)
if task - 1:
decrypt()
else:
encrypt()
|
53ff13cf6c30c553b647374f69771cadf960cd7e | Damodharan5/Data_structures | /Huffman Tree/treee.py | 991 | 3.65625 | 4 | m = ""
d = {}
class _Tree_node():
def __init__(self):
self.left = None
self.right = None
self.ch = False
self.count = 0
def _traverse(root,value):
global m
global d
m+=value
if root.left == None or root.right == None:
d[root.ch] = m
else:
_traverse(root.left,'0')
m=m[:-1]
_traverse(root.right,'1')
m=m[:-1]
def _create_Tree(listt):
while len(listt)>1:
listt = sorted(listt,key=lambda x: x[1],reverse=True)
a = _Tree_node()
if len(listt[-1]) == 2:
(x1,y1) = listt[-1]
a.left = _Tree_node()
a.left.ch = x1
a.left.count = y1
else:
(x1,y1,z1) = listt[-1]
a.left = z1
if len(listt[-2]) == 2:
(x2,y2) = listt[-2]
a.right = _Tree_node()
a.right.ch = x2
a.right.count = y2
else:
(x2,y2,z2) = listt[-2]
a.right = z2
listt.pop()
listt.pop()
a.count = y1+y2
listt.append((a.ch,a.count,a))
return a
if __name__ == '__main__':
l = [('b',11),('c',8),('d',12),('e',49)]
gg = _create_Tree(l)
_traverse(gg,"")
print(d)
|
d5ff0d704d84bd58ec2a07ec537a1639166bf6ee | bakliwalvaibhav1/python_basic_udemy | /3_Greatest_of_Three/greatest_of_three.py | 185 | 4.0625 | 4 | a= int(input('Enter First Number'))
b= int(input('Enter Second Number'))
c= int(input('Enter Third Number'))
if b<= a >=c:
print(a)
elif a<= b >=c:
print (b)
else:
print(c)
|
676ce06b56afda9d8860f681fa0108b8949ba89d | wujam/neu_cs_sdev | /Santorini/Design/observermanager.py | 831 | 3.984375 | 4 | from abc import ABC, abstractmethod
""" ObserverManager manages Observers """
class ObserverManager(ABC):
def __init__(self):
pass
@abstractmethod
def add_observer(self, observer):
""" Adds an observer.
:param Observer observer: an Observer to be added
"""
pass
@abstractmethod
def remove_all_observers(self):
""" Removes all observers """
pass
@abstractmethod
def notify_all(self, fun_name, *args, **kwargs):
""" Notifies all observers by calling the given function
on all observers. If an observer misbehaves they will be
booted.
:param String fun_name: name of function to call
:param list args: arguments of function
:param list kwargs: keyword arguments of function
"""
pass
|
bad94eddd40c0b9b909706a83cb7fc1cb5d3cf89 | AceRodrigo/CodingDojoStuffs | /Python_Stack/_python/python_fundamentals/Rodriguez_Austin_VS_Functions_Intermediate_2.py | 3,254 | 4.0625 | 4 | #Challenge 1: Update Values in Dictionaries and Lists
x= [ [5,2,3], [10,8,9] ]
students = [
{'first_name': 'Michael', 'last_name': 'Jordan'},
{'first_name': 'John', 'last_name': 'Rosales'}
]
sports_directory = {
'basketball' : ['Kobe', 'Jordan', 'James', 'Curry'],
'soccer' : ['Messi', 'Ronaldo', 'Rooney']
}
z = [ {'x':10, 'y':20}]
# #a Change the value 10 in x to 15. Once you're done, x should now be [[5,2,3],[15,8,9]]
def funcA(lst, idx, chgVal):
# print(lst)
lst[idx[0]][idx[1]] = chgVal
print(lst)
return lst
funcA(x, [1,0],15 )
# #b Change the last_name of the first student from 'Jordan' to 'Bryant'
students = [
{'first_name': 'Michael', 'last_name': 'Jordan'},
{'first_name': 'John', 'last_name': 'Rosales'}
]
#shorter version to change it to anything
def funcB(lst, lstname):
lst[0]['last_name'] = lstname
print(lst)
funcB(students, 'Bryant')
# #c In the sports_directory, change 'Messi' to 'Andres'
sports_directory = {
'basketball': ['Kobe', 'Jordan', 'James', 'Curry'],
'soccer': ['Messi', 'Ronaldo', 'Rooney']
}
def funcC(my_dict, keyname, idx, val):
print(my_dict)
my_dict[keyname][idx]=val
print(my_dict)
funcC(sports_directory, 'soccer', 0, 'andress')
# #b Change the value 20 in z to 30
z = [{'x': 10, 'y': 20}]
def funcD(lst,idx, mykey, val):
lst[idx][mykey]=val
print(lst)
funcD(z, 0, 'y', 30)
#2
students = [
{'first_name': 'Michael', 'last_name': 'Jordan'},
{'first_name': 'John', 'last_name': 'Rosales'},
{'first_name': 'Mark', 'last_name': 'Guillen'},
{'first_name': 'KB', 'last_name': 'Tonel'}
]
def iterateDict(some_list):
for i in range(len(some_list)):
print(some_list[i])
return some_list
iterateDict(students)
should output: (it's okay if each key-value pair ends up on 2 separate lines
bonus to get them to appear exactly as below!)
first_name - Michael, last_name - Jordan
first_name - John, last_name - Rosales
first_name - Mark, last_name - Guillen
first_name - KB, last_name - Tonel
#3
students = [
{'first_name': 'Michael', 'last_name': 'Jordan'},
{'first_name': 'John', 'last_name': 'Rosales'},
{'first_name': 'Mark', 'last_name': 'Guillen'},
{'first_name': 'KB', 'last_name': 'Tonel'}
]
def iterateDict2(key_name, some_list):
for i in range(len(some_list)):
print(some_list[i][key_name])
return 'first_name','last_name'
iterateDict2('first_name', students)
iterateDict2('last_name', students)
# 4
dojo = {
'locations':['San Jose','Seattle','Dallas','Chicago','Tulsa','DC','Burbank'],
'instructors':['Michael','Amy','Eduardo','Josh','Graham','Patrick','Minh','Devon']
}
numbLocations = 0
numbInstructors = 0
def printinfo(lst):
print(len(lst['locations']),"Locations")
for i in range(len(lst['locations'])):
# print('entered i loop')
print(lst['locations'][i])
numbLocations = len(lst['locations'])
print(len(lst['instructors']), "Instructors")
for j in range(len(lst['instructors'])):
# print('entered j loop')
print(lst['instructors'][j])
numbInstructors = len(lst['instructors'])
return numbLocations, numbInstructors
printinfo(dojo)
|
312f1f97e1f569ba3f5fbad5dde881e497fe2aa4 | akcauser/Python | /education_07032020/015_if_else_elif.py | 285 | 3.890625 | 4 |
a = 10
b = 10
if a < b:
print("a küçüktür b")
elif a == b:
print("a eşittir b")
else:
print("a küçük değildir b")
print("bitti")
"""
> büyüktür
< küçüktür
>= büyük eşittir
<= küçük eşittir
== eşittir
!= eşit değildir
""" |
ab14b905c7221f16d1837859b8400c3282e7ebb3 | psmano/pythonworks | /pyworks/readTxtFile.py | 138 | 3.96875 | 4 | #Reading the Text File
filename = input('Enter File Name: ')
file = open(filename,mode='r')
text = file.read()
file.close()
print(text)
|
6c7cd043fb4915cab0c157e5d79028a4e42f2dca | hyybuaa/AlgorithmTutorial | /ReConstructBinaryTree.py | 1,400 | 3.671875 | 4 | # -*- coding:utf-8 -*-
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 返回构造的TreeNode根节点
def reConstruBinaryTree(self, pre, tin):
node = self.construBinaryTree(pre, 0, len(pre)-1, tin, 0, len(tin)-1)
return node
def construBinaryTree(self, pre, ps, pe, tin, ts, te):
"""
重构二叉树
:param pre: 前序列表
:param ps: 前序起点
:param pe: 前序终点
:param tin: 中序列表
:param ts: 中序起点
:param te: 中序终点
:return:
"""
if ps > pe:
return None
value = pre[ps]
# 检查中序的根结点是否一致
index = ts
while(ts<=te and tin[index]!=value):
index += 1
while(ts>te):
return None
node = TreeNode(value)
# 左子树的节点个数为index-ts+1
# 右子树的节点个数为te-index+1
node.left = self.construBinaryTree(pre, ps+1, ps+index-ts,tin, ts, index-1)
node.right = self.construBinaryTree(pre, ps+index-ts+1, pe, tin, index+1, te)
return node
if __name__ == "__main__":
pre = [1,2,4,7,3,5,6,8]
tin = [4,7,2,1,5,3,8,6]
solution = Solution()
result = solution.reConstruBinaryTree(pre, tin)
print(result) |
9771f08b07549eaae1ed47e400efad008fe10504 | Anupaul24/pythonclasses | /src/list.py | 890 | 3.9375 | 4 |
# l=("apple","mango","grapes","banana","kiwi")
# print(l)
# l.append("papaya")
# l.append("lichi")
# l1=[1,2,3,4]
# l.extend(l1)
# l.insert(0,"watermelon")
# print(l)
# l.remove(l[2])
# l.pop()
# print(l)
# print(l[2:5])
# print(len(l))
# l={"apple","mango","grapes","banana","kiwi"}
l={1,3,5,6,7,3,5}
print(l)
s={1,2,4,6,8,9}
l=l.union(s)
print(l)
l=l.intersection(s)
print(l)
l2=l.difference(s)
print(l2)
# l1={1,2,3,6,8,9}
# l2=l.union(l1)
# print(l2)
# l2.remove(3)
# print(l2)
# print(len(l2))
# l2=l.intersection(l1)
# print(l2)
# l2=l.difference(l1)
# print(l2)
# l3={7,9,10,11}
# l2.update(l3)
# print(l2)
# dict = {
# "brand": "Ford",
# "electric": False,
# "year": 1964,
# "colors": ["red", "white", "blue"]
# }
# dict["speed"]=180
# print(dict)
# x=dict["year"]
# print(x)
# dict.pop("speed")
# print(dict)
# for x in dict.values():
# print(x)
|
75ecdd8457bd6c9df240912616db1ff3360520cf | afuyo/PREDICT400 | /Python/graphs.py | 1,298 | 4.4375 | 4 | import matplotlib.pyplot
from matplotlib.pyplot import *
import numpy
from numpy import linspace
# The example shows how to plot a system of consistent equations.
# This is Example 1 Section 2.1 of Lial. The function linspace divides the
# interval [-1,15] into 100 points. For each value in x, y1 and y2 will have
# a corresponding value based on the calculations shown below.
#x= linspace(0,200,100)
#y1= 0.25*x +30
#y2= 0.3*x +25
# Plots can be built up in layers. What follows shows how to plot individual
# colored lines. plt.legend will associate the indicated equations to the
# preceding plt.plot statements. The order of appearance must be the same.
# loc=3 places the legend in the lower left corner.
#figure()
#xlabel('x-axis')
#ylabel('y-axis')
#plot (x, y1, 'r')
#plot (x, y2, 'b')
#legend (('Plan A y=0.25x +30','Plan B y=0.3x +25'),loc=4)
#title ('Comparing Cell Phone Companies')
#show()
x=linspace(0,100,20)
y1=30.0- 0.66*x
y2=60.0- 1.5*x
figure()
xlabel('x-axis')
ylabel('y-axis')
plot (x,y1,'r')
plot (x,y2,'b')
legend(('2x+3y=90','3x+2y=120'),loc='best')
show()
x=linspace(0,100,20)
y1=21-1.5*x
y2=12-0.4*x
y3=8
figure()
xlabel('x-axis')
ylabel('y-axis')
plot (x,y1,'r')
plot (x,y2,'b')
plot(x,y3,'g')
legend(('30x+20y=420','10x+25y=300','0x+1y=8'),loc='best')
show() |
2010d8904d749091e6a7866805a1d0f556b4d388 | Soujash-123/SAGNIK | /Sequence_Analyzer.py | 1,183 | 3.953125 | 4 | print("Enter the first 3 digits")
a=int(input("1"))
b=int(input("2"))
c=int(input("3"))
dr4=0
rr4=0
l=0
if 2*b==(a+c):
print("the series is in AP")
d=b-a
print(c+d,"is the next term")
dr4=c+d
elif b**2==(a*c):
print("The series is in GP")
d=b//a
print(c*d,"is the next term")
dr4=c*d
else:
print("special series")
l=int(input("Enter another number"))
found=False
while(found==False):
d1=b-a
d2=c-b
d3=l-c
dr=d2-d1
dr2=d3-d2
if dr==dr2:
print("lw")
dr4=l+(d3+dr2)
print(dr4)
break
else:
r1=b//a
r2=c//b
r3=l//c
rr=r2//r1
rr2=r3//r2
if rr==rr2:
print("Nw")
rr4=l*(r3*rr2)
print(rr4)
break
else:
print("Invalid Sequence")
reschk=int(input("Let's Check, enter orignal final value"))
if dr4==0:
dr4=rr4
print("Predicted Value",dr4)
d=abs(dr4-reschk)
percentage=(100-d)//100 *100
print("Accuracy",percentage,"%")
|
d7526178e964cba7b1acada57d5ae6605d3b892f | krishnasairam/sairam | /cspp1-assignments/m14/2/poker.py | 2,389 | 3.890625 | 4 | ''' Write a program to evaluate poker hands and determine the winner
Read about poker hands here.
https://en.wikipedia.org/wiki/List_of_poker_hands'''
def is_straight(ranks):
''' straight '''
return len(set(ranks)) == 5 and (max(ranks) -min(ranks) == 4)
def is_flush(hand):
suit = hand[0]
for h_input in hand:
if suit[1] != h_input[1]:
return False
return True
def card_rank(hand):
ranks =sorted(['--23456789TJQKA'.index(c) for c,s in hand],reverse=True)
return ranks
def kind(ranks,n):
for r in ranks:
if ranks.count(r)==n:
return r
return 0
def two_pair(ranks):
one = kind(ranks,2)
two = kind(sorted(ranks),2)
if one and two:
return (one,two)
return None
def hand_rank(hand):
'''
You will code this function. The goal of the function is to
return a value that max can use to identify the best hand.
As this function is complex we will progressively develop it.
The first version should identify if the given hand is a straight
or a flush or a straight flush.
'''
ranks = card_rank(hand)
if is_straight(ranks) and is_flush(hand):
return (8,ranks)
if kind(ranks,4):
return (7,kind(ranks,4),ranks)
if kind(ranks,3) and kind(ranks,2):
return (6,kind(ranks,3),kind(ranks,2))
if is_flush(hand):
return(5,ranks)
if is_straight(ranks):
return(4,ranks)
if kind(ranks,3):
return (3,kind(ranks,3),ranks)
if two_pair(ranks):
return(2,two_pair(ranks),ranks)
if kind(ranks,2):
return(1,kind(ranks,2),ranks)
return (0,ranks)
def poker(hands):
'''
This function is completed for you. Read it to learn the code.
Input: List of 2 or more poker hands
Each poker hand is represented as a list
Print the hands to see the hand representation
Output: Return the winning poker hand
'''
return max(hands, key=hand_rank)
if __name__ == "__main__":
# read the number of test cases
COUNT = int(input())
# iterate through the test cases to set up hands list
HANDS = []
for x in range(COUNT):
line = input()
ha = line.split(" ")
HANDS.append(ha)
# test the poker function to see how it works
print(' '.join(poker(HANDS)))
|
f40e65df26eecce167f7b456b1c38d640f2ecbf8 | im-greysen/afs505_u1 | /project/game_of_life.py | 4,480 | 3.890625 | 4 | """Conway's Game of Life Python Script.
.. module:: AFS505_U1 Project_01
:platform: Windows
:synopsis: This is a Python3 script for Conway's Game of Life, a cellular automation program that implements
rules designed to mimic a cellular lifeform. Thi specific program achieves this goal by using a matrix with 30 rows
and 80 columns. This zero player game will run for the user-specified amount of ticks, ticks in this case refers. to the
number of generations
.. moduleauthor:: Greysen W. Danae greysen.danae@wsu.edu
.. modulereviewer: Nicole Rouleau nicole.rouleau@wsu.edu
"""
# reviewerscore: 100
from sys import argv
def first_grid(grid, locations):
"""Activates grid cells by converting 0s to 1s within the starting grid.
:param locations: the locations of the cell index in each row and column
:param grid: establishes the dimensions of the matrix
:type locations: string
:type grid: list
:return: A 30x80 matrix that has all active cells representing values of 1
:rtype: A 2400 element list with specified elements having a value of 1
"""
for live in locations:
i, j = live.split(':') # numbers in command line are split if there is a colon separation
grid[int(i)-1][int(j)-1] = 1
def print_grid(grid, rows, cols):
"""Establishes a 30x80 matrix and converts elements with values of 0 to '-'
and elements with values of 1 to 'X', simultaneously preserving numerical values.
:param grid: gives the size of the matrix
:param rows: an integer for the quantity of rows
:param cols: an integer for the quantity of columns
:type grid: string
:type rows: int
:type cols: int
:return: a matrix of '-' & 'X' symbols specified by the command line inputs
:rtype: a list of 2400 elements of either '-' or 'X' symbols
"""
for i in range(rows - 1):
for j in range(cols - 1):
if grid[i][j] == 1: print("X", end = "")
if grid[i][j] == 0: print("-", end = "")
print() # prints the '-' and 'X' values
print() # prints the 30x80 matrix
def active_grid(grid, rows, cols):
"""A new grid matrix is created with 0 for all elements followed by application
of Conway's rules to activate cells and retuns the activated grid.
:param grid: gives the size of the matrix
:param rows: an integer for the quantity of rows
:param cols: an integer for the quantity of columns
:type grid: string
:type rows: int
:type cols: int
:return: a grid matrix with '-' and 'X' characters specified in command line
:rtype: a list of 2400 elements containing either '-' or 'X' characters
"""
next_grid = [[0] * cols for i in range(rows)] # creates new null grid matrix
for i in range(rows - 1):
for j in range(cols - 1):
neighbor = int(grid[i - 1][j - 1]) + \
int(grid[i][j - 1]) + int(grid[i + 1][j - 1]) + int(grid[i - 1][j]) + \
int(grid[i + 1][j]) + int(grid[i - 1][j + 1]) + int(grid[i][j + 1]) + \
int(grid[i + 1][j + 1]) # takes the summation of the neighbors in the specified cell locations
if grid[i][j] == 1 and neighbor < 2:
next_grid[i][j] = 0
elif grid[i][j] == 1 and (neighbor == 2 or neighbor == 3):
next_grid[i][j] = 1
elif grid[i][j] == 1 and neighbor > 3:
next_grid[i][j] = 0
elif grid[i][j] == 0 and neighbor == 3:
next_grid[i][j] = 1
return(next_grid)
def main(argv):
"""Takes comand line inputs while reading the code and runs with the specified inputs.
:param argv: the argument vector
:type argv: a list
:return: nothing
:rtype: nothing
"""
script = argv[0] # calls the specified script
ticks = int(argv[1]) # the number of generation cycles
locations = argv[2:] # the specified cells in the grid matrix to be activated
rows = 31 # the number of rows in the grid matrix
cols = 81 # the number of columns in the grid matrix
grid = [[0] * cols for i in range(rows)] # establishes the null value grid matrix
tick = 0 # the number of ticks run by the program
first_grid(grid, locations)
print_grid(grid, rows, cols)
while tick < ticks:
grid = active_grid(grid, rows, cols) # implements rules and presents the resulting changes
print_grid(grid, rows, cols)
tick += 1
if __name__ == "__main__":
main(argv)
|
03c059fc12a78f89df01583aded1f4f34651faa4 | zhangchizju2012/LeetCode | /217.py | 425 | 3.71875 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 24 11:13:19 2017
@author: zhangchi
"""
class Solution(object):
def containsDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
dic = {}
for item in nums:
if item in dic:
return True
else:
dic[item] = 1
return False
|
6bfad8728604a59149501b535c522e0ce90c65e7 | H-Cong/LeetCode | /83_RemoveDuplicatesFromSortedList/83_RemoveDuplicatesFromSortedList.py | 645 | 3.796875 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
curr = head
while curr and curr.next:
if curr.val == curr.next.val:
curr.next = curr.next.next
else:
curr = curr.next # this has to be under else instead of getting excuted in every while loop
return head
# TC: O(N)
# As each node in the list is checked exactly once
# SC: O(1)
# No extra space is used
|
cbf1a93f60f8e83b95115e3c428da2a3ce0d3a57 | Bighetto/EstudosCursoPython | /7-Operadores de Atribuição.py | 715 | 4.0625 | 4 | x = 20
# Atribuir mais quantidade a variavel "x"
# Maneira Basica: x = x + 10
x += 10
y = 10
y -= 5
#Sinal "+=" é o valor de x mais o valor colocado e ja da o resultado.
#Sinal "-=" é o valor de x menos o valor colocado e ja da o resultado.
z= 10
z *= 5
#Serve também para multiplicação."*=" é multiplicado por ... = valor.
w = 50
w /= 5
#Serve também para Divisão."/=" é dividido por ... = valor.
v = 10
v %= 4
print (v)
''' Neste caso a porcentagem funciona exemplo: quantas vezes o numero consegue se multiplicar
dentro do valor dele, e o resultado é o que sobra.
No caso do exemplo "v" o 4 é multiplicado por 2 = 8, sobra 2.
O resultado que ele vai dar é o que sobra, no caso 2.
'''
|
d5a0fd23a5bab282d65c3ac782ee297856d46fa8 | otavioacb/ProjetoMulticomandoMiniRobos | /Esp8266/Motor/motor.py | 1,058 | 3.84375 | 4 | from machine import Pin,PWM
class Motor:
"""
This class is an attempt to represent
a DC Motor for ESP8266 to controll
its movements.
Pwm Pin -> Controll the motor speed.
Dir Pin -> Controll the motor direction.
"""
def __init__(self, pin_pwm, pin_dir):
"""
Accepts a pwm pin value and direction pin value.
"""
self.__pwm = PWM(Pin(pin_pwm), freq=1000, duty = 0)
self.__dir= Pin(pin_dir, Pin.OUT)
def __repr__(self):
return "<Motor object>"
def spd(self, value):
"""
Accepts a speed value to controll the DC Motor.
"""
self.__pwm.duty(value)
def dir(self, direction = 0):
"""
Accepts a direction value to controll the DC Motor.
"""
if direction == 1:
self.__dir.off()
elif direction == 0:
self.__dir.on()
else:
print("Error! Please, inform just 1 or 0 as direction value.")
|
dd736d14583bf81ea55a5e95940b0db5fb1749a8 | FerCremonez/College-1st-semester- | /renata_a2_e1.py | 133 | 3.890625 | 4 | num1=int(input('Insira o primeiro número:'))
num2=int(input('Insira o segundo número:'))
calc=num1+num2
print('Resultado:',calc) |
476854314ccef8b6065284e2c092d39406b4b02b | AleksandraSzoldra/PpI | /cw3.py | 165 | 3.546875 | 4 | a=int(input("Podaj a: "))
b=int(input("Podaj b: "))
c=int(input("Podaj c: "))
p=(a+b+c)*0.5
P=(p*(p-a)*(p-b)*(p-c))**0.5
print ("Pole trójkąta wynosi: ",P) |
d1382a2301d7aba71c63e5b22e19550b256cd211 | egewarth/uri | /1005.py | 98 | 3.625 | 4 | a = float(input())
b = float(input())
m=((a*3.5)+(b*7.5))/11.0
print("MEDIA = {0:.5f}".format(m))
|
56feb0aaa6156317635579e561f7654c56028663 | chaitanyaPaikara/Py_Workspace | /Py_AI/Path_search.py | 2,726 | 3.875 | 4 | # ----------
# User Instructions:
#
# Define a function, search() that returns a list
# in the form of [optimal path length, row, col]. For
# the grid shown below, your function should output
# [11, 4, 5].
#
# If there is no valid path from the start point
# to the goal, your function should return the string
# 'fail'
# ----------
# Grid format:
# 0 = Navigable space
# 1 = Occupied space
grid = [[0, 0, 1, 0, 0, 0],
[0, 0, 1, 0, 0, 0],
[0, 0, 1, 0, 1, 0],
[0, 0, 1, 0, 1, 0],
[0, 0, 0, 0, 1, 0]]
'''
grid = [[0, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 1, 0],
[0, 1, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
[0, 1, 0, 0, 1, 0]]
'''
init = [0, 0]
goal = [len(grid)-1, len(grid[0])-1]
unit_cost = 1
check = [[0 for row in range(len(grid[0]))] for col in range(len(grid))]
expand = [[-1 for row in range(len(grid[0]))] for col in range(len(grid))]
action = [[' ' for col in range(len(grid[0]))] for row in range(len(grid))]
action[0][0] = 's'
action[len(grid)-1][len(grid[0])-1] = 'g'
delta = [[-1, 0,'^'], # go up
[ 0,-1,'<'], # go left
[ 1, 0,'v'], # go down
[ 0, 1,'>']] # go right
delta_name = ['^', '<', 'v', '>']
def search(grid,init,goal,unit_cost):
path = []
time = 0
init.append(0)
path.append(init)
check[path[0][0]][path[0][1]] = 1
while path:
# print path, "\t"+str(time)
for j in delta:
new = [path[0][0] + j[0],path[0][1] + j[1],path[0][2]]
if new[0] >= 0 and new[1] >= 0 and new[0] < 5 and new[1] < 6:
if check[new[0]][new[1]] is 0 and grid[new[0]][new[1]] is 0:
if new[0] == goal[0] and new[1] == goal[1]:
new[2]+=unit_cost
expand[new[0]][new[1]] = time
return new
else:
new[2]+=unit_cost
path.append(new)
#action[new[0]][new[1]] = j[2]
action[path[0][0]][path[0][1]] = j[2]
check[new[0]][new[1]] = 1
elif grid[new[0]][new[1]] is 1:
expand[new[0]][new[1]] = -1
del path[0]
expand[path[0][0]][path[0][1]] = time
time+=unit_cost
'''
def traversal(action):
current = init
while current is not goal:
for j in delta:
new = [current[0] + j[0],current[1] + j[1]]
if new[0] >= 0 and new[1] >= 0 and new[0] < 5 and new[1] < 6:
if action[new[0]][new[1]] is not ' ':
'''
print search(grid,init,goal,unit_cost)
'''
for z in action:
print z
for z in expand:
print z
'''
|
fda0c3328176210ca6baee89dd7005e6c2c52455 | sdjukic/GamazeD | /Geometry.py | 2,231 | 4.125 | 4 | from math import sqrt
class Point(object):
"""Class that defines Point structure in 2D Cartesian space."""
def __init__(self, *args):
self._x_coordinate = args[0]
self._y_coordinate = args[1]
def get_x(self):
return self._x_coordinate
def get_y(self):
return self._y_coordinate
def set_x(self, new_x):
self._x_coordinate = new_x
def set_y(self, new_y):
self._y_coordinate = new_y
def euclidean_distance(self, other):
return sqrt((self._x_coordinate - other.get_x())**2 + (self._y_coordinate - other.get_y())**2)
class LineSegment(object):
"""Class that defines Line Segment in 2D Cartesian space."""
def __init__(self, *points):
self.end_points = []
self.end_points.append(Point(points[0][0], points[0][1]))
self.end_points.append(Point(points[1][0], points[1][1]))
self.segment_length = self.end_points[0].euclidean_distance(self.end_points[1])
self._coefficient_a = self.end_points[1].get_y() - self.end_points[0].get_y()
self._coefficient_b = self.end_points[0].get_x() - self.end_points[1].get_x()
self._coefficient_c = self._coefficient_a * self.end_points[0].get_x() + self._coefficient_b * self.end_points[0].get_y()
def do_intersect(self, other):
determinant = 1.0 * self._coefficient_a * other._coefficient_b - other._coefficient_a * self._coefficient_b
if not determinant:
return False, Point(float("inf"), float("inf"))
else:
intersection_x = (other._coefficient_b * self._coefficient_c - self._coefficient_b * other._coefficient_c) / determinant
intersection_y = (other._coefficient_c * self._coefficient_a - self._coefficient_c * other._coefficient_a) / determinant
return True, Point(intersection_x, intersection_y)
def _in_segment(self, point):
"""Function that checks whether point is in the segment."""
distance_from_endpoints = 0
for p in self.end_points:
distance_from_endpoints += point.euclidean_distance(p)
return abs(distance_from_endpoints - self.segment_length) < 0.05 |
60787fa80a2f65113c0816b317ae77b2c6b6d4df | horeilly1101/countdown | /countdown/display_text.py | 1,802 | 4.21875 | 4 | """File that contains various responses to the player."""
RULES: str = f"""
WELCOME TO COUNTDOWN
You will be given 6 numbers and a goal number.
Your task: Use the 6 numbers to get as close to the
goal number as possible.
You may add, subtract, multiply, and divide the given numbers,
but the result MUST be an integer. You don't have to use all
of the numbers, but you can't use any numbers that haven't
been given. The order of the numbers in your answer does not
matter.
Give your solution as an algebraic expression (e.g. 5 * 6 + 9).
You may use parentheses.
Good luck! Press ENTER to begin.
"""
def START_ROUND(round_num, cards, goal) -> str:
return f"""
Round {round_num}:
Your cards are {[card for card in cards]}.
Your goal is {goal}.
Your answer: """
PARSE_ERROR: str = """
Your answer was unable to be parsed! Please try again in the
next round.
"""
INVALID_NUMBERS_ERROR: str = """
Your answer included number(s) that weren't given! Please try
again in the next round.
"""
EVALUATION_ERROR: str = """
Your input expression did not evalute to an integer! Please try
again in the next round.
"""
def CORRECT_ANSWER(expression, result) -> str:
return f"""
Congratulations!
You submitted {expression} = {result}, which was exactly
correct.
"""
def INCORRECT_ANSWER(expression, result, goal_expression, goal_result) -> str:
return f"""
You submitted {expression} = {result}.
Our solution was {goal_expression} = {goal_result}.
You were {abs(result - goal_result)} away!
"""
CONTINUE_PLAYING: str = f"""
Would you like to play again? (y/n)
"""
END_GAME: str = f"""
Thanks for playing!
"""
|
db601f8a3e9f753385daccec2db0d3d4102b28ee | IronE-G-G/algorithm | /leetcode/101-200题/144preorderTraversal.py | 1,659 | 4.09375 | 4 | """
144 二叉树的前序遍历
给定一个二叉树,返回它的 前序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,2,3]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-preorder-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
# 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 preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
前序遍历:中左右
递归
"""
if not root:
return []
if not root.left and not root.right:
return [root.val]
left = self.preorderTraversal(root.left)
right = self.preorderTraversal(root.right)
return [root.val] + left + right
class Solution1(object):
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
前序遍历:中左右
栈方法
"""
if not root:
return []
if not root.left and not root.right:
return [root.val]
stack = [root]
res = []
while stack:
node = stack.pop()
res.append(node.val)
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return res
|
0cf8acb30cf69b4da998fc0ce8ca21678c5417b2 | henrryyanez/web_practicas | /Python_L1_Bucles.py | 181 | 3.953125 | 4 | # For Loops
seq = [1,2,3,4,5,6]
for henrry in seq:
# Code here
print(henrry)
# For Loops
seq = [1,2,3,4,5,6]
for henrry in seq:
# Code here
print('HOLA')
|
aa434379f4026a6fb42a643f3c50ebb3b7101ea0 | lelencho/Homeworks | /Examples from Slides/Lesson 7 Python Collections/DefaultDict.py | 154 | 3.625 | 4 | from collections import defaultdict
def some():
return [1, 2, 3]
d = defaultdict(some)
d['a'] = 1
d['b'] = 2
d['c'] = 3
print(d['ddd']) |
19e2ee55734d5e00e1990eb03b947a157e033e93 | asxzhy/Leetcode | /leetcode/question_824/solution_1.py | 819 | 3.90625 | 4 | """
I firstly separeted the sentence to a list of words. Then for every word, I checked if the first letter is a vowel. If it's a vowel, then do the correspongind conversion for the
word. If it is not a vowel, do the other conversion. Join the list back together and return the sentence
"""
class Solution:
def toGoatLatin(self, S: str) -> str:
S = S.split() # seperate the words
for i in range(0, len(S)):
if S[i][0] in "aeiouAEIOU": # if the word starts with a vowel, add ma to the end and then add some amount of a
S[i] = S[i] + "ma" + "a" * (i + 1)
else: # if the word starts with consonant, add the first letter to the end and then add ma
S[i] = S[i][1:] + S[i][0] + "ma" + "a" * (i + 1)
return " ".join(S)
|
2cf9359f79f58aca55b561f6b7ebade244fac5fc | chrisglencross/advent-of-code | /aoc2019/day6/day6.py | 1,728 | 3.546875 | 4 | #!/usr/bin/python3
# Advent of code 2019 day 6
import copy
with open("input.txt") as f:
lines = f.readlines()
# Build dictionary object -> set(orbiters)
direct_orbits = {}
for line in lines:
parts = line.strip().split(")")
if parts[0] in direct_orbits:
direct_orbits[parts[0]].add(parts[1])
else:
direct_orbits[parts[0]] = set([parts[1]])
# Part 1
indirect_orbits = copy.deepcopy(direct_orbits)
# Inefficient - would be better to have the direct_orbits
# dictionary inverted and have a count_descendents recursive function
# that returns the number of descendents of each node, caching the result.
modified = True
while modified:
modified = False
for orbited, orbiters in indirect_orbits.items():
for orbiter in list(orbiters):
new_orbiters = set(indirect_orbits.get(orbiter, set()))
new_orbiters.difference_update(orbiters)
if new_orbiters:
orbiters.update(new_orbiters)
modified = True
count = 0
for orbiter in indirect_orbits.values():
count = count + len(orbiter)
print(count)
# Part 2
def find_orbit(orbiter):
# Again, this would be better if the direct_orbits dictionary was inverted
# Not my finest solution.
for l, rs in direct_orbits.items():
if orbiter in rs:
return l
return None
def find_chain(orbiter):
result = []
while True:
orbiter = find_orbit(orbiter)
if orbiter is None:
break
result.insert(0, orbiter)
return result
you_chain = find_chain("YOU")
san_chain = find_chain("SAN")
while you_chain[0] == san_chain[0]:
you_chain.pop(0)
san_chain.pop(0)
print(len(you_chain) + len(san_chain))
|
ab56e30d81daa7f4accadfe6b74ab0bd04d1f67b | ryanswong/Python-git | /U3L1.1 Shopping List Lab.py | 2,240 | 3.953125 | 4 | shopping_list = [] # pylint: disable=locally-disabled, invalid-name
def invalid_input():
print "That\'s not a valid answer, try again. "
def print_list():
print '\n' + 'Grocery List: [' + ', ' .join(shopping_list) + ']' '\n'
def appender():
response = raw_input("What item do you want to add to your list?" + '\n')
if len(response) > 0:
shopping_list.append(response)
else:
invalid_input()
def deleter():
'''this code if to delete items from the list'''
response = raw_input("what item do you want to DELETE from your list?"\
" type name, or the position number" + '\n')
if (response.isalpha()) and (response in shopping_list):
item_index = shopping_list.index(response)
shopping_list.pop(item_index)
print shopping_list
elif (response.isalpha()) and (response not in shopping_list):
invalid_input()
deleter()
elif type(int(response)) == int and (0 < int(response) <= len(shopping_list)):
item_index = response
shopping_list.pop(int(item_index) - 1)
print shopping_list
else:
invalid_input()
deleter()
def del_empty():
y_n = raw_input("Do you want to delete an item (type 1)," \
" or empty the entire list (type 2)?" + '\n')
if y_n == "1":
deleter()
print_list()
modify_list()
if y_n == "2":
y_n = raw_input("Are you sure you want to delete the whole list?" + '\n')
if y_n == "y":
del shopping_list[:]
print_list()
make_list()
elif y_n == "n":
modify_list()
def modify_list():
y_n = raw_input("Do want want to add another item? " \
"Reply with y for yes, and n if you want to delete" + '\n')
if y_n == "y":
appender()
print_list()
modify_list()
elif y_n == "n":
del_empty()
invalid_input()
modify_list()
def make_list():
y_n = raw_input("Do you want to make a grocery list? Reply with y or n" + '\n')
if y_n == "y":
appender()
print_list()
modify_list()
invalid_input()
make_list()
make_list()
|
bdada98295d49c879919accd40b4781b09c3ec29 | SchaeStewart/cis115 | /092916/tempCheck.py | 257 | 4.03125 | 4 | #Schaffer Stewart, Alan Skonieczny, Nathan Dabbs
#09/29/16
#Temperature Check
temp = float(input("Please enter the temperature: "))
if temp > 70:
print("Temperature is too hot")
elif temp < 40:
print("Temperature is too cold")
else:
print("Temperature is just right")
|
d7a6822736ad617146908f3f984c2d070451b32b | JeffHritz/practice | /wage_calculator.py | 820 | 4.15625 | 4 | # wage_calculator.py - Jeff Hritz
"""
This module gathers inputs and calculates your paycheck based on your hourly wage, how many hours you work,
tax rates, and pay-check deductions.
"""
pay_rate = int(input("Pay rate: "))
hours_worked = float(input("Hours worked: "))
tax_rate = float(.1981)
deductions = float(6.47)
gross_pay = (hours_worked * pay_rate)
total_deduction = ((gross_pay * tax_rate) - deductions)
net_pay = (gross_pay - total_deduction)
print("-----------")
print("Here are your paycheck details:")
print("Pay rate - %s" % round(pay_rate, 2))
print("Hours work - %s" % hours_worked)
print("Tax Rate - %s" % (tax_rate * 100) + "%")
print("Deductions - %s" % "$" + str(deductions))
print("==")
print("Gross Pay - %s" % "$" + str(gross_pay))
print("Net Pay - %s" % "$" + str(net_pay))
|
1278b1f058a4cbf9d3b0d309530536c8fbb8a981 | brunoliberal/exercises | /stacks_and_queues/animal_shelter.py | 1,761 | 3.625 | 4 | from linked_list.likedlist2 import LinkedList
class AnimalShelter:
dogs = LinkedList()
cats = LinkedList()
# Time O(n). Space O(1)
def enqueue(self, name, type):
if name:
if type == 'dog':
self.dogs.add(name)
self.cats.add(None)
elif type == 'cat':
self.cats.add(name)
self.dogs.add(None)
# Time O(n). Space O(1)
def dequeue(self, type):
if type == 'dog':
stk_sch, stk_rm = self.dogs, self.cats
else:
stk_sch, stk_rm = self.cats, self.dogs
aux_s, aux_r = stk_sch.head, stk_rm.head
if aux_s and aux_s.value: # maybe use a method in list to remove from idx (don't exist yet)
stk_rm.remove()
return stk_sch.remove()
while aux_s.next and not aux_s.next.value:
aux_s, aux_r = aux_s.next, aux_r.next
if aux_s.next and aux_s.next.value:
v = aux_s.next.value
aux_s.next, aux_r.next = aux_s.next.next, aux_r.next.next
return v
# Time O(1). Space O(1)
def dequeueAny(self):
dog = self.dogs.remove()
cat = self.cats.remove()
return dog if dog else cat
def __str__(self):
return 'dogs:' + str(self.dogs) + ' cats:' + str(self.cats)
# Tests:
# shelter = AnimalShelter()
# shelter.enqueue('Bobby', 'dog')
# shelter.enqueue('Mingau', 'cat')
# shelter.enqueue('Branco', 'dog')
# shelter.enqueue('Pretinha', 'dog')
#
# print(shelter)
# print(shelter.dequeue('cat'))
# print(shelter)
# print(shelter.dequeue('dog'))
# print(shelter)
# print(shelter.dequeueAny())
# print(shelter)
# print(shelter.dequeueAny())
# print(shelter)
# print(shelter.dequeueAny())
|
a99e63ef261494e89df6d3107c739583ebe1c289 | selam-weldu/algorithms_data_structures | /leet_code/python/searching/find_max_in_inc_dec_array.py | 539 | 3.765625 | 4 | def find_max_element(arr):
if len(arr) == 0:
raise Error('No elements in the input array')
if len(arr) == 1:
return arr[0]
if len(arr) == 2:
return max(arr[0], arr[1])
low = 0
high = len(arr) - 1
while low < high:
mid = (low + high) / 2
# Compare mid's neighbors
if arr[mid - 1] < arr[mid] and arr[mid] > arr[mid + 1]:
# Found max
return arr[mid]
elif arr[mid -1] < arr[mid]:
low = mid
else:
high = mid |
3a332ffa33a722f4896abba811763f43148e7b3e | SuperEnderSlayerr/STV-algorism | /algorithm.py | 1,179 | 3.5 | 4 | '''
Ender (Michael Hanks)
STV algorithm implimentation.
'''
import random
class algorithm:
def __init__(self, candidates_with_parties, votes):
self.candidates_with_parties = candidates_with_parties
self.votes = votes
self.candidates = []
parties = list(candidates_with_parties.keys())
for party in parties:
self.candidates.extend(candidates_with_parties[party])
def generate_random_votes(candidates_with_parties, voter_count):
votes = {}
for i in range(voter_count):
votes[i] = []
parties = list(candidates_with_parties.keys())
random.shuffle(parties)
for party in parties:
rand_votes = candidates_with_parties[party].copy()
random.shuffle(rand_votes)
[votes[i].append(item) for item in rand_votes]
return votes
def main():
random.seed(69)
candidates_with_parties = {'Mammal': ['Dog', 'Cat'], 'Other': ['Bird', 'Fish']}
voter_count = random.randint(500, 1000)
votes = generate_random_votes(candidates_with_parties, voter_count)
system = algorithm(candidates_with_parties, votes)
if __name__ == '__main__':
main() |
529a16d183525118688b752d6831f8ce51ce9750 | yingxingtianxia/python | /PycharmProjects/my_practice/untitled1/9.py | 345 | 3.546875 | 4 | #!/usr/bin/env python3
# -*-coding: utf8-*-
favorite_languages = {
'jen':'python',
'seach':'c',
'kenji':'ruby',
'chihiro':'html',
}
#print('Seach~s favorite language is '+ favorite_languages['seach'].title())
for name, language in favorite_languages.items():
print(name.title() + "'s favorite language is " +language.title()) |
c60fe6aba196f419b9bfaa7f840fc05ac002d84e | melanie197/PROGRAMACION-APLICADA-P57.py | /apenfileconwhile.py | 316 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Feb 8 17:06:54 2021
@author: pc
"""
file=open("devices.txt","a")
while True:
newItem=input("Ingrese nuevo dispositivo: ")
if newItem=="exit":
print("LISTPO" +"\n")
break
else:
file.write(newItem+"\n")
file.close()
|
99f858d6dcfdeb60d3c19657ec7a5724dbff6fc0 | WilliamFWG/Warehouse | /python/PycharmProjects/py01/day04/stack.py | 890 | 4.0625 | 4 | #!/root/nsd1905/bin/python
''' stack
append stack
pop stack
show stack
'''
stack=[]
def show_menu():
menu='''
0) Push into Stack
1) Pull from Stack
2) Show Stack
3) Quit
Please Choose (0/1/2/3):'''
cmds={'0':push_stack,'1':pull_stack,'2':show_stack}
choice=''
while choice!='3':
choice=input(menu).strip()
if choice not in ['0','1','2','3']:
print('%s Invalid Entering' % choice)
continue
elif choice=='3':
print('\nbye')
else:
cmds[choice]()
def push_stack():
data=input("data: ").strip()
if data:
stack.append(data)
print('OK! Pushing %s' % data)
def pull_stack():
if stack:
data=stack.pop()
print('OK! Pull out %s' % data )
else:
print('Sorry!Nothing')
def show_stack():
print(stack)
if __name__=='__main__':
show_menu()
|
86e474e7d315fb575cea118b4e49a47496737fa5 | UWPCE-PythonCert-ClassRepos/SP_Online_PY210 | /students/scottebetts/lesson04/trigrams.py | 1,224 | 3.9375 | 4 | #!/usr/bin/env python3
# author: Scott Betts
import random
from collections import defaultdict
import pprint
import re
def words(file_in):
with open(file_in, 'r') as infile:
x = infile.read()
x = re.sub(r'[^\w\s]', ' ', x).lower()
x = x.split()
return x
def build_trigrams(words):
trigrams = defaultdict(list)
for i in range(len(words) - 2):
element = (words[i], words[i+1])
trigrams[element].append(words[i+2])
return trigrams
def build_text(trigram_dict, length):
working_text = list(random.choice(list(trigram_dict.keys())))
key = tuple(working_text[-2:])
while key in trigram_dict:
value = random.choice(trigram_dict[key])
working_text.append(value)
key = tuple(working_text[-2:])
if len(working_text) > length:
break
return working_text
def paragraph(trigram_dict, num_para, length):
for number in range(num_para):
text = " ".join(build_text(trigram_dict, length))
text = text.capitalize()
print("\t{}.".format(text))
return
if __name__ == "__main__":
file_in = "./sherlock.txt"
trigrams = build_trigrams(words(file_in))
paragraph(trigrams, 2, 100)
|
7f4aa5ed70ba4ba82bdddb95a06ec19fb6cf6f31 | scaredginger/ieeextreme-2017 | /competition/bubbleChallenge.py | 1,506 | 3.515625 | 4 | #def printMatrix(m):
# for x in range(4):
# print("")
# for y in range(4):
# print(str(m[x][y]) + " ", end="")
# print("")
def checkForCycle(adjacencyMatrix, maxNum):
for x in range(0, maxNum+1):
for y in range(1, maxNum+1):
if adjacencyMatrix[x][y] == 1:
#go to the y'th row and try and find a similar element
for p in range(0, maxNum+1):
if adjacencyMatrix[y][p] == 1:
#check if column matches
if adjacencyMatrix[x][p] == 1:
return True
return False
if __name__ == "__main__":
tests = int(input())
for x in range(tests):
inter = input()
inputs = inter.split(' ')
vertices = int(inputs[0])
edges = int(inputs[1])
maxVertex = 0
inter = input()
inputs = inter.split(' ')
inputs = list(map(int, inputs))
maxNum = max(inputs)
adjacencyMatrix = [[0]*(maxNum+1) for _ in range(maxNum+1)]
for z in range(edges):
a = int(inputs[2*z])
b = int(inputs[2*z+1])
if a==b:
print(1)
break
else:
adjacencyMatrix[a][b] = 1
adjacencyMatrix[b][a] = 1
if checkForCycle(adjacencyMatrix, maxNum) == True:
print(1)
else:
print(0)
|
92eb27c4f97e5b30b8edb5eedfc8d1e22b7fce88 | arnabs542/achked | /python3/sorting/insertion_sort.py | 412 | 3.734375 | 4 | #!/usr/bin/env python3
def insertion_sort(l):
for i in range(len(l)):
key = l[i]
j = i
while j > 0:
if l[j - 1] > key:
l[j] = l[j - 1]
j -= 1
else:
break
l[j] = key
def main():
l = [4, 3, 45, 2, 22, 15, 6, 22, 19, 18, 27]
insertion_sort(l)
print(l)
if __name__ == '__main__':
main()
|
16fa5bb8f9ec59fb24c0be485cb74c5f799136db | LuanaSchlei/HackerRank_Python | /python-mod-divmod/python-mod-divmod.py | 320 | 3.5625 | 4 | #!/bin/python3
#
# Url: https://www.hackerrank.com/challenges/python-mod-divmod/problem
#
# Title: Mod Divmod
#
input_a = int(input())
input_b = int(input())
division_a_b = input_a // input_b
print(division_a_b)
modul_a_b = input_a % input_b
print(modul_a_b)
divmod_a_b = divmod(input_a, input_b)
print(divmod_a_b) |
1cfec5b901e0adab367981541fc9771ad999a97e | dagute/Coding_Interview | /Python/Find pair that sums up to k/sumpair3.py | 277 | 3.53125 | 4 | # By using a dictionary:
# Time complexity: O(n)
# Space complexity: O(n)
# arr = [8, 2, 9, 5, 10, 1]
# k = 12
def findPair(arr, k):
visited = {}
for element in arr:
if visited.get(k-element):
return True
else:
visited[element] = True
return False
|
10e85a5adedaf0fb1543e02a12cd3e4a3372c36a | AnneNamuli/python-code-snippets | /rev.py | 169 | 4.125 | 4 | def reverse(s):
s = list(s)
for i in range (len(s)//2):
temp = s[i]
s[i] = s[len(s)- i -1]
s[len(s) - 1 - i] = temp
return "".join(s)
print reverse("hello")
|
ad5b4c82e65d05d7466809361d0d1bed7aa8508f | ngetachew/LinkedList | /linkedlists.py | 861 | 4.03125 | 4 |
class Node:
def __init__(self, v : int, p):
self.value = v
self.pointer = p
class LinkedList:
#Data values are ints
def __init__(self, h):
self.head = Node(h, None)
def create_node(self):
return Node(0, None)
def add_node(self, val):
temp = self.create_node()
p = None
temp.value = val
if self.head == None:
self.head = temp
else:
p = self.head
while (p.pointer != None):
p = p.pointer
p.pointer = temp
def print_list(self):
nd = self.head
while( nd != None):
print(str(nd.value) + '--> \n')
nd = nd.pointer
#Implementation
link_lst = LinkedList(2)
link_lst.add_node(2)
link_lst.add_node(4)
link_lst.add_node(21231)
link_lst.print_list()
|
0df208508c3ada41f3ff40943d9d7a0a65d00e4b | 981377660LMT/algorithm-study | /11_动态规划/dp分类/双字符dp/97. 交错字符串.py | 1,368 | 3.59375 | 4 | # 请你帮忙验证 s3 是否是由 s1 和 s2 交错 组成的。
from functools import lru_cache
class Solution:
def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
@lru_cache(None)
def dfs(i: int, j: int) -> bool:
if i == len(s1) and j == len(s2):
return True
res = False
if i < len(s1) and s1[i] == s3[i + j]:
res |= dfs(i + 1, j)
if j < len(s2) and s2[j] == s3[i + j]:
res |= dfs(i, j + 1)
return res
if len(s1) + len(s2) != len(s3):
return False
return dfs(0, 0)
def isInterleave2(self, s1: str, s2: str, s3: str) -> bool:
n1, n2, n3 = len(s1), len(s2), len(s3)
if n1 + n2 != n3:
return False
dp = [[False] * (n2 + 1) for _ in range(n1 + 1)]
dp[0][0] = True
for i in range(n1 + 1): # !注意取0个字符的情况
for j in range(n2 + 1):
if i > 0:
if s1[i - 1] == s3[i + j - 1]:
dp[i][j] |= dp[i - 1][j]
if j > 0:
if s2[j - 1] == s3[i + j - 1]:
dp[i][j] |= dp[i][j - 1]
return dp[-1][-1]
print(Solution().isInterleave("aabcc", "dbbca", "aadbbcbcac"))
|
976d6c85555856c688a1ebac95a1048b0788766e | LeonNerd/PyTorch-Tutorial | /PythonScript/PythonScript/DeleteInBatches.py | 1,169 | 3.796875 | 4 | import os
#批量删除指定文件夹下的指定文件
#定义一个返回所有图片绝对路径的函数
def all_path(dirname):
result = []
for maindir, subdir, file_name_list in os.walk(dirname):
for filename in file_name_list:
apath = os.path.join(maindir, filename)
result.append(apath)
return result
def main():
path = 'H:/data/poles/poles2/'
list1 = all_path(path)
remove_path = 'H:/del.txt'
with open(remove_path) as f:
list2 = list(map(lambda s:s.strip(), f.readlines()))
#得到所有图片的名字并添加到list3中
list3 = []
for i in range(len(list1)):
line = os.path.split(list1[i])[-1].split('/')[0]
fname = os.path.splitext(line)[0]
list3.append(fname)
#将需要删除的图片的路径添加到list4中
list4 = []
for j in range(len(list3)):
for k in range(len(list2)):
if list3[j] == list2[k]:
out_path = list1[j]
list4.append(out_path)
for n in range(len(list4)):
os.remove(list4[n])
if __name__ == '__main__':
main()
|
888a7c8dd6a8d005b52df8b8b3c651d28f83e09c | tarun-n/python_daily_tasks | /random_password.py | 1,172 | 3.609375 | 4 | import random
def check_username(username):
fr=open("randompassword.txt","r")
lines=fr.readlines()
names=[]
for i in lines:
names.append((i.split('-')[0]).rstrip())
if username in names:
return 1
else:
return 0
def gen_char(n):
opstr=''
letters_small=[chr(i) for i in range(ord("a"),(ord("z")+1))]
letters_big=[chr(i) for i in range(ord("A"),(ord("Z")+1))]
letters_small.extend(letters_big)
for i in range(n):
opstr+=random.choice(letters_small)
return opstr
def gen_nums(m):
opnums=''
for i in range(m):
opnums+=str(random.randint(0,9))
return opnums
def gen_randompassword():
password=''
pw_pattern=int(input("enter pw pattern : "))
for i in range(2):
chars=gen_char(pw_pattern)
nums=gen_nums(pw_pattern)
password+=chars+nums
return password
def write_password_to_file():
fw=open("randompassword.txt","a")
username=input("enter the username :")
if check_username(username) is 1:
print('username already exists')
else:
random_password=gen_randompassword()
fw.write(f'{username} - {random_password} \n')
fw.close()
write_password_to_file()
|
710b82a258e1a5c1d00d0807ca8fd6750f85f740 | poo5/Hacker_rank | /solving problem/plus-minus.py | 483 | 3.609375 | 4 | def plusMinus(arr):
pos = 0
neg = 0
zero_count = 0
for i in arr:
if i > 0:
pos = pos+ 1
elif i < 0:
neg = neg + 1
else:
zero_count = zero_count + 1
pos_cal = pos/n
neg_cal = neg/n
zero_cal = zero_count/n
return(pos_cal,neg_cal,zero_cal)
if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().rstrip().split()))
print("%.6f\n%.6f\n%.6f\n" %plusMinus(arr))
|
2cab0dbecc72bb2e22f112cc6926f95887c0eb0f | jjkr/code-jam | /archive/python/consonants/consonants.py | 1,222 | 3.65625 | 4 | import sys
def is_vowel(c):
vowels = ['a', 'e', 'i', 'o', 'u']
try:
vowels.index(c)
return True
except:
return False
def nvalue(s, n):
print('NVAL')
print(s + str(n))
substrs = []
i=0
while i<= len(s)-n:
# print( 'I LOOP' )
j = 0
while not is_vowel(s[i+j]):
#print(s[i+j])
j += 1
if i+j > len(s)-1:
break
if j >= n:
substrs.append([i,j])
i += j + 1
print(substrs)
return count_substrs(substrs, len(s), n)
def count_substrs(cstrs, l, n):
count = 0
low = 0
for r in cstrs:
for i in range(r[1]-n+1):
print('i ' + str(i))
for j in range(low, r[0]+i+1):
print('substr ' + str(i) + ', ' + str(j))
count += 1
last = r
return count
def main():
T = int(sys.stdin.readline())
for i in range(T):
prefix = 'Case #' + str(i+1) + ': '
inputs = [s for s in sys.stdin.readline().split()]
s = inputs[0]
n = int(inputs[1])
print(prefix + str(nvalue(s, n)))
if __name__ == '__main__':
#print(nvalue('quartz', 3))
main()
|
f223ea831a27ae77bbfa7c32781a13b659a6c55b | Pooja-svg801/15072021ML01 | /day 9 csv.py | 1,427 | 3.515625 | 4 | import tkinter as tk
import csv
app = tk.Tk(__name__)
app.title('Form')
app.geometry('300x200')
name = tk.Variable(app)
name.set('')
email = tk.Variable(app)
email.set('')
mobilenumber = tk.Variable(app)
mobilenumber.set('')
tk.Label(app, text = 'Name',\
font=('Arial',14),
bg='black',fg='white'
).place(x=0,y=0)
tk.Entry(app, textvariable = name,\
font=('Arial',10)
).place(x=70,y=0)
tk.Label(app, text = 'Email',\
font=('Arial',12),
bg='black',fg='white'
).place(x=0,y=30)
tk.Entry(app, textvariable = email,\
font=('Arial',10)
).place(x=70,y=30)
tk.Label(app, text = 'Mobile',\
font=('Arial',12),
bg='black',fg='white'
).place(x=0,y=60)
tk.Entry(app, textvariable = mobilenumber,\
font=('Arial',10)
).place(x=70,y=60)
def file_entry(name,email,mobilenumber):
with open("data_form.csv","a") as f:
datawriter =csv.writer(f)
datawriter.writerow(['name','email','mobilenumber'])
f.close()
def result():
Name=name.get()
Email=email.get()
Mobile=mobilenumber.get()
file_entry(Name,Email,Mobile)
print("Submitted Successfully")
name.set('')
email.set('')
mobilenumber.set('')
tk.Button(app,text="Submit",command=result).place(x=100,y=160)
app.mainloop()
|
528ce2f3121e33c8652c2faff4f473bc1d8b017b | greatabel/PythonRepository | /04Python workbook/ch3loop/78DecimaltoBinary.py | 315 | 3.71875 | 4 | line = input("Enter n:")
while line != "":
bN = ""
mylist = []
xN = int(line)
while xN >=1:
if xN % 2 == 0:
reminder = 0
else:
reminder = 1
print("reminder=",reminder)
xN =xN/2
mylist.append(reminder)
for item in reversed(mylist):
bN+=str(item)
print(str(bN))
line = input("Enter n:")
|
83dcc46e1ea325c8d2bbf1ee0b18eb75cffcaa47 | fary86/GeneralisedNeuralNetwork | /NeuralNetwork.py | 3,827 | 3.734375 | 4 | """
Title: OCR Neural Network from scratch
Author: Abhinav Thukral
Language: Python
Dataset: MNIST
Description: Implementing a simpler, more readable version of OCR Neural Network from scratch to teach beginners.
"""
import pandas as pd
import numpy as np
import time
#Reading the MNSIT dataset
def read_MNIST(path):
data = pd.read_csv(path,skiprows=1)
X = data.iloc[:, 1:]
Y = data.iloc[:, 0]
#Normalisation
X = X.values/255
Y = Y.values
#10 values of MNIST dataset
transformedY = [[0 for _ in range(10)] for x in range(len(Y))]
#Transformation of Y
for i in range(len(Y)):
transformedY[i][Y[i]] = 1
Y = transformedY
"""Limiting data to run locally
return X[0:4000], Y[0:4000]"""
return X, Y
#Spliting data to test and train
def train_test_split(X,Y,split):
l = len(X)
limit = int(np.floor(split*l))
#Since, MNSIT data is randomly arranged, we can simply slice
x_train = X[0:limit]
y_train = Y[0:limit]
x_test = X[limit:l]
y_test = Y[limit:l]
return x_train,y_train,x_test,y_test
#ReLU activation function for hidden layers
def relu(input_layer):
return np.maximum(0,input_layer)
#Softmax activation for output layers
def softmax(input_layer):
exp_layer = np.exp(input_layer)
softmax_layer = exp_layer/np.sum(exp_layer)
return softmax_layer
#Using the structure of layers defined, initializing weight matrices
def generate_weights(layers):
weights = []
np.random.seed(1)
for i in range(len(layers) - 1):
#Adding 1 for bias
w = 2*np.random.rand(layers[i]+1,layers[i+1]) - 1
weights.append(w)
return weights
#Feedforward network
def feedforward(x_vector,W):
network = [np.append(1,np.array(x_vector))]
for weight in W[:-1]:
next_layer = relu(np.dot(network[-1],weight))
network.append(np.append(1,next_layer))
out_layer = softmax(np.dot(network[-1],W[-1]))
network.append(out_layer)
return network
#Backpropagation through the network
def backprop(network,y_vector,W,learning_rate):
deltas = [np.subtract(network[-1],y_vector)]
prev_layer = np.dot(W[-1],deltas[0])
deltas.insert(0,prev_layer)
for weight in list(reversed(W))[1:-1]:
prev_layer = np.dot(weight,deltas[0][1:])
deltas.insert(0,prev_layer)
#Weight Update
for l in range(len(W)):
for i in range(len(W[l])):
for j in range(len(W[l][i])):
W[l][i][j] -= learning_rate*deltas[l][j]*network[l][i]
#Compute accuracy of the network for given weight parameters
def analyse_net(W,X,Y):
correct_pred = 0
for i in range(len(X)):
y_pred = np.argmax(feedforward(X[i],W)[-1])
if(y_pred==np.argmax(Y[i])):
correct_pred+=1
return np.round(correct_pred/i,4)
#Stochastic training for each training data
def train(x_train,y_train,W,epoch,learning_rate,x_test,y_test):
for iteration in range(epoch):
t0 = time.clock()
for i in range(len(x_train)):
network = feedforward(x_train[i],W)
backprop(network,y_train[i],W,learning_rate)
print("Epoch",iteration+1,"Accuracy",analyse_net(W,x_train,y_train),"Time",time.clock()-t0)
#Printing test data accuracy
def test_accuracy(x_test,y_test,W):
print("Test Data Accuracy",analyse_net(W,x_test,y_test))
def run(hidden_layers,learning_rate,epoch,split):
print("Epochs",epoch,"LR",learning_rate,"Hidden Layers",hidden_layers,"Split",split,sep=" ")
X, Y = read_MNIST("MNISTtrain.csv")
input_layer = len(X[0])
output_layer = len(Y[0])
layers = [input_layer] + hidden_layers + [output_layer]
W = generate_weights(layers)
x_train,y_train,x_test,y_test = train_test_split(X,Y,split)
train(x_train,y_train,W,epoch,learning_rate,x_test,y_test)
test_accuracy(x_test,y_test,W)
run([50],0.01,1,0.90)
"""
To implement a neural network with 2 hidden layers, with layer parameters 55, 25 respectively use:
run([55,25],0.003,30,0.9)
""" |
e93a5a9bb9a2958ed9dd9fd0c607dd0092422795 | SeperinaJi/PythonExercise | /pizza.py | 1,461 | 4.28125 | 4 | # Exercise list in dictionary
pizza = {
'crust' : 'thick',
'toppings' : ['mushroom', 'extra cheese', 'pepperoni']
}
print("You ordered a " + pizza['crust'] + "-crist pizza " +
"With the fllowing toppings:")
for topping in pizza['toppings']:
print('\t' + topping)
#Exercise dictionary in dictionary
users = {
'jony' : {
'first': 'jony',
'last': 'ma',
'age': 27
},
'seperina' :{
'first': 'seperina',
'last': 'ji',
'age': 26
}
}
for username, userinfo in users.items():
print('\nUsername:' + username.title())
full_name = userinfo['first'].title() + " " + userinfo['last'].title()
age = userinfo['age']
print("\tFull name : " + full_name)
print("\tAge is " + str(age))
#Exercise 6-11
cities = {
'London' : {
'Country' : 'UK',
'Population' : 5000,
'Fact' : 'Captain of UK'
},
'Beijing' :{
'Country' : 'China',
'Population' : 10000,
'Fact' : 'Captain of China'
},
'New York':{
'Country': 'America',
'Population': 10000,
'Fact': 'Captain of America'
}
}
for city, city_info in cities.items():
print('\n City :' + city.title())
country = city_info['Country']
population = city_info['Population']
fact = city_info['Fact']
print('\t Country: ' +country.title())
print("\t Population:" + str(population))
print("\t Fact: " + fact) |
c0620dc89173629e608233ff9688be6a73b5d605 | luodanping/learn-python-by-coding | /design_pattern/10_facade.py | 1,432 | 3.59375 | 4 | #facade
import time
SLEEP=0.5
#complex parts
class TC1:
def run(self):
print("#"*5+" In Text 1 "+"#"*5)
time.sleep(SLEEP)
print("Setting up")
time.sleep(SLEEP)
print("Running test")
time.sleep(SLEEP)
print("Tearing down")
time.sleep(SLEEP)
print("Test finished\n")
class TC2:
def run(self):
print("#"*5+" In Text 2 "+"#"*5)
time.sleep(SLEEP)
print("Setting up")
time.sleep(SLEEP)
print("Running test")
time.sleep(SLEEP)
print("Tearing down")
time.sleep(SLEEP)
print("Test finished\n")
class TC3:
def run(self):
print("#"*5+" In Text 3 "+"#"*5)
time.sleep(SLEEP)
print("Setting up")
time.sleep(SLEEP)
print("Running test")
time.sleep(SLEEP)
print("Tearing down")
time.sleep(SLEEP)
print("Test finished\n")
#Facade
class TestRunner:
def __init__(self):
self.tc1=TC1()
self.tc2=TC2()
self.tc3=TC3()
self.tests=[i for i in (self.tc1,self.tc2,self.tc3)]
def runAll(self):
#[i.run() for i in self.tests] #跟下面的具有同样的功能
for i in self.tests:
i.run()
def main():
testrunner = TestRunner()
testrunner.runAll()
if __name__=="__main__":
main()
|
eb62cc70c9812589bd8e7cdccb3b1dfae0698410 | benglish00/STP_CH3 | /ch3.py | 1,080 | 3.984375 | 4 | # basic for loop, i starts at 0
for i in range (10):
print(i+1)
import math
# length of a diagonal
l = 4
w = 10
d = math.sqrt(l**2 + w**2)
print(d)
#print long line
print("""Colooooooooooooooooooooooooooooooooooooooraddo
ooooo""")
#conditional
home = "Colorado"
if home == "Colorado":
print("Hello, Colorado!")
else:
print("Hello, Loser! :D")
x = 2
if x ==2:
print("The number is 2!")
if x%2 == 0:
print("The number is even!")
if x%2 != 0:
print("The number is odd. TT")
x = 10
y = 11
if x ==10:
if y == 11:
print(x+y)
#Challenge 1. printe 3 strings
print("Colorado")
print("Winter")
print("Ski")
#Challenge 2 sort a number
x = 8
if x == 10:
print("x is 10!")
if x>10:
print("x is greater than 10!")
if x<10:
print("x is less than 10!")
#Challenge 4 and 5. Find the remainder and quotient
print("The remainder is",10%3)
print("The quotient is",10//3)
#6 Sort an a variable age
age = 44
if age == 44:
print(age, "is just right!")
elif age > 44:
print("Damn!",age, " is old!")
else:
print(age,"! Spring Chicken!") |
8e3a0aafeca9ca8868b3d5c353a745d5d4f658d5 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_199/2702.py | 544 | 3.578125 | 4 | def flip(char):
if char == '+':
return '-'
else:
return '+'
T = int(raw_input())
for t in range(T):
pattern, flipper = raw_input().split(' ')
flipper = int(flipper)
pattern = list(pattern)
flips = 0
fixed = 0
length = len(pattern)
while True:
while fixed<length and pattern[fixed]=='+':
fixed+=1
if fixed==length:
print "Case #"+str(t+1)+":",flips
break
if fixed+flipper > length:
print "Case #"+str(t+1)+": IMPOSSIBLE"
break
for i in range(fixed, fixed+flipper):
pattern[i] = flip(pattern[i])
flips+=1 |
1b95214b694b107a3e9cb8924db0c80b15f45971 | mccoderpy/alphabetic-to_json-Encoder | /converter_consolen-version.py | 2,928 | 3.625 | 4 | import json
import os
import time
class converter():
print('░▒▓███Welcome to the alphabetic-to_json-encoder of mccoderpy aka. mccuber04#2960██▓▒░ ©mccoderpy 2021')
loop= 0
while True:
inpu = input("Please enter the name of the file(with the ending) you want to convert in to an JSON>> ")
if not inpu == '':
if not os.path.isfile(inpu):
print(f"Could not find the file <{inpu}> in this directiony. Please put it in the same directory this script is is placed in")
if os.path.isfile(inpu):
alphint0 = 0
alphint1 = 0
alp = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'ä', 'ö', 'ü']
alp1 = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'Ä', 'Ö', 'Ü']
data = {}
data["list"] = {}
D = data["list"]
for letter in alp:
alphint0 += 1
D[letter] = {}
for let in alp:
name = alp[alphint0-1]+let
D[letter][name] = []
print(end='|█')
zeile = 0
with open(inpu, "r", encoding='utf-8') as file:
for wort in file:
zeile += 1
if zeile == 300:
print(end='█')
time.sleep(0.1)
zeile = 0
weg_damit = wort.split('\n')
l = weg_damit.pop(0)
#print(l)
for lu in alp1:
alphint1 += 1
if l.upper().startswith(lu):
b0 = lu.lower()
for let in alp:
if l[1:2] == let:
b1 = let
#print(alphint1)
#print(b0+b1)
D[b0][b0+b1].append(f"{l}")
print(end='| [100%]')
weg_mit_die_endung = inpu.split(".")
neuer_name = weg_mit_die_endung[0]
with open(f'{neuer_name}.json', 'w', encoding='utf-8') as new:
json.dump(data, new)
print(f"\nConverted file successfully\nFile saved as {os.getcwd()}\{neuer_name}.json")
#(f'{neuer_name}.json')
#print(data)
|
f3eea484a492c274832789ca74d1ef9d94da778e | MikeCardona076/PythonDocuments | /python/Practica.py | 400 | 3.84375 | 4 | palabra=input("Escribe una palabra: ")
veces_palabra= int(input("Numero de veces: "))
for recorrido in range(0,veces_palabra):
if (veces_palabra > 120):
print("Pedro ", palabra)
else:
print(palabra)
if (veces_palabra==500):
print("Hola")
elif(veces_palabra < 100):
print("Hola Mortales")
else:
print("HOLAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA") |
794f9d7b3649d82a90420d646c16563bddc0c8ec | gerrycfchang/leetcode-python | /medium/subarray_product_less_than_k.py | 1,774 | 3.59375 | 4 | # 713. Subarray Product Less Than K
#
# Input: nums = [10, 5, 2, 6], k = 100
# Output: 8
# Explanation: The 8 subarrays that have product less than 100 are:
# [10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6].
# Note that [10, 5, 2] is not included as the product of 100 is not strictly less than k.
class Solution(object):
def numSubarrayProductLessThanK(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
def dfs(nums, i, k, value, res):
if i >= len(nums) or value * nums[i] >= k:
reslist.append(res)
res = []
return
else:
res.append(nums[i])
dfs(nums, i+1, k, value* nums[i], res)
reslist = []
for i in range(len(nums)):
if nums[i] < k:
reslist.append([nums[i]])
dfs(nums, i + 1, k, nums[i], [nums[i]])
return len(reslist)
def numSubarrayProductLessThanKSol(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
if k == 0:
return 0
start, prod, cnt = 0, 1, 0
for end in range(len(nums)):
while start <= end and prod*nums[end] >= k:
prod = prod/nums[start]
start += 1
prod = 1 if start > end else prod*nums[end]
cnt = cnt if start > end else cnt+(end-start+1)
return cnt
if __name__ == '__main__':
sol = Solution()
assert sol.numSubarrayProductLessThanKSol([10, 5, 2, 6], 100) == 8
assert sol.numSubarrayProductLessThanKSol([10, 5, 2, 7], 14) == 5
assert sol.numSubarrayProductLessThanK([], 1) == 0
|
6aa082d2b14c8f9c356438ca8760d0711da9a2de | avinash-nonholonomy/hack_diversity_office_hours | /archive/2021/graphs_and_trees.py | 1,649 | 4 | 4 | #!/usr/bin/python
import networkx as nx
"""
Helpful resources:
NetworkX - Great python library for working with graphs
https://networkx.org/documentation/stable/tutorial.html
Summary of graph terms and alogorithms:
https://towardsdatascience.com/10-graph-algorithms-visually-explained-e57faa1336f3
"""
# Detect Loops from Graphs
def loop_detector_working(graph):
try:
cycles = nx.find_cycle(graph)
if cycles:
return True
except nx.exception.NetworkXNoCycle:
return False
return False
def loop_detector(graph):
if not graph:
return False
for edge in nx.dfs_edges(graph):
current_node, next_node = edge
print("outer edge: ", edge)
for inner_edge in nx.dfs_edges(graph, next_node):
print(f" inner edge for {current_node}", inner_edge)
if current_node == inner_edge[1]: # next_next_node
return True
return False
def p1():
tests = []
tests.append(nx.DiGraph())
tests[-1].add_edges_from([(0, 1), (0, 2), (1, 2), (2, 0), (2, 3), (3, 3)])
tests.append(nx.DiGraph())
tests[-1].add_edges_from([(0, 1), (0, 2), (1, 2), (2, 3)])
tests.append(nx.DiGraph())
tests[-1].add_edges_from([])
for test_input in tests:
print("\n" + "#"*40)
print("input", test_input.edges)
correct_result = loop_detector_working(test_input)
my_result = loop_detector(test_input)
print("Loop? correct: ", correct_result, " my: ", my_result)
if correct_result != my_result:
print("!"*20, " ERROR ", "!"*20)
if __name__ == "__main__":
p1()
|
6333ce2053bbd67e3d1b825074f5c931dd1ac96b | Pjmcnally/algo | /strings/seven_segment_display/find_longest_word.py | 1,191 | 4.0625 | 4 | """Find the longest english word representable on a seven segment display.
This is based on the YouTube video by Tom Scott found here:
https://www.youtube.com/watch?v=zp4BMR88260&feature=youtu.be
"""
import os
import re
def find_longest_words(file_path):
"""Find longest word representable on a seven segment display."""
# Get list of words to check sort longest first.
with open(file_path, "r") as file:
sorted_words = sorted(file.read().splitlines(), reverse=True, key=len)
# Build regex of letters unrepresentable on a seven segment display
pattern = re.compile(r'^[^gkmqvwxzio]+$') # cspell: ignore gkmqvwxzio
out_list = []
max_words = 10
for word in sorted_words:
if pattern.search(word):
out_list.append(word)
# If you have found the desired number of words stop
if len(out_list) == max_words:
break
return out_list
def main():
"""Execute main function."""
_dir = os.path.dirname(__file__)
file_path = os.path.join(_dir, "..", "english_words", "alphabetical.txt")
for word in find_longest_words(file_path):
print(word)
if __name__ == '__main__':
main()
|
803388179f449e7031f14def34ab7cd646ad1ff0 | mr-finnie-mac/mirror-meno | /display_main.py | 1,670 | 3.640625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# display_main.py
# Author: Fin Mead [Meadeor]
# Desc: Aggregate display for display mirror
# Last updated: 10/5/2020
#
# Imports
import RPi.GPIO as GPIO
import time
import tkinter
from tkinter import *
date = time.strftime('%b %d, %Y')
Time = time.strftime('%l:%M%p')
window = Tk()
GPIO.setwarnings(False) # Ignore warning for now
GPIO.setmode(GPIO.BOARD) # Use physical pin numbering
GPIO.setup(10, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # Set pin 10 to be an input pin and set initial value to be pulled low (off)
GPIO.setup(12, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # Set pin 12 to be an input pin and set initial value to be pulled low (off)
GPIO.setup(16, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # Set pin 10 to be an input pin and set initial value to be pulled low (off)
GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # Set pin 12 to be an input pin and set initial value to be pulled low (off)
def main():
window.geometry('1440x720')
window.title("main")
lbl = Label(window, text= date + Time, font=("Arial Bold", 50))
lbl.grid(column=0, row=0)
window.mainloop()
#print date
#print time
while True: # Run forever
if GPIO.input(10) == GPIO.LOW:
print("Button 0 was pushed!")
#main()
time.sleep(0.5)
if GPIO.input(12) == GPIO.LOW:
print("Button 1 was pushed!")
#main()
time.sleep(0.5)
if GPIO.input(16) == GPIO.LOW:
print("Button 2 was pushed!")
#main()
time.sleep(0.5)
if GPIO.input(18) == GPIO.LOW:
print("Button 3 was pushed!")
#main()
time.sleep(0.5)
|
16977f124a3f31d5596f71b897fa056f78cad1fa | techadddict/Python-programmingRG | /Dictionaries/python dictionary 1.py | 567 | 4 | 4 | ##Write a program that counts how often each word occurs in a user specified text file
file = open('text.txt','r')
lines= file.readlines()
myDict={}
for line in lines:
#print(line)
wordList = line.strip().split()
for word in wordList:
word=word.strip(',!;.')
if(word in myDict):
#if words are many
myDict[word]=myDict[word] +1
else:
#if word is the only one
myDict[word] = 1
#file.close()
for word in myDict:
print(word,myDict[word])
|
13cd6328ce809710b023f67a05108ea944a2fbbd | rayhan60611/Python-A-2-Z | /7.Chapter-7/test.py | 2,299 | 3.78125 | 4 | #Problem No 1:!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
number =input("Enter Your Number: ")
for i in range(1,11):
print(f"{number}x{i} = {int(number)*i}")
#Problem No 2:!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
l= ['Rayhan','Sumon','Sony','Tony','Sunny']
for name in l:
if name.startswith("S"):
print(f"Hello Mr. {name} !!")
#Problem No 3:!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
number =input("Enter Your Number: ")
i=1
while i<11:
print(f"{number}x{i} = {int(number)*i}")
i+=1
#Problem No 4:!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
num = int(input("Enter the number: "))
prime = True
for i in range(2, num):
if(num%i == 0):
prime = False
break
if prime:
print("This number is Prime")
else:
print("This number is not Prime")
#Problem No 5:!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
num = int(input("Enter the number: "))
i=1
sum=0
k=1
while i <= num:
i+=1
sum+=k
k+=1
print(f"Sum of N Natural Number is: {sum}")
#Problem No 6:!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
num = int(input("Enter the number: "))
j=num+1
fact=1
for i in range(1,j):
fact=fact*i
print(f"The Factorial value of {num} is : {fact}" )
#Problem No 7:!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
num = int(input("Enter the number: "))
for i in range(num):
print(" " * (num-i-1),end="")
print("*" * (2*i+1),end="")
print(" " * (num-i-1),)
#Problem No 8:!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
num = int(input("Enter the number: "))
for i in range(num):
print("*" * (i+1))
#Problem No 9:!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#num = int(input("Enter the number: ")) not solved yet
for i in range(3):
if i==0 or i==2 :
print("*" * (1),end="")
print(" " * (1),end="")
print("*" * (1),end="")
print(" " * (1),end="")
print("*" * (1))
if i==1:
print("*" * (i),end="")
print(" " * (i+2),end="")
print("*" * (i))
#Problem No 10:!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
number =input("Enter Your Number: ")
i=10
while i>0:
print(f"{number}x{i} = {int(number)*i}")
i-=1
|
7b2b2c1592e7ea7b921ecd29acb52626a4c014a2 | trevllew751/python3course | /selects.py | 325 | 3.9375 | 4 | import sqlite3
conn = sqlite3.connect("my_friends.db")
c = conn.cursor()
c.execute("SELECT * FROM friends WHERE closeness > 5 ORDER BY closeness")
# Iterate over a cursor
# for reslut in c:
# print result
# fetch one result
print(c.fetchone())
#fetch all results as a list
print(c.fetchall())
conn.commit()
conn.close() |
3091c0406a70fd92c9084987a352c1643e21cfbc | Phomint/Udacity_DataScienceFoundations_BR | /Projects/Project_1/chicago_bikeshare_pt.py | 12,085 | 4 | 4 | # coding: utf-8
# Começando com os imports
import csv
import matplotlib.pyplot as plt
# Vamos ler os dados como uma lista
print("Lendo o documento...")
with open("chicago.csv", "r") as file_read:
reader = csv.reader(file_read)
data_list = list(reader)
print("Ok!")
# Vamos verificar quantas linhas nós temos
print("Número de linhas:")
print(len(data_list))
# Imprimindo a primeira linha de data_list para verificar se funcionou.
print("Linha 0: ")
print(data_list[0])
# É o cabeçalho dos dados, para que possamos identificar as colunas.
# Imprimindo a segunda linha de data_list, ela deveria conter alguns dados
print("Linha 1: ")
print(data_list[1])
input("Aperte Enter para continuar...")
# TAREFA 1
# TODO: Imprima as primeiras 20 linhas usando um loop para identificar os dados.
print("\n\nTAREFA 1: Imprimindo as primeiras 20 amostras")
# Vamos mudar o data_list para remover o cabeçalho dele.
data_list = data_list[1:]
indice = 0
while indice < 20:
print(data_list[indice])
indice += 1
# Nós podemos acessar as features pelo índice
# Por exemplo: sample[6] para imprimir gênero, ou sample[-2]
input("Aperte Enter para continuar...")
# TAREFA 2
# TODO: Imprima o `gênero` das primeiras 20 linhas
print("\nTAREFA 2: Imprimindo o gênero das primeiras 20 amostras")
# Ótimo! Nós podemos pegar as linhas(samples) iterando com um for, e as colunas(features) por índices.
# Mas ainda é difícil pegar uma coluna em uma lista. Exemplo: Lista com todos os gêneros
indice = 0
while indice < 20:
print(data_list[indice][6])
indice += 1
input("Aperte Enter para continuar...")
# TAREFA 3
# TODO: Crie uma função para adicionar as colunas(features) de uma lista em outra lista, na mesma ordem
def column_to_list(data, index):
"""
Função Coluna para Lista.
Argumentos:
data: Requer uma lista de listas.
index: Referencia a qual coluna quer criar uma lista.
Retorna:
Uma lista com os valores da coluna requirida.
"""
column_list = [element[index] for element in data]
# Dica: Você pode usar um for para iterar sobre as amostras, pegar a feature pelo seu índice, e dar append para
# uma lista
return column_list
# Vamos checar com os gêneros se isso está funcionando (apenas para os primeiros 20)
print("\nTAREFA 3: Imprimindo a lista de gêneros das primeiras 20 amostras")
print(column_to_list(data_list, -2)[:20])
# ------------ NÃO MUDE NENHUM CÓDIGO AQUI ------------
assert type(column_to_list(data_list, -2)) is list, "TAREFA 3: Tipo incorreto retornado. Deveria ser uma lista."
assert len(column_to_list(data_list, -2)) == 1551505, "TAREFA 3: Tamanho incorreto retornado."
assert column_to_list(data_list, -2)[0] == "" and column_to_list(data_list, -2)[
1] == "Male", "TAREFA 3: A lista não coincide."
# -----------------------------------------------------
input("Aperte Enter para continuar...")
# Agora sabemos como acessar as features, vamos contar quantos Male (Masculinos) e Female (Femininos) o dataset tem
# TAREFA 4
# TODO: Conte cada gênero. Você não deveria usar uma função para isso.
male = 0
female = 0
for gender in column_to_list(data_list, -2):
if gender == 'Male':
male += 1
elif gender == 'Female':
female += 1
# Verificando o resultado
print("\nTAREFA 4: Imprimindo quantos masculinos e femininos nós encontramos")
print("Masculinos: ", male, "\nFemininos: ", female)
# ------------ NÃO MUDE NENHUM CÓDIGO AQUI ------------
assert male == 935854 and female == 298784, "TAREFA 4: A conta não bate."
# -----------------------------------------------------
input("Aperte Enter para continuar...")
# Por que nós não criamos uma função para isso? TAREFA 5 TODO: Crie uma função para contar os gêneros. Retorne uma
# lista. Isso deveria retornar uma lista com [count_male, count_female] (exemplo: [10, 15] significa 10 Masculinos,
# 15 Femininos)
def count_gender(data_list):
"""
Função que contabiliza a quantidade de vezes que se repete o Genêro.
Argumentos:
data_list: Requer uma lista de listas, para gerar uma lista dos genêros.
Retorna:
Uma lista [male, female] com valores inteiros da quantidade de cada um respectivamente.
"""
male = 0
female = 0
for gender in column_to_list(data_list, -2):
if (gender == 'Male'):
male += 1
elif (gender == 'Female'):
female += 1
return [male, female]
print("\nTAREFA 5: Imprimindo o resultado de count_gender")
print(count_gender(data_list))
# ------------ NÃO MUDE NENHUM CÓDIGO AQUI ------------
assert type(count_gender(data_list)) is list, "TAREFA 5: Tipo incorreto retornado. Deveria retornar uma lista."
assert len(count_gender(data_list)) == 2, "TAREFA 5: Tamanho incorreto retornado."
assert count_gender(data_list)[0] == 935854 and count_gender(data_list)[
1] == 298784, "TAREFA 5: Resultado incorreto no retorno!"
# -----------------------------------------------------
input("Aperte Enter para continuar...")
# Agora que nós podemos contar os usuários, qual gênero é mais prevalente?
# TAREFA 6
# TODO: Crie uma função que pegue o gênero mais popular, e retorne este gênero como uma string.
# Esperamos ver "Male", "Female", ou "Equal" como resposta.
def most_popular_gender(data_list):
"""
Função genêro mais popula na lista.
Argumentos:
param1: Requer lista de listas para verificar o genêro contido na mesma.
Retorna:
Uma string contendo Male ou Female como resultado da verificação.
"""
answer = ""
resultado = count_gender(data_list)
if resultado[0] == resultado[1]:
answer = 'Equal'
elif resultado[0] > resultado[1]:
answer = 'Male'
else:
answer = 'Female'
return answer
print("\nTAREFA 6: Qual é o gênero mais popular na lista?")
print("O gênero mais popular na lista é: ", most_popular_gender(data_list))
# ------------ NÃO MUDE NENHUM CÓDIGO AQUI ------------
assert type(most_popular_gender(data_list)) is str, "TAREFA 6: Tipo incorreto no retorno. Deveria retornar uma string."
assert most_popular_gender(data_list) == "Male", "TAREFA 6: Resultado de retorno incorreto!"
# -----------------------------------------------------
# Se tudo está rodando como esperado, verifique este gráfico!
gender_list = column_to_list(data_list, -2)
types = ["Male", "Female"]
quantity = count_gender(data_list)
y_pos = list(range(len(types)))
plt.bar(y_pos, quantity)
plt.ylabel('Quantidade')
plt.xlabel('Gênero')
plt.xticks(y_pos, types)
plt.title('Quantidade por Gênero')
plt.show(block=True)
input("Aperte Enter para continuar...")
# TAREFA 7
# TODO: Crie um gráfico similar para user_types. Tenha certeza que a legenda está correta.
print("\nTAREFA 7: Verifique o gráfico!")
user_type_list = column_to_list(data_list, -3)
types = ["Customer", "Subscriber"]
joined_list = ', '.join(user_type_list)
quantity = [joined_list.count('Customer'), joined_list.count('Subscriber')]
y_pos = list(range(len(types)))
plt.bar(y_pos, quantity)
plt.ylabel('Quantidade')
plt.xlabel('Tipos de Usuários')
plt.xticks(y_pos, types)
plt.title('Quantidade por Tipo de Usuário')
plt.show(block=True)
input("Aperte Enter para continuar...")
# TAREFA 8
# TODO: Responda a seguinte questão
male, female = count_gender(data_list)
print("\nTAREFA 8: Por que a condição a seguir é Falsa?")
print("male + female == len(data_list):", male + female == len(data_list))
answer = "Porque em algumas das tuplas dada pelo conjunto de dados não foram preenchidas na coluna Gênero"
print("resposta:", answer)
# ------------ NÃO MUDE NENHUM CÓDIGO AQUI ------------
assert answer != "Escreva sua resposta aqui.", "TAREFA 8: Escreva sua própria resposta!"
# -----------------------------------------------------
input("Aperte Enter para continuar...")
# Vamos trabalhar com trip_duration (duração da viagem) agora. Não conseguimos tirar alguns valores dele.
# TAREFA 9
# TODO: Ache a duração de viagem Mínima, Máxima, Média, e Mediana.
# Você não deve usar funções prontas para isso, como max() e min().
trip_duration_list = column_to_list(data_list, 2)
min_trip = 0.
max_trip = 0.
mean_trip = 0.
median_trip = 0.
# Loop para fazer a somatoria dos valores da lista e encontrar o maior valor.
soma = 0.
for duration in trip_duration_list:
soma += float(duration)
if float(duration) > max_trip:
max_trip = float(duration)
# Faz o cálculo para média
mean_trip = round(soma / len(trip_duration_list))
# Loop para encontrar o menor valor na lista
min_trip = max_trip
for duration in trip_duration_list:
if float(duration) < min_trip:
min_trip = float(duration)
# Cálcula a mediana
lista_refeita = [float(item) for item in trip_duration_list]
ordenada = sorted(lista_refeita)
indice = len(ordenada) // 2
if len(ordenada) % 2 == 0:
median_trip = (float(ordenada[indice - 1]) + float(ordenada[indice])) / 2
print(median_trip)
else:
median_trip = ordenada[indice]
print("\nTAREFA 9: Imprimindo o mínimo, máximo, média, e mediana")
print("Min: ", min_trip, "Max: ", max_trip, "Média: ", mean_trip, "Mediana: ", median_trip)
# ------------ NÃO MUDE NENHUM CÓDIGO AQUI ------------
assert round(min_trip) == 60, "TAREFA 9: min_trip com resultado errado!"
assert round(max_trip) == 86338, "TAREFA 9: max_trip com resultado errado!"
assert round(mean_trip) == 940, "TAREFA 9: mean_trip com resultado errado!"
assert round(median_trip) == 670, "TAREFA 9: median_trip com resultado errado!"
# -----------------------------------------------------
input("Aperte Enter para continuar...")
# TAREFA 10
# Gênero é fácil porque nós temos apenas algumas opções. E quanto a start_stations? Quantas opções ele tem?
# TODO: Verifique quantos tipos de start_stations nós temos, usando set()
start_stations = set(column_to_list(data_list, 3))
print("\nTAREFA 10: Imprimindo as start stations:")
print(len(start_stations))
print(start_stations)
# ------------ NÃO MUDE NENHUM CÓDIGO AQUI ------------
assert len(start_stations) == 582, "TAREFA 10: Comprimento errado de start stations."
# -----------------------------------------------------
input("Aperte Enter para continuar...")
# TAREFA 11 Volte e tenha certeza que você documentou suas funções. Explique os parâmetros de entrada, a saída,
# e o que a função faz. Exemplo: def new_function(param1: int, param2: str) -> list:
"""
Função de exemplo com anotações.
Argumentos:
param1: O primeiro parâmetro.
param2: O segundo parâmetro.
Retorna:
Uma lista de valores x.
"""
input("Aperte Enter para continuar...")
# TAREFA 12 - Desafio! (Opcional)
# TODO: Crie uma função para contar tipos de usuários, sem definir os tipos
# para que nós possamos usar essa função com outra categoria de dados.
print("Você vai encarar o desafio? (yes ou no)")
answer = "yes"
def count_items(column_list):
"""
Função generica para contagem dos itens.
Argumentos:
column_list: Lista da coluna que quer fazer a contagem.
Retorna:
item_types: uma lista com os tipos de itens diferentes.
count_items: uma lista respectiva com os tipos dos items, contabilizando quantas vezes se repete na coluna.
"""
item_types = list(set(column_list))
count_items = []
for item in item_types:
count = 0
for object in column_list:
if item == object:
count += 1
count_items.append(count)
return item_types, count_items
if answer == "yes":
# ------------ NÃO MUDE NENHUM CÓDIGO AQUI ------------
column_list = column_to_list(data_list, -2)
types, counts = count_items(column_list)
print("\nTAREFA 12: Imprimindo resultados para count_items()")
print("Tipos:", types, "Counts:", counts)
assert len(types) == 3, "TAREFA 12: Há 3 tipos de gênero!"
assert sum(counts) == 1551505, "TAREFA 12: Resultado de retorno incorreto!"
# -----------------------------------------------------
|
da02b179db282c8c287caff4808f478da505b8d6 | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/distantBarcodes.py | 1,611 | 3.8125 | 4 | """
Distant Barcodes
In a warehouse, there is a row of barcodes, where the i-th barcode is barcodes[i].
Rearrange the barcodes so that no two adjacent barcodes are equal. You may return any answer, and it is guaranteed an answer exists.
Example 1:
Input: [1,1,1,2,2,2]
Output: [2,1,2,1,2,1]
Example 2:
Input: [1,1,1,1,2,2,3,3]
Output: [1,3,1,3,2,1,2,1]
Note:
1 <= barcodes.length <= 10000
1 <= barcodes[i] <= 10000
"""
"""
PQ
Time: O(Nlog(N))
Space: O(N)
"""
class Solution:
def rearrangeBarcodes(self, barcodes: List[int]) -> List[int]:
counts = collections.Counter(barcodes)
pq = []
for n in counts:
heapq.heappush(pq, (-counts[n], n))
res = []
while len(pq) > 1:
ct1, n1 = heapq.heappop(pq)
ct2, n2 = heapq.heappop(pq)
if not res or res[-1] != n1:
res.extend([n1, n2])
else:
res.extend([n2, n1])
ct1 += 1
ct2 += 1
if ct1 < 0:
heapq.heappush(pq, (ct1, n1))
if ct2 < 0:
heapq.heappush(pq, (ct2, n2))
if pq:
res.append(pq[0][1])
return res
"""
Use Odd even pos
Time: O(N)
Space: O(1)
"""
def rearrangeBarcodes(self, packages):
i, n = 0, len(packages)
res = [0] * n
for k, v in collections.Counter(packages).most_common():
for _ in xrange(v):
res[i] = k
i += 2
if i >= n:
i = 1
return res
|
48db4d76385cf690f5527168ba47f212c3f4b9bb | rpivo/leetcode-answers | /find-value-of-variable-after-performing-operations-2.py | 652 | 3.71875 | 4 | # define class Solution
class Solution:
# define function finalValueAfterOperations, which takes in the class
# instance (self), a list of strings called operations, and returns an
# integer
def finalValueAfterOperations(self, operations: List[str]) -> int:
# create variable x and set it equal to 0
x = 0
# loop through each op in operations
for op in operations:
# if op is in the list ["X++", "++X"]
if op in ["X++", "++X"]:
# increment x by 1
x += 1
else:
# decrement x by 1
x -= 1
return x |
ab9804bcfa130d920b5b3f8159628c69855bf01f | RicardoVeronica/python-exercises | /fizz-buzz/fizz-buzz.py | 547 | 3.71875 | 4 | # fizz buzz problem with list comprehension
fizz = [value for value in range(1, 101) if value % 3 == 0]
buzz = [value for value in range(1, 101) if value % 5 == 0]
FizzBuzz = [value for value in range(1, 101)
if value % 3 == 0 and value % 5 == 0]
# fizz buzz problem with for
for number in range(1, 101):
if number % 3 == 0 and number % 5 == 0:
print(f'{number} fizzbuzz')
elif number % 3 == 0:
print(f'{number} fizz')
elif number % 5 == 0:
print(f'{number} buzz')
else:
print(number)
|
b738a81128b3c1ed09f11f1f5bdd7760cd292a92 | marykamau2/katas | /python kata/leap_year/leap.py | 332 | 4.21875 | 4 | year = int(input('Please put in your year?'))
def leap(year):
if (year % 4) == 0 and (year % 100) == 0 and (year % 400) == 0:
# year = True
return True
print(f'{year} entered is a leap year')
else:
# year = False
return False
print(f'{year} entered is not a leap year')
year2 = leap(year)
print(year2) |
4e552537703a056d48eb7291c7381e6ddc94dcdd | caveman0612/python_fundeamentals | /Practice/easy/Find CLosest Value in BST.py | 1,344 | 3.90625 | 4 | def findClosestValueInBst(tree, target):
return findClosestValueInBstHelper(tree, target, tree.value)
def findClosestValueInBstHelper(tree, target, closest):
# check current value
if tree is None:
print(type(tree))
return closest
# check the difference between target and current value compared to closest value
if abs(target - closest) > abs(target - tree.value):
closest = tree.value
# if target is smaller search left side of tree with helper
if target < tree.value:
print(type(tree))
return findClosestValueInBstHelper(tree.left, target, closest)
# elif target is larger search right side
elif target > tree.value:
print(type(tree))
return findClosestValueInBstHelper(tree.right, target, closest)
else:
print(type(tree))
return closest
# This is the class of the input tree. Do not edit.
class BST:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert(self, data):
pass
tree = BST(10)
tree.right = BST(15)
tree.right.left = BST(13)
tree.right.left.right = BST(14)
tree.right.right = BST(22)
tree.left = BST(5)
tree.left.left = BST(2)
tree.left.right = BST(5)
tree.left.left.left = BST(1)
target = 4
print(findClosestValueInBst(tree, target)) |
a5d9cbf40e4ee06b12ba029bdacc9c9126804d57 | HkageProject/HKAGE_Project | /StudentSystem.py | 2,922 | 3.875 | 4 | students = ['demo']
scores = [60]
what_to_do = ''
from os import system
def antierror():
pass
def clear():
system('clear')
def add_student():
student_name = input('Enter the name of the student: ')
passed = 0
score = 0
while passed == 0:
try:
score = input('Enter score of student: ')
score = float(score)
passed = 1
except:
print('Error, Please enter a nuermal value for score.')
print()
students.append(student_name)
scores.append(score)
print(students)
def changestudentinfo():
passed = 0
while passed == 0:
try:
student_name = input('Please enter the name of the student: ')
studentname = students.index(student_name)
passed = 1
passed_2 = 0
while passed_2 == 0:
try:
score = input('Please enter the score of student: ')
score = float(score)
passed_2 = 1
except:
print('Please enter a number for score!')
except:
print('Student does not exist')
print('Changing student info...')
print(studentname)
scores[studentname] = score
print('Success!')
def viewstudent(_name, score):
print(' - Student Info - ')
print('Name of student: ' + _name)
print('Score: ' + str(score))
print('-------------------')
def view_student():
brea = 0
passed = 0
while passed == 0:
clear()
name = input('Enter student name (enter exit to exit): ')
try:
student = students.index(name)
student_score = scores[student]
viewstudent(name, student_score)
input('Press enter to continue')
except:
print('Invaild student name, enter exit to exit.')
print()
input('Press enter to continue')
if name == 'exit':
passed = 1
if brea == 1:
break
antierror()
antierror()
def fetch_student_info():
length = len(students)
i = 0
while i < length:
name = students[i]
score = scores[i]
viewstudent(name, score)
print()
i += 1
if length == 0:
print('No data. Add a student!')
input('Press Enter to perceed')
def delete_all_info():
e = input('Press enter to confirm deleting, enter e to exit:')
if e == '':
students.clear()
scores.clear()
def processinputs():
clear()
if what_to_do == '1':
add_student()
elif what_to_do == '2':
changestudentinfo()
elif what_to_do == '3':
view_student()
elif what_to_do == '4':
fetch_student_info()
elif what_to_do == '5':
delete_all_info()
else:
print('Invaild command, please look at the instructions')
while True:
clear()
print(' - Student Info System -')
print('Press 1 to add a student')
print('Press 2 to change student info')
print('Press 3 to view the info of a student')
print('Press 4 to get infos of all students')
print('Press 5 to delete all student info')
what_to_do = input('Enter your Option: ')
processinputs()
|
b3637103f5afa718e350853a0d449d671fd97861 | AnushaSatram/guvi | /p11.py | 82 | 3.828125 | 4 | hk=input()
if(hk=="Saturday" or hk=="Sunday"):
print("yes")
else:
print("no")
|
311b0058e1c8186ea7348f2c3a0f06069cc18fd6 | beerfleet/udemy_tutorial | /Oefeningen/uDemy/bootcamp/033_oop_inheritance_exercise.py | 1,332 | 3.796875 | 4 | class Character:
def __init__(self, name, hp, level):
self.name = name
if not isinstance(hp, int):
raise ValueError("Hit points has to be an integer value.")
self.hp = hp
if not isinstance(level, int):
raise ValueError("Level has to be an integer value.")
self.level = level
class NPC(Character):
def speak(self):
print("I heard there were monsters running around last night!")
"""
villager = NPC("Bob", 100, 12)
print(villager.name)
print(villager.hp)
print(villager.level)
villager.speak()
"""
class Aquatic:
def __init__(self, name):
print("**** AQUATIC INIT *****")
self.name = name
def swim(self):
return f"{self.name} is swimming"
def greet(self):
return f"I am {self.name} of the sea!"
class Ambulatory:
def __init__(self, name):
print("**** AMBULATORY INIT *****")
self.name = name
def walk(self):
return f"{self.name} is walking"
def greet(self):
return f"I am {self.name} of the land"
class Penguin(Ambulatory, Aquatic):
def __init__(self, name):
super().__init__(name = name)
Aquatic.__init__(self, name = name)
print("***** PENGUIN INIT ********")
"""
pengo = Penguin("Pengo")
print(pengo.greet())
"""
|
f2cd71189d8226e07bf707e75583af56ee3246f2 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/223/users/4173/codes/1716_2503.py | 131 | 3.5 | 4 |
n = int(input())
pi = 0
while(n>=1):
if(n%2 == 1):
pi = pi+(4/(2*n-1))
else:
pi = pi-(4/(2*n-1))
n = n-1
print(round(pi,8)) |
f1a0c18b6faa5783429639436b9462e92850677c | KKP127/pythonexample | /ex9.py | 244 | 3.6875 | 4 | days="Mon Tue Wed Thu Fri Sat Sun"
months="\nJan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
print("Here are the days:",days)
print("Here are the months:",months)
print(""" There's something going on here
the three double Quotes
No problem """)
|
63eec268d7bfae89111fa68693bab59f983fabcd | dldydrhkd/Problem-Solving | /프로그래머스/징검다리.py | 567 | 3.578125 | 4 | def check(mid, distance, rocks, n):
cur = 0
cut = 0
for i in rocks:
if(i-cur>=mid):
cur = i
else:
cut+=1
if(distance-cur<mid):
cur+=1
if(cut<=n):
return True
else:
return False
def solution(distance, rocks, n):
answer = 0
rocks.sort()
start = 0
end = distance
while(start<=end):
mid = (start+end)//2
if(check(mid, distance, rocks, n)):
start = mid+1
answer = mid
else:
end = mid-1
return answer |
e3c9e0fe09909701f1a0b0d9812325215b2728bc | erichuang2015/python-examples | /threading/04Condition.py | 1,778 | 3.90625 | 4 | #!/usr/bin/env python3
# coding: utf-8
"""Condition类
使用Condition演示生产者/消费者问题.
"""
import threading
from random import randint
from time import sleep
# 自定义生产者线程类
class Producer(threading.Thread):
def __init__(self, threadname):
super().__init__(name=threadname)
def run(self):
global x
while True:
# 获取锁
con.acquire()
# 假设共享列表中最多能容纳20个元素
if len(x) == 3:
# 如果共享列表已满,生产者等待
con.wait()
print('Producer is waiting...')
else:
print('Producer:', end=' ')
# 产生新元素,添加至共享列表
x.append(randint(1, 1000))
print(x)
sleep(1)
# 唤醒等待条件的线程
con.notify()
# 释放锁
con.release()
# 自定义消费者线程类
class Consumer(threading.Thread):
def __init__(self, threadname):
super().__init__(name=threadname)
def run(self):
global x
while True:
# 获取锁
con.acquire()
if not x:
# 等待
con.wait()
print('Consumer is waiting...')
else:
print(x.pop())
print(x)
sleep(2)
# 唤醒等待条件的线程
con.notify()
# 释放锁
con.release()
# 创建Condition对象以及生产者线程和消费者线程
con = threading.Condition()
x = []
p = Producer('Producer')
c = Consumer('Consumer')
p.start()
c.start()
p.join()
c.join()
|
30c2787690d1ffb2fa33bd34649a4a6181a59b80 | bigfairy-Jing/python-basis | /3.instance/26.二分查找.py | 421 | 3.765625 | 4 | def binarySearch(arr,l,r,x):
if r>=1:
mid = int(l + (r - 1)/2)
if arr[mid] == x:
return mid
elif arr[mid] > x:
return binarySearch(arr,l,mid-1,x)
else:
return binarySearch(arr,mid+1,r,x)
else:
return -1
arr = [2,3,4,10,40]
x = 10
result = binarySearch(arr,0,len(arr) - 1,x)
if result != -1:
print("元素的索引为{}".format(result))
else:
print("元素不在数组中") |
1c0091d6428a2eed0e9c2109e264fb571db7a316 | Tela96/cc_work | /week3/Excluder.py | 605 | 3.8125 | 4 | import random
import string
def excluder(orig_list):
exc_list = []
for item in orig_list:
if item not in exc_list:
exc_list.append(item)
print (exc_list)
def letter_gen():
letter_list = []
for letter in range(0, 10):
letter_list.append(random.choice(string.ascii_lowercase))
return letter_list
def num_gen():
num_list = []
for i in range(0, 6):
num_list.append(random.randint(0, 4))
return num_list
def main():
num_list = num_gen()
letter_list = letter_gen()
excluder(num_list)
excluder(letter_list)
main()
|
750abb56747fe162cb6b6253ba2a202d311ee82d | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_200/5166.py | 1,646 | 3.671875 | 4 | """
Written by blackk100 for Google Code Jam 2017 Qualifications
Problem
Tatiana likes to keep things tidy. Her toys are sorted from smallest to largest, her pencils are sorted from shortest
to longest and her computers from oldest to newest. One day, when practicing her counting skills, she noticed that some
integers, when written in base 10 with no leading zeroes, have their digits sorted in non-decreasing order. Some
examples of this are 8, 123, 555, and 224488. She decided to call these numbers tidy. Numbers that do not have this
property, like 20, 321, 495 and 999990, are not tidy.
She just finished counting all positive integers in ascending order from 1 to N. What was the last tidy number she
counted?
Input
The first line of the input gives the number of test cases, T. T lines follow. Each line describes a test case with a
single integer N, the last number counted by Tatiana.
Output
For each test case, output one line containing Case #x: y, where x is the test case number (starting from 1) and y is
the last tidy number counted by Tatiana.
"""
def solve(a):
b = a
l = len(a)
z = 0
while z < l:
i = 0
while i < l - 1:
if int(b) % 10 == 0:
b = str(int(b) - 1)
l = len(b)
elif int(b[i + 1]) < int(b[i]):
b = str(int(b) - 1)
l = len(b)
elif int(b[i + 1]) >= int(b[i]):
i += 1
z += 1
return b
t = int(input())
for x in range(0, t):
n = input()
y = solve(n)
print("Case #{}: {}".format(x + 1, y))
|
1cfa4c4bbee1c0e94082e2245872e4d3e0a0cbd6 | venkisagunner93/2048_AI | /src/logic.py | 741 | 3.8125 | 4 | #!/usr/bin/env python
import numpy as np
import random
class Game():
def __init__(self):
self.game_over = False
self.current_matrix = np.zeros((4,4), dtype = np.int)
for i in range(2):
self.create_population()
def create_population(self):
i = random.randint(0,3)
j = random.randint(0,3)
populated = False
while not populated:
if self.current_matrix[i][j] == 0:
self.current_matrix[i][j] = random.choice([2,4])
populated = True
else:
i = random.randint(0,3)
j = random.randint(0,3)
def display(self):
print(self.current_matrix)
game = Game()
game.display()
|
5d5b668b7f25696aa51f10056f1484a7229186a4 | radomirbrkovic/algorithms | /hackerrank/other/the-grid-search.py | 425 | 3.734375 | 4 | # The Grid Search https://www.hackerrank.com/challenges/the-grid-search/problem
def gridSearch(G, P):
def check(x, y):
for i in range(r):
if P[i] != G[x+i][y:y+c]:
return False
return True
for i in range(R):
for j in range(C):
if G[i][j] == P[0][0]:
if check(i, j):
return 'YES'
return "NO"
|
a6c9ff4e0de7c105285965b499c4967fabae62e0 | phycog/guygit | /data_structure_lab/non-linear/binary_tree/creation_bi_tree_with_jon_snow.py | 1,005 | 3.65625 | 4 | '''
after i try to make tree (data structure) by my own
i have no idea what i am doing
'''
sibling_left_side = []
sibling_rifgt_side = []
class guy_tree:
def color_tree(self,color):
self.color = color
def main_tree(self,root,branch_l,branch_r):
self.root = root
self.branch_l = branch_l
self.branch_r = branch_r
def add_sibling_node_lv2(self,left_side,right_side):
self.left_side = left_side
global sibling_left_side
sibling_left_side.append(left_side)
self.right_side = right_side
global sibling_rifgt_side
sibling_rifgt_side.append(right_side)
tree = guy_tree()
tree.main_tree("electronic device","labtop","PC")
tree.add_sibling_node_lv2("HP","Dell")
tree.add_sibling_node_lv2("Sumsung","MAC")
tree.add_sibling_node_lv2("SONY","Toshiba")
def show_tree():
print(tree.root)
print(tree.branch_l," ",tree.branch_r)
print(sibling_left_side," ",sibling_rifgt_side)
show_tree()
|
1ba3d786e3f603c7d4a8eee8da533952f278313a | ywl0911/leetcode | /80. Remove Duplicates from Sorted Array II.py | 848 | 3.53125 | 4 | class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
current = None
current_count = 0
length = 0
i = 0
while i < len(nums):
if nums[i] == current:
# print i
# print current
# print current_count
# print '>>'
current_count += 1
if current_count <= 2:
length += 1
i += 1
else:
del nums[i]
continue
else:
current = nums[i]
current_count = 1
length += 1
i += 1
return length
|
b433d5457bd51a50d8deb247e743fbf4aea53635 | DeepLearningHB/PythonMentoring | /Python_Mentoring_01/20183237 이시온 lab01/20183237 이시온 lab02_task03.py | 187 | 3.546875 | 4 | #3
A = [10, 4, 2, 7, 6, 1, 5, 8]
max = 0
for i in A :
if i > max :
max = i
print(max)
min = 100
for i in A :
if i < min :
min = i
print(min)
#
|
275a2c6e5d3151716e2595e6a93cd0773070f92c | manna422/pool_sim | /src/ball.py | 2,260 | 3.515625 | 4 | from math import sqrt, pow, sin, cos, pi
from physics import *
class Ball(object):
def __init__(self, table, x_pos, y_pos, score):
self.table = table
self.x_pos = x_pos
self.y_pos = y_pos
self.x_vel = 0
self.y_vel = 0
self.x_acc = 0
self.y_acc = 0
self.mass = 1
self.score = score
self.active = True
def check_collision(self, b_other):
if check_collision(self.x_pos, self.y_pos,
self.table.b_radius, b_other.x_pos, b_other.y_pos,
self.table.b_radius):
ball_collision(self, b_other)
def check_collision_table(self):
if check_collision_table(self.table, self.x_pos,
self.y_pos):
table_collision(self.table, self)
def check_collision_pocket(self):
pocket_rad = self.table.pocket_radius
pocket_offset = self.table.pocket_offset
# top left
pocket_x = pocket_offset
pocket_y = pocket_offset
if (check_collision(self.x_pos, self.y_pos,
0, pocket_x, pocket_y, pocket_rad)):
self.table.remove_ball(self)
# center left
pocket_y = self.table.length // 2
if (check_collision(self.x_pos, self.y_pos,
0, pocket_x, pocket_y, pocket_rad)):
self.table.remove_ball(self)
# bottom left
pocket_y = self.table.length - pocket_offset
if (check_collision(self.x_pos, self.y_pos,
0, pocket_x, pocket_y, pocket_rad)):
self.table.remove_ball(self)
# bottom right
pocket_x = self.table.width - pocket_offset
if (check_collision(self.x_pos, self.y_pos,
0, pocket_x, pocket_y, pocket_rad)):
self.table.remove_ball(self)
# center right
pocket_y = self.table.length // 2
if (check_collision(self.x_pos, self.y_pos,
0, pocket_x, pocket_y, pocket_rad)):
self.table.remove_ball(self)
# top right
pocket_y = pocket_offset
if (check_collision(self.x_pos, self.y_pos,
0, pocket_x, pocket_y, pocket_rad)):
self.table.remove_ball(self)
|
a881e0ee6332d6e71150a0fb76b5c7eedd20fbc7 | StonecutterX/Python3 | /script/generators.py | 692 | 4.28125 | 4 | # /usr/bin/python
# usage of generators
# shawn 2018/1/12
def generator_function(n):
i = 0
while i < n:
print('before yield %d' %i)
yield i
i = i + 1
print('after yield %d' % i)
def fibon(n):
"""caculate Fibonacci
"""
a = b = 1
for i in range(n):
yield a
a, b = b, a+b
def test1():
"""Test the generator_function()
"""
gen = generator_function(3)
print('-'*10)
print(gen.__next__())
print('-'*10)
print(gen.__next__())
print('-'*10)
print(gen.__next__())
def testFibon():
for x in fibon(100):
print(x)
if __name__ == '__main__':
#test1()
testFibon()
|
7ae532ae20bd0fe06a2c66174bbebeb7e38690ac | kviiim/AdventOfCode2020 | /day5/day5-1.py | 705 | 3.6875 | 4 | import math
def findRow(currentRange, halfs):
if halfs[0] == 'F' or halfs[0] == 'L':
newRange = [currentRange[0], math.floor((currentRange[1]-currentRange[0])/2) + currentRange[0]]
else:
newRange = [math.ceil((currentRange[1]-currentRange[0])/2) + currentRange[0], currentRange[1]]
if len(halfs) == 1:
return newRange
else:
return (findRow(newRange, halfs[1:]))
highest = 0
with open('advent2020/day5/day5input.txt', 'r') as file:
for line in file.readlines():
currentSeatId = (findRow([0,127],line[:7])[0] * 8 + findRow([0,7], line[7:])[0])
if currentSeatId > highest:
highest = currentSeatId
print('highest', highest) |
9a453174b960f3a23ee32860c1b696008ac267b0 | clongcurious1/py_turtle_graphics_exercises | /cecil_hexagon_nestedloop.py | 470 | 4.3125 | 4 | import turtle #import module
#add variable
cecil = turtle.Turtle() #name our turtle Cecil
cecil.shape('turtle') #make Cecil look like a turtle
#nested loop - create single shape (inner loop) first
#outer loop - repeat hexagon 36x, each time turning 10 degrees to the right
for n in range (36):
#inner loop - create one hexagon
for i in range(6):
cecil.forward(100)
cecil.left(60)
#turn right 10 degrees before repeating the loop
cecil.right(10) |
fb89c80d091ce954936bd45cd951ebb91d006a39 | syeon-c/CodingTestArchive | /KAKAOBlindRecruitment/2021/ACombinedTaxiFare_Dijkstra.py | 1,199 | 3.59375 | 4 | import heapq
def printGraph(graph):
for i in range(len(graph)):
print(graph[i])
def solution(n, s, a, b, fares):
INF = int(1e9)
graph = [[] for _ in range(n+1)]
for x, y, z in fares:
graph[x].append((y, z))
graph[y].append((x, z))
# printGraph(graph)
def dijkstra(start):
distance = [INF] * (n + 1)
distance[start] = 0
heap = []
heapq.heappush(heap, (0, start))
while heap:
fare, now = heapq.heappop(heap)
if distance[now] < fare:
continue
for i, j in graph[now]:
cost = fare + j
if distance[i] > cost:
distance[i] = cost
heapq.heappush(heap, (cost, i))
return distance
minFare = [[]] + [dijkstra(i) for i in range(1, n+1)]
printGraph(minFare)
answer = INF
for i in range(1, n+1):
answer = min(minFare[i][s] + minFare[i][a] + minFare[i][b], answer)
return answer
n = 6
s = 4
a, b = 6, 2
fares = [[4, 1, 10], [3, 5, 24], [5, 6, 2], [3, 1, 41], [5, 1, 24], [4, 6, 50], [2, 4, 66], [2, 3, 22], [1, 6, 25]]
print(solution(n, s, a, b, fares))
|
2e356dd3634cf07369e6cc9e61c38525b6c421c6 | IacovColisnicenco/100-Days-Of-Code | /DAYS_001-010/Day - 003/Exercises/day-3-5-exercise.py | 716 | 4.1875 | 4 | print("Welcome to Python Pizzas Deliveries !")
size = input("What size pizza do you want ? S, M or L ? ")
add_pepperoni = input("Do you want to add Pepperoni ? Y or N ? ")
extra_cheese = input("Do you want to add Extra Cheese ? Y or N ? ")
bill = 0
if size == "S" or size == "s":
bill += 15
if add_pepperoni == "Y" or add_pepperoni == "y":
bill += 2
elif size == "M" or size == "m":
bill += 20
if add_pepperoni == "Y" or add_pepperoni == "y":
bill += 3
elif size == "L" or size == "l":
bill += 25
if add_pepperoni == "Y" or add_pepperoni == "y":
bill += 3
if extra_cheese == "Y" or extra_cheese == "y":
bill += 1
print(f"Your Final Bill is : ₹{bill}")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.