blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
649c5fd1161f462816e1292832c4382a0c8e418a | Chrisaor/StudyPython | /GeeksforGeeks/Practice/2. Basic/44.RearrangeArray.py | 426 | 3.875 | 4 | def rearrange_array(arr):
rearray = list()
for i in range(len(arr)):
if i % 2 == 0:
num = arr.pop()
rearray.append(num)
else:
num = arr[0]
del arr[0]
rearray.append(num)
return ' '.join(map(str, rearray))
t = int(input())
for i in range(t):
n = int(input())
arr = list(map(int, input().split()))
print(rearrange_array(arr))
|
c5fb257eee3e7d2bdc141cf71fa928099ddbfbb5 | 809709370/hello-word | /game.py | 1,931 | 3.84375 | 4 |
import random
import sys
class sprite:
"""这是一个基类"""
move_len = (-3,-2,2,3)
def __init__(self,postion1 = None):
self.energy = 0
self.step = random.choice(sprite.move_len)
if postion1 is None:
self.postion = random.randint(0,20)
else:
self.postion = postion1
def gojump(self):
self.step = random.choice(sprite.move_len)
if(self.postion + self.step >=0 and self.postion + self.step <=20):
self.postion += self.step
class Ant(sprite):
"""这是一个蚂蚁类"""
def __init__(self,postion = None):
super().__init__(postion)
self.energy = 6
class Worm(sprite):
"""这是一个虫子类"""
def __init__(self,postion = None):
super().__init__(postion)
class Map:
"""这是一个地图类"""
def __init__(self,ant1,worm1):
self.ant1 = ant1
self.worm1 = worm1
def gamestart(self):
while(self.ant1.energy > 0):
while(self.ant1.postion != self.worm1.postion):
self.ant1.gojump()
print("the ant:",self.ant1.postion)
self.worm1.gojump()
print("the worm:",self.worm1.postion)
print("energy :",self.ant1.energy)
self.ant1.energy = self.ant1.energy - 1
self.ant1.postion = random.randint(0,20)
self.worm1.postion = random.randint(0,20)
print("energy is ",self.ant1.energy)
print("game over")
class father1:
def __init__(self):
print("father1")
class father2:
def __init__(self):
print("father2")
class son(father1,father2):
def __init__(self):
father2.__init__(self)
if __name__ == "__main__":
ant1 = Ant()
worm1 = Worm()
map1 = Map(ant1,worm1)
map1.gamestart()
|
3383e60254d290899fcbe6b77aedbb3df5668093 | lincookie/Code | /python/lab2/字串處理.py | 107 | 3.59375 | 4 | str = input()
now = input()
new = input()
print(str.upper())
print(str.lower())
print(str.replace(now,new)) |
4b916d89a07a428c5c49da488d861de7898904a8 | gbravo5/PyGame-Carrera_PyGame | /2430_Mover_Corredor_PyGame_2.py | 1,887 | 3.5 | 4 | import pygame
import actions
import random
class Game():
# assumptions:
# 1.- screen:
# size
screen_size = width, height = 640, 480
# title
game_title = 'Mover_Corredor_PyGame'
# background
coordinates_background = 0, 0
game_background = 'images/circuito.png'
# 2.- participants:
participants = ('fish', 'moray', 'octopus', 'smallball', 'turtle', 'prawn')
startline = 5/100 * width
finishline = 95/100 * width
def __init__(self):
# 1.- screen:
# a) create
self.screen = pygame.display.set_mode(self.screen_size)
# b) customize
# title
pygame.display.set_caption(self.game_title)
# background
self.background = pygame.image.load(self.game_background)
# 2.- participants:
ix_participant = random.randint(0, len(self.participants) -1)
x_coordinate_participant = self.startline
y_coordinate_participant = 1/2 * self.height
self.name = self.participants[ix_participant]
self.custome = pygame.image.load('images/{}.png'.format(self.name))
self.coordinates_participant = [x_coordinate_participant, y_coordinate_participant]
def update(self):
# a) draw screen
self.screen.blit(self.background, self.coordinates_background)
# b) draw runner
self.screen.blit(self.custome, self.coordinates_participant)
def refresh(self):
pygame.display.flip()
# actions
def move_forward(self):
actions.move_forward(self)
def move_all_direction(self):
actions.move_all_direction(self)
if __name__ == '__main__':
pygame.init()
play = Game()
play.move_all_direction()
#play.move_forward()
|
364b6e53db1b81b40349bc434cc3b9cebbd2b008 | miguelgallo/Python2019_1 | /Aula1/aula1_ex6.py | 204 | 3.828125 | 4 | print ('Programa usado para calcular a velocidade final de um objeto em queda livre ')
g = 9.8 #m/s^2
h = 3 #metros
v_final = (2*g*h)**(1/2)
print('A velocidade final do objeto é: ', "%.3f" % v_final)
|
bdd3e09b2dd8f5566c9fd6a1dbb116bce50d9c70 | Hacketex/PycharmProjects | /word avarage.py | 376 | 4.03125 | 4 | sum1 = 0
word = ' '
while word != '':
word = input("enter the word or press enter to exit: ")
print(len(word))
# count = len(word)
sum1 = sum1 + len(word)
print("total word is ", sum1)
# key='yes'
# while key=='yes':
# word=input("enter the word: ")
# count=len(word)
# print(count)
# if word=='':
# key='no'
# sum=sum+count
# print(sum)
|
f16e20bb6541fee0a735d3834ad33afa15704583 | havenshi/leetcode | /508. Most Frequent Subtree Sum.py | 822 | 3.609375 | 4 | # 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 findFrequentTreeSum(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
self.d = {}
self.dfs(root)
mostFreq = 0
ans = []
for key in self.d:
if self.d[key] > mostFreq:
mostFreq = self.d[key]
ans = [key]
elif self.d[key] == mostFreq:
ans.append(key)
return ans
def dfs(self, root):
if not root:
return 0
tmp = root.val + self.dfs(root.left) + self.dfs(root.right)
self.d[tmp] = self.d.get(tmp, 0) + 1
return tmp |
ec8cb58a83a00b28bd7315a5246e77779c9bc02e | UmmuRasul/python-training | /Tutorials/controlStr/forLoop.py | 658 | 3.765625 | 4 | my_string = 'abcabc'
print("-"*20 +"strings for loop" + "-"*20)
# for c in my_string:
# print(c)
# print(c, end=" ")
for c in my_string:
if c =='a':
print('A', end=" ")
else:
print(c, end=" " )
print("f"*100)
print("-"*20 +"list for loop" + "-"*20)
cars = ['bmw', 'masedez', 'benz']
for cars in cars:
print(cars)
nums = [1, 2, 3, 4, 5]
for n in nums:
print(n * 10)
print("*" *30)
print("-"*20 +"dictionaries for loop" + "-"*20)
d = {'one': '1', 'two': '2', 'three': '3'}
for k in d:
print(k)
print(k + " " + str(d[k]))
print("*" *90)
for k, v in d.items():
print(k,v)
print(k)
print(v)
|
0b3a948fe6831ac4b1e9d0d0fd722e2b9e779ea7 | privateOmega/coding101 | /hackerearth/CodeMonk/Basic Programming/Basics of Implementation/array-sum.py | 236 | 3.53125 | 4 | def main():
arrayLength = int(input())
sum = 0
array = list(map(int, input().strip().split(' ')))
for iterator in range(arrayLength):
sum += array[iterator]
print(sum)
if __name__ == '__main__':
main()
|
14f34d465b61b3beacfa3d27faec4c8231b49efd | Mihika16/Project-Euler-Solutions | /Problem10.py | 363 | 3.765625 | 4 |
def Primefunction(num):
if num<2: return "False"#From the next 3 lines, I got help from a website but I understood it fully
for i in range(2, int(num**0.5) + 1):#this
if num % i == 0:# and this
return False
return True
sum=0
for i in range(2, 2000000):
if Primefunction(i):
sum=sum+i
print(sum)
|
44d08f27236771fd93a427de06ef5e508d95c42a | robbyt/query_tool-py | /query_tool/user_input.py | 4,013 | 3.90625 | 4 | import argparse
class UserInput(object):
usage = "Please read --help"
data = {}
facts = {}
debug = False
def __init__(self, args):
'''
sets up the user input system. When setting up this
class, pass sys.argv[1:] into the class, otherwise for testing
pass in a dict of simulated arguments.
When a class object is created, and passed a list of the unparsed
args, it will auto-parse them into dicts, stored as Class Variables
data, facts.
'''
# setup the parser
self.parser = argparse.ArgumentParser(description='query_tool')
# prep some variables
self.args = args
self.htext = {
'fact': "The fact:data that you want to search for, can be used multiple times to filter for multiple facts. Usage Example: --fact kernel Linux --fact ec2_instance_type m1.small",
'puppetmaster': 'The PuppetMaster REST address to query against. Must be formatted like this: https://127.0.0.1:8140/',
'ssl_cert': 'The SSL cert to use for authentication',
'ssl_key': 'The SSL key to use for authentication',
'yaml': 'Output the results in raw yaml',
'output_fact': 'What fact do you want to find out from these servers'
}
# run the arg parser methods
self._setup_args()
# create a class variable with parsed args
self._parse_args()
# and store the results as class variables
UserInput.data = self._get_args_as_dict()
UserInput.facts = self._get_facts_as_dict()
# setting a class variable so that accessing debug status is easier
UserInput.debug = UserInput.data['debug']
def _setup_args(self):
'''operands, or server/cluster to perform an operation on'''
# elb_name
self.parser.add_argument(
"-f", "--fact",
action='append',
dest="fact",
help=self.htext['fact'],
required=True,
nargs=2,
metavar=('factname', 'factvalue')
)
self.parser.add_argument(
"-p", "--puppetmaster",
dest="puppetmaster",
help=self.htext['puppetmaster'],
default='https://127.0.0.1:8140'
)
self.parser.add_argument(
"-c", "--cert",
dest="ssl_cert",
help=self.htext['ssl_cert'],
default='/var/lib/puppet/ssl/certs/query_tool.pem'
)
self.parser.add_argument(
"-k", "--key",
dest="ssl_key",
help=self.htext['ssl_key'],
default='/var/lib/puppet/ssl/private_keys/query_tool.pem'
)
"""
self.parser.add_argument(
"--yaml",
action="store_true",
dest="yaml",
help=self.htext['yaml'],
default=False
)
"""
self.parser.add_argument(
"-o", "--output_fact",
dest="output_fact",
help=self.htext['output_fact'],
default='fqdn'
)
## other options
self.parser.add_argument("--debug", action="store_true", dest="debug", default=False)
def _parse_args(self):
"""
Parses the args that were passed into sys.argv, then creates a dict
containing the various key/values after being parsed
"""
UserInput.data = vars(self.parser.parse_args(self.args))
UserInput.facts = vars(self.parser.parse_args(self.args))['fact']
return UserInput.data
def _get_args_as_dict(self):
if UserInput.debug:
print 'parsed args in dict:'
for i in UserInput.data.iteritems():
print i
return UserInput.data
def _get_facts_as_dict(self):
if UserInput.debug:
print 'parsed facts: ' + str(UserInput.data['fact'])
return dict(UserInput.data['fact'])
|
56e35de4078aaf3c79d5123728c3f805b4e678a3 | refiute/nlp100 | /code/chapter1/prob08.py | 261 | 3.828125 | 4 | # -*- coding: utf-8 -*-
def cipher(s):
ret = ""
for i in range(len(s)):
if s[i].islower():
ret += chr(219-ord(s[i]))
else:
ret += s[i]
return ret
if __name__ == '__main__':
print(cipher("HeLlo WoRLd"))
|
7ec0fd23dd856187253cef7097a79e87015c17e9 | prashuym/IKPrograms | /DP-0140H-WordBreakList.py | 1,722 | 3.75 | 4 | """
140. Word Break II
https://leetcode.com/problems/word-break-ii/
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences.
Note:
The same word in the dictionary may be reused multiple times in the segmentation.
You may assume the dictionary does not contain duplicate words.
Example 1:
Input:
s = "catsanddog"
wordDict = ["cat", "cats", "and", "sand", "dog"]
Output:
[
"cats and dog",
"cat sand dog"
]
"""
class Solution:
def wordBreak(self, s: str, wordDict) -> bool:
if not s : return False
# Conver the wordDict to set
wordDict = set(wordDict)
# Create the datastructure
table = [ [] for _ in range(len(s)+1) ]
table[0] = [[]]
#words = []
for i in range(1, len(table)):
for j in range(0,i):
print (i, len(table), len(table[i-j-1]))
#print (i,j,s[i-j-1:i],len(table[i-j-1]), table)
if s[i-j-1:i] in wordDict and len(table[i-j-1]) > 0 :
for wlist in table[i-j-1] :
table[i].append(wlist + [s[i-j-1:i]])
#print (table, words)
return [" ".join(w) for w in table[-1]]
if __name__ == "__main__":
#s = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
s = "aaaaaaa"
wordDict = ["a","aa","aaa","aaaa","aaaaa","aaaaaa","aaaaaaa","aaaaaaaa","aaaaaaaaa","aaaaaaaaaa"]
soln = Solution()
result = soln.wordBreak(s,wordDict)
print (f"Result : {result}") |
eb87effe6727039e4192d242cb22e729be28b3c0 | VictorMinsky/Algorithmic-Tasks | /HackerRank/Python/Lists.py | 1,678 | 4.5625 | 5 | """
Consider a list (list = []). You can perform the following commands:
insert i e: Insert integer at position .
print: Print the list.
remove e: Delete the first occurrence of integer .
append e: Insert integer at the end of the list.
sort: Sort the list.
pop: Pop the last element from the list.
reverse: Reverse the list.
Initialize your list and read in the value of followed by lines of commands where each command will be of the types listed above. Iterate through each command in order and perform the corresponding operation on your list.
Input Format
The first line contains an integer, , denoting the number of commands.
Each line of the subsequent lines contains one of the commands described above.
Constraints
The elements added to the list must be integers.
Output Format
For each command of type print, print the list on a new line.
Sample Input 0
12
insert 0 5
insert 1 10
insert 0 6
print
remove 6
append 9
append 1
sort
print
pop
reverse
print
Sample Output 0
[6, 5, 10]
[1, 5, 9, 10]
[9, 5, 1]
"""
if __name__ == '__main__':
N = int(input())
lst = []
for _ in range(N):
command = input()
if 'insert' in command:
_, i, e = command.split()
lst.insert(int(i), int(e))
if 'print' in command:
print(lst)
if 'remove' in command:
_, e = command.split()
lst.remove(int(e))
if 'append' in command:
_, e = command.split()
lst.append(int(e))
if 'sort' in command:
lst = sorted(lst)
if 'pop' in command:
lst.pop()
if 'reverse' in command:
lst = lst[::-1]
|
7c6f87c762ad62b2d8708d6c7e719af984ce66be | subash2617/Task-4 | /Task 4B.py | 287 | 4.5 | 4 | # Creating a tuple and printing the reverse of the created tuple #
TupleA=("26 NOVEMBER 2020")
x=reversed(TupleA)
print(tuple(x))
# Creating a tuple and converting tuple into list #
TupleB=("apple", "banana", "cherry", "orange")
ListB=list(TupleB)
print(ListB)
print(type(ListB)) |
6df9d047b82c52d6e1837d83ba5a84824c2a1578 | alisakolot/Coding-and-Testing-Practice- | /Jan/01_11/dict_review.py | 1,075 | 3.921875 | 4 | """Tests:
>>> wordcount(poem)
{'seven': 4,
'Kits: 1,
'sack': 1,
'As': 1,
'kits': 1,
'Ives?': 1,
'How': 1,
'St.': 2,
'had': 3,
'sacks':1,
'to': 2,
'going': 2,
'was': 1,
'cats': 1,
'wives': 1,
'met': 1,
'Every': 3,
'with': 1,
'man': 1,
'a':1,
'wife': 1,
'I:2,
'many': 1,
'cat': 1,
'Ives': 1,
'sacks': 1,
'wives.': 1
'were': 1,
'cats':1
}
"""
poem = open('test1.txt', 'r')
# poem = 'the cat in the cat'
print(poem)
def wordcount(poem):
count_words = {}
# poem = poem.split(' ')
for word in poem:
if word in count_words:
count_words[word] +=1
else:
count_words[word] = 1
print(count_words)
if __name__== '__main__':
import doctest
if doctest.testmod().failed == 0:
print("\n*** ✨Good job practicing dictionaries today!✨ ***") |
0c06baec6f482537ed94f009a064e5815a549b1d | ocdarragh/Computer-Science-for-Leaving-Certificate-Solutions | /Chapter 9/Tasks/pg190_Task7.py | 1,066 | 4.1875 | 4 | # see https://realpython.com/python-square-root-function/
import math
a = int(input("enter size of stick A:"))
b = int(input("enter size of stick B:"))
c = int(input("enter size of stick C:"))
if a > b and b > c:
hypotonuse = a
opp = c
adj = b
elif b > a and b > c:
hypotonuse = b
opp = a
adj = c
elif c > a and c > b:
hypotonuse = c
opp = b
adj = a
else:
hypotonuse = str("All three sides are the same")
triangleSides = opp*opp + adj*adj
calc = math.sqrt(triangleSides)
print(calc)
if calc == hypotonuse:
print("Yes a right angled triangle is possible")
else:
print(math.sqrt(triangleSides),"is not equal to the hypotonuse:", hypotonuse)
# solution 2
a = int(input("enter size of stick A:"))
b = int(input("enter size of stick B:"))
c = int(input("enter size of stick C:"))
sideA = a*a
sideB = b*b
sideC = c*c
print(sideA, sideB, sideC)
if sideA+sideB == sideC or sideA+sideC == sideB or sideB+sideC == sideA:
print("Right angled triangle")
else:
print ("not a right anled triangle")
|
a5c182a6ec4fdb2d302541813d7aef4a640e2ce9 | manish1822510059/Python-1000-Programs | /Pattern/43_pattern.py | 208 | 3.75 | 4 | n = 5
cen = 1 #centre
for x in range(1,n+1):
for y in range(1,n+1):
if(x==y or y==cen ):
print("* ",end="")
else:
print(" ",end="")
print() |
ccddc220111bd8f9385e5309bfa219488decc2df | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/bob/4f0a5ffac46a4ccf8a4d53740bff9edc.py | 254 | 3.5 | 4 | def hey(what):
strippedText = what.strip()
if strippedText.isupper():
return 'Whoa, chill out!'
if not strippedText:
return 'Fine. Be that way!'
if strippedText.endswith('?'):
return 'Sure.'
return "Whatever."
|
38aff40cf28e9faa80cc48d1fd7d3f98518ac6ee | imtiaz-rahi/Py-CheckiO | /Dropbox/The Most Frequent Weekdays/mission.py | 1,140 | 4.25 | 4 | from calendar import weekday, day_name
def most_frequent_days(year):
return [day_name[day] for day in sorted({weekday(year, 1, 1), weekday(year, 12, 31)})]
if __name__ == '__main__':
print("Example:")
print(most_frequent_days(1084))
assert most_frequent_days(1084) == ['Tuesday', 'Wednesday']
assert most_frequent_days(1167) == ['Sunday']
assert most_frequent_days(1216) == ['Friday', 'Saturday']
assert most_frequent_days(1492) == ['Friday', 'Saturday']
assert most_frequent_days(1770) == ['Monday']
assert most_frequent_days(1785) == ['Saturday']
assert most_frequent_days(212) == ['Wednesday', 'Thursday']
assert most_frequent_days(1) == ['Monday']
assert most_frequent_days(2135) == ['Saturday']
assert most_frequent_days(3043) == ['Sunday']
assert most_frequent_days(2001) == ['Monday']
assert most_frequent_days(3150) == ['Sunday']
assert most_frequent_days(3230) == ['Tuesday']
assert most_frequent_days(328) == ['Monday', 'Sunday']
assert most_frequent_days(2016) == ['Friday', 'Saturday']
print("Coding complete? Click 'Check' to earn cool rewards!")
|
1cf18d820279706468e520e2ef8b3097e2992206 | wo-shi-lao-luo/Python-Practice | /Tutorial/class.py | 558 | 3.765625 | 4 | class Animal:
def run(self):
print("running")
class Dog(Animal):
def __init__(self, habbit):
self.habbit = habbit
def eat(self):
print("eating")
class Cat(Animal):
pass
dog1 = Dog("eat")
dog2 = Dog("run")
dog1.run()
dog2.run()
print(dog1.habbit, dog2.habbit)
#
# book
# 属性
# author
# public date
# name
# ISBN
class book:
def __init__(self, author, public_date, name, ISBN=None):
self.author = author
self.public_date = public_date
self.name = name
self.ISBN = ISBN
|
56e00a8baf0f5432ac82d3edd199829521096ce1 | billchuan/python2 | /project1/demo08.py | 1,519 | 4.15625 | 4 | # 3月23日学习代码
# 1、创建一个函数,计算20+30的值
# def sum_2():
# n1 = 20
# n2 = 30
# sum1 = n1 + n2
# print("%d+%d=%d" % (n1, n2, sum1))
#
#
# sum_2()
# 2、修改函数,提高该函数的通用性,使其能计算任意2个数的和
# def sum_2(n1, n2):
# """计算任意两个数的和"""
# result = n1 + n2
# print("%d+%d=%d" % (n1, n2, result))
#
#
# sum_2(10, 20)
# 3、默认参数的定义与调用
# 打印班级同学的信息 姓名 年龄 国籍(中国)
# def print_stu_info(name, age, country="中国"):
# print("该同学名字为:%s,年龄为:%d,国籍为:%s" % (name, age, country))
#
#
# print_stu_info("lisi", 17)
# 练习1
# def print_info(class_num, name):
# print("欢迎%d班%s同学进入Python直播间" % (class_num, name))
#
#
# print_info(21810, "张三")
# 返回值
# def sum_1(n1, n2):
# """计算两个数的和"""
# result = n1 + n2
# print("%d+%d=%d" % (n1, n2, result))
# return
#
#
# sum_1(1, 2)
# 1、有返回值
# def sum_1(n1, n2):
# """计算两个数的和"""
# result = n1 + n2
# if n2 == 2:
# return 1
# elif n2 == 1:
# return result
#
#
# value = sum_1(1, 1)
# print(value)
# 练习2
def get_info(name, sex):
if sex == "男":
return "欢迎%s男士光临本直播间" % name
else:
return "欢迎%s女士光临本直播间" % name
value = get_info("张三", "男")
value1 = get_info("李四", "女")
print(value)
print(value1)
|
bef94dbbb4dcb9df43658109f4ccb6d9d36a814e | MichaelOtt/PythonRPG | /sprites/healthsprite.py | 735 | 3.6875 | 4 | import pygame
class HealthSprite(object):
''' Simple object that moves left and right across the screen '''
def __init__(self, health):
''' Initializes the obstacle sprite '''
self.health = health
self.maxhealth = health
self.reduction = 0.0
self.dead = False
def damage(self, damagetaken):
self.health -= damagetaken*((100.0-self.reduction)/100.0)
if self.health <= 0:
self.dead = True
def heal(self,healing):
self.health += healing
if self.health > self.maxhealth:
self.health = self.maxhealth
def update(self):
pass
''' Changes the direction of the sprite if it hits the edge of the screen '''
|
a8bada726dd3bd96d33017c063e2472d6136d17c | slavafive/GPN-Hackaton | /python_scripts/text_processing.py | 557 | 3.640625 | 4 | from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
import pymorphy2
def normalize_word(word):
morph = pymorphy2.MorphAnalyzer(lang='ru')
return morph.parse(word)[0].normal_form
def clean_text(text, normalize=False):
tokens = word_tokenize(text.lower())
words = [word for word in tokens if word.isalpha()]
stopwords_list = stopwords.words('russian')
words = [word for word in words if word not in stopwords_list]
if normalize:
words = list(map(normalize_word, words))
return ' '.join(words)
|
436536bb1b933d6a9a2dbc80e467e0743e19858f | JoanValencia/Python---Clase-4 | /PruebaTemporizador.py | 1,189 | 3.546875 | 4 |
class Hora(UnidadTiempo):
def __init__(self)
self.hora = v
self.htope = 23
class Minuto(UnidadTiempo):
def __init__(self)
self.minuto = v
self.mtope = 59
class Segundo(UnidadTiempo):
def __init__(self)
self.segundo = v
self.stope = 59
class UnidadTiempo(v, t):
def __init__(self, v, t):
self.valor = v
self.tope = t
def iniciar():
s = self.segundo.valor()
m = self.minuto.valor()
h = self.hora.valor()
def retroceder():
if s >= 0:
s -= 1
elif s < 0:
s = t
m -= 1
if m >= 0:
m -= 1
elif m < 0:
m = t
h -= 1
if h >= 0:
h -= 1
elif h < 0:
h = t
s == 0
def reiniciar():
class Temporizador(UnidadTiempo):
def __init__(self, h, m, s):
self.hora = h
self.minuto = m
self.segundo = s
def iniciar(UnidadTiempo[]):
def retroceder():
def reiniciar():
|
146b45cdb56c7c0cab2e228cfd3f7bda94fcd482 | IaroslavaDubitkaia/07.10.2020 | /Problema_7.py | 123 | 3.53125 | 4 | v=int(input('Introduceti varsta:'))
print("Greutatea ideala este de", 2*v+8, "kg, Inaltimea ideala este de", 5*v+80, "cm") |
7256e3fa3efe0c897f14567c55c6bc85be94ae4c | Protocol73/CIS-122 | /Hunterville-Tuition-10yr.py | 1,332 | 3.609375 | 4 | #For CIS122 p#224 Q10
#Written by Protocol73
import os
import sys
import time
import json
try: #for py v2 vs v3 input
input = raw_input
except NameError:
pass
def clear_term(): #clear the Screen
os.system('cls' if os.name=='nt' else 'clear')
#call to Clear the Terminal
def Check_Prompt():#For Asking the User Yes or No answers
input_answer = input("Yes/No:")
answer = input_answer.lower()
if answer in ['n','no']:
return False
elif answer in ['y','yes']:
return True
else:
print("Error: Expected Yes or No, Got:" + input_answer)
time.sleep(2)
clear_term()
return -1
def end_of_job():#quits the Program
print("Are you sure you want to quit?")
print("No,Clears Data and Restarts the Kiosk.")
if Check_Prompt() is True:
clear_term()
sys.exit()
else:
print("Restarting Program")
time.sleep(1)
os.execl(sys.executable, sys.executable, *sys.argv)
#START
clear_term()
rate = 1.05
TUITION = 10000
def welcome_screen():#<--
clear_term()
print("---Hunterville College Interest---")
def math():
print(TUITION)
years = input("Years:")
yr = int(years)
for_year = TUITION
print("\n---Interest for the next "+ years +" years---\n")
while yr > 1:
yr = yr - 1
for_year = for_year * rate
print(int(for_year))
def main():
welcome_screen()
math()
print("\n")
main() |
c02b96bcfe38c93fcbe412e4bf9289cc5d5d5742 | orimamo/check-bot | /exercises middel/targil-11.py | 110 | 4.03125 | 4 | a=input("insert one word :")
b=input("insert the second word :")
print("the new sentence is :" + b + " " + a ) |
efa17b970bdef0043825ca2d03032f4d59ffca08 | OakdaleRaspberryPi/RaspberryPiProjects | /Hangman.py | 4,137 | 3.765625 | 4 | #!/usr/bin/env python
2.
3.import random
4.import cPickle
5.
6.class Hangman(object):
7. '''A simple hangman game that tries to improve your vocabulary a bit '''
8. def __init__(self):
9. # the variables used, this is not necessary
10. self.dumpfile = '' #the dictionary file
11. self.dictionary = {} #the pickled dict
12. self.words = [] #list of words used
13. self.secret_word = '' #the 'key'
14. self.length = 0 #length of the 'key'
15. self.keys = [] #inputs that match the 'key'
16. self.used_keys = [] #keys that are already used
17. self.guess = '' #player's guess
18. self.mistakes = 0 #number of incorrect inputs
19.
20. return self.load_dict()
21.
22. #insert some random hints for the player
23. def insert_random(self, length):
24. randint = random.randint
25.
26. # 3 hints
27. if length >= 7: hint = 3
28. else: hint = 1
29. for x in xrange(hint):
30. a = randint(1, length - 1)
31. self.keys[a-1] = self.secret_word[a-1]
32.
33. def test_input(self):
34. #if the guessed letter matches
35. if self.guess in self.secret_word:
36. indexes = [i for i, item in enumerate(self.secret_word) if item == self.guess]
37. for index in indexes:
38. self.keys[index] = self.guess
39. self.used_keys.append(self.guess)
40. print "used letters ",set(self.used_keys),'\n'
41.
42. #if the guessed letter didn't match
43. else:
44. self.used_keys.append(self.guess)
45. self.mistakes += 1
46. print "used letters ",set(self.used_keys),'\n'
47.
48.
49. # load the pickled word dictionary and unpickle them
50. def load_dict(self):
51. try :
52. self.dumpfile = open("~/python/hangman/wordsdict.pkl", "r")
53. except IOError:
54. print "Couldn't find the file 'wordsdict.pkl'"
55. quit()
56. self.dictionary = cPickle.load(self.dumpfile)
57. self.words = self.dictionary.keys()
58. self.dumpfile.close()
59. return self.prepare_word()
60.
61. #randomly choose a word for the challenge
62. def prepare_word(self):
63.
64. self.secret_word = random.choice(self.words)
65. #don't count trailing spaces
66. self.length = len(self.secret_word.rstrip())
67. self.keys = ['_' for x in xrange(self.length)]
68. self.insert_random(self.length)
69. return self.ask()
70.
71. #display the challenge
72. def ask(self):
73. print ' '.join(self.keys), ":", self.dictionary[self.secret_word]
74. print
75. return self.input_loop()
76.
77. #take input from the player
78. def input_loop(self):
79. #four self.mistakes are allowed
80. chances = len(set(self.secret_word)) + 4
81. while chances != 0 and self.mistakes < 5:
82. try:
83. self.guess = raw_input("> ")
84.
85. except EOFError:
86. exit(1)
87. self.test_input()
88. print ' '.join(self.keys)
89. if '_' not in self.keys:
90. print 'well done!'
91. break
92. chances -= 1
93.
94. if self.mistakes > 4: print 'the word was', ''.join(self.secret_word).upper()
95. return self.quit_message()
96.
97. def quit_message(self):
98. print "\n"
99. print "Press 'c' to continue, or any other key to quit the game. "
100. print "You can always quit the game by pressing 'Ctrl+D'"
101. try:
102. command = raw_input('> ')
103. if command == 'c': return self.__init__() #loopback
104. else : exit(0)
105. except EOFError: exit(1)
106.
107.
108.
109.
110.
111.
112.if __name__ == '__main__':
113. game = Hangman()
114. game.__init__()
|
388ecda0263b611f91ec57237f59c33041cf7297 | fullacc/chocoremint | /week1/collections_named_tuple28.py | 256 | 3.671875 | 4 | from collections import namedtuple
import statistics
n = int(input())
columns = input().split()
Tuple = namedtuple("Tuple", columns)
res = []
for i in range(n):
s = input().split()
res.append(int(Tuple._make(s).MARKS))
print(statistics.mean(res))
|
4db50a7407ceb9f3c62ce21c36f16921a36592ba | haidragon/Python | /Python核心编程/Python-03/02-内建方法/04-内建方法-sorted.py | 359 | 4.21875 | 4 | a = [5,2,3,4,1]
a.sort()
print(a)
#[1, 2, 3, 4, 5]
b = [5,2,3,4,1]
b.sort(reverse=True)
print(b)
#[5, 4, 3, 2, 1]
print("sorted========>")
print(sorted([1,4,2,3,5]))#由小到大
print(sorted([1,4,2,3,5],reverse=0))#由小到大
print(sorted([1,4,2,3,5],reverse=2))#由大到小
print(sorted(['A','B','D','a','b'],reverse=0))#按照ACSII排序 |
80b30bd0a35fb8a81eedfb51aeef77951714fb13 | dhyoon1112/python_practiceproblems | /13. Fibonacci.py | 261 | 4.125 | 4 | def fibonacci(n):
a = []
for i in range(n):
if i <= 1:
a.append(1)
else:
a.append(a[i-1]+a[i-2])
return a
number = input("How many fibonacci numbers do you want? ")
print(fibonacci(int(number)))
|
778e04a2a99bef78aa119e8e45018c1ab12c0c79 | wangleiliugang/data | /aid1805/pbase/67_read_write_exercise.py | 2,279 | 3.515625 | 4 | # 1.写一个程序,从键盘输入如下信息:
# 姓名 和 电话号码
# 如: 请输入姓名:xiaozhang
# 请输入电话:13888888888
# 请输入姓名:xiaoli
# 请输入电话:13999999999
# 请输入姓名:<回车>
# 把从键盘读取的信息存入'phone_book.txt'文件中,然后用sublime text打开并查看写入的内容
# def phone_number():
# L = []
# while True:
# name = input('请输入姓名:')
# if not name:
# break
# number = input('请输入电话:')
# L.append((name, number)) # 形成元组('姓名','电话')
# return L
# def write_to_file(lst, filename='phone_book.txt'):
# try:
# f = open(filename, 'w')
# for name,number in lst:
# f.write(name)
# f.write(',')
# f.write(number)
# f.write('\n')
# f.close()
# except OSError:
# print('写入文件失败!')
# if __name__ == '__main__':
# L = phone_number()
# print(L)
# write_to_file(L)
# 2.写一个读取'phone_book.txt'文件的程序,把保存的信息以表格的形式打印出来
# +-------------+-------------------+
# | name | number |
# +-------------+-------------------+
# | xiaozhang | 13888888888 |
# +-------------+-------------------+
def read_info_from_file(filename='phone_book.txt'):
L = []
try:
f = open(filename)
while True:
s = f.readline()
if not s:
break
s = s.rstrip() # 去掉右侧的换行符'\n'
name, number = s.split(',') # 拆成['姓名', '电话']
L.append((name, number))
f.close()
except OSError:
print('打开文件失败!')
return L
def print_info(lst):
print('+-------------+-----------------------+')
print('| name | number |')
print('+-------------+-----------------------+')
for t in L:
t =(t[0].center(13), t[1].center(23))
line = "|%s|%s|" % t
print(line)
print('+-------------+-----------------------+')
if __name__ == '__main__':
L = read_info_from_file()
print(L)
print_info(L)
|
b22d91b2fd5493c2d4a488cfed0eced7562a7b0c | kaizencodes/algorithms | /queue.py | 2,457 | 4.0625 | 4 | class Queue:
def __init__(self):
self.first = None
self.last = None
def remove(self):
if self.first is None:
raise EmptyQueueException('Can\'t remove from empty queue')
item = self.first.data
self.first = self.first.next
if self.first is None:
self.last = None
return item
def add(self, item):
node = _Node(item)
if self.last is not None:
self.last.next = node
self.last = node
if self.first is None:
self.first = self.last
def peek(self):
if self.first is None:
raise EmptyQueueException('Can\'t peek empty queue')
return self.first.data
def is_empty(self):
return self.first is None
def __str__(self):
if self.is_empty():
return ''
n = self.first
result = str(n.data)
while n.next is not None:
n = n.next
result += ', ' + str(n.data)
return result
class _Node:
def __init__(self, data):
self.data = data
self.next = None
def __str__(self):
return str(self.data)
class EmptyQueueException(Exception):
def __init__(self, message):
super().__init__(message)
self.message = message
def main():
q = Queue()
print('\nEmpty queue')
print('Expected: ')
print('Result: ', q)
print('\nAdd 1, 2, 3')
q.add(1)
q.add(2)
q.add(3)
print('Expected: 1, 2, 3')
print('Result: ', q)
print('\nPeek')
print('Expected: 1')
print('Result: ', q.peek())
print('\nRemove')
print('Expected: 2, 3')
q.remove()
print('Result: ', q)
print('\nCheck emptiness')
print('Expected: False')
print('Result: ', q.is_empty())
print('\nTry to remove when empty')
print('Expected: Can\'t remove from empty queue')
try:
q.remove()
q.remove()
q.remove()
except EmptyQueueException as e:
print('Result: ', e)
else:
print('Result: no error occured')
print('\nTry to peek when empty')
print('Expected: Can\'t peek empty queue')
try:
q.peek()
except EmptyQueueException as e:
print('Result: ', e)
else:
print('Result: no error occured')
print('\nCheck emptiness')
print('Expected: True')
print('Result: ', q.is_empty())
if __name__ == "__main__":
main()
|
acf2483e15dfc783f64b1b8b476760d3d33c6eb2 | treebbb/homeschool2020 | /math/graph.py | 481 | 4.09375 | 4 | #! /usr/bin/env python
"""
Matplotlib users guide:
https://matplotlib.org/users/index.html
"""
import numpy as np
import matplotlib.pyplot as plt
RED = (1.0, 0, 0)
GREEN = (0, 1.0, 0)
BLUE = (0, 0, 1.0)
x = np.arange(0, 5, 0.1)
y = np.sin(x)
#plt.plot(x, y)
def add_shape(points, color):
polygon = plt.Polygon(points, color=RED, fill=0)
plt.gca().add_patch(polygon)
square_points = [(3,3), (3, -3), (-3, -3), (-3, 3)]
add_shape(square_points, RED)
plt.show()
|
ce3912fb7df69ec3ae8724c2894967570c7e9d39 | venkat24/advent-of-code | /2019/06/part1.py | 1,576 | 3.53125 | 4 | from copy import copy
class Node:
def __init__(self, name, depth, parent):
self.name = name
self.depth = depth
self.parent = parent
def __eq__(self, other):
return type(self) == type(other) and self.name == other.name
def __hash__(self):
return hash(self.name)
def __repr__(self):
return f"{{ {self.name} : {self.depth} }}"
if __name__ == "__main__":
with open ("input.txt", "r") as f:
edges = []
nodelist = {}
for line in f:
edges.append(tuple(line.strip().split(")")))
COM = edges[0][0]
for edge in edges:
parent_name = edge[0]
child_name = edge[1]
parent = None
child = None
if parent_name in nodelist.keys():
parent = nodelist[parent_name]
else:
parent = Node(parent_name, 0, None)
if child_name in nodelist.keys():
child = nodelist[child_name]
else:
child = Node(child_name, 0, None)
child.parent = parent
child.depth = parent.depth + 1
nodelist[parent_name] = parent
nodelist[child_name] = child
sum = 0
for name, node in nodelist.items():
current = node
count = 0
while current != None and current.name != COM:
# print(current.name + " -> ", end='')
count += 1
current = current.parent
sum += count
print(sum)
|
c88f51ed4ceb059725d860dd8745edb29f5b74de | NGBashir/PDE1130 | /Week 7/wordslice.py | 152 | 4.15625 | 4 | #using slice
word="computing"
x= slice(3,6)
print ("Slicing of ", word ," is",word[x])
# change the above to let the user to specify the start and end
|
234df6eb3a95862d1efd0a8cd33f4c8b0b8f7491 | a523/leetcode | /344.py | 896 | 3.78125 | 4 | """
344. 反转字符串
编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 char[] 的形式给出。
不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。
你可以假设数组中的所有字符都是 ASCII 码表中的可打印字符。
https://leetcode-cn.com/problems/reverse-string/
"""
s = ["h", "e", "l", "l", "o"]
def reverseString(s):
"""
:type s: List[str]
:rtype: None Do not return anything, modify s in-place instead.
"""
i = 0
j = len(s) - 1
while j > i:
s[i], s[j] = s[j], s[i]
i += 1
j -= 1
return s
print(reverseString(s))
"""
执行用时 :
172 ms
, 在所有 Python 提交中击败了
83.83%
的用户
内存消耗 :
18.6 MB
, 在所有 Python 提交中击败了
89.10%
的用户
""" |
2c97affe6ca46fbbab4bbc1fd8079e26f2f01205 | kellyseeme/pythonexample | /314/hotel.py | 502 | 3.734375 | 4 | #!/usr/bin/env python
class HotelRoomCalc(object):
"Hotel room rate calculator"
def __init__(self,rt,sales=0.0085,rm=0.1):
"""Hotel romm calc default arguments"""
self.salesTax = sales
self.roomTax = rm
self.roomRate = rt
def calcTotal(self,days=1):
"Calculate total:default to daily rate"
daily = round((self.roomRate*14*(1+self.roomTax+self.salesTax)),2)
return float(days) * daily
kel = HotelRoomCalc(2)
print kel.calcTotal()
|
c591cb1ad898c1a64b4df637da4301274a84bd76 | hyuk02006/Jusung | /Python 20210628/e_file_class/Ex01_readFile_exam.py | 728 | 3.71875 | 4 | """ [연습]
함수 정의 : count_words
인자 : filename
인자로 받은 파일명을 open 하여 파일을 읽어서 단어를 수를 출력한다.
존재하지 않는 파일명으로 예외가 발생해도 아무런 일을 하지 않는다
"""
def count_words(filename):
try:
with open('./data/'+filename, 'r', encoding='utf-8') as f:
line = f.read()
word = line.split()
cnt = len(word)
except FileNotFoundError as e:
pass
else:
print('파일명:' + filename + ',단어수:' + str(cnt))
# 존재하지 않는 파일명도 있음
filenames = ['sample.xml', 'xxxx.xxx', 'temp.json']
for filename in filenames:
count_words(filename) |
81dbded45cebae8648de29b09b6250b4fa76c69d | andrewbrimusu/mis5500.sp21 | /week5_json/algo.py | 286 | 3.71875 | 4 | import numpy
lst = [3,1,4,1,5,9,3,6,5,8,9,7,9,3,2,3,8,4,6]
lst = numpy.random.randint(50, size=10000000)
for i in range(len(lst)):
for j in range(len(lst)):
if lst[i] + lst[j] == 13:
print("found the pair!, its ", lst[i], "and", lst[j])
# O(n^2)
|
719277daa8a95471032643a7e5b5774fd6503694 | mahvish23/CP | /tower of hanoi.py | 716 | 3.921875 | 4 | """ ower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:
1) Only one disk can be moved at a time.
2) Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
3) No disk may be placed on top of a smaller disk.
"""
def toh(n,source,aux,dest):
if n==1:
print(f"move {n} disk from {source} to {dest}")
return
toh(n-1,source,dest,aux)
print(f"move {n} disk from {source} to {dest}")
toh(n-1,aux,source,dest)
toh(3,"A","B","C") |
4f902d891424198ca14176f76d762d1c3ca1bc42 | luca-m/cv_homeworks | /hworks/morpho.py | 7,738 | 3.515625 | 4 | # -*- coding: utf-8 -*-
__author__ = "Luca Mella"
__version__ = "$Revision: 0.1 $"
__date__ = "$Date: 2013/05/20 $"
__copyright__ = "Copyright (c) 2012-2013 Luca Mella"
__license__ = "CC BY-NC-SA"
"""
MATHEMATICAL MORPHOLOGY
All the routines must work with logical (B/W) and greyscale images, with
automatic detection of image type.
Alternatively, you can build different functions for greyscale and binary images.
IPA_im2bw(img,th)
IPA_morph(img,mask,op_type)
IPA_closing(img,mask)
IPA_opening(img,mask)
IPA_hitmiss(img,SE1,SE2)
IPA_tophat(img,mask)
IPA_bothat(img,mask)
IPA_top-bot_enhance(img,mask)
IPA_imreconstruct(marker,mask,SE1)
NOTE: input image is loaded in grayscale and thresholded at with OTSU method (after a gaussian smoothing).
"""
import cv2
import numpy as np
import histo # NOTE: rely on thresholding function implemented in hworks.histo
import plots
def run(inImPath,outImPath):
print "DISCLAIMER: Convolution in Python is pretty SLOW.."
print " This does not mean that python cannot be used for this kind of computation,"
print " but also mean that we should use libraries like 'numpy' or 'cv' which provide"
print " access to native algorithm implementation (read 'C/C++') directly from python."
print " However, this is only a homework.."
im=cv2.imread(inImPath, cv2.CV_LOAD_IMAGE_GRAYSCALE)
square_3x3=IPA_se_square(3)
print "[MORPHO] IPA_im2bw"
gauss_kernel=[1,2,3,4,5,4,3,2,1]
gauss_kernel_norm= [float(x)/sum(gauss_kernel) for x in gauss_kernel]
im_bin=IPA_im2bw(im,histo.IPA_FindThreshold_Otsu(histo.IPA_histoConvolution1D(histo.IPA_histo(im, rang=[0,255]),gauss_kernel_norm)))
#im_bin=IPA_im2bw(im,1)
# Binary ops
print "[MORPHO] IPA_dilate"
im_bin_dil=IPA_dilate(im_bin,square_3x3)
print "[MORPHO] IPA_erode"
im_bin_ero=IPA_erode(im_bin,square_3x3)
print "[MORPHO] IPA_opening"
im_bin_open=IPA_opening(im_bin,square_3x3)
print "[MORPHO] IPA_closing"
im_bin_close=IPA_closing(im_bin,square_3x3)
print "[MORPHO] IPA_imreconstruct"
im_bin_ric=IPA_imreconstruct(im_bin_open,im_bin,square_3x3)
# Gray scale ops
print "[MORPHO] IPA_dilate"
im_dil=IPA_dilate(im,square_3x3)
print "[MORPHO] IPA_erode"
im_ero=IPA_erode(im,square_3x3)
print "[MORPHO] IPA_opening"
im_open=IPA_opening(im,square_3x3)
print "[MORPHO] IPA_closing"
im_close=IPA_closing(im,square_3x3)
print "[MORPHO] IPA_imreconstruct"
im_ric=IPA_imreconstruct(im_open,im,square_3x3)
print "[MORPHO] IPA_tophat"
im_tophat=IPA_tophat(im,square_3x3)
print "[MORPHO] IPA_bothat"
im_bothat=IPA_bothat(im,square_3x3)
print "[MORPHO] IPA_topbot_enhance"
im_topbot=IPA_topbot_enhance(im,square_3x3)
print "Plotting.."
plots.plotImage(im_bin,"[MORPHO] Bin Original")
plots.plotImage(im_bin_ero,"[MORPHO]Bin Eroded")
plots.plotImage(im_bin_dil,"[MORPHO]Bin Dilated")
plots.plotImage(im_bin_open,"[MORPHO]Bin Opening")
plots.plotImage(im_bin_close,"[MORPHO]Bin Closing")
plots.plotImage(im_bin_ric,"[MORPHO]Bin Reconstruction (geodesic dilation)")
plots.plotImage(im,"[MORPHO] Gray Original")
plots.plotImage(im_ero,"[MORPHO] Gray Eroded")
plots.plotImage(im_dil,"[MORPHO] Gray Dilated")
plots.plotImage(im_open,"[MORPHO] Gray Opening")
plots.plotImage(im_close,"[MORPHO] Gray Closing")
plots.plotImage(im_ric,"[MORPHO] Gray Reconstruction (geodesic dilation)")
plots.plotImage(im_tophat,"[MORPHO] Gray TopHat")
plots.plotImage(im_bothat,"[MORPHO] Gray BotHat")
plots.plotImage(im_topbot,"[MORPHO] Gray TopBot Enanche")
plots.showPlots()
def IPA_se_square(size):
""" Squared structural element """
return np.matrix([[1]*size for i in range(size)])
def IPA_apply(fun, *imgs):
"""
Obtain a new image by appling the specified
function on every couple of pixels
"""
shp=imgs[0].shape
for x in imgs:
if x.shape!=shp:
raise Exception("Images must have the same shape")
y,x=shp
nim=np.zeros((y,x))
for j in range(y):
for i in range(x):
params=[p.item(j,i) for p in imgs] # Pick the j,i pixel of each image in imgs
nim.itemset((j,i),fun(*params)) # pass these pixels to the function and put the
# result in the j,i pixel of the new image
return nim # Otherwise np.array(map(fun, imgs))
def IPA_conv2(img, mask, op=lambda px, mask, val:0.0 ,pad_type=1, init=lambda px:0):
"""
Performs a convolution-like user defined local operation.
Supported padding:
zero-padding (pad_type=1)
replicate (pad_type=2)
The user defined operation MUST return a float value and
MUST handle 3 input parameters:
pixel, mask, prev_value
Also user may specify an initialization function that could
be useful to specify in case of erosion operation.
In this case the function must return a float and handle 1 param.
"""
my,mx = mask.shape
iy,ix = img.shape
if iy/my<=0 or ix/mx<=0:
raise Exception("Mask must be smaller than image")
mcx=mx/2
mcy=my/2
nim=np.zeros((iy,ix))
for i in range(iy):
for j in range(ix):
val=init(img.item(i,j))
for p in range(my):
for q in range(mx):
if i+p-mcy<0 or j+q-mcx<0 or i+p-mcy>=iy or j+q-mcx>=ix:
if pad_type==1: # 0-padding
impix=0
elif pad_type==2: # repricate-padding
ip,iq=(0,0)
if i+p-mcy<0:
ip=i+p+mcy
if j+q-mcx<0:
iq=j+q+mcx
if i+p-mcy>=iy:
ip=i+p-my
if j+q-mcx>=ix:
iq=j+q-mx
impix=img.item(ip,iq)
else:
impix=img.item(i+p-mcy, j+q-mcx)
val=op(impix, mask.item(p,q), val)
nim.itemset((i,j),val)
return nim
def IPA_im2bw(img,th):
""" Binarize """
return histo.IPA_Bynarize(img,th)
def IPA_morph(img,mask,op_type):
"""
Morphological primitives
op_type=(dilate,erode)
"""
if op_type=='dilate':
return IPA_dilate(img,mask)
elif op_type=='erode':
return IPA_erode(img,mask)
return None
def IPA_dilate(img,mask):
""" Morphological Dilatation """
return IPA_conv2(img, mask, op=lambda px,msk,val:max(msk*px,val), pad_type=2)
def IPA_erode(img,mask):
""" Morphological Erosion """
return IPA_conv2(img, mask, op=lambda px,msk,val:min(msk*px,val), pad_type=2,init=lambda px:px)
def IPA_closing(img,mask):
""" Closing """
return IPA_erode(IPA_dilate(img,mask),mask)
def IPA_opening(img,mask):
""" Opening """
return IPA_dilate(IPA_erode(img,mask),mask)
def IPA_hitmiss(img,SE1,SE2,fun=min):
""" Binary hit and miss """
return IPA_apply(fun, IPA_erode(img,SE1), IPA_erode(IPA_apply(lambda a:1^int(a), img), SE2))
def IPA_tophat(img,mask):
""" Top Hat """
return IPA_apply(lambda a,b:max(a-b,0), img, IPA_opening(img, mask))
def IPA_bothat(img,mask):
""" Bottom Hat """
return IPA_apply(lambda a,b:max(a-b,0), IPA_closing(img, mask), img)
def IPA_topbot_enhance(img,mask):
""" TopHat BottomHat enanchment """
# - (+ img tophat) bothat
return IPA_apply(lambda a,b:max(a-b,0),
IPA_apply(lambda a,b:min(a+b,255), img, IPA_tophat(img,mask)),
IPA_bothat(img,mask))
def IPA_imreconstruct(marker, mask, SE, method='dilate', niter=4):
""" Reconstruction by geodesic dilation/erosion (dilate/erode) """
stop=False
new_marker=None
i=0
while not stop and i<niter:
new_marker=IPA_apply(min, IPA_morph(marker, SE, method), mask)
i+=1
if (new_marker!=marker).any():
marker=new_marker;
else:
stop=True
return new_marker
|
e26636fe864928507364e99a108c94a6b45da93a | atronk/python | /regexp/match_search.py | 1,132 | 4.0625 | 4 | #For regular expressions мы импортируем РЕ
import re
# used in this format:
#a = re.match(pattern, string, oprtional flags)
myStr = 'You can learn any programming language, whether it is Python2, Python3, Perl, Java, JavaScript, or PHP'
a = re.match('You', myStr)
print('\'a\' is ', a)
print('Find it ignoring the case of letters')
a = re.match('you', myStr, re.I)
print('\'a\' is ', a)
#a = re.search(pattern, string)
arp = '22.22.22.1 0 b4:a9:5a:ff:c8:45 VLAN#222 L'
newSearch = re.search(r"(.+?) +(\d) +(.+?)\s{2,}(\w)*", arp)
# () - is a group of symbols. dot . is any char except a newline. plus + means previous expression
# may repeat one or more time. ? - means no 'greedy manner' (does not include spaces like above)
# \d is a single digit
# \s any whitespace char
# {2,} - expecting 2 or more occurrences of the previous expression. Comma , means 2 or more. Without
# a comma that would be strictly 2.
# (\w)* any symbol?
print("|%s|" % newSearch.group(1))
print("|%s|" % newSearch.group(2))
print("|%s|" % newSearch.group(3))
print("|%s|" % newSearch.group(4))
print(newSearch.groups()) |
c3a9491f7a908196a10e935349575ee9ac49c43c | krishnakpatel/Summer2017 | /graphv6.py | 6,230 | 3.53125 | 4 | # add functionality: modifying values
import networkx as nx
from xml.etree.ElementTree import ElementTree, Element, SubElement
# as soon as the program loads
def initialize():
global circ
global num_node
circ = nx.MultiDiGraph()
num_node = 0
# component generation
def click(type, value):
circ.add_node(num_node)
circ.add_node(num_node+1)
# ask for value?
circ.add_edges_from([(num_node, num_node+1, {'type': type, 'value': value})])
num_node += 2
# click on a resistor
def resistor(value):
click('r', value)
# click on a capacitor
def capacitor(value):
click('c', value)
# click on an inductor
def inductor(value):
click('i', value)
# just adding wire
def wire():
click('w', 0)
# joining two components
def connect(edge1, edge2):
old_node = edge2[0]
edge2[0] = edge1[1]
to_change = circ.edges(old_node)
for edge in to_change:
edge[0] = edge1[1]
circ.remove_edge(old_node)
# splitting components apart---edge being dragged away must be second argument
def cleave(stationary, dragged):
if stationary[1] == dragged[0]:
dragged[0] = num_node+1
elif stationary[0] == dragged[1]:
dragged[1] = num_node+1
num_node += 1
# delete a component
def delete(edge):
start = circ.edges(edge[0])
end = circ.edges(edge[1])
if not start and not end:
circ.remove_node(edge[0])
circ.remove_node(edge[1])
circ.remove_edge(edge)
# save a graph that has been created
# def save(file_name):
def save():
file = open('test.xml', 'wb')
root = Element('circuit')
document = ElementTree(root)
nodes = SubElement(root, 'max_num_node')
nodes.text = str(num_node)
edges_list = SubElement(root, 'edges_list')
edges = circ.edge
for start, dicts in edges.items():
if bool(dicts):
s = SubElement(edges_list, 'start', {'at': str(start)})
for end, keys in dicts.items():
e = SubElement(s, 'end', {'at': str(end)})
string = ''
for key, data in keys.items():
for t, v in data.items():
if not isinstance(v, str):
v = str(v)
string += v
string += ' '
e.text = string
document.write(file, encoding='UTF-8', xml_declaration=True)
file.close()
# open from a saved file
def open_saved(file_name):
file = open(file_name, 'rb')
tree = ElementTree()
tree.parse(file)
root = tree.getroot()
num_node = root.findtext('max_num_node')
for start in root.find('edges_list'):
node1 = start.attrib['at']
for end in start:
node2 = end.attrib['at']
edges_str = ''.join(end.itertext())
edges = edges_str.split( )
if bool(edges):
circ.add_edges_from([(node1, node2, {'type': edges[0], 'value': edges[1:]})])
# how to integrate this to show a visual picture
# you'll know that the nodes of this segment are all connected w/ the same start node
# properly closes the graph
def close():
save()
circ.clear()
# only for plot/delete this later
import matplotlib.pyplot as plot
initialize()
circ.add_node(num_node+1, important=False, into=[])
for node in circ.nodes_iter(data=True):
if node[1]['into'] == 56:
node[1]['important'] = True
# circ.add_edges_from([(1, 2, {'type': 'r', 'value': 25}), (1, 2, {'type': 'r', 'value': 50}), (1, 5, {'type': 'r', 'value': 77}), (1, 3,{'type': 'r', 'value': 85}),(2, 7,{'type': 'r', 'value': 63}), (6, 7,{'type': 'r', 'value': 50}), (3, 4,{'type': 'r', 'value': 200}), (4, 5,{'type': 'r', 'value': 100}), (4, 6,{'type': 'r', 'value': 85})])
# circ.add_edges_from([(1, 2, {'type': 'r', 'value': 3}), (2, 3, {'type': 'r', 'value': 1}), (3, 4, {'type': 'r', 'value': 4}), (4, 5,{'type': 'r', 'value': 3}),(5, 6,{'type': 'r', 'value': 1}), (3, 5,{'type': 'r', 'value': 7}), (2, 6,{'type': 'r', 'value': 6}), (6, 1,{'type': 'r', 'value': 1})])
circ.add_edges_from([(1, 2, {'type': 'w', 'value': 0}), (2, 3, {'type': 'r', 'value': 50}), (2, 5, {'type': 'r', 'value': 77}), (2, 5,{'type': 'r', 'value': 85}),(2, 7,{'type': 'r', 'value': 63}), (5, 7,{'type': 'r', 'value': 50}), (7, 3,{'type': 'r', 'value': 200}), (3, 1,{'type': 'r', 'value': 100})])
edge = circ.edges()[1]
edge2 = circ.edges()[0]
for edge in circ.edges_iter(data=True):
if edge['pos'] == 0:
edge['important'] = False
for node in circ.nodes_iter(data=True):
edges = circ.edges(node[0])
for edge in edges:
# if edge[0] == node[0]:
# node[1]['out'].append(edge)
# else:
node[1]['into'].append(edge)
pos = nx.random_layout(circ)
nx.draw_networkx_nodes(circ,pos,node_size=700)
nx.draw_networkx_edges(circ,pos,width=1.0)
nx.draw_networkx_labels(circ,pos)
save()
circ.clear()
open_saved('test.xml')
plot.show()
# only for plot/delete this later
# import matplotlib.pyplot as plot
# c = circuit()
# circ.add_edges_from([(1, 2, {'type': 'r', 'value': 25}), (1, 2, {'type': 'r', 'value': 50}), (1, 5, {'type': 'r', 'value': 77}), (1, 3,{'type': 'r', 'value': 85}),(2, 7,{'type': 'r', 'value': 63}), (6, 7,{'type': 'r', 'value': 50}), (3, 4,{'type': 'r', 'value': 200}), (4, 5,{'type': 'r', 'value': 100}), (4, 6,{'type': 'r', 'value': 85})])
# circ.add_edges_from([(1, 2, {'type': 'r', 'value': 3}), (2, 3, {'type': 'r', 'value': 1}), (3, 4, {'type': 'r', 'value': 4}), (4, 5,{'type': 'r', 'value': 3}),(5, 6,{'type': 'r', 'value': 1}), (3, 5,{'type': 'r', 'value': 7}), (2, 6,{'type': 'r', 'value': 6}), (6, 1,{'type': 'r', 'value': 1})])
# circ.add_edges_from([(1, 2, {'type': 'w', 'value': 0}), (2, 3, {'type': 'r', 'value': 50}), (2, 5, {'type': 'r', 'value': 77}), (2, 5,{'type': 'r', 'value': 85}),(2, 7,{'type': 'r', 'value': 63}), (5, 7,{'type': 'r', 'value': 50}), (7, 3,{'type': 'r', 'value': 200}), (3, 1,{'type': 'r', 'value': 100})])
# pos = nx.random_layout(circ)
# nx.draw_networkx_nodes(circ,pos,node_size=700)
# nx.draw_networkx_edges(circ,pos,width=1.0)
# nx.draw_networkx_labels(circ,pos)
# save()
# circ.clear()
# open_saved('test.xml')
# plot.show() |
5936f561d4c0cb43244cb3cbf7c3c8c8234e5a10 | hazemshokry/Algo | /HackerRank/Left Rotation.py | 530 | 4.28125 | 4 | # A left rotation operation on an array shifts each of the array's elements 1 unit to the left.
# For example, if 2 left rotations are performed on array [1,2,3,4,5], then the array would become [3,4,5,1,2].
def rotLeft(a, d):
for rot in range(d):
for i in range(len(a) - 1):
a[i], a[i + 1] = a[i + 1], a[i]
return a
def rotLeft_v2(a, d):
res = []
res = a[d:] + a[:d]
return res
if __name__ == '__main__':
a = [1, 2, 3, 4, 5]
print(rotLeft(a, 2))
#print(rotLeft_v2(a, 4))
|
56df00c882e087901ca3582b0c5ddf21528a7326 | breezekiller789/LeetCode | /873_Length_of_Longest_Fibonacci_Subsequence.py | 1,012 | 4 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# https://leetcode.com/problems/length-of-longest-fibonacci-subsequence/
# Output: 5
# Explanation: The longest subsequence that is fibonacci-like: [1,2,3,5,8].
arr = [1, 2, 3, 4, 5, 6, 7, 8]
# Output: 3
# Explanation: The longest subsequence that is fibonacci-like:
# [1,11,12], [3,11,14] or [7,11,18]
# arr = [1, 3, 7, 11, 12, 14, 18]
# Output: 5
arr = [2, 4, 7, 8, 9, 10, 14, 15, 18, 23, 32, 50]
# arr = [1,5,6,7,10,12,17,24,41,65]
maxLength = float("-inf")
length = len(arr)
for k in range(length-2):
for i in range(k+1, length-1):
tmpList = [arr[k], arr[i]]
supposedToBe = tmpList[-1] + tmpList[-2]
for j in range(i+1, length):
if arr[j] == supposedToBe:
tmpList.append(supposedToBe)
maxLength = max(maxLength, len(tmpList))
supposedToBe = tmpList[-1] + tmpList[-2]
elif arr[j] > supposedToBe:
break
print tmpList
print maxLength
|
35fa48e4b3223a7798a4c8833a2bc11ae5a9a9d6 | mrsingh3131/Foobar | /Some other foobar gits/SadeghHayeri/questions/002 Hey, I Already Did That!/solution.py | 628 | 3.578125 | 4 | def baseN(num,b,numerals="0123456789abcdefghijklmnopqrstuvwxyz"):
return ((num == 0) and numerals[0]) or (baseN(num // b, b, numerals).lstrip(numerals[0]) + numerals[num % b])
def getNext(n, b, k):
x = ''.join(sorted(list(n), reverse=True))
y = ''.join(sorted(list(n)))
z = baseN(int(x, b) - int(y, b), b)
return '0' * (k - len(z)) + z
def answer(n, b):
k = len(n)
index = 0
funded = {}
while True:
if n in funded:
return index - funded[n]
else:
funded[n] = index
index += 1
n = getNext(n, b, k)
# answer('210022', 3) #-> 3
|
b8984e8c25dc44179f92e32e4d41291d62525101 | Ilis/zed | /ex24.py | 770 | 4.0625 | 4 | print("Давайте попрактикуемся")
print("Экранирование\\")
print("Перенос\nстрок и\tтабуляция")
poem = """\tПоэт
Я — поэт
Зовусь я Цветик
От меня вам всем приветик
\t\tЦветик"""
print("-" * 20)
print(poem)
print("-" * 20)
five = 2**2 + 1
print(f"Five to be here: {five}")
def secret_formula(started):
jelly_beans = started * 500
jars = jelly_beans // 100
crates = jars // 2
return jelly_beans, jars, crates
start_point = 10_000
beans, jars, crates = secret_formula(start_point)
# Comments
formula = secret_formula(start_point)
print("Starting with: {}".format(start_point))
print("We have {} beans, {} jars and {} crates.".format(*formula))
|
0ddafedefbba514aa065349fcf3ba7023bfb2762 | reddyimr/Mallikarjunaa | /reverse string.py | 186 | 4.21875 | 4 | #a=input("enter the string")
#b=a[::-1]
#print (b)
#to reverse an array
n=int(input("enter the size of an array"))
a=[]
for i in range(n):
a.append(int(input()))
b=a[::-1]
print (b)
|
7450365995b6d160179a9d138e6fd927f1c8edaa | ShiJingChao/Python- | /PythonStart/Blackhorse/HM_Class/面向对象.py | 8,346 | 4.15625 | 4 | # 类:用来描述具有相同的属性和方法的对象的集合,
# 它定义了该集合中每个对象所共有的属性和方法,对象是类的实例
# class Persion(object):
# nick = 'limiao'
#
# def run(self):
# print("你会走路?")
#
# def song(self):
# print("你只会爬")
# a = Persion()
# a.run()
# a.song()
# 类 定义
# 定义类的语法规则:
# class 大驼峰法命名(父类):
# 属性 = 属性的值
# def 方法名(self):
# 方法执行的代码
# def 方法名(self):
# 方法执行的代码
# 例如现在我想定义一个小狗的类
# class Dog(object):
# type = '犬科'
#
# def eat(self):
# print('看门 啃骨头')
#
# def swim(self):
# print('狗刨')
# class Dog(object):
# print("猫")
# def zhuahaozi(self):
# print("抓三只耗子")
# def jiaohuan(self):
# print('叫三声喵')
# b = Dog()
# b.zhuahaozi()
# b.jiaohuan()
# CLASS 361 面向对象——01基本概念
# 面向过程和面向对象基本概念
# 面向过程
# 1.把完成某一个需求的 所有步骤 从头到尾 逐步实现
# 2.根据开发需求,将某些功能独立的代码 封装成一个又一个的函数
# 3.最后完成的代码,就是顺序的调用不同的函数
# 特点:
# 1.注重步骤与过程,不注重职责分工
# 2.如果需求复杂,代码会变得很复杂
# 3.开发复杂项目,没有固定的套路,开发难度很大!
# 面向对象
# 相比较函数,面向对象是更大的封装,根据职责在一个对象中封装多个方法
# 1.在完成某一个需求前,首先确定职责——要做的事情(方法)
# 2.根据职责确定不同的对象,在对象内部封装不同的方法(多个)
# 3.最后完成的代码,就是顺序地让不同的对象调用不同的方法
# 特点
# 1.注重对象和职责,不同的对象承担不同的职责
# 2.更加适合应对负责的需求变化,是专门应对复杂项目开发,提供的固定套路
# 3.需要在面向对象基础上,再学习一些面向对象的语法
# Class 362 面向对象——类和对象的基本概念
# 类 是对一群㕛相同特征 或者行为的事物的一个统称,是抽象的,不能直接使用
# 特征被称为属性
# 行为被称为方法
# CLASS 363 面向对象设计类的三要素和名词提炼法
# 设计类,要满足的三个要素:
# 1.类名 这类事物的名字,满足大驼峰命名法(每一个单词的首字母大写,单词之间没有下划线)
# 2.属性 这类事物具有什么样的的特征
# 3.方法 这类事物具有什么样的行为
# CLASS 364 内置的dir函数查询对象的方法列表
# dir内置函数
# 1.在标识符/数据后输入一个.然后按下TAB键,python会提示该对象能够够调用的方法列表
# 2.使用内置函数dir传入标识符/书u,可以查看对象内所有的属性和方法
# print(dir(Persion))
# CLASS 365定义简单类——基本语法
# 和函数基本一样
# 区别在于第一个参数必须是self
# 类名的命名规则要符合大驼峰命名法
# CLASS 366定义简单类——案例演练
# 需求:小猫爱吃鱼,小猫爱喝水
# class Cat:
# def eat(self):
# print('%s chiyu'%self.name)
# def drink(self):
# print('hehsui')
# tom=Cat()
# tom.name = "小猫"
# tom.eat()
#
# tom.drink()
# print(tom)
# 再创建一个猫对象,和tom的内存地址不同
# lazy_cat = Cat()
# lazy_cat.name = "大懒猫"
# lazy_cat.eat()
# lazy_cat.drink()
# print(lazy_cat)
# CLASS 369在类外部给类增加属性(不推荐使用)
# lazy_cat.name="大懒猫"
# 在类外给类增加属性的隐患 在运行时没有找到属性,程序会报错
# 对象应该包含有哪些属性,应该封装在类的内部
# a, b = 3, 4
#
#
# def fun(x):
# c, d = 1, 2
# print(locals())
#
#
# fun(6)
# print(globals())
# CLASS 372初始化方法
# 当使用 类名 创建对象时,会自动执行以下操作:
# 1.为对象在内存中 分配空间——创建对象
# 2.为对象的属性 设置初始值——初始化方法(init)
# 这个初始化方法就是 __init__ 方法,__init__是对象的内置方法
class Cat:
def __init__(self):
print("这是一个初始化方法")
# 使用类名()创建对象的时候,会自动执行以下操作
# 1.为对象在内存中分配空间--创建对象
# 2.为对象的属性设置初始值——初始化方法(init)
# 这个初始化方法就是 __init__方法, init__是对象的内置方法
# __init__方法是专门用来定义一个类 具有哪些属性的方法
# CLASS 373 在初始化方法中定义属性
# 在 __init__方法内部使用self.属性名=属性的初始值 就可以定义属性
# 定义属性之后,再使用Cat类创建的对象,都会拥有该属性
# class Cat:
# def __init__(self):
# print("这是一个初始化方法")
# 定义用Cat类创建的猫对象都有一个name的属性
# self.name = "TOM"
#
# def eat(self):
# print("%s 爱吃鱼" % self.name)
# 使用类名()创建对象的时候,会自动调用初始化方法__init___
# tom = Cat()
# print(tom.name)
# tom.eat()
# CLASS 374 使用参数设置属性初始值,初始化的同时设置初始值
# 在开发中,如果希望在创建对象的同时,就设置对象的属性,对__init__方法进行改造
# 1.把希望设置的属性值,定义成__init__方法的函数
# 2.在方法内部使用self.属性 = 形参接收外部传递的参数
# 3.在创建对象时,使用类名(属性1,属性2...)调用
# class Cat:
# def __init__(self, name):
# print("初始化方法:%s" % name)
# self.name = name
#
#
# tom = Cat("Tom")
# lazy_cat = Cat("大懒猫")
# CLASS 375内置方法 del方法和对象的生命周期
# Tom是全局变量,在程序结束的时候系统才回收如果在print("-"*60)上面加上del tom,那么输出我去了就会在分割线上面
# class Cat:
# def __init__(self, new_name):
# self.name = new_name
# print("%s 来了" % self.name)
#
# def __del__(self):
# print("%s我去了" % self.name)
#
#
# tom = Cat("Tom")
# print(tom.name)
# # del 关键字可以删除一个对象
# del tom
# print("-" * 60)
# 在Python中
# 当使用 类名()创建对象时,为对象分配完空间后,自动调用__init__方法
# 当一个对象被内存中销毁前,会自动调用__del__方法
# 应用场景
# __init__改造初始化方法,可以让创建对象更加灵活
# __del__如果希望在对象被销毁前,再做一些事情,可以考虑一下__del__方法
# 一个对象从调用类名()创建,生命周期开始
# 一个对象的__del__方法一旦被调用,生命周期结束
# 在对象的生命周期内,可以访问对象属性,或者让对象调用方法
# 内置方法str方法定制变量输出信息
# 在Python中,使用print输出对象变量,默认情况下,
# 会输出这个变量引用的对象是由那一个类创建的对象,
# 以及在内存中的地址(十六进制表示)
# 如果在开发汇总,希望使用print输出对象变量时,能够打印自定义的内容,就可以利用__str__这个内置方法了
# 注意::__str__方法必须返回一个字符串
# class Cat:
# def __init__(self, new_name):
# self.name = new_name
# print("%s来了" % self.name)
#
# def __del__(self):
# print("%s去了" % self.name)
#
# def __str__(self):
# return "我是小猫:%s" % self.name
#
#
# tom = Cat("Tom")
# print(tom)
# class Restaurant:
# def __init__(self):
# self.restaurant_name = "中餐"
# self.cuisine_type = "西餐"
# def describe_restaurant(self):
# print(self.restaurant_name,self.cuisine_type)
# def open_restaurant(self):
# print("餐馆正在营业")
# #
# restaurant = Restaurant()
# print(restaurant.restaurant_name,restaurant.cuisine_type)
# restaurant.describe_restaurant()
# restaurant.open_restaurant()
# um_str = "0123456789"
# d= um_str[:]
# G = um_str[-1:-3:-1]
# e= um_str[-2:]
# print(e)
# print(G)
a = [lambda x,i=i:x*i for i in range(9)]
print(a[0](3))
print(a[4](3))
print(a[8](3)) |
188345ff8813e403de97070ee7b87ace456939fb | RichardDev01/MazeRunner | /mazerunner_sim/envs/maze_generator.py | 3,876 | 3.984375 | 4 | """Generator for a maze for the envirement."""
# Maze generation using recursive backtracker algorithm
# https://en.wikipedia.org/wiki/Maze_generation_algorithm#Recursive_backtracker
from queue import LifoQueue
from random import choice
from random import randint
from typing import Tuple
from PIL import Image
import numpy as np
from mazerunner_sim.utils.pathfinder import manhattan_distance
def generate_maze(size: int = 16, center_size: int = 4) -> Tuple[np.array, np.array, np.array]:
"""
Generate maze.
:param size: size of the maze
:param center_size: size of center section
:return: numpy array of booleans with shape = [size * 2 + 1, size * 2 + 1]
"""
# Modified from https://github.com/ravenkls/Maze-Generator-and-Solver/blob/master/maze_generator.py
pixels = np.zeros((2 * size + 1, 2 * size + 1), dtype=bool)
pixels[size - center_size + 1:size + center_size, size - center_size + 1:size + center_size] = True
safe_zone = pixels.copy()
# Creating exit
random_height = randint(1, size * 2 - 1)
exit_x, exit_y, offset_x, offset_y = choice([
[0, random_height, 1, 0], # left side
[size * 2, random_height, -1, 0], # right side
[random_height, size * 2, 0, -1], # bottom side
[random_height, 0, 0, 1] # top side
])
pixels[exit_y, exit_x] = True
pixels[exit_y + offset_y, exit_x + offset_x] = True
stack = LifoQueue()
cells = np.zeros((size, size), dtype=bool)
cells[size // 2 - center_size // 2:size // 2 + center_size // 2, size // 2 - center_size // 2:size // 2 + center_size // 2] = True
stack.put((size // 2 + center_size // 2, size // 2))
while not stack.empty():
x, y = stack.get()
adjacents = []
if x > 0 and not cells[x - 1, y]:
adjacents.append((x - 1, y))
if x < size - 1 and not cells[x + 1, y]:
adjacents.append((x + 1, y))
if y > 0 and not cells[x, y - 1]:
adjacents.append((x, y - 1))
if y < size - 1 and not cells[x, y + 1]:
adjacents.append((x, y + 1))
if adjacents:
stack.put((x, y))
neighbour = choice(adjacents)
neighbour_on_img = (neighbour[0] * 2 + 1, neighbour[1] * 2 + 1)
current_on_img = (x * 2 + 1, y * 2 + 1)
wall_to_remove = (neighbour[0] + x + 1, neighbour[1] + y + 1)
pixels[neighbour_on_img] = True
pixels[current_on_img] = True
pixels[wall_to_remove] = True
cells[neighbour] = True
stack.put(neighbour)
# Creating the entries
for x_b, y_b in [(-1, 0), (0, 1), (1, 0), (0, -1)]:
pixels[size + center_size * x_b, size + center_size * y_b] = True
pixels[size + (center_size + 1) * x_b, size + (center_size + 1) * y_b] = True
# Creating random openings in the walls
corrupt_mask = np.zeros(pixels.shape)
corrupt_mask[1:-1, 1:-1] = np.random.rand(*(pixels.shape - np.array([2, 2])))
corrupt_mask = corrupt_mask > 0.95
pixels = np.logical_or(pixels, corrupt_mask)
# Leaves
leaves = np.zeros((2 * size + 1, 2 * size + 1), dtype=float)
for y in range(leaves.shape[0]):
for x in range(leaves.shape[1]):
if pixels[y, x]:
leaves[y, x] = manhattan_distance((x, y), (exit_x, exit_y))
leaves = np.random.rand(*leaves.shape) > leaves / (sum(leaves.shape) - 4)
return pixels, safe_zone, leaves
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("size", nargs="?", type=int, default=16)
parser.add_argument('--output', '-o', nargs='?', type=str, default='generated_maze.png')
args = parser.parse_args()
maze = generate_maze(args.size)
image = Image.fromarray(maze * 255).convert('RGB')
image.save(args.output)
|
06d7a94ea199955e4662e0337c5eb37b9c48ff62 | objarni/langames | /src/table_builders.py | 2,100 | 3.84375 | 4 | class HtmlTableBuilder:
"""Produces HTML table code to be inserted into a larger HTML document"""
def __init__(self):
self.rows = []
def set_headers(self, column_headers):
self.headers = column_headers
def add_row(self, cells):
self.rows.append(cells)
def get_html(self):
rows_html = self._get_row_html(self.headers)
for row in self.rows:
rows_html += self._get_row_html(row)
return f"<table>\n{rows_html}</table>\n"
# This method name begins with '_' which is
# convention for 'private' in Python. It is
# available outside of the class however,
# it is just a convention!
# Also, it could have been a local function
# in get_html method, it is a matter of taste!
# Or, a static method, as PyCharm suggests...
def _get_row_html(self, cells):
cells_html = ""
for cell in cells:
cells_html += f"<td>{cell}</td>"
return f" <tr>{cells_html}</tr>\n"
class ConsoleTableBuilder:
"""Produces a simple string to be printed to standard output (console)"""
def __init__(self, column_width):
self.column_width = column_width
def set_headers(self, column_headers):
self.result = self._format_row(column_headers)
def add_row(self, cells):
self.result += self._format_row(cells)
def get_string_output(self):
return self.result
def _format_row(self, values):
fmtstr = '{:>' + str(self.column_width) + '}'
result = ''
for value in values:
result += fmtstr.format(value)
return result + "\n"
# TODO: implement this class by filling in the methods
# Hint 1: look at test in test_tablebuilders.py for expected behaviour!
# Hint 2: CSV stands for comma-separated-values
class CsvTableBuilder:
"""Produces an output string with comma separated values to written to file"""
def __init__(self):
pass
def set_headers(self, column_headers):
pass
def add_row(self, cells):
pass
def get_csv_text(self):
pass
|
cb691085e825c0a5b0a1e1347666daa88ae0c509 | Ads99/python_learning | /Bitbucket Python Lessons/lesson8.py | 698 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Lesson 8
Pulling data from a Microsoft SQL database
"""
from pandas import DataFrame, date_range, concat
import pandas as pd
import sys
from sqlalchemy import create_engine, MetaData, Table, select
'''
Version 1
In this section we use the sqlalchemy library to grab data from a sql database
'''
# Parameters
ServerName = "PMSISQL06"
Database = "Smiths_Dev"
TableName = "Main_Sales"
# Create the connection
engine = create_engine('mssql+pyodbc://' + ServerName + '/' + Database)
conn = engine.connect()
# Required for querying tables
metadata = MetaData(conn)
# Table to query
tbl = Table(TableName, metadata, autoload=True, schema="dbo")
#tbl.create(checkfirst=) |
fe8a977e976ad65f621fcd2ec6a1602d6b9f8c0a | Aasthaengg/IBMdataset | /Python_codes/p02952/s457740316.py | 245 | 3.8125 | 4 | def readinput():
n=int(input())
return n
def main(n):
count=0
for i in range(1,n+1):
if(len(str(i))%2==1):
count+=1
return count
if __name__=='__main__':
n=readinput()
ans=main(n)
print(ans)
|
4a9fef432427ba0b1b8b24e5461c422ac63316c3 | topDreamer/PyTorch-MRCToolkit | /pytorch_mrc/nn/similarity_function.py | 8,383 | 3.5 | 4 | """
This module implements the two matrices similarity calculation.
Here we assume input shape is ``(batch_size, seq_len1, dim1)` and ``(batch_size, seq_len2, dim2)`, and
we will return output whose shape is ``(batch_size, seq_len1, seq_len2)``.
"""
import torch
import torch.nn as nn
import math
class CosineSimilarity(nn.Module):
"""
This similarity function simply computes the cosine similarity between two matrixes.
It has no parameters.
"""
def forward(self, tensor_1, tensor_2):
normalized_tensor_1 = tensor_1 / tensor_1.norm(dim=-1, keepdim=True)
normalized_tensor_2 = tensor_2 / tensor_2.norm(dim=-1, keepdim=True)
return torch.bmm(normalized_tensor_1, normalized_tensor_2.transpose(1, 2))
class DotProductSimilarity(nn.Module):
"""
This similarity function simply computes the dot product between two matrixes, with an
optional scaling to reduce the variance of the output elements.
"""
def __init__(self, scale_output=False):
super(DotProductSimilarity, self).__init__()
self.scale_output = scale_output
def forward(self, tensor_1, tensor_2):
result = torch.bmm(tensor_1, tensor_2.transpose(1, 2))
if self.scale_output:
# TODO why allennlp do multiplication here ?
result /= math.sqrt(tensor_1.size(-1))
return result
class ProjectedDotProductSimilarity(nn.Module):
"""
This similarity function does a projection and then computes the dot product between two matrices.
It's computed as ``x^T W_1 (y^T W_2)^T + b(Optional)``. An activation function applied after the calculation.
Default is no activation.
"""
def __init__(self, tensor_1_dim, tensor_2_dim, projected_dim,
reuse_weight=False, bias=False, activation=None):
super(ProjectedDotProductSimilarity, self).__init__()
self.reuse_weight = reuse_weight
self.projecting_weight_1 = nn.Parameter(torch.Tensor(tensor_1_dim, projected_dim))
if self.reuse_weight:
if tensor_1_dim != tensor_2_dim:
raise ValueError('if reuse_weight=True, tensor_1_dim must equal tensor_2_dim')
else:
self.projecting_weight_2 = nn.Parameter(torch.Tensor(tensor_2_dim, projected_dim))
self.bias = nn.Parameter(torch.Tensor(1)) if bias else None
self.activation = activation
def reset_parameters(self):
nn.init.xavier_uniform_(self.projecting_weight_1)
if not self.reuse_weight:
nn.init.xavier_uniform_(self.projecting_weight_2)
if self.bias is not None:
self.bias.data.fill_(0)
def forward(self, tensor_1, tensor_2):
projected_tensor_1 = torch.matmul(tensor_1, self.projecting_weight_1)
if self.reuse_weight:
projected_tensor_2 = torch.matmul(tensor_2, self.projecting_weight_1)
else:
projected_tensor_2 = torch.matmul(tensor_2, self.projecting_weight_2)
result = torch.bmm(projected_tensor_1, projected_tensor_2.transpose(1, 2))
if self.bias is not None:
result += self.bias
if self.activation is not None:
result = self.activation(result)
return result
class BiLinearSimilarity(nn.Module):
"""
This similarity function performs a bilinear transformation of the two input matrices. It's
computed as ``x^T W y + b(Optional)``. An activation function applied after the calculation.
Default is no activation.
"""
def __init__(self, tensor_1_dim, tensor_2_dim, bias=False, activation=None):
super(BiLinearSimilarity, self).__init__()
self.weight_matrix = nn.Parameter(torch.Tensor(tensor_1_dim, tensor_2_dim))
self.bias = nn.Parameter(torch.Tensor(1)) if bias else None
self.activation = activation
self.reset_parameters()
def reset_parameters(self):
nn.init.xavier_uniform_(self.weight_matrix)
if self.bias is not None:
self.bias.data.fill_(0)
def forward(self, tensor_1, tensor_2):
intermediate = torch.matmul(tensor_1, self.weight_matrix)
result = torch.bmm(intermediate, tensor_2.transpose(1, 2))
if self.bias is not None:
result += self.bias
if self.activation is not None:
result = self.activation(result)
return result
class TriLinearSimilarity(nn.Module):
"""
This similarity function performs a trilinear transformation of the two input matrices. It's
computed as ``w^T [x; y; x*y] + b(Optional)``. An activation function applied after the calculation.
Default is no activation.
"""
def __init__(self, input_dim, bias=False, activation=None):
super(TriLinearSimilarity, self).__init__()
self.input_dim = input_dim
self.weight_vector = nn.Parameter(torch.Tensor(3 * input_dim))
self.bias = nn.Parameter(torch.Tensor(1)) if bias else None
self.activation = activation
self.reset_parameters()
def reset_parameters(self):
std = math.sqrt(6 / (self.weight_vector.size(0) + 1))
self.weight_vector.data.uniform_(-std, std)
if self.bias is not None:
self.bias.data.fill_(0)
def forward(self, tensor_1, tensor_2):
w1, w2, w12 = self.weight_vector.chunk(3, dim=-1)
tensor_1_score = torch.matmul(tensor_1, w1) # B*L1
tensor_2_score = torch.matmul(tensor_2, w2) # B*L2
combined_score = torch.bmm(tensor_1 * w12, tensor_2.transpose(1, 2)) # B*L1*L2
result = combined_score + tensor_1_score.unsqueeze(2) + tensor_2_score.unsqueeze(1)
if self.bias is not None:
result += self.bias
if self.activation is not None:
result = self.activation(result)
return result
class MLPSimilarity(nn.Module):
"""
This similarity function performs Multi-Layer Perception to compute similarity. It's
computed as ``w^T f(linear(x) + linear(y)) + b(Optional)``. Notify we will use the
activation(Default tanh) between two perception layers rather than output layer.
"""
def __init__(self, tensor_1_dim, tensor_2_dim, hidden_dim, bias=False, activation=torch.tanh):
super(MLPSimilarity, self).__init__()
self.projecting_layers = nn.ModuleList([nn.Linear(tensor_1_dim, hidden_dim),
nn.Linear(tensor_2_dim, hidden_dim)])
self.score_weight = nn.Parameter(torch.Tensor(hidden_dim))
self.score_bias = nn.Parameter(torch.Tensor(1)) if bias else None
self.activation = activation
self.reset_parameters()
def reset_parameters(self):
std = math.sqrt(6 / (self.score_weight.size(0) + 1))
self.score_weight.data.uniform_(-std, std)
if self.score_bias is not None:
self.score_bias.data.fill_(0)
def forward(self, tensor_1, tensor_2):
projected_tensor_1 = self.projecting_layers[0](tensor_1) # B*L1*H
projected_tensor_2 = self.projecting_layers[1](tensor_2) # B*L2*H
combined_tensor = projected_tensor_1.unsqueeze(2) + projected_tensor_2.unsqueeze(1) # B*L1*L2*H
result = torch.matmul(self.activation(combined_tensor), self.score_weight) # B*L1*L2
if self.score_bias is not None:
result += self.score_bias
return result
# class SymmetricProject(nn.Module):
# def __init__(self, tensor_1_dim, tensor_2_dim, hidden_dim, reuse_weight=True, activation=F.relu):
# super(SymmetricProject, self).__init__()
# self.reuse_weight = reuse_weight
# with tf.variable_scope(self.name):
# diagonal = tf.get_variable('diagonal_matrix', shape=[self.hidden_dim],initializer=tf.ones_initializer, dtype=tf.float32)
# self.diagonal_matrix = tf.diag(diagonal)
# self.projecting_layer = tf.keras.layers.Dense(hidden_dim, activation=activation,
# use_bias=False)
# if not reuse_weight:
# self.projecting_layer2 = tf.keras.layers.Dense(hidden_dim, activation=activation, use_bias=False)
#
# def __call__(self, t0, t1):
# trans_t0 = self.projecting_layer(t0)
# trans_t1 = self.projecting_layer(t1)
# return tf.matmul(tf.tensordot(trans_t0,self.diagonal_matrix,[[2],[0]]),trans_t1,transpose_b=True)
|
5b7b2bfc34316dc863ea43773c2fa0c46b8ae5b6 | thomasnield/oreilly-strata-london-2020-ml-spark-sklearn | /section_ii_preprocessing/2_3_normalization_sklearn.py | 881 | 3.9375 | 4 | import pandas as pd
from sklearn.preprocessing import Normalizer
'''
We can also use normalization which is slightly more complicated.
This rescales the input variables so the resulting vector has a length of 1.
For example, for a point (x1,x2) has a given value (2,2),
this would be transformed to (.70710678, .70710678)
because the hypotenuse from the origin will be 1.0.
This works best for sparse datasets with attributes of many scales,
for neural networks, k-nearest neighbors, and other ML algorithms.
'''
df = pd.read_csv('../data/diabetes.csv', delimiter=",")
# Extract input variables (all rows, all columns but last column)
X = df.values[:, :-1]
# Extract output column (all rows, last column)
Y = df.values[:, -1]
# Rescale all the input variables to be normalized
# This
scaler = Normalizer().fit(X)
rescaled_X = scaler.fit_transform(X)
print(rescaled_X)
|
9c5d15606f9bc9b4d63c839bb66fed0671d46cb1 | pythonCore24062021/pythoncore | /HW/homework06/rrasi/task6.py | 689 | 4.15625 | 4 | #У другому списку зберегти індекси парних елементів першого списку. Наприклад,
#якщо дано список зі значеннями 8, 3, 15, 6, 4, 2, то другий треба заповнити значеннями 1, 4, 5, 6
#(або 0, 3, 4, 5 - якщо індексація починається з нуля),
#оскільки саме в цих позиціях першого масиву стоять парні числа.
mylist = [8, 3, 15, 6, 4, 2]
indexlist = []
for i in range(0, len(mylist)):
if mylist[i] % 2 == 0:
indexlist.append(i)
print(mylist)
print(indexlist)
|
302b5f20e7fceed5dadd292678088dd727b265bb | joel35/challenges | /263/islands.py | 1,678 | 4.28125 | 4 | def count_islands(grid):
"""
Input: 2D matrix, each item is [x, y] -> row, col.
Output: number of islands, or 0 if found none.
Notes: island is denoted by 1, ocean by 0 islands is counted by continuously
connected vertically or horizontally by '1's.
It's also preferred to check/mark the visited islands:
- eg. using the helper function - mark_islands().
"""
islands = 0 # var. for the counts
for row_num, row in enumerate(grid):
for col_num, item in enumerate(row):
islands += mark_islands(row_num, col_num, grid)
return islands
def mark_islands(row_num, col_num, grid):
"""
Input: the row, column and grid
Output: None. Just mark the visited islands as in-place operation.
"""
if is_item_invalid(row_num, col_num, grid) or \
grid[row_num][col_num] == '#' or \
grid[row_num][col_num] == 0:
return 0
grid[row_num][col_num] = '#'
top_neighbor = {
'row': row_num - 1,
'col': col_num
}
bottom_neighbor = {
'row': row_num + 1,
'col': col_num
}
left_neighbor = {
'row': row_num,
'col': col_num - 1
}
right_neighbor = {
'row': row_num,
'col': col_num + 1
}
neighbors = [
top_neighbor,
bottom_neighbor,
left_neighbor,
right_neighbor
]
for neighbor in neighbors:
mark_islands(neighbor['row'], neighbor['col'], grid)
return 1
def is_item_invalid(row_num, col_num, grid):
return row_num < 0 or \
row_num >= len(grid) or \
col_num < 0 or \
col_num >= len(grid[0])
|
2695e2aa290da28a224eb3f987b8b4e8741a095c | bopopescu/VS2017_GIT | /test_1.1/test_1.1/file_test.py | 1,296 | 3.828125 | 4 | def file_open(filename):
try :
with open (filename,'r+')as file_object:
msg=file_object.read()
print (msg.rstrip())
return msg
except FileNotFoundError:
print ("无法找到文件"+filename)
def file_add_write(filename,add_msg):
file_msg=file_open(filename)
file_msg+=add_msg
try :
with open (filename,'w+')as file_object:
"""需要载入模式为W+,否则会没有read的权限"""
file_object.write(file_msg)
msg=file_object.read()
print(msg)
except FileNotFoundError:
print ("无法找到文件"+filename)
class File_test():
def __init__(self,filename):
self.filename = filename
def file_change(self):
try :
with open (self.filename)as file_object:
msg=file_object.read()
except FileNotFoundError:
print ("无法找到文件"+self.filename)
try :
msg=int(msg)
except ValueError:
msg=float(msg)
print (msg*10)
return msg
def file_write(self):
msg = file_open(self.filename)
msg =float(msg)+123
filename="test.txt"
file_open(filename)
a=File_test(filename)
file_add_write(filename,"\n123456789") |
d16e128b612e871b0578bbc863626bdef64feeff | AdamZhouSE/pythonHomework | /Code/CodeRecords/2308/60870/284319.py | 1,602 | 3.578125 | 4 | class Node:
def __init__(self, item, lf=None, rg=None, nextNode=None):
self.next = nextNode
self.item = item
self.lf = lf
self.rg = rg
class Tree:
def __init__(self, root):
self.root = root
def middle_travel(self):
if self.root is None:
return []
res_queue = []
def loop(root):
if root is None:
return
loop(root.lf)
res_queue.append(root.item)
loop(root.rg)
loop(self.root)
return res_queue
info_list = input().split()
nums = int(info_list[0])
node_info = [] # 存储每个节点根、左右子树item的列表
newNode_list = [] # 存储只含有根信息的列表
Node_list = [] # 存储节点完整关系的列表
for i in range(nums):
single_node_info = input().split()
node_info.append(single_node_info)
newNode = Node(single_node_info[0])
newNode_list.append(newNode)
for i in range(nums):
opeNode = newNode_list[i]
opeNode_item = node_info[i][0]
opeNode_lf_item = node_info[i][1]
opeNode_rg_item = node_info[i][2]
for j in range(i + 1, nums):
if node_info[j][0] == opeNode_lf_item:
opeNode.lf = newNode_list[j]
elif node_info[j][0] == opeNode_rg_item:
opeNode.rg = newNode_list[j]
Node_list.append(opeNode)
tree = Tree(Node_list[0])
relation_list = tree.middle_travel()
search = input()
index = relation_list.index(search)
if index < len(relation_list) - 1:
item_goal = relation_list[index + 1]
print(item_goal)
else:
print(0) |
48e437e41ce782afb7d0c0fda7267eea70716e77 | yonus/sparkStudyPython | /L8_2.py | 1,506 | 3.53125 | 4 | import tensorflow as tf;
from tensorflow.examples.tutorials.mnist import input_data
import matplotlib.pyplot as plt;
import numpy as np
sess = tf.InteractiveSession()
mnist = input_data.read_data_sets("MNIST_data/",one_hot=True)
a = tf.Variable(1,name="a")
b = tf.Variable(2,name="b")
f = a + b;
init = tf.global_variables_initializer()
with tf.Session() as Session:
init.run()
print(f.eval())
def display_sample(num):
print(mnist.train.labels(num))
label = mnist.train.labels(num).argmax(0)
images = mnist.train.images[0].reshape((1,784))
for i in range(1,500):
images = np.concatenate((images,mnist.train.images[i].reshape([1,784])))
plt.imshow(images,cmap=plt.get_cmap('gray_r'))
##plt.show()
input_images = tf.placeholder(tf.float32 , shape=[None,784])
target_labels = tf.placeholder(tf.float32 , shape=[None,10])
hidden_nodes = 512;
input_weights = tf.Variable(tf.truncated_normal([784,hidden_nodes]))
input_biases = tf.Variable(tf.zeros([hidden_nodes]))
hidden_weights = tf.Variable(tf.truncated_normal([hidden_nodes,10]))
hidden_biases = tf.Variable(tf.zeros([10]))
input_layer = tf.matmul(input_images,input_weights)
hidden_layer = tf.nn.relu(input_layer+input_biases)
digit_weights = tf.matmul(hidden_layer,hidden_weights) + hidden_biases
loss_function = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logit=digit_weights,labels=target_labels))
optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss_function)
correct_predictions = tf.equal() |
ba0b9e2461d1e9f337bfb20fc0879268744e5be1 | balta2ar/scratchpad | /myleetcode/020_valid_parentheses/20.valid-parentheses.py | 1,712 | 3.90625 | 4 | #
# @lc app=leetcode id=20 lang=python3
#
# [20] Valid Parentheses
#
# https://leetcode.com/problems/valid-parentheses/description/
#
# algorithms
# Easy (35.68%)
# Total Accepted: 526.8K
# Total Submissions: 1.5M
# Testcase Example: '"()"'
#
# Given a string containing just the characters '(', ')', '{', '}', '[' and
# ']', determine if the input string is valid.
#
# An input string is valid if:
#
#
# Open brackets must be closed by the same type of brackets.
# Open brackets must be closed in the correct order.
#
#
# Note that an empty string is also considered valid.
#
# Example 1:
#
#
# Input: "()"
# Output: true
#
#
# Example 2:
#
#
# Input: "()[]{}"
# Output: true
#
#
# Example 3:
#
#
# Input: "(]"
# Output: false
#
#
# Example 4:
#
#
# Input: "([)]"
# Output: false
#
#
# Example 5:
#
#
# Input: "{[]}"
# Output: true
#
#
#
class Solution:
def isValid(self, s: str) -> bool:
stack = []
mapping = {'(': ')', '{': '}', '[': ']'}
for c in s:
if c in '([{':
stack.append(mapping[c])
else:
if not stack:
return False
top = stack.pop()
if c != top:
return False
return False if stack else True
def assert_eq(actual, expected):
if actual != expected:
raise AssertionError('expected: %s, actual: %s' % (expected, actual))
def test(input_, output):
assert_eq(Solution().isValid(input_), output)
if __name__ == '__main__':
test('', True)
test('{}', True)
test('[]', True)
test('[[[]]]', True)
test('[[[]]', False)
test('[]]', False)
test('[{()}]', True)
test('[()(){([])}]', True)
|
c845a016ed5d4a1928fba4c68ca0213e601713d5 | corridda/Studies | /CS/Programming_Languages/Python/Python_Documentation/The_Python_Tutorial/Chapter 9. Classes/9.6. Private Variables/Mapping.py | 1,281 | 3.71875 | 4 | class Mapping:
def __init__(self, iterable):
self.items_list = []
self.__update(iterable)
def update(self, iterable):
for item in iterable:
self.items_list.append(item)
__update = update # private copy of original update() method
class MappingSubclass(Mapping):
def update(self, keys, values):
# provides new signature for update()
# but does not break __init__()
for item in zip(keys, values):
self.items_list.append(item)
mapping_obj = Mapping([1, 2, 3])
print('mapping_obj.items_list:', mapping_obj.items_list)
mapping_obj.update([4, 5, 6])
print('mapping_obj.items_list:', mapping_obj.items_list)
print()
mappingSub_obj = MappingSubclass([1, 2, 3])
print('mappingSub_obj.items_list:', mappingSub_obj.items_list)
# execute update() from MappingSubclass
mappingSub_obj.update([4, 5, 6], [7, 8, 9])
print('mappingSub_obj.items_list:', mappingSub_obj.items_list)
# Note that the mangling rules are designed mostly to avoid accidents;
# it still is possible to access or modify a variable that is considered private.
# execute update() from Mapping for 'mappingSub_obj'
Mapping.update(mappingSub_obj, [10, 11, 12])
print('\nmappingSub_obj.items_list:', mappingSub_obj.items_list)
|
5d94ee32d2f13dd3088229a40508eabfef487aa3 | lpham4/PythonPractice | /NextMeeting.py | 976 | 4.34375 | 4 | # Class: 1321L
# Section: 02
# Term: Fall 2018
# Instructor: Professor Malcolm
# Name: Ly Pham
# Lab: Python
day = int(input("Enter today's day: "))
days = int(input('Enter days until meeting: '))
if day == 0:
print('Today is Sunday')
elif day == 1:
print('Today is Monday')
elif day == 2:
print('Today is Tuesday')
elif day == 3:
print('Today is Wednesday')
elif day == 4:
print('Today is Thursday')
elif day == 5:
print('Today is Friday')
elif day == 6:
print('Today is Saturday')
print('Days to the meeting is', days, 'days')
meeting = (day + days) % 7
if meeting == 0:
print('Meeting day is Sunday')
elif meeting == 1:
print('Meeting day is Monday')
elif meeting == 2:
print('Meeting day is Tuesday')
elif meeting == 3:
print('Meeting day is Wednesday')
elif meeting == 4:
print('Meeting day is Thursday')
elif meeting == 5:
print('Meeting day is Friday')
elif meeting == 6:
print('Meeting day is Saturday')
|
dc980d7fd99f6daf80f33c964a88d85a5392261c | BDialloASC/AllStarCode | /Loopy.py | 117 | 3.765625 | 4 | #Some practice with loops
i=0
while i:
print(i)
j = i
while j<3:
print (j)
j+=1
i+=1 |
9357a8b9173a22715f39db4f1d53d91a9ee40126 | epuriprakash123/permutations | /num.py | 115 | 3.5625 | 4 | from itertools import permutations
n=list(input())
l = list(permutations(n,len(n)))
for i in l:
print(''.join(i))
|
77466526e3c9c86054d8414c77f2e53871859090 | ian-njuguna11/Stress-management-chat-bot | /gui.py | 494 | 3.8125 | 4 | from tkinter import *
import tkinter as tk
r = tk.Tk()
def send():
send = "You => "+ e.get()
txt.insert(END,"\n"+send)
if e.get() == "hello":
txt.insert(END, "\n" + "Counsellor => Hello")
e.delete(0,END)
txt = Text(r,bg = "green")
txt.grid(row=0,column=0,columnspan=2)
e=Entry(r, width='100',bg = 'blue')
send=Button(r,text="Send",command=send,bg = "green").grid(row=1,column=1)
e.grid(row=1,column=0)
r.title('Counsellor Chatbot ')
r.mainloop()
|
bfc0708103e30801f2a49620568c57dd40e945bd | AdamZhouSE/pythonHomework | /Code/CodeRecords/2899/39200/301615.py | 158 | 3.671875 | 4 | x = int(input())
def func(x):
if x == 1:
return "true"
elif x < 1:
return "false"
else:
return func(x / 4)
print(func(x))
|
339e5674affbc0dc5a19b43fc6a5c0ce7aacc4ce | jawad1505/SoftwareEngineering | /Stacks/balance_brackets.py | 762 | 3.859375 | 4 |
from stack import Stack
def is_matched(b1, b2):
if b1 == "(" and b2 ==")":
return True
else:
return False
def brackets_balanced(my_str):
s = Stack()
is_balanced = True
index = 0
while index < len(my_str) and is_balanced:
paren = my_str[index]
if paren == "(":
s.push(paren)
else:
if s.is_empty():
is_balanced = False
break
else:
top = s.pop()
if not is_matched(top, paren):
is_balanced = False
break
index += 1
if s.is_empty() and is_balanced:
return True
else:
return False
print(brackets_balanced("(())))"))
|
7aee5e6261a69d20d7ee543ff23e0c7acc731d82 | chowdhurykaushiki/python-exercise | /PracticePython/Exercise9.py | 883 | 4.3125 | 4 | # -*- coding: utf-8 -*-
"""
Generate a random number between 1 and 9 (including 1 and 9).
Ask the user to guess the number, then tell them whether they guessed too low,
too high, or exactly right.
Extras:
Keep the game going until the user types “exit”
Keep track of how many guesses the user has taken, and when the game ends, print this out.
"""
import random
randNum=random.randint(1,9)
#print(randNum)
count = 0
tries='Y'
while tries in ('y','Y'):
num=int(input("Enter your guess between 1 and 9 : "))
if num>randNum:
print("You guessed too high")
elif num<randNum:
print("You guessed too low")
else:
count=count+1
print("Viola! you guessed correct")
tries = input("Please press 'y' to play again and 'n' to exit ")
if tries not in ('Y','y'):
print("Your correct guess: ",count,"! Good bye")
break
|
6b098767cded28d5e1bb8dae58172ca639131834 | cdalsania/python-challenge | /PyBank/main.py | 2,801 | 3.734375 | 4 | #Importing the necessary modules/libraries
import os
import csv
#csv_file = os.path.join('folder_name', 'file.csv')
csvpath = os.path.join('Resources', 'budget_data.csv')
#define variables as integers
total_months = 0
total_profit_or_loss = 0
month_change_profit_or_loss = 0
prior_month_change_profit_or_loss = 0
first_month_profit_or_loss = 0
last_month_profit_or_loss = 0
average_change = 0
greatest_increase = 0
greatest_decrease = 0
greatest_increase_month = ''
greatest_decrease_month = ''
#Opening and reading the CSV file
with open(csvpath) as csvfile:
csvreader = csv.reader(csvfile, delimiter = ',')
#Reading the header row
csv_header = next(csvreader)
#Reading the first row (that we tract the changes properly)
#Variable to hold first_months_Profit_or_loss
first_months_profit_or_loss = 0
last_months_profit_or_loss = 0
for row in csvreader:
total_months += 1
total_profit_or_loss +=int(row[1])
if total_months == 1:
first_months_profit_or_loss = int(row[1])
else:
last_months_profit_or_loss = int(row[1])
if total_months > 1:
month_change_profit_or_loss = int(row[1]) - prior_month_change_profit_or_loss
prior_month_change_profit_or_loss = int(row[1])
#Total_months to be one less : 86 - 1 = 85
if month_change_profit_or_loss > greatest_increase:
greatest_increase = month_change_profit_or_loss
greatest_increase_month = row[0]
if month_change_profit_or_loss < greatest_decrease:
greatest_decrease = month_change_profit_or_loss
greatest_decrease_month = row[0]
average_change = (last_months_profit_or_loss - first_months_profit_or_loss) /(total_months - 1)
#Displaying information
print('Financial Analysis')
print('---------------------------')
print('Total Months: ' +str(total_months))
print('Total: $' + str(total_profit_or_loss))
print('Average Change: $' + str(round(average_change,2)))
print('Greatest Increase in Profits: ' + greatest_increase_month + ' ($' + str(greatest_increase) +')')
print('Greatest Decrease in Profits: ' + (greatest_decrease_month) + ' ($' + str(greatest_decrease) + ')')
output = open('analysis.txt', 'w')
line1 = 'Financial Analysis'
line2 = '--------------------------'
line3 = str(f'Total Months: {str(total_months)}')
line4 = str(f'Total: ${str(total_profit_or_loss)}')
line5 = str(f'Average Change: ${str(round(average_change,2))}')
line6 = str(f'Greatest Increase in Profits: {greatest_increase_month} (${str(greatest_increase)}')
line7 = str(f'Greatest Decrease in Profits: {greatest_decrease_month} (${str(greatest_decrease)}')
output.write('{}\n{}\n{}\n{}\n{}\n{}\n{}\n'.format(line1, line2,line3,line4,line5,line6,line7)) |
226476ee605d5c0e191c6543dd39e5647fc29e98 | M0Rph3U56031769/commondtools | /commondtools/filehandling/csvreader.py | 1,126 | 3.734375 | 4 | import csv
class Reader:
file: str = None
delimiter: str = ','
def __init__(self, file: str, delimiter: str = ','):
self.file = file
self.delimiter = delimiter
def read(self):
csv_header: list = []
with open(file=self.file, mode="r") as csv_file:
csv_reader = csv.reader(csv_file, delimiter=self.delimiter)
line_count = 0
for row in csv_reader:
if line_count == 0:
print(f'Column names are {", ".join(row)}')
csv_header.append(row)
else:
print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.')
line_count += 1
print(f'Processed {line_count} lines.')
if __name__ == "__main__":
import os
def get_data(file_name: str):
directory_name = os.path.dirname(__file__)
directory_name = os.path.dirname(directory_name)
return os.path.join(directory_name, "data/" + file_name)
csv_example = Reader(file=get_data(file_name="example.csv"))
csv_example.read()
|
bc6cdd6374cd7c87bce380e22f606f88a4dab258 | eliecer11/Uip-prog3 | /Tareas/tarea4/programa4.py | 322 | 3.609375 | 4 |
chance = 0
minutos = 0
while chance < 10:
tiempo = int(input("Introduzca el tiempo en minutos: "))
chance +=1
if tiempo / 60:
dias = 24 - tiempo % 24
horas = 8 - tiempo % 8
minutos = 60 - tiempo % 60
print(dias)
print(horas)
print(minutos)
|
ba8c55e8efeed1ece197edb8783b52963a727516 | dankodak/Programmierkurs | /Abgaben/Blatt 1/Aufgabe 3/Team 41411/Ben Romdhane_Houssem_HoussemBenRomdhane_755653/Aufgabe3_HoussemBenRomdhane.py | 487 | 3.625 | 4 | summand1 = int(input("Zahl 1: "))
summand2 = int(input("Zahl 2: "))
length_summand1 = len(str("{:b}".format(summand1)))
length_summand2 = len(str("{:b}".format(summand2)))
length_binary_sum = len(str("{:b}".format(summand1+summand2)))
print()
print(" "*(length_binary_sum-length_summand1+2)+str("{:b}".format(summand1)))
print("+ "+" "*(length_binary_sum-length_summand2)+str("{:b}".format(summand2)))
print("-"*(length_binary_sum+2))
print("= "+str("{:b}".format(summand1+summand2)))
|
9119a1d9abf0063b7a3223a48b1460d8290de8f2 | herjh0405/Coding_Test | /Chapter5. DFS&BFS/5-5. 2가지 방식으로 구현한 팩토리얼 예제.py | 1,015 | 3.65625 | 4 | # 컴퓨터 내부에서 재귀 함수의 수행은 스택 자료구조를 이용한다.
# 함수를 계속 호출했을 떄 가장 마지막에 호출한 함수가 먼저 수행을 끝내야 그 앞의 함수 호출이 종료되기 때문이다.
# 재귀 함수는 내부적으로 스택 자료구조와 동일하다는 것을 기억하자.
# 반복적으로 구현한 n!
def factorial_iterative(n):
result = 1
for i in range(1, n+1):
result *= i
return result
# 재귀적으로 구현한 n!
def factorial_recursive(n):
if n <= 1 : # n이 1 이하인 경우 1을 반환
return 1
# n! = n*(n-1)!인 코드를 그대로 작성
return n * factorial_recursive(n-1)
print('반복적으로 구현:', factorial_iterative(5)) # 반복적으로 구현: 120
print('재귀적으로 구현:', factorial_recursive(5)) # 재귀적으로 구현: 120
# 재귀 함수의 장점은 ? 더 간결하다. 수학의 점화식을 그대로 소스코드로 옮겼기 때문 |
b02588ec05d93f4d6a6cc007662d3af161348065 | nandwanarohan/Python | /Longest Substring.py | 476 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed May 30 17:58:22 2018
@author: HP PC
"""
s = " dfabhdfsaebjggdfgsdghsrgsergaefr"
maxlen = 0
current = s[0]
longest = s[0]
for i in range(len(s)-1):
if s[i+1] >= s[i]:
current += s[i+1]
if len(current) > maxlen:
maxlen = len(current)
longest = current
else:
current = s[i+1]
i += 1
print("Longest substring possible is:- " + longest)
|
2169cfa4dfe95f9226a26b48fd6bda9483008642 | infomuscle/algorithms-leetcode | /leetcode-python/86. Partition List.py | 1,107 | 3.53125 | 4 | # 제출 코드 - Runtime 85.36 Memory 98.41
class Solution:
def partition(self, head, x: int):
if not head:
return head
partition1, head1 = None, None
partition2, head2 = None, None
current = head
while current:
if current.val < x:
if not head1:
head1 = current
partition1 = current
else:
partition1.next = current
partition1 = partition1.next
else:
if not head2:
head2 = current
partition2 = current
else:
partition2.next = current
partition2 = partition2.next
current = current.next
if partition1:
partition1.next = head2
if partition2:
partition2.next = None
return head1 if head1 else head2
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
|
8c8c33591711fa474f9cfab92348a7e36d0f98a1 | rogcomfox/python | /python/latihan/palindrom.py | 175 | 3.75 | 4 | a = int(input())
for b in range(a):
b = input()
for i in b:
if b(chr(i)) == b(chr(-i)):
print("Palindrom")
else:
print("Bukan") |
ebe16d4f339952c6661434104ffa18b46bf9b015 | windmzx/pyleetcode | /543. Diameter of Binary Tree.py | 777 | 3.84375 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
res = 0
def diameterOfBinaryTree(self, root: TreeNode) -> int:
def helper(root):
if root is None:
return 0
leftlen = helper(root.left)
rightlen = helper(root.right)
self.res = max(self.res, leftlen+rightlen+1)
return max(leftlen, rightlen)+1
helper(root)
return self.res-1
if __name__ == "__main__":
x=Solution()
root=TreeNode(1)
root.left=TreeNode(2)
root.right=TreeNode(3)
# root.left.left=TreeNode(4)
# root.left.right=TreeNode(5)
print(x.diameterOfBinaryTree(root)) |
06d785a3a0e0f9409b8118079aaf5c68e64c5ccf | amaljyothicollegeaes/S1-A-JILSE-JACOB-43 | /PYTHON PROGRAMING LAB/27-1-2021/3b.square of N numbers.py | 365 | 3.96875 | 4 | Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec 7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> list=[5,6,7,8,9,10]
>>> for x in list:
square=x*x
print(x," square is ",square)
5 square is 25
6 square is 36
7 square is 49
8 square is 64
9 square is 81
10 square is 100
>>> |
1ebf251f35c811d579ee866a78b311a40fda63ed | mswift42/project-euler-2 | /euler56.py | 611 | 3.828125 | 4 | #!/usr/bin/python
#-*- coding: utf-8 -*-
"""Powerful digit sum
Problem 56
A googol (10100) is a massive number: one followed by one-hundred zeros; 100100 is almost unimaginably large: one followed by two-hundred zeros. Despite their size, the sum of the digits in each number is only 1.
Considering natural numbers of the form, ab, where a, b 100, what is the maximum digital sum?"""
def sum_digits(number):
return sum([int(i) for i in str(number)])
max = 0
for i in range(10,100):
for j in range(10,100):
if sum_digits(pow(i,j)) > max:
max = sum_digits(pow(i,j))
print max
|
0a323514f89d6f3d0566421226d6c48be96f4255 | jeffakins/numpy_pandas_visualization_exercises | /pandas_series.py | 10,148 | 4.3125 | 4 | # Pandas Exercises
import pandas as pd
fruit_series = pd.Series(["kiwi", "mango", "strawberry", "pineapple", "gala apple", "honeycrisp apple", "tomato", "watermelon", "honeydew", "kiwi", "kiwi", "kiwi", "mango", "blueberry", "blackberry", "gooseberry", "papaya"])
# Type and output of the fruit_series
type(fruit_series)
fruit_series
# 1. Determine the number of elements in fruits.
fruit_series.size # Answer: 17
#2. Output only the index from fruits.
fruit_series.index # RangeIndex(start=0, stop=17, step=1)
fruit_series.index.tolist()
# 3. Output only the values from fruits.
fruit_series.values # Complete
# 4. Confirm the data type of the values in fruits.
fruit_series.dtype
# 5. Output only the first five values from fruits.
fruit_series.head(5)
# Output the last three values.
fruit_series.tail(3)
# Output two random values from fruits.
fruit_series.sample(2)
# 6. Run the .describe() on fruits to see what information it returns when called on a Series with string values
fruit_series.describe()
# 7. Run the code necessary to produce only the unique string values from fruits.
fruit_series.unique() # This method needs parenthasis to work
# 8. Determine how many times each unique string value occurs in fruits.
fruit_series.unique().size # Answer: 13
# 9. Determine the string value that occurs most frequently in fruits.
fruit_series.value_counts().head(1) # Kiwi
# 10. Determine the string value that occurs least frequently in fruits.
fruit_series.value_counts().nsmallest(n=1, keep="all")
#--------------------------------------------------------------------------
# Exercises Part II
import pandas as pd
fruit_series = pd.Series(["kiwi", "mango", "strawberry", "pineapple", "gala apple", "honeycrisp apple", "tomato", "watermelon", "honeydew", "kiwi", "kiwi", "kiwi", "mango", "blueberry", "blackberry", "gooseberry", "papaya"])
#1. Capitalize all the string values in fruits.
fruit_series.str.capitalize()
# 2. Count the letter "a" in all the string values (use string vectorization).
fruit_series.str.count("a").sum() # Answer: 14
# 3. Output the number of vowels in each and every string value.
vowels = list('aeiou')
fruit_series[fruit_series.isin(vowels)] # No worky
# 4. Write the code to get the longest string value from fruits.
max(fruit_series, key=len) # 'honeycrisp apple'
# 5. Write the code to get the string values with 5 or more letters in the name.
fruit_series.str.len() >= 5
# 6. Use the .apply method with a lambda function to find the fruit(s) containing the letter "o" two or more times.
fruit_series[fruit_series.apply(lambda fruit: fruit.count('o') > 1)]
# 7. Write the code to get only the string values containing the substring "berry".
fruit_series[fruit_series.str.contains('berry')]
# 8. Write the code to get only the string values containing the substring "apple".
fruit_series[fruit_series.str.contains('apple')]
# 9. Which string value contains the most vowels?
fruit_series[fruit_series.str.count('[aeiou]').max()] # 'honeycrisp apple'
#--------------------------------------------------------------------------
# Exercises Part III
import pandas as pd
letters = pd.Series(['hnvidduckkqxwymbimkccexbkmqygkxoyndmcxnwqarhyffsjpsrabtjzsypmzadfavyrnndndvswreauxovncxtwzpwejilzjrmmbbgbyxvjtewqthafnbkqplarokkyydtubbmnexoypulzwfhqvckdpqtpoppzqrmcvhhpwgjwupgzhiofohawytlsiyecuproguy'])
letters
# 1. Which letter occurs the most frequently in the letters Series?
split_letters = letters.str.split(pat="", n=0, expand=True) # Splits the string into individual letters
split_letters # Letters split into columns (one row)
transpose_letters = split_letters.transpose() # Turns the columns into rows
transpose_letters # Display rows
transpose_letters.value_counts() # Groups the letters by number of occurence
transpose_letters.value_counts().head(1) # Answer: y; 13
# This is the (better) way... (thanks to Eli's quesiton and Brandon's assist)
letter_list = list('hnvidduckkqxwymbimkccexbkmqygkxoyndmcxnwqarhyffsjpsrabtjzsypmzadfavyrnndndvswreauxovncxtwzpwejilzjrmmbbgbyxvjtewqthafnbkqplarokkyydtubbmnexoypulzwfhqvckdpqtpoppzqrmcvhhpwgjwupgzhiofohawytlsiyecuproguy')
letter_series = pd.Series(letter_list) # Convert the list into a series
letter_series # Check outpu
letter_series.value_counts().head(1) # Answer: y; 13
# 2. Which letter occurs the Least frequently?
transpose_letters.value_counts().tail() # Answer: l; 4
# 3. How many vowels are in the Series?
vowels = list('aeiou')
letter_series[letter_series.isin(vowels)].value_counts().sum()
# 4. How many consonants are in the Series?
letter_series.value_counts().sum() - letter_series[letter_series.isin(vowels)].value_counts().sum()
# # Answer: 166
# 5. Create a Series that has all of the same letters but uppercased
letter_series.str.upper()
# 6. Create a bar plot of the frequencies of the 6 most commonly occuring letters.
import matplotlib.pyplot as plt
letter_series.value_counts().head(6).plot.bar()
plt.show() # Vertical bar plot of top 6
# New Series
numbers = pd.Series(list(['$796,459.41', '$278.60', '$482,571.67', '$4,503,915.98', '$2,121,418.3', '$1,260,813.3', '$87,231.01', '$1,509,175.45', '$4,138,548.00', '$2,848,913.80', '$594,715.39', '$4,789,988.17', '$4,513,644.5', '$3,191,059.97', '$1,758,712.24', '$4,338,283.54', '$4,738,303.38', '$2,791,759.67', '$769,681.94', '$452,650.23']))
numbers
# 1. What is the data type of the numbers Series?
numbers.dtype # Object
# 2. How many elements are in the number Series?
numbers.value_counts().sum() # 20
# or
numbers.size # 20
# 3. Perform the necessary manipulations by accessing Series attributes and methods to convert the numbers Series to a numeric data type.
num_no_dollar = numbers.str.replace("$", "") # Remove $
just_numbers = num_no_dollar.str.replace(",", "") # Remove commas
just_numbers = just_numbers.astype(float) # Convert to float type
just_numbers # dtype: float64
# 4. Run the code to discover the maximum value from the Series.
just_numbers.max() # Answer: 4789988.17
# 5. Run the code to discover the minimum value from the Series.
just_numbers.min() # Answer: 278.6
# 6. What is the range of the values in the Series?
just_numbers.shape
# 7. Bin the data into 4 equally sized intervals or bins and output how many values fall into each bin.
bin_just_numbers = pd.cut(just_numbers, 4).value_counts()
bin_just_numbers
# 8. Plot the binned data in a meaningful way. Be sure to include a title and axis labels.
bin_just_numbers.plot.bar(title='Frequency of Numbers',
color='steelblue').set(xlabel='Numeric Grouping',
ylabel='Frequency')
plt.show()
# New Series
exam_scores = pd.Series([60, 86, 75, 62, 93, 71, 60, 83, 95, 78, 65, 72, 69, 81, 96, 80, 85, 92, 82, 78])
# 1. How many elements are in the exam_scores Series?
exam_scores.size # Answer: 20
# 2. Run the code to discover the minimum, the maximum, the mean, and the median scores for the exam_scores Series.
exam_scores.min() # Answer: 60
exam_scores.max() # Answer: 96
exam_scores.mean() # Answer: 78.15
exam_scores.median() # Answer: 79
# 3. Plot the Series in a meaningful way and make sure your chart has a title and axis labels.
bins = pd.IntervalIndex.from_tuples([(60, 69), (70, 79), (80, 89), (90, 100)]) # Grouped/binned by letter grade
pd.cut(exam_scores, bins).value_counts(sort=False).plot.bar(title='Exam Grades', color='steelblue').set(xlabel='Grade', ylabel='Frequency')
plt.show() # Got it to work!
# 4. Write the code necessary to implement a curve for your exam_grades Series and save this as curved_grades.
# Add the necessary points to the highest grade to make it 100, and add the same number of points to every other score in the Series as well.
curved_exam_scores = exam_scores + 4 # Curved the grades by adding 4 points to all scores
pd.cut(curved_exam_scores, bins).value_counts(sort=False).plot.bar(title='Exam Grades', color='steelblue').set(xlabel='Grade', ylabel='Frequency')
plt.show() # Bar plot showes a shift right
# 5. Use a method to convert each of the numeric values in the curved_grades Series into a categorical value of letter grades.
# For example, 86 should be a 'B' and 95 should be an 'A'. Save this as a Series named letter_grades.
def score_to_letter_grade(score):
if score >= 0 and score <= 59:
return "F"
elif score >= 60 and score <= 69:
return "D"
elif score >= 70 and score <= 79:
return "C"
elif score >= 80 and score <= 89:
return "B"
elif score >= 90 and score <= 100:
return "A"
else:
return "Not a valid score"
curved_letter_grade = curved_exam_scores.apply(score_to_letter_grade)
curved_letter_grade
# 6. Plot your new categorical letter_grades Series in a meaninful way and include a title and axis labels.
curved_letter_grade.value_counts()
curved_letter_grade.value_counts(sort=False).sort_index(ascending=False).plot.bar(title='Exam Grades', color='steelblue').set(xlabel='Grade', ylabel='Frequency')
plt.show() |
b7ee6c535ba1581733949b56c78ed67c013189f9 | thiagomess/pyhton | /OO2/Heranca.py | 1,442 | 3.90625 | 4 | class Funcionario:
def __init__(self, nome):
self.nome = nome
def registra_horas(self, horas):
print('Horas registradas...')
def mostrar_tarefas(self):
print('Fez muita coisa...')
class Caelum(Funcionario):
def mostrar_tarefas(self):
print('Fez muita coisa, Caelumer')
def busca_cursos_do_mes(self, mes=None):
print(f'Mostrando cursos - {mes}' if mes else 'Mostrando cursos desse mês')
class Alura(Funcionario):
def mostrar_tarefas(self):
print('Fez muita coisa, Alurete!')
def busca_perguntas_sem_resposta(self):
print('Mostrando perguntas não respondidas do fórum')
# Chamamos estas classes pequenas, cujos objetos nem precisam ser instanciados, de Mixins. Elas são bastante
# utilizadas em Python no caso de precisarmos compartilhar algum comportamento que não é o mais importante desta
# classe.
class Hipster: # class MIXINS classes
def __str__(self):
return f'Hipster, {self.nome}.'
class Junior(Alura):
pass
# aqui herdamos duas classes, e em caso de decisao de qual metodo usar, será usado o da esquerda para a direita
class Pleno(Caelum, Alura):
pass
class Senior(Alura, Caelum, Hipster):
pass
joao = Junior("joao")
joao.busca_perguntas_sem_resposta()
joao.mostrar_tarefas()
carlos = Pleno('carlos')
carlos.busca_perguntas_sem_resposta()
carlos.mostrar_tarefas()
luan = Senior('luan')
print(luan)
|
8e9a404e65491f0a4c5799f7be378ef0cfc55453 | EsC369/CodeSignal_Python_3_Algorithms | /Plant_Growing.py | 873 | 4.6875 | 5 | """
Each day a plant is growing by upSpeedmeters. Each night that plant's height decreases by downSpeed meters due to the lack of sun heat. Initially, plant is 0 meters tall. We plant the seed at the beginning of a day. We want to know when the height of the plant will reach a certain level.
Example
For upSpeed = 100, downSpeed = 10, and desiredHeight = 910, the output should be
growingPlant(upSpeed, downSpeed, desiredHeight) = 10.
"""
def growingPlant(upSpeed, downSpeed, desiredHeight):
plantHeight = 0
count = 0
while plantHeight < desiredHeight:
plantHeight += upSpeed
count += 1
if upSpeed >= desiredHeight:
return 1
if(plantHeight >= desiredHeight):
return count
else:
plantHeight -= downSpeed
if plantHeight > desiredHeight:
count -= 1
return count
|
361274373e370ab7fb4212d73edb0730e6164cc2 | pcakhilnadh/Cryptography | /Ciphers/MONOALPHA.py | 246 | 3.859375 | 4 | cipAlp=list(map(str,input("Enter CipherText Alphabet").split()))
plainText=str(input("Enter Plain Text:"))
plainText=str.upper(plainText)
print("Cipher Text:",end='')
for v in plainText:
ind=ord(v)-ord('A')
print(cipAlp[ind],end='') |
bf37599490bc753845d0bafdf6a984828a9a8d1d | suzanneloures/recpoints | /model/route.py | 1,693 | 3.546875 | 4 | # coding=utf-8
class Route:
def __init__(self,googleRoute,pois):
self.google_route = googleRoute #rota inicial google
self.pois = pois #pontos de interesse
self.route_with_waypoints = False
self.scores = [] #scores das predições
self.final_score = 0.0 #score final (apos a aplicacao da equacao)
self.final_google_route = None #rota final redesehada passando pelos pois
self.final_distance = 0.0 #distancia da rota final
def get_pois_coordinates(self):
pois_return = []
for poi in self.pois:
pois_return.append((poi['latitude'],poi['longitude']))
return pois_return
#funcao = ([quant pois] * [soma_scores] * 1000) / distancia final
def get_final_score(self): #aplica a funcao e salva na variavel final_score
self.final_distance = 0.0
for l in self.final_google_route['legs']: #soma as distancas das "pernas" das rotas
self.final_distance += l['distance']['value']
len_pois = len(self.pois) #quantas posicoes existem no arrayde pois
sum_score = sum([x[1] for x in self.scores]) #soma todos os scores
self.final_score = ((len_pois * sum_score)* 1000) / self.final_distance
def print_final_info(self, legs = False):
print("Rota por " + self.final_google_route['summary'])
print("Distancia (metros): " + str(self.final_distance))
print("Score final : " + str(self.final_score))
for p in self.pois:
print(p['name'])
if(legs):
for l in self.final_google_route[u'legs']:
for s in l[u'steps']:
print(s[u'html_instructions'])
|
38a8a817dd40ad8059ace90772207d89208a14f0 | GCleuziou/IntroPythonUNC | /source/exercicesDefiCode/SousChaine.py | 573 | 3.671875 | 4 | entrees_visibles = [
("program","J'aime la programmation"),
("programme","J'aime la programmation"),
("","bonjour"),
]
entrees_invisibles = [
("Jaime","la vie est belle"),
("elle","la vie est belle"),
("elle","la viell est belle"),
("la vie","la vie est belle"),
("belles","la vie est belle"),
("telle","la vie est belle"),
("la c","la vie est belle"),
("ala vie","la vie est belle"),
]
@solution
def sousChaine(s1,s2):
i=0
j=0
while i<len(s2) and j<len(s1):
if s1[j]==s2[i]:
j+=1
elif j>0:
i-=1
j=0
i+=1
return j==len(s1)
|
919b441584e5ef1fea53ff08b60c6859320c1c3b | gittygitgit/python-sandbox | /sandbox/practicepython/e12.py | 330 | 4.09375 | 4 | #!/usr/bin/python
'''
Write a program that takes a list of numbers (for example, a = [5, 10, 15, 20, 25]) and makes a new list of only the first and last elements of the given list. For practice, write this code inside a function.
'''
l = [5,10,15,20,25]
result=[]
result.append(l[0])
result.append(l[len(l) - 1])
print result
|
cb9fd4bd99a6ba5fbf6ecaa7c0bb67ae2a0ae748 | huangqiank/Algorithm | /leetcode/other/findCelebrity.py | 1,841 | 3.640625 | 4 | # 假设你是一个专业的狗仔,参加了一个 n 人派对,其中每个人被从 0 到 n - 1 标号。
# 在这个派对人群当中可能存在一位 “名人”。所谓 “名人” 的定义是:其他所有 n - 1 个人都认识他/她,而他/她并不认识其他任何人。
# 现在你想要确认这个 “名人” 是谁,或者确定这里没有 “名人”
# 。而你唯一能做的就是问诸如 “A 你好呀,请问你认不认识 B呀?” 的问题,
# 以确定 A 是否认识 B。你需要在(渐近意义上)尽可能少的问题内来确定这位 “名人” 是谁(或者确定这里没有 “名人”)。
# 在本题中,你可以使用辅助函数 bool knows(a, b) 获取到 A 是否认识 B。请你来实现一个函数 int findCelebrity(n)。
# 派对最多只会有一个 “名人” 参加。若 “名人” 存在,请返回他/她的编号;若 “名人” 不存在,请返回 -1。
##输入: graph = [
# [1,1,0],
# [0,1,0],
# [1,1,1]
# ]
# 输出: 1
# 解释: 有编号分别为 0、1 和 2 的三个人。graph[i][j] = 1
# 代表编号为 i 的人认识编号为 j 的人,而 graph[i][j] = 0 则代表编号为 i 的人不认识编号为 j 的人。
# “名人” 是编号 1 的人,因为 0 和 2 均认识他/她,但 1 不认识任何人。
# The knows API is already defined for you.
# return a bool, whether a knows b
# def knows(a: int, b: int) -> bool:
## f[i,j] = 1 all i
## f[j,i] = 0 all i
class Solution:
def findCelebrity(self, n):
res = 0
for i in range(1, n):
if knows(res, i):
res = i
for i in range(n):
if i == res:
continue
if knows(i, res) == 0 or knows(res, i) == 1:
return -1
return res
|
04a8e3d040e94f90333fea121b7c3543f7c6f1cf | jeongm-in/UVACS1110- | /Jihoon/crypto.py | 3,845 | 4.1875 | 4 | import string
def shift(text, key):
"""adds key to every letter in text, where a = 0, b = 1, etc.
Wrap around if you reach the end: z + 1 = a.
Don’t change non-letters.
Preserve case"""
answer = ''
for character in text:
if character.isupper():
index = string.ascii_uppercase.index(character)
new_index = (index + key) % 26
answer += string.ascii_uppercase[new_index]
elif character.islower():
index = string.ascii_lowercase.index(character)
new_index = (index + key) % 26
answer += string.ascii_lowercase[new_index]
else:
answer += character
return answer
# If you prefer substituting to building up, this is also possible.
def shift2(text, key):
answer = list(text)
for i, character in enumerate(text):
if character.isupper():
index = string.ascii_uppercase.index(character)
new_index = (index + key) % 26
answer[i] = string.ascii_uppercase[new_index]
elif character.islower():
index = string.ascii_lowercase.index(character)
new_index = (index + key) % 26
answer[i] = string.ascii_lowercase[new_index]
return ''.join(answer)
def unshift(text, key):
"""subtracts key to every letter in text"""
return shift(text, -key)
def vignere(text, key):
"""much like the shift cipher, but instead of adding a single number to all letters, a different number is added to each. Those numbers to add are selected by a the letters of a key word"""
answer = ''
for index_text, character in enumerate(text):
if character.isupper():
index_character = string.ascii_uppercase.index(character)
letter_chosen = key[index_text % len(key)]
amount_to_shift = string.ascii_lowercase.index(letter_chosen)
new_index = (index_character + amount_to_shift) % 26
answer += string.ascii_uppercase[new_index]
elif character.islower():
index_character = string.ascii_lowercase.index(character)
letter_chosen = key[index_text % len(key)]
amount_to_shift = string.ascii_lowercase.index(letter_chosen)
new_index = (index_character + amount_to_shift) % 26
answer += string.ascii_lowercase[new_index]
else:
answer += character
return answer
def unvignere(text, key):
"""subtracts the key from text instead of adding it to the text"""
answer = ''
for index_text, character in enumerate(text):
if character.isupper():
index_character = string.ascii_uppercase.index(character)
amount_to_shift = index_text % len(key)
index_shift = string.ascii_lowercase.index(key[amount_to_shift])
new_index = (index_character - index_shift) % 26
answer += string.ascii_uppercase[new_index]
elif character.islower():
index_character = string.ascii_lowercase.index(character)
amount_to_shift = index_text % len(key)
index_shift = string.ascii_lowercase.index(key[amount_to_shift])
new_index = (index_character - index_shift) % 26
answer += string.ascii_lowercase[new_index]
else:
answer += character
return answer
def interleave(text):
"""splits the string in half and return a string alternating letters from the first and second half"""
middle_index = int((1 + len(text)) / 2)
first_half = text[:middle_index]
second_half = text[middle_index:]
answer = ''
for i in range(len(first_half)):
answer += first_half[i]
if i <= len(second_half) - 1:
answer += second_half[i]
return answer
def deinterleave(text):
return text[0::2] + text[1::2]
|
208845d7ffbcc38362b0b245b2d0d34b7add8ea4 | ddh/leetcode | /python/reverse_linked_list.py | 2,469 | 4.15625 | 4 | """
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
"""
# Idea:
# For iteratively, we'll load each node in the array. Then we'll iterate from both ends of the array towards the middle, swapping VALUES as we go along.
# This is kind of cheating since this takes advantage that the only difference between the nodes are its values.
#
# For Recursive: TBD
#
# Explanation from Gayle (cracking code): https://www.youtube.com/watch?v=njTh_OwMljA
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# Uses a stack. Looks straightforward
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
# Base case:
if not head:
return None
# Create a list of nodes
nodes = []
while head:
nodes.append(head)
head = head.next
head_pointer = 0
tail_pointer = len(nodes) - 1
while head_pointer < tail_pointer:
nodes[head_pointer].val, nodes[tail_pointer].val = nodes[tail_pointer].val, nodes[head_pointer].val
head_pointer += 1
tail_pointer -= 1
return nodes[0] # return head node
# Another way to iterate, swapping nodes and not the values. More proper in case nodes are complicated to swap data.
# This is a little confusing to me because of the temporary node in the while loop.
class Solution2:
def reverseList(self, head: ListNode) -> ListNode:
# Base case:
if not head:
return None
previous_node = None
current_node = head
while current_node:
temp_node = current_node
current_node = current_node.next
temp_node.next = previous_node
previous_node = temp_node
return previous_node
# I don't the recursive one. I translated the following from a java recursive solution.
# Besides, it's hard to comprehend from first glance. Iterative is easier to understand!
class Solution3:
def reverseList(self, head: ListNode) -> ListNode:
if not head or head.next is None:
return head
node = self.reverseList(head.next)
head.next.next = head
head.next = None
return node
# Driver
a = ListNode(1)
b = ListNode(2)
c = ListNode(3)
d = ListNode(4)
e = ListNode(5)
a.next = b
b.next = c
c.next = d
d.next = e
Solution().reverseList(a)
Solution2().reverseList(a) |
d287800fec7b0e959d6148d203b70031855d56a0 | Chrispresso/Artificial-Intelligence-Reinforcement-Learning-in-Python | /tic_tac_toe.py | 13,424 | 3.953125 | 4 | import numpy as np
import matplotlib.pyplot as plt
from typing import Tuple
LENGTH = 3 # Height/Width of board
class Environment(object):
def __init__(self):
self.board = np.zeros((LENGTH, LENGTH))
self.x = -1 # Represents 'x' on the board
self.o = 1 # Represents 'o' on the board
self.winner = None
self.ended = False # Has the game ended
self.num_states = 3**(LENGTH*LENGTH) # Number of possible states for the board
def is_empty(self, row: int, col: int) -> bool:
"""
Determines whether a spot on the board is empty
"""
return self.board[row, col] == 0
def game_over(self, force_recalculate: bool = False) -> bool:
"""
Returns True if game is over (player won or it's a draw)
Sets self.winner and self.ended
"""
if not force_recalculate and self.ended:
return self.ended
# Check rows
for row in range(LENGTH):
for player in (self.x, self.o):
if self.board[row].sum() == player*LENGTH:
self.winner = player
self.ended = True
return True
# Check columns
for column in range(LENGTH):
for player in (self.x, self.o):
if self.board[:, column].sum() == player*LENGTH:
self.winner = player
self.ended = True
return True
# Check diagonals
for player in (self.x, self.o):
# Top-left -> Bottom-right diag
if self.board.trace() == player*LENGTH:
self.winner = player
self.ended = True
return True
# Top-right -> Bottom-left diag
if np.fliplr(self.board).trace() == player*LENGTH:
self.winner = player
self.ended = True
return True
# Check draw
if np.all((self.board == 0) == False):
self.winner = None
self.ended = True
return True
# Game is not over if there are still 0's on board
self.winner = None
return False
def get_state(self) -> int:
"""
Returns the current state of the board, represented as an int from 0...{S}-1.
Where {S} = set of all possible states. {S} = 3^(LENGTH*LENGTH) since each
board space can be 0, 1 or -1 representing empty, 'o', or 'x', respectively.
Equivalent of finding value of base-3 number
"""
k = 0
h = 0
for row in range(LENGTH):
for col in range(LENGTH):
if self.board[row, col] == 0:
val = 0
elif self.board[row, col] == self.x:
val = 1
elif self.board[row, col] == self.o:
val = 2
h += (3**k) * val # (base^position) * value
k += 1 # Move to next position
return h
def is_draw(self) -> bool:
"""
True if game is a draw
"""
return self.ended and self.winner is None
def draw_board(self) -> None:
"""
Draws the board
i.e.
-------------
| x | | |
-------------
| | | |
-------------
| | | o |
-------------
"""
for row in range(LENGTH):
print('--------------')
print('| ', end='')
for col in range(LENGTH):
if self.board[row, col] == self.x:
print(' x |', end='')
elif self.board[row, col] == self.o:
print(' o |', end='')
else:
print(' |', end='')
print('') # End of column
print('--------------') # End of rows
def reward(self, symbol: int) -> bool:
"""
Get the reward for a agent's symbol
"""
if not self.game_over():
return 0
# Game is over, did we win?
return 1 if self.winner == symbol else 0
class Agent(object):
def __init__(self, epsilon: float, learning_rate: float, symbol: int, verbose: bool = False):
self.epsilon = epsilon # Probability of choosing random action instead of greedy
self.learning_rate = learning_rate
self.state_history = []
self.V = None
self.verbose = verbose
self.symbol = symbol
def reset_history(self) -> None:
"""
Reset self.state_history
"""
self.state_history = []
def update_state_history(self, state: int) -> None:
"""
Update the state history
"""
self.state_history.append(state)
def update(self, environment: Environment) -> None:
"""
Backtrack over the states such that:
V(prev_state) = V(prev_state) + learning_rate*(V(next_state) - V([prev_state]))
where V(next_state) = reward if it's the most current state
@Note:
We only do this at the end of an episode (for tic-tac-toe)
"""
reward = environment.reward(self.symbol)
target = reward
for prev_state in reversed(self.state_history):
value = self.V[prev_state] + self.learning_rate*(target - self.V[prev_state])
self.V[prev_state] = value
target = value
self.reset_history()
def take_action(self, environment: Environment) -> None:
# Epsilon-greedy
r = np.random.rand()
best_state = None
if r < self.epsilon:
# Random action
if self.verbose:
print('Taking a random action')
possible_moves = []
for row in range(LENGTH):
for col in range(LENGTH):
if environment.is_empty(row, col):
possible_moves.append((row, col))
selection = np.random.choice(len(possible_moves))
next_move = possible_moves[selection]
# Greedy
else:
pos2value = {} # For verbose
next_move = None
best_value = -1
for row in range(LENGTH):
for col in range(LENGTH):
if environment.is_empty(row, col):
# What is the state if we made this move?
environment.board[row, col] = self.symbol
state = environment.get_state()
environment.board[row, col] = 0 # Change it back
pos2value[(row, col)] = self.V[state]
if self.V[state] > best_value:
best_value = self.V[state]
best_state = state
next_move = (row, col)
# If verbose, print board with values
if self.verbose:
print("Taking a greedy action")
for row in range(LENGTH):
print("------------------")
for col in range(LENGTH):
if environment.is_empty(row, col):
# Print the value
print(" %.2f|" % pos2value[(row, col)], end="")
else:
print(" ", end="")
if environment.board[row, col] == environment.x:
print("x |", end="")
elif environment.board[row, col] == environment.o:
print("o |", end="")
else:
print(" |", end="")
print("")
print("------------------")
# Make the move
environment.board[next_move[0], next_move[1]] = self.symbol
class Human(object):
def __init__(self, symbol: int):
self.symbol = symbol
def take_action(self, envrionment: Environment) -> None:
while True:
move = input('Enter corrdinate row,col for your next move (row,col=0..2): ')
row, col = move.split(',')
row = int(row)
col = int(col)
if envrionment.is_empty(row, col):
envrionment.board[row, col] = self.symbol
break
def update(self, environment: Environment) -> None:
pass
def update_state_history(self, state: int) -> None:
pass
def get_state_hash_and_winner(environment: Environment, row: int = 0, col: int = 0):
results = []
for v in (0, environment.x, environment.o):
environment.board[row, col] = v
# End of the column, so go to next row
if col == LENGTH-1:
# If we are also at the end of the rows then the board is full
if row == LENGTH-1:
state = environment.get_state()
ended = environment.game_over(True)
winner = environment.winner
results.append((state, winner, ended))
# Just move to next row
else:
results += get_state_hash_and_winner(environment, row + 1, 0)
# Just go to next column
else:
results += get_state_hash_and_winner(environment, row, col + 1)
return results
def init_x_vals(envrionment: Environment, state_winner_triples: Tuple[int, int, bool]) -> 'np.ndarray':
"""
Initialize state values such that
if x wins, V(s) = 1
if x loses or it's a draw, V(s) = 0
otherwise, V(s) = 0.5
"""
V = np.zeros((envrionment.num_states, 1))
for state, winner, ended in state_winner_triples:
if ended:
if winner == envrionment.x:
v = 1
else:
v = 0
else:
v = .5
V[state] = v
return V
def init_o_vals(envrionment: Environment, state_winner_triples: Tuple[int, int, bool]) -> 'np.ndarray':
"""
Initialize state values such that
if o wins, V(s) = 1
if o loses or it's a draw, V(s) = 0
otherwise, V(s) = 0.5
"""
V = np.zeros((envrionment.num_states, 1))
for state, winner, ended in state_winner_triples:
if ended:
if winner == envrionment.o:
v = 1
else:
v = 0
else:
v = .5
V[state] = v
return V
def play_game(p1, p2, environment: Environment, draw: bool = False) -> int:
current_player = None
while not environment.game_over():
# Alternate players
if current_player == p1:
current_player = p2
else:
current_player = p1
# Draw board before the user who wants to see it makes a move
if draw:
if draw == 1 and current_player == p1:
environment.draw_board()
elif draw == 2 and current_player == p2:
environment.draw_board()
current_player.take_action(environment)
# Update state history
state = environment.get_state()
p1.update_state_history(state)
p2.update_state_history(state)
if draw:
environment.draw_board()
p1.update(environment)
p2.update(environment)
if isinstance(p1, Human):
if environment.winner is not None:
if environment.winner == p1.symbol:
return 1 # Win
else:
return 2 # Lose
else:
return 3 # Draw
elif isinstance(p2, Human):
if environment.winner is not None:
if environment.winner == p2.symbol:
return 1 # Win
else:
return 2 # Lose
else:
return 3 # Draw
else:
return None
if __name__ == '__main__':
# Train the agent
eps = .1
learning_rate = 0.5
environment = Environment()
p1 = Agent(eps, learning_rate, environment.x)
p2 = Agent(eps, learning_rate, environment.o)
state_winner_triples = get_state_hash_and_winner(environment)
Vx = init_x_vals(environment, state_winner_triples)
p1.V = Vx
Vo = init_o_vals(environment, state_winner_triples)
p2.V = Vo
T = 10000
for t in range(T):
if t % 200 == 0:
print(t)
play_game(p1, p2, Environment())
# Play human vs. agent
human = Human(environment.o)
first = True
while True:
p1.verbose = True
print('\nrow=0, col=0 is top left\n')
# First time, let the AI go first
if first:
print('AI goes first')
win = play_game(p1, human, Environment(), draw=2)
first = False
else:
if np.random.rand() < .5:
print('AI goes first')
win = play_game(p1, human, Environment(), draw=2)
else:
print('You go first')
win = play_game(human, p1, Environment(), draw=1)
if win == 1:
print('You won!!')
elif win == 2:
print('Sorry, you lost... try again!')
elif win == 3:
print('TIE! Try again!')
answer = input('Play again? [Y/n]: ')
if answer and answer.lower()[0] == 'n':
break
|
650eeb051e25ee1207d15c5f4c9513c270ae176b | yinyinyin123/algorithm | /数组/majorityElement.py | 1,220 | 3.546875 | 4 |
### one code one day
### 2020/03/13
### leetcode 169 多数元素
### 投票法
def majorityElement(self, nums: List[int]) -> int:
count = 0
majority = 0
for num in nums:
if(count == 0):
count = 1
majority = num
else:
if(num == majority):
count += 1
else:
count -= 1
return majority
### 中位数法
def majorityElement(self, nums: List[int]) -> int:
### 快排的partition
def partition(start, end):
small = start - 1
for i in range(start, end):
if(nums[i] < nums[end]):
small += 1
nums[small], nums[i] = nums[i], nums[small]
small += 1
nums[small], nums[end] = nums[end], nums[small]
return small
### 找第K大元素
def kthMax(start, end):
if(start < end):
k = partition(start, end)
if(k == K):
return nums[k]
elif(k < K):
return kthMax(k+1, end)
else:
return kthMax(start, k-1)
elif(start == end):
return nums[start]
K = len(nums) // 2
return kthMax(0,len(nums)-1) |
b31d9c315f41e0e61f033aeb504b74433e28e2f8 | alexjercan/algorithms | /old/hackerrank/ai/saveprincess.py | 601 | 3.734375 | 4 | #!/usr/bin/python
def displayPathtoPrincess(n, grid):
# print all the moves here
if grid[0][0].lower() == 'p':
dir_1 = "LEFT"
dir_2 = "UP"
elif grid[-1][0].lower() == 'p':
dir_1 = "LEFT"
dir_2 = "DOWN"
elif grid[0][-1].lower() == 'p':
dir_1 = "RIGHT"
dir_2 = "UP"
elif grid[-1][-1].lower() == 'p':
dir_1 = "RIGHT"
dir_2 = "DOWN"
for i in range(n // 2):
print(dir_1)
print(dir_2)
m = int(input())
grid = []
for i in range(0, m):
grid.append(input().strip())
displayPathtoPrincess(m, grid)
|
533e148a9dece47185c4551aa0af285cc2c7373f | mikeghen/snap-eligibility-estimate | /household_size_pdfs.py | 1,207 | 3.625 | 4 | import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import simulator
"""
Work in progress
STEP 1: Produce the Income PDF for a county from the US Census data
"""
income_pdf, n = simulator.get_incomes_pdf(42, 101) # Philadelphia
"""
STEP 2: Produce the normally distributed PDF for a household size
"""
household_size = 7
household_size_income_pdf = simulator.get_household_size_incomes_pdf(household_size, 42, 101)
print("PDF:", household_size_income_pdf)
"""
STEP 3: Sum the two PDFs together
"""
df = pd.DataFrame({'income_pdf':income_pdf,
'household_size_income_pdf':household_size_income_pdf})
df['adjusted_pdf'] = df['income_pdf'] + df['household_size_income_pdf']
print("DF:", df)
"""
STEP 4: Normalize to get the household size adjusted income PDF
"""
df['adjusted_pdf'] = df['adjusted_pdf'] / df['adjusted_pdf'].sum()
df.index = simulator.INCOMES
print("DF Normalized:", df)
axes = df.plot(kind='bar',subplots=True, title='Income PDF Adjustment for Philadelphia County')
axes[0].set_title('Income PDF (household_size = 7)')
axes[1].set_title('Income PDF (All Households)')
axes[2].set_title('Household Size Adjusted PDF (household_size = 7)')
plt.show()
|
ffba3e8f6bb32a6db8288f2d52fecab476366741 | watsyurname529/significant-digits-soup | /prototype/extract_digits.py | 1,048 | 3.78125 | 4 | #!/usr/local/bin/python3
#Python code to do data wrangling / formatting from raw data files from the
#webscraper code.
import re
import locale
import json
locale.setlocale( locale.LC_ALL, 'en_US.UTF-8' )
#json_file = input('Enter a JSON database file: ')
json_file = '../digits.json'
with open(json_file, 'r') as file:
database = json.loads(file.read())
print(database)
list_of_digits_str = []
list_of_digits_num = []
extract_digits = re.compile(r'[0-9]*[\.\,]?[0-9]+')
for key, value in database.items():
print(key)
for entry in value:
#print(re.findall(r'[0-9]*[\.\,]?[0-9]+', entry))
list_of_digits_str.extend(extract_digits.findall(entry))
#list_of_digits.append(float(s) for s in entry.split() if s.isdigit())
#print(float(s)) for s in entry.split() if s.isdigit()
#for s in entry.split():
#if s.isdigit():
#print(s)
for str in list_of_digits_str:
list_of_digits_num.append(locale.atof(str))
print(list_of_digits_str)
print(list_of_digits_num)
|
76c36f605e559ec2f1e6477ebb6bd6725f5d4c44 | joe-arriaga/portfolio | /spark_python/22-most-popular-movie/most-popular-movie.py | 799 | 3.703125 | 4 | # most-popular-movie.py
# Auust 4, 2020
#
# Sort the MovieLens database by popularity. Which movie was watched most often?
# That is, which movie(ID) appears most often in the data set?
from pyspark import SparkConf, SparkContext
conf = SparkConf().setMaster('local').setAppName('MoviePopularity')
sc = SparkContext(conf = conf)
def parseLines(line):
fields = line.split()
return (int(fields[1]), 1)
# Data format: UserID MovieID Rating Timestamp
lines = sc.textFile('../data/ml-100k/u.data')
parsedLines = lines.map(parseLines)
countedMovies = parsedLines.reduceByKey(lambda x,y: x + y)
sortedMovies = countedMovies.sortBy(lambda x: x[1])
#sortedMovies = countedMovies.sortBy(lambda x: x[1], ascending=False)
results = sortedMovies.collect()
for result in results:
print result
|
9afd8cfd72923db5e2864ab27935eccb6873ec6b | afusco059/what_to_eat | /food/food.py | 2,900 | 3.703125 | 4 | import random
chinese_food = ["House of China", "Imperial Garden", "Golden Hunan", "Main Moon", "Chinatown Inn",]
Buffet_food = ["Royale Grill", "Golden Corral", "Ponderosa"]
japanese_food = ["Izumi", "Mizu", "Tokyo House", "Sakura", "Asuka"]
mexican_food = ["Plaza Mexico", "Los Gallos", "Jalisco's"]
pizza_food =["Belleria", "Rise Pies", "Brick oven"]
fast_food = ["Chic Fil A", "Sonic", "Hardy's"]
italian_food = ["Salvatores", "Scarsellas", "Nicolinni's"]
cuisine_choice_responses = ["Oh Snap great idea. ", "Oh yeah sure that sounds great. ", "Oh yeah all them carbs are mine today ", "One of my favs. ", "Looks like I'm going to struggle with all this food. "]
random_response = random.choice(cuisine_choice_responses)
def Hola():
print("Hello there, having trouble deciding what your in the mood for, I got you")
cuisine_choice = input("Please select what type of cuisine you prefer: \n1 = Chinese\n2 = Japanese\n3 = Mexican\n4 = Pizza \n5 = Fast Food\n6 = Italian\n7 = Buffet \n8 = I Don't Know!\nPlease enter a number: ")
if cuisine_choice == "1":
print(random_response+"You should eat at: "+random.choice(chinese_food))
elif cuisine_choice == "2":
print(random_response+"You should eat at: "+random.choice(japanese_food))
elif cuisine_choice == "3":
print(random_response+"You should eat at: "+random.choice(mexican_food))
elif cuisine_choice == "4":
print(random_response+"You should eat at: "+random.choice(pizza_food))
elif cuisine_choice == "5":
print(random_response+"You should eat at: "+random.choice(fast_food))
elif cuisine_choice == "6":
print(random_response+" You should eat at: "+random.choice(italian_food))
elif cuisine_choice == "7":
print(random_response+" You should eat at: "+random.choice(Buffet_food))
elif cuisine_choice == "8":
my_random_choice = random.randint(1,8)
if my_random_choice == 1:
print(random_response+"You should eat at: "+random.choice(chinese_food))
elif my_random_choice == 2:
print(random_response+"You should eat at: "+random.choice(japanese_food))
elif my_random_choice == 3:
print(random_response+"You should eat at: "+random.choice(mexican_food))
elif my_random_choice == 5:
print(random_response+"You should eat at: "+random.choice(pizza_food))
elif my_random_choice == 6:
print(random_response+"You should eat at: "+random.choice(fast_food))
elif cuisine_choice == 7:
print(random_response+" You should eat at: "+random.choice(Buffet_food))
else:
print(random_response+" You should eat at: "+random.choice(italian_food))
else:
print("\033[1;32;47m You did not select a number. Please try again. ")
Hola()
Hola() |
d57f3ffa5724ff541d10ec088b3de03f197b9971 | scorum/scorum-py | /scorum/graphenebase/amount.py | 6,422 | 3.703125 | 4 | class Amount(dict):
""" This class helps deal and calculate with the different assets on the
chain.
:param str amount_string: Amount string as used by the backend
(e.g. "10 SCR")
"""
def __init__(self, amount_string="0 SCR"):
self._prec = 9
if isinstance(amount_string, Amount):
self["amount"] = amount_string["amount"]
self["asset"] = amount_string["asset"]
elif isinstance(amount_string, str):
self["amount"], self["asset"] = amount_string.split(" ")
amount = self['amount'].replace('.', '')
if len(amount) < self._prec + 1:
amount += '0'*((self._prec + 1) - len(amount))
amount.lstrip('0')
self['amount'] = int(amount) if len(amount) > 0 else 0
else:
raise ValueError(
"Need an instance of 'Amount' or a string with amount " +
"and asset")
@property
def amount(self):
return self["amount"]
@property
def symbol(self):
return self["asset"]
@property
def asset(self):
return self["asset"]
def _to_string(self, prec):
def insert_zeroes_at_start(string):
multiplier = prec - len(string)
string = ('0' * (multiplier + 1)) + string
return string
def add_dot_separator(string):
list_to_insert = list(string)
list_to_insert.insert(-prec, '.')
string = ''.join(list_to_insert)
return string
negative = False
if self.amount < 0:
negative = True
self["amount"] *= -1
amount_string = str(self.amount)
if len(amount_string) <= prec:
amount_string = insert_zeroes_at_start(amount_string)
amount_string = add_dot_separator(amount_string)
if negative:
amount_string = "-" + amount_string
self["amount"] *= -1
return amount_string
def __str__(self):
return "{} {}".format(
self._to_string(self._prec), self["asset"])
def __float__(self):
return self["amount"]
def __int__(self):
return self["amount"]
def __add__(self, other):
a = Amount(self)
if isinstance(other, Amount):
a["amount"] += other["amount"]
else:
a["amount"] += int(other)
return a
def __sub__(self, other):
a = Amount(self)
if isinstance(other, Amount):
a["amount"] -= other["amount"]
else:
a["amount"] -= int(other)
return a
def __mul__(self, other):
a = Amount(self)
if isinstance(other, Amount):
a["amount"] *= other["amount"]
else:
a["amount"] *= other
if isinstance(other, float):
a["amount"] = int(a["amount"])
return a
def __floordiv__(self, other):
a = Amount(self)
if isinstance(other, Amount):
raise Exception("Cannot divide two Amounts")
else:
a["amount"] //= other
return a
def __div__(self, other):
a = Amount(self)
if isinstance(other, Amount):
raise Exception("Cannot divide two Amounts")
else:
'''
need to use floordiv to get result type int
'''
a["amount"] //= other
return a
def __mod__(self, other):
a = Amount(self)
if isinstance(other, Amount):
a["amount"] %= other["amount"]
else:
a["amount"] %= other
return a
def __pow__(self, other):
a = Amount(self)
if isinstance(other, Amount):
a["amount"] **= other["amount"]
else:
a["amount"] **= other
return a
def __iadd__(self, other):
if isinstance(other, Amount):
self["amount"] += other["amount"]
else:
self["amount"] += other
return self
def __isub__(self, other):
if isinstance(other, Amount):
self["amount"] -= other["amount"]
else:
self["amount"] -= other
return self
def __imul__(self, other):
if isinstance(other, Amount):
self["amount"] *= other["amount"]
else:
self["amount"] *= other
return self
def __idiv__(self, other):
if isinstance(other, Amount):
assert other["asset"] == self["asset"]
return self["amount"] / other["amount"]
else:
'''
need to use floordiv to get result type int
'''
self["amount"] //= other
return self
def __ifloordiv__(self, other):
if isinstance(other, Amount):
self["amount"] //= other["amount"]
else:
self["amount"] //= other
return self
def __imod__(self, other):
if isinstance(other, Amount):
self["amount"] %= other["amount"]
else:
self["amount"] %= other
return self
def __ipow__(self, other):
self["amount"] **= other
return self
def __lt__(self, other):
if isinstance(other, Amount):
return self["amount"] < other["amount"]
else:
return self["amount"] < int(other or 0)
def __le__(self, other):
if isinstance(other, Amount):
return self["amount"] <= other["amount"]
else:
return self["amount"] <= int(other or 0)
def __eq__(self, other):
if isinstance(other, Amount):
return self['amount'] == other['amount']
else:
return self["amount"] == int(other or 0)
def __ne__(self, other):
if isinstance(other, Amount):
return self["amount"] != other["amount"]
else:
return self["amount"] != int(other or 0)
def __ge__(self, other):
if isinstance(other, Amount):
return self["amount"] >= other["amount"]
else:
return self["amount"] >= int(other or 0)
def __gt__(self, other):
if isinstance(other, Amount):
return self["amount"] > other["amount"]
else:
return self["amount"] > int(other or 0)
__repr__ = __str__
__truediv__ = __div__
__truemul__ = __mul__
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.