blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
1a47ce4b14527145732b7c9701526f910c6b26ed | Pasinozavr/5th-year-le-man | /GP/projet/francais.py | 1,174 | 3.578125 | 4 | class Question:
def __init__(self, difficulty, question, answer, propositions):
self.difficulty=difficulty
self.question = question
self.answer = answer
self.propositions = propositions
def difficulty():
return self.difficulty
def question():
return self.question
def answer():
return self.answer
def propositions():
return self.propositions
def select_word_question(difficulty):
question1 = Question(1,"je ... une pomme","mange",["mange","bois"])
question2 = Question(2,"je ... en cours","vais",["vais","vait","va"])
question3 = Question(3,"cette question est ...","difficile",["facile","normale","difficile"])
questions = [question1,question2,question3]
for quest in questions:
if quest.difficulty == difficulty:
return quest
def qfacile():
q = select_word_question(1)
return(q.question,q.answer,q.propositions)
def qmoyen():
q = select_word_question(2)
return(q.question,q.answer,q.propositions)
def qdiff():
q = select_word_question(3)
return(q.question,q.answer,q.propositions)
|
8b5102d8cad871ef0c7eef261ff17f65eb531fbe | floorberkhout/commit4life | /code/algorithms/randomize.py | 917 | 3.765625 | 4 | ###############################################################
# randomize.py
# Runs random algorithm
###############################################################
import random
import time
def randomize(board):
""" Makes random algorithm to solve Rush Hour """
solution = []
counter = 0
# Plays the game untill won
while board.game_won == False:
# Gets random car and move
request_car = random.choice(list(board.cars.values()))
request_move = random.choice([-1, 1])
# Moves car and if moved adds step to solution
moved = board.move(request_car, request_move)
if moved is not 0:
solution.append(", ".join([request_car.name, str(request_move)]))
# Checks if another car prevents the winning car from getting out
board.game_won, time_elapsed = board.check_win(board.start)
return solution, time_elapsed
|
fb7963f02bd9327a4e04c01258e0c465ad02b413 | aweret1/OOP | /Практика new upgr/a1/012.py | 522 | 3.875 | 4 | w = input('Наш or Не наш:')
if w == 'Не наш':
weight = float(input('Вага:'))
height = float(input('Ріст:'))
print('IMT:',703*weight/height**2)
elif w == 'Наш':
weight = float(input('Вага:'))
height = float(input('Ріст:'))
print('IMT:',weight/height**2)
import datetime
def printTimeStamp(name):
print('Автор програми: ' + name)
print('Час компіляції: ' + str(datetime.datetime.now()))
printTimeStamp("Іщенко")
|
4710e1e5abef2aaa2a5d6ed267d247e56b681713 | riteshsharthi/botx | /FAQ/nlp_engine/extractors/Company_next.py | 690 | 3.640625 | 4 | import re
class CompanyNameExtractor:
def __init__(self):
pass
def company_code_extract(self,txt):
match = re.findall(r'[\w\.-]+-[\w\.-]+', txt)
if len(match)==0:
number = re.findall(r'[\w\.-]+\d[\w\.-]+', txt)
else:
#number = re.findall(r'[\w\.-]+\d[\w\.-]+', txt)
# print((dict({"Company Details are: ":match})))
if match:
number = match
#print(dict({'Company Name is': match}))
return number[0]
if __name__ == '__main__':
user_input=input("Enter Company Name: ")
obj=CompanyNameExtractor()
print(obj.company_code_extract(user_input))
|
b3f9583dc914397397e6541830cb750321d1a955 | SiddharthaHaldar/leetcodeProblems | /297-serialize-and-deserialize-binary-tree/297-serialize-and-deserialize-binary-tree.py | 1,828 | 3.671875 | 4 | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
ser = ""
if(root):
q = deque([])
q.append(root)
while(len(q) != 0):
l = len(q)
for x in range(0,l):
node = q.popleft()
if(node):
q.append(node.left)
q.append(node.right)
ser += str(node.val)
ser += ","
else:
ser += "#,"
#print(ser)
return ser
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
q = deque([])
idx = 1
root = TreeNode()
if(len(data) == 0):
return None
data = data.split(",")
root.val = data[0]
q.append(root)
while(len(q) != 0):
node = q.popleft()
left = data[idx]
right = data[idx + 1]
if(left != '#'):
newNode = TreeNode(left)
node.left = newNode
q.append(newNode)
if(right != '#'):
newNode = TreeNode(right)
node.right = newNode
q.append(newNode)
idx += 2
return root
#1236n45nnnnnn
# Your Codec object will be instantiated and called as such:
# ser = Codec()
# deser = Codec()
# ans = deser.deserialize(ser.serialize(root)) |
5797688d1b231c3d44167465e85ce9dfe0a5012e | mAzurkovic/Interview-Prep | /ds-algos/binary-search.py | 402 | 4.0625 | 4 | def binarySearch(arr, left, right, val):
if (left <= right):
mid = (left + right) // 2
if (arr[mid] == val):
return mid
elif (val < arr[mid]):
return binarySearch(arr, left, mid - 1, val)
else:
return binarySearch(arr, mid + 1, right, val)
else:
return -1
print(binarySearch([1,2,3,4,5,6,7,8,9,10], 0, 9, -12))
|
890ab0093276295ce41455d4f528b3bfa551512c | manikshahkataria/codes | /eee.py | 614 | 4.09375 | 4 | def nth_prime_number(n):
if n==1:
return 2
count = 1
num = 3
while(count <= n):
if is_prime(num):
count +=1
if count == n:
return num
num +=2 #optimization
def is_prime(num):
factor = 2
while (factor < num):
if num%factor == 0:
return False
factor +=1
return True
def fib(n):
if n==1:
return 0
elif n==2:
return 1
else:
return fib(n-1)+fib(n-2)
n=int(input(""))
if n%2==0:
print(nth_prime_number(n/2))
else:
n=n//2+2
print(fib(n))
|
5390283e707dde13a8802ab9bbc27a0ff7c5b36a | Engi20/Python-Programming-for-Beginners | /14. OOPS/101.3.DefiningCreatingClasses.py | 463 | 3.828125 | 4 | class Student:
def __init__(self,name,roll,marks):
self.name = name
self.roll = roll
self.marks = marks
def display(self):
print('Student Name: ',self.name)
print('Student Roll No: ', self.roll)
print('Student Marks: ', self.marks)
print()
Students = [ Student('aaa',101,78.25),
Student('bbb',102,62.75),
Student('ccc',103,89.50)]
for s in Students:
s.display()
|
30f39a52e1ce8ec5419c3b43630dfa5d58b17c3f | ttyskg/ProgrammingCompetition | /AtCoder/ABC/035/d.py | 1,350 | 3.53125 | 4 | import sys
from heapq import heappush, heappop, heapify
def dijkstra(s, links):
"""Dijkstra algorism
s: int, start node.
t: int, target node.
links: iterable, link infomation.
links[i] contains edges from node i: (cost, target_node).
return int, minimal cost from s node to t node.
"""
INF = 10**9
dist = [INF] * len(links)
dist[s] = 0
heap = list(links[s])
heapify(heap)
while len(heap) > 0:
cost, node = heappop(heap)
if dist[node] < cost:
continue
dist[node] = cost
for cost2, node2 in links[node]:
if dist[node2] < cost + cost2:
continue
dist[node2] = cost + cost2
heappush(heap, (cost + cost2, node2))
return dist
def main():
input = sys.stdin.readline
N, M, T = map(int, input().split())
A = list(map(int, input().split()))
Gf = [set() for _ in range(N)]
Gr = [set() for _ in range(N)]
for _ in range(M):
a, b, c = map(int, input().split())
a, b = a-1, b-1
Gf[a].add((c, b))
Gr[b].add((c, a))
minf = dijkstra(0, Gf)
minr = dijkstra(0, Gr)
ans = 0
for i in range(N):
res = (T - minf[i] - minr[i]) * A[i]
ans = max(ans, res)
return ans
if __name__ == '__main__':
print(main())
|
5907c8b14724e678abd619240a378d3553c1f7b8 | alexanderlao/CptS-355_Programming_Language_Design | /HW1/HW1.py | 4,362 | 3.859375 | 4 | # Alexander Lao
# Intended for Windows
# returns a dictionary defined by mapping a char
# in s1 to the corresponding char in s2
# PRECONDITION: s1 and s2 must be the same length
def makettable (s1, s2):
dictionary = dict (zip (s1, s2))
return dictionary
# loops through each char in s and replaces them with
# their values if they exist in the ttable. chars are kept
# the same if their keys do not exist in the ttable.
# returns the modified string
def trans (ttable, s):
for c in s:
s = s.replace (c, ttable.get (c,c))
return s
# tests the trans () function with unique strings that
# contain both upper and lower case letters
def testtrans ():
ttable = makettable ('TuRkEy', 'MoNkEy')
revttable = makettable ('MoNkEy', 'TuRkEy')
teststring = "Animal: TuRkEy"
expectedstring = "Animal: MoNkEy"
if trans (ttable, teststring) != expectedstring:
return False
if trans (revttable, trans (ttable, teststring)) != teststring:
return False
if trans (ttable, ' ') != ' ':
return False
if trans (makettable (' ', ' '), 'MoNkEy') != 'MoNkEy':
return False
return True
# creates a histogram list based on the most frequent char
# that appears in the string s. this function is adapted to help
# the digraphs () function; appending ('/' + c + '/') vs. appending (c)
# and sorting alphabetically vs. sorting alphabetically and
# then sorting based on frequency
def histo (s, digraph):
freq = []
seen = []
for c in s:
if c in seen:
pass
elif c not in seen and digraph == False:
freq.append ((c, s.count (c)))
seen.append (c)
elif c not in seen and digraph == True:
freq.append (('/' + c + '/', s.count (c)))
seen.append (c)
sortedhisto = sorted (freq, key = lambda item : item[0])
if digraph == False:
sortedhisto = sorted (sortedhisto, key = lambda item : item[1], reverse = True)
return sortedhisto
# tests the histo () function with a regular string,
# a backwards string, and a string with both upper and
# lower case characters
def testhisto ():
firststring = "aaabbbcccddd"
firsthisto = [('a', 3), ('b', 3), ('c', 3), ('d',3)]
secondstring = "dddcccbbbaaa"
secondhisto = [('a', 3), ('b', 3), ('c', 3), ('d',3)]
thirdstring = "BbBaAaDdDcCc"
thirdhisto = [('B', 2), ('D', 2), ('a', 2), ('c', 2),
('A', 1), ('C', 1), ('b', 1), ('d', 1)]
if histo (firststring, False) != firsthisto:
return False
if histo (secondstring, False) != secondhisto:
return False
if histo (thirdstring, False) != thirdhisto:
return False
return True
# creates a digraph from a string. histo () will split
# the string into pairs of characters and put them into a list.
# the histo () function is then called on the list of pairs in order
# to determine their frequency and sort them
def digraphs (s):
split = [s[i:i+2] for i in range (0, len (s) - 1, 1)]
return histo (split, True)
# tests the digraphs () function using a string with an even
# number of characters, an odd number of characters, and a
# string with only one unique character
def testdigraphs ():
firststring = "aaabbbcccddd"
firstdigraph = [('/aa/', 2), ('/ab/', 1), ('/bb/', 2), ('/bc/', 1),
('/cc/', 2), ('/cd/', 1), ('/dd/', 2)]
secondstring = "abc"
seconddigraph = [('/ab/', 1), ('/bc/', 1) ]
thirdstring = " " # 10 spaces
thirddigraph = [('/ /', 9)]
if digraphs (firststring) != firstdigraph:
return False
if digraphs (secondstring) != seconddigraph:
return False
if digraphs (thirdstring) != thirddigraph:
return False
return True
if __name__ == '__main__':
passedMsg = "%s passed"
failedMsg = "%s failed"
if testtrans () and testhisto () and testdigraphs ():
print ( passedMsg % 'testtrans, testhisto, testdigraphs' )
elif testtrans () == False:
print ( failedMsg % 'testtrans' )
elif testhisto () == False:
print ( failedMsg % 'testhisto' )
elif testdigraphs () == False:
print ( failedMsg % 'testdigraphs' )
|
66f4415bf11d9d5f20d9187493a97d1e4b1b2232 | netor27/codefights-solutions | /arcade/python/arcade-theCore/12_ListBackwoods/100_ReverseOnDiagonals.py | 1,029 | 4.40625 | 4 | '''
The longest diagonals of a square matrix are defined as follows:
the first longest diagonal goes from the top left corner to the bottom right one;
the second longest diagonal goes from the top right corner to the bottom left one.
Given a square matrix, your task is to reverse the order of elements on both of its longest diagonals.
Example
For
matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
the output should be
reverseOnDiagonals(matrix) = [[9, 2, 7],
[4, 5, 6],
[3, 8, 1]]
'''
def reverseOnDiagonals(matrix):
middle = len(matrix) // 2
n = len(matrix) - 1
for i in range(middle):
# left to right
aux = matrix[i][i]
matrix[i][i] = matrix[n-i][n-i]
matrix[n-i][n-i] = aux
# right to left
aux = matrix[i][n-i]
matrix[i][n-i] = matrix[n-i][i]
matrix[n-i][i] = aux
return matrix |
324034e1cf6d41061184d38c03efbb8ab43ba977 | mathieu-clement/cs560-restaurants | /scores.py | 6,981 | 3.65625 | 4 | #!/usr/bin/env python3
import csv
import datetime
class Restaurant:
def __init__(self, rest_id, name, street, zip_code, lat, lon):
self.id = rest_id
self.name = name
self.street = street
self.zip_code = zip_code
self.lat = lat
self.lon = lon
self._inspections = []
@property
def inspections(self):
return sorted(self._inspections)
@property
def score(self):
return self.inspections[0].score # most recent inspection score
def add_inspection(self, inspection):
self._inspections.append(inspection)
def __repr__(self):
return 'Restaurant(%s, %s, San Francisco, CA %s, id=%s, inspections=%s' % \
(self.name, self.street, self.zip_code, self.id, self.inspections)
class Inspection:
def __init__(self, date, score):
self.date = date
self.score = score
self._violations = []
@property
def violations(self):
return sorted(self._violations)
def add_violation(self, violation):
self._violations.append(violation)
def __repr__(self):
return 'Inspection(date=%s, score=%s, violations=%s' % (self.date, self.score, self.violations)
def __eq__(self, other):
return self.date == other.date
def __lt__(self, other):
# most recent first
return other.date < self.date
class Violation:
def __init__(self, description, risk):
self.description = description
self.risk = risk
def __repr__(self):
return '(%s) %s' % (self.risk, self.description)
def __eq__(self, other):
return self.risk == other.risk and self.description == other.description
def __lt__(self, other):
if self.risk == other.risk:
return self.description < other.description
else:
return other.risk_value < self.risk_value
return self.description < other.description
@property
def risk_value(self):
return {'Low Risk': 1, 'Moderate Risk': 2, 'High Risk': 3}.get(self.risk, 0)
class ScoresReader:
def __init__(self, filename):
self.filename = filename
# Columns
# -------
# business_id
# business_name
# business_address
# business_city
# business_state
# business_postal_code
# business_latitude
# business_longitude
# business_location
# business_phone_number
# inspection_id
# inspection_date
# inspection_score
# inspection_type
# violation_id
# violation_description
# risk_category
def get_rows(self):
rows = []
with open(self.filename, 'r') as csv_file:
csv_reader = csv.DictReader(csv_file)
for row in csv_reader:
# Only consider unscheduled inspections
if 'Unscheduled' not in row['inspection_type']:
continue
# Ignore if inspection score is missing
if not row['inspection_score']:
continue
# Ignore if ZIP code is missing or incorrect ("CA")
if not row['business_postal_code']:
continue
try:
int(row['business_postal_code'])
float(row['business_latitude'])
float(row['business_longitude'])
except ValueError:
continue
rows.append({
'id': row['business_id'],
'name': row['business_name'],
'street': row['business_address'],
'zip_code': int(row['business_postal_code']),
'lat': float(row['business_latitude']),
'lon': float(row['business_longitude']),
'inspection_date': row['inspection_date'],
'inspection_score': int(row['inspection_score']),
'inspection_type': row['inspection_type'],
'violation': row['violation_description'],
'risk': row['risk_category']
})
return rows
def get_restaurants(self):
restaurants = []
rows = self.get_rows()
# Sort by restaurant ID
rows = sorted(rows, key=lambda k: k['id'])
dict_rows = {} # key is restaurant id, value is list of rows for that restaurant
for row in rows:
if row['id'] not in dict_rows:
dict_rows[row['id']] = []
dict_rows[row['id']].append(row)
for rest_id, rest_rows in dict_rows.items():
dict_inspections = {} # key is inspection date, value is list
# of rows for that restaurant and that inspection
r = rest_rows[0]
restaurant = Restaurant(r['id'], r['name'], r['street'], r['zip_code'],
r['lat'], r['lon'])
for row in rest_rows:
date = row['inspection_date']
if date not in dict_inspections:
dict_inspections[date] = []
dict_inspections[date].append(row)
for date, insp_rows in dict_inspections.items():
score = insp_rows[0]['inspection_score']
python_date = datetime.datetime.strptime(date.split()[0], '%m/%d/%Y').date()
inspection = Inspection(python_date, score)
for insp_row in insp_rows:
if insp_row['violation'] and insp_row['risk']:
violation = Violation(insp_row['violation'], insp_row['risk'])
if violation not in inspection.violations:
inspection.add_violation(violation)
restaurant.add_inspection(inspection)
restaurants.append(restaurant)
return restaurants
def get_restaurants_dict(self):
restaurants = self.get_restaurants()
d = {}
for r in restaurants:
d[r.id] = r
return d
def get_ids(self, start_id, num):
"""Read dataset until start_id is found, and then look
for num other IDs and return start_id (if found) and those other IDs.
start_id must be an integer. IDs will be returned as integers."""
rows = self.get_rows()
# Sort by restaurant ID
all_ids = sorted(
list(
set(
map(lambda k: int(k['id']),
filter(lambda k: int(k['id']) >= start_id, rows)))))
return all_ids[:num]
def get_row(self, business_id):
"""Returns one/any row with ID = business_id"""
return next(filter(lambda k: k['id'] == business_id, self.get_rows()))
if __name__ == '__main__':
reader = ScoresReader('restaurant_scores.csv')
from pprint import pprint
pprint(reader.get_restaurants())
|
a56995f43c9c365cea356797185cef17635d0dbc | jaydee220/PCSII_Sapienza | /Ex42.py | 143 | 3.796875 | 4 | import math
if __name__ == '__main__':
b = int(input())
a = int(input())
print (str(round((math.degrees(math.atan2(b,a)))))+"°")
|
9d8f44435e2a55054d50a659d656ba6d6192305b | adikadu/DSA | /longestWordInSentence.py | 272 | 3.890625 | 4 | import re
def LongestWord(sen):
a = re.findall(r"[a-zA-Z]+", sen)
l = len(a[0])
ind = 0
for i in range(1, len(a)):
if len(a[i]) > l:
l=len(a[i])
ind = i
# code goes here
return a[ind]
# keep this function call here
print(LongestWord(input())) |
fd0e5bc2875e7108a9c015f5ac7efc3be4acf793 | ganhan999/ForLeetcode | /506、相对名次.py | 1,523 | 4.0625 | 4 | """
给出N 名运动员的成绩,找出他们的相对名次并授予前三名对应的奖牌。
前三名运动员将会被分别授予 “金牌”,“银牌” 和“ 铜牌”("Gold Medal", "Silver Medal", "Bronze Medal")。
(注:分数越高的选手,排名越靠前。)
示例 1:
输入: [5, 4, 3, 2, 1]
输出: ["Gold Medal", "Silver Medal", "Bronze Medal", "4", "5"]
解释: 前三名运动员的成绩为前三高的,因此将会分别被授予 “金牌”,“银牌”和“铜牌” ("Gold Medal", "Silver Medal" and "Bronze Medal").
余下的两名运动员,我们只需要通过他们的成绩计算将其相对名次即可。
"""
"""
如果直接排序是不行的,因为会丢失老的索引。 因此我用了一个 pairs 数组,
来维护一个 nums -> 索引的映射。之后对 paris 进行降序排列即可。由于我事先保存了老的索引信息,因此是没有问题的。
"""
#大神做法1
class Solution:
def findRelativeRanks(self, nums: List[int]) -> List[str]:
pairs = []
for i in range(len(nums)):
pairs.append([nums[i], i])
pairs.sort(key=lambda a: a[0], reverse=True)
for i in range(len(nums)):
if i == 0:
nums[pairs[i][1]] = "Gold Medal"
if i == 1:
nums[pairs[i][1]] = "Silver Medal"
if i == 2:
nums[pairs[i][1]] = "Bronze Medal"
if i > 2:
nums[pairs[i][1]] = str(i + 1)
return nums
|
aeffa44e5b5e12448c08811d9b103468ff1cb7e3 | junwha0511/ALGOPY | /2018/euclidean.py | 273 | 3.75 | 4 |
def getGCD(a, b):
if a%b == 0:
return b
elif a%b >0:
return getGCD(b,a%b)
a = int(input('두 정수를 입력하세요\n'))
b = int(input())
if a<b:
l=b
s=a
else:
l=a
s=b
print('최대공약수는 '+str(getGCD(l,s))+'입니다')
|
01137bccda7a0998798a4eab0dfb6ca360161a2e | gmal1/algoholics-anon | /python/cracking-coding/stacks_queues/animal_shelter.py | 2,174 | 3.78125 | 4 | from enum import Enum
class AnimalSpecies(Enum):
dog = 1,
cat = 2
class Animal:
def __init__(self, species: AnimalSpecies, name: str):
self.species = species
self.name = name
class Node:
def __init__(self, animal: Animal):
self.animal = animal
self.next = None
class AnimalShelter:
def __init__(self):
self.head = None
self.tail = None
def enqueue(self, animal: Animal):
node = Node(animal)
if not self.head:
self.head = node
self.tail = node
else:
self.tail.next = node
self.tail = node
def dequeueAny(self):
if not self.head:
raise Exception('Shelter is empty')
output = self.head
self.head = self.head.next
return output.animal
def __dequeueAnimal(self, species: AnimalSpecies):
if not self.head:
raise Exception('Shelter is empty')
currentAnimal = self.head
previousAnimal = None
while currentAnimal.next and not currentAnimal.animal.species == species:
previousAnimal = currentAnimal
currentAnimal = previousAnimal.next
if not currentAnimal.animal.species == species:
print('dog not found')
return None
if currentAnimal == self.head:
self.head = currentAnimal.next
if self.head.next == None:
self.tail = None
return currentAnimal.animal
def dequeueDog(self):
return self.__dequeueAnimal(AnimalSpecies.dog)
def dequeueCat(self):
return self.__dequeueAnimal(AnimalSpecies.cat)
# dog1 = Animal(AnimalSpecies.dog, 'Fido')
# dog2 = Animal(AnimalSpecies.dog, 'Bud')
# dog3 = Animal(AnimalSpecies.dog, 'Sam')
# cat1 = Animal(AnimalSpecies.cat, 'Joe')
# cat2 = Animal(AnimalSpecies.cat, 'Mew')
# shelter = AnimalShelter()
# shelter.enqueue(dog1)
# shelter.enqueue(dog2)
# shelter.enqueue(cat1)
# shelter.enqueue(cat2)
# shelter.enqueue(dog3)
# print(shelter.dequeueCat().name)
# print(shelter.dequeueAny().name)
# print(shelter.dequeueDog().name)
# print(shelter.dequeueDog().name)
|
e930a6b73fa86e80ebd85b197f71480f3b9da528 | c-boe/Reinforcement-learning | /4 Dynamic programming/Gambler's Problem/value_iteration.py | 5,591 | 3.5625 | 4 | """
Implementation of Exercise 4.9 in Chapter 4 of Sutton and Barto's "Reinforcement
Learning"
"""
import matplotlib.pyplot as plt
import numpy as np
from gamblersproblem import GamblersProblem
def value_iteration(env, theta):
'''
Value iteration
Parameters
----------
env :
Gambler's problem MDP
theta : float
treshold for value iteration
Returns
-------
V_optimal : ndarray, shape (number of states,)
optimal state-value function
pi : ndarray, shape (number of states,)
policy
'''
states = env.state_space()
terminal_states = env.terminal_states
p_h = env.p_h
V_init = int_val_fun(terminal_states)
# Value iteration
V_optimal = value_loop(V_init, p_h, states)
pi = det_policy(V_optimal, states, terminal_states, p_h)
return V_optimal, pi
def int_val_fun(terminal_states):
'''
Initial value function
Parameters
----------
terminal_states : tuple
terminal states of MDP
Returns
-------
V_init : ndarray, shape (number of states,)
initial state value function
'''
V_init = np.zeros(terminal_states[1] + 1)
return V_init
def value_loop(V, p_h, states):
'''
Parameters
----------
V : ndarray, shape (number of states,)
state value function
p_h: float
probability for head
states :
states of MDP
Returns
-------
V : ndarray, shape (number of states,)
state value function
'''
v_tmp = np.zeros(V.shape)
while(1):
Delta = 0
for state in states:
v_tmp[state] = V[state]
V_prev = 0
# determine possible actions for given state
actions = det_actions(state, terminal_states)
for action in actions:
# print(s, a)
# Calculate value function for given action
V_next = val_fun(state, action, V, p_h)
if V_next > V_prev:
V_prev = V_next
V[state] = V_prev
# compare value function with previous value function
Delta = np.max([Delta, np.linalg.norm(v_tmp - V)])
if Delta < theta:
break
return V
def det_actions(current_state, terminal_states):
'''
determine action space for the given current state
Parameters
----------
current_state : float
current state of MDP
terminal_states : tuple , shape (1,1)
terminal states of MDP
Returns
-------
actions : iterable
possible action for current state
'''
actions = range(1, min(current_state,
terminal_states[1] - current_state) + 1)
return actions
def det_policy(V, states, terminal_states, p_h):
'''
Determine policy from optimal value function
Parameters
----------
V : ndarray, shape (number of states,)
state value function
states : iterable
states of MDP
terminal_states : tuple
terminal states of MDP
p_h : float
probability of head
Returns
-------
pi : ndarray, shape (number of states,)
policy
'''
pi = np.zeros(V.shape)
for state in states:
Q_prev = 0
# determine possible actions for given state
actions = det_actions(state, terminal_states)
for action in actions:
# Calculate Q value function for given state (cars_A, cars_B)
# and action a
Q_next = val_fun(state, action, V, p_h)
if Q_next > Q_prev:
Q_prev = Q_next
pi[state] = action
return pi
def val_fun(current_state, action, V, p_h):
'''
Determine value of value function V(s) for given state s
Parameters
----------
current_state : float
current state of MDP
action : action
current action
V : ndarray, shape (number of states,)
state value function
p_h : float
probability of head
Returns
-------
V_value : float
value of current state
'''
V_value = 0
# possible next states after taking action a
next_state_up = current_state + action
next_state_down = current_state - action
if next_state_up == 100: # terminal state
reward = 1
V_value = (p_h*(reward + V[next_state_up]) +
(1 - p_h)*V[next_state_down])
elif next_state_down == 0: # terminal state
V_value = (p_h*(V[next_state_up]) +
(1 - p_h)*V[next_state_down])
else:
V_value = (p_h*(V[next_state_up]) +
(1 - p_h)*V[next_state_down])
return V_value
#%%
def plot_val_fun(V):
'''
plot state value function
'''
plt.figure()
plt.plot(V[1:-1])
plt.title("Value function")
plt.xlabel("Capital")
plt.ylabel("value")
def plot_policy(pi):
'''
plot policy
'''
plt.figure()
plt.plot(pi[1:-1])
plt.title("policy function")
plt.xlabel("Capital")
plt.ylabel("Stake")
#%%
if __name__ == "__main__":
theta = 1e-10
terminal_states = (0, 100)
num_states = 99
p_h = 0.25
env = GamblersProblem(num_states, terminal_states, p_h)
V, pi = value_iteration(env, theta)
plot_val_fun(V)
plot_policy(pi) |
8d0c24bafc991e1bd3b4e81af4222a54f643476d | gabriellaec/desoft-analise-exercicios | /backup/user_054/ch26_2020_10_07_14_57_45_448762.py | 279 | 3.921875 | 4 | casa = float(input('valor da casa? '))
salário = float (input('salário? ' ))
meses = float (input('durante quantos meses quer pagar? ' ))
prestação = casa/meses
if prestação< 0.3*salário:
print ('Empréstimo aprovado')
else:
print ('Empréstimo não aprovado')
|
3b78a6d3a19b261f34a70755b70284c7c730ca41 | halucinka/projectEuler | /p45.py | 412 | 3.6875 | 4 | #!/usr/bin/env python3
import math
triangle = set()
pentagonal = set()
hexagonal = set()
big_number = 10000000000
i = 1
while (i*(i+1)/2 < big_number):
triangle.add(i*(i+1)/2)
if (i*(3*i-1)/2 < big_number):
pentagonal.add(i*(3*i-1)/2)
if (i*(2*i-1) < big_number):
hexagonal.add(i*(2*i-1))
i += 1
for a in hexagonal:
if ((a in triangle) & (a in pentagonal)):
print(a)
|
f904a94d92b3ee5ca3e0bb90a7cdb45e4869b61b | NitzanRoi/Histogram-Quantization | /sol1.py | 7,257 | 3.59375 | 4 | from skimage import color
from skimage import io
import numpy as np
from numpy.linalg import inv
import matplotlib.pyplot as plt
GREYSCALE_CODE = 1
RGB_CODE = 2
MAXIMUM_PIXEL_INTENSE = 255
TRANSFORMATION_MATRIX = np.array([
[0.299, 0.587, 0.114],
[0.596, -0.275, -0.321],
[0.212, -0.523, 0.311]
])
THREE_DIM = 3
TWO_DIM = 2
ERROR_MSG = "Error: the given image has wrong dimensions"
def norm_it(element):
"""
this function normalizes elements between range 0 and 255 to range 0 to 1
if the element is negative it makes it zero
"""
if (element < 0):
return 0
else:
return element / MAXIMUM_PIXEL_INTENSE
def normalize_helper(array):
"""
this is a helper function to normalize operations
"""
normal = np.vectorize(norm_it, otypes=[np.float64])
return normal(array)
def normalize(array):
"""
this function normalize array values from range between 0 and 255
to range 0 to 1
"""
array = array.astype(np.float64)
array = normalize_helper(array)
return array.astype(np.float64)
def read_image(filename, representation):
"""
this function reads an image file and returns it in a given representation
filename is the image
representation code: 1 is grayscale, 2 is RGB
returns an image
"""
final_img = io.imread(filename)
if (representation == GREYSCALE_CODE):
final_img = color.rgb2gray(final_img)
# if the return wanted image is greyscale so the rgb2gray function does the normalization
else:
final_img = normalize(final_img)
return final_img.astype(np.float64)
def imdisplay(filename, representation):
"""
this function utilizes the read_image function to display the given image
in the given representation
"""
view_img = read_image(filename, representation)
if (representation == GREYSCALE_CODE):
plt.imshow(view_img, cmap=plt.get_cmap('gray'))
else:
plt.imshow(view_img)
plt.show()
def rgb2yiq(imRGB):
"""
this function converts RGB image to YIQ
"""
return np.dot(imRGB, TRANSFORMATION_MATRIX.T)
def yiq2rgb(imYIQ):
"""
this function converts YIQ image to RGB
"""
inverse_transform = inv(TRANSFORMATION_MATRIX)
return np.dot(imYIQ, inverse_transform.T)
def histogram_equalize(im_orig):
"""
this function performs histogram equalization on a given image input - im_orig
(greyscale or rgb - in float64 between 0 and 1)
returns:
im_eq - the equalized image
hist_orig - histogram of the original image
hist_eq - histogram of the equalized image
"""
is_rgb = False
cur_img = im_orig.copy() # Greyscale
if (im_orig.ndim == THREE_DIM): # RGB
im = rgb2yiq(im_orig.copy())
cur_img = im[:, :, 0] # yiq - y channel
is_rgb = True
elif (im_orig.ndim != TWO_DIM):
print(ERROR_MSG)
exit()
full_range_img = cur_img * MAXIMUM_PIXEL_INTENSE # from range [0-1] to [0-255]
hist_orig = np.histogram(full_range_img, np.arange(MAXIMUM_PIXEL_INTENSE + 2))[0]
cumulative_hist = np.cumsum(hist_orig)
normed_hist = cumulative_hist / hist_orig.size
if (np.min(normed_hist) == 0 and np.max(normed_hist) == MAXIMUM_PIXEL_INTENSE):
rounded_hist = np.around(normed_hist).astype('uint8')
else:
cdf_masked = np.ma.masked_equal(normed_hist, 0) # ignore zeroes
cdf_masked = (cdf_masked - cdf_masked.min()) \
/ (cdf_masked.max() - cdf_masked.min()) * MAXIMUM_PIXEL_INTENSE
cdf_masked = np.ma.filled(cdf_masked, 0)
rounded_hist = np.around(cdf_masked).astype('uint8')
im_eq = rounded_hist[np.around(full_range_img).astype('uint8')]
hist_eq = np.histogram(im_eq, np.arange(MAXIMUM_PIXEL_INTENSE + 2))[0]
if (is_rgb):
im[:, :, 0] = (im_eq / MAXIMUM_PIXEL_INTENSE).clip(0, 1)
im_eq = yiq2rgb(im).clip(0, 1).astype(np.float64)
else:
im_eq = normalize(im_eq)
return [im_eq, hist_orig, hist_eq]
def calc_pixel_error(q_i, z_i, z_i_1, hist):
"""
calc error by pixel
"""
res_err = 0
for g in range(z_i, z_i_1 + 1):
res_err += np.power(q_i - g, 2) * hist[g]
return res_err
def calc_z(n_quant, q):
"""
calc z
"""
z_new = np.zeros(n_quant + 1)
for t in range(1, len(q)):
z_new[t] = (q[t - 1] + q[t]) / 2
z_new[0] = 0
z_new[-1] = MAXIMUM_PIXEL_INTENSE
return np.round(z_new).astype("uint8")
def calc_q(z_i, z_i_1, hist):
"""
calc q
"""
g_vector = np.arange(z_i, z_i_1 + 1)
hist_vector = hist[z_i:(z_i_1 + 1)]
top = np.dot(g_vector, hist_vector)
bottom = np.sum(hist_vector)
return np.round(top / bottom)
def quantize(im_orig, n_quant, n_iter):
"""
this function performs optimal quantization of a given greyscale or RGB image
im_orig - the input image (float64 values between [0, 1])
n_quant - the number of intensities for the output
n_iter - the maximum number of iterations for the procedure
returns:
im_quant - quantized image
error - an array with shape n_iter or less, of the total intensities error for each iteration
"""
is_rgb = False
cur_im = im_orig.copy() # if greyscale
if (im_orig.ndim == THREE_DIM): # if RGB
cur_im = rgb2yiq(im_orig.copy())[:, :, 0] # y channel of yiq
is_rgb = True
elif (im_orig.ndim != TWO_DIM):
print(ERROR_MSG)
exit()
cur_im = np.around(MAXIMUM_PIXEL_INTENSE * cur_im)
# init borders z (approx. pixel equal division to segments)
total_pixels = cur_im.size
num_of_colors = n_quant
pixels_per_segment = total_pixels / num_of_colors
hist = np.histogram(cur_im, np.arange(MAXIMUM_PIXEL_INTENSE + 2))[0]
cdf = np.cumsum(hist)
z = np.zeros(n_quant + 1)
for i in range(1, n_quant):
tmp_idx_arr = np.where(cdf >= i * pixels_per_segment)[0]
if tmp_idx_arr.size > 0:
tmp_idx = tmp_idx_arr[0]
z[i] = tmp_idx
else:
z[i] = z[i - 1] if i > 0 else 0
z[0] = 0
z[-1] = MAXIMUM_PIXEL_INTENSE
z = z.astype("uint8")
cur_q = np.zeros(n_quant) # init the values (q)
cur_z = z.copy()
cumulative_pixel_error = 0
error = []
last_z = np.zeros(n_quant + 1)
for k in range(n_iter):
for j in range(len(cur_q)):
cur_q[j] = calc_q(cur_z[j], cur_z[j + 1], hist)
cumulative_pixel_error += calc_pixel_error(cur_q[j], cur_z[j], cur_z[j + 1], hist)
error.append(cumulative_pixel_error)
cumulative_pixel_error = 0
cur_z = calc_z(n_quant, cur_q)
if (np.array_equal(cur_z, last_z)):
break
else:
last_z = cur_z.copy()
# build lookup table
lut = np.zeros(MAXIMUM_PIXEL_INTENSE + 1)
cur_z = np.ceil(cur_z).astype("uint8")
for n in range(len(cur_q)):
lut[cur_z[n]:cur_z[n + 1]] = cur_q[n]
im_quant = lut[np.ceil(cur_im).astype("uint8")]
im_quant /= MAXIMUM_PIXEL_INTENSE
if (is_rgb):
tmp_im = rgb2yiq(im_orig.copy())
tmp_im[:, :, 0] = im_quant
im_quant = yiq2rgb(tmp_im)
return [im_quant, error]
|
c5eafe7e423a587215bf02993150f3b6800a6d4f | jessie-JNing/Algorithms_Python | /Recursion_DP/Magic_index.py | 1,332 | 4.1875 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
A magic index makes A[i]=i.
Given a sorted array of distinct integers, try to find a magic index,
if one exists, in array A.
@author: Jessie
@email: jessie.JNing@gmail.com
"""
def find_magic_index(nums):
if len(nums)<1:
return None
else:
mid = len(nums)/2
if nums[mid] == mid:
return mid
elif nums[mid] > mid:
return find_magic_index(nums[0:mid])
elif nums[mid] < mid:
return find_magic_index(nums[mid+1:])
def find_magic_naive(nums):
for i in range(len(nums)):
if i == nums[i]:
return i
return None
# find magic index in an array with duplicate elements
def find_magic_duplicate(nums):
return _find_magic_dupliate(nums, 0, len(nums)-1)
def _find_magic_dupliate(nums, left, right):
if left>right or left<0 or right>len(nums):
return None
mid = (left + right)/2
if nums[mid] == mid:
return mid
# search left
left_min = min(mid-1, nums[mid])
left = _find_magic_dupliate(nums, left, left_min)
if left >=0:
return left
right_min = min(mid+1, nums[mid])
right = _find_magic_dupliate(nums, right_min, right)
return right
if __name__=="__main__":
print "find_magic_index", find_magic_duplicate([2,2,2,5,6,7,8,9]) |
293fd59027e7984239965970dffe697e951f7a2a | rlerichev/IntCurvSurf | /tests/functions.py | 3,096 | 3.984375 | 4 | #!/usr/bin/env python3
#
# Ejemplo de Funciones
#
# Mutables!!!
def putNext(n, s, things):
n += 1
s = s*2
things.append(n)
things.append(s)
print( things )
# Riemman's Z
def riemannZ(z, n=3):
res = 0
i = 1
while i <= n:
res += i**z
i += 1
return res
# Evaluar expresión
def feval(expr, x=1.0):
return eval( expr )
# Fibonacci:
# f_0 = 1
# f_1 = 1
# f_n = f_{n-2} + f_{n-1}
def fibRec(n):
if n > 1:
return fibRec(n-2) + fibRec(n-1)
else:
return 1
def fib(n):
i = 1
n_1 = 1
n_2 = 1
while i < n:
temp = n_1
n_1 = n_2 + n_1
n_2 = temp
i += 1
return n_1
def fibPy(n):
n_2, n_1, i = 1, 1, 1
while i < n:
n_2, n_1 = n_1, n_2 + n_1
i += 1
return n_1
def numRD(f, delta=0.1):
def nd(x):
return ( f(x+delta) - f(x) ) / delta
return nd
def numLD(f, delta=0.1):
def nd(x):
return ( f(x) - f(x-delta) ) / delta
return nd
def numCD(f, delta=0.1):
def nd(x):
return ( f(x+delta/2) - f(x-delta/2) ) / delta
return nd
#return lambda x: ( f(x+delta/2) - f(x-delta/2) ) / delta
if __name__ == "__main__":
m = 5
name = "Yo"
ns = [1]
putNext(m, name, ns)
print(ns, "with", m, name)
#putNext(m, name, ns)
#print(ns, "with:, m, name)
#putNext(m, name, ns.copy())
#print(ns, "with:", m, name)
#print( "Z(1)=", riemannZ( 1.0 ) )
#print( "Z(2)=", riemannZ( 2.0 ) )
#14.135, 21.022, 25.011
print( "Z(z)=", riemannZ( 0.5 + 14.135j, 10 ) )
#print( [ riemannZ( 0.5 + (i/5)*1j ) for i in range(1,20) ] )
#n = 10
#print( [ fibRec(i) for i in range(0,n) ] )
#print( [ fib(i) for i in range(0,n) ] )
#print( [ fibPy(i) for i in range(0,n) ] )
# Time it!!!
#import timeit
#print( "x*x:", timeit.timeit( "x*x", setup="x=2", number=10000 ) )
#print( "x**2:", timeit.timeit( "x**2", setup="x=2", number=10000 ) )
#print( "eval1:", timeit.timeit( "feval(\"x*x\",x=2.0)", setup="from __main__ import feval", number=10000 ) )
#print( "eval2:", timeit.timeit( "feval(\"x**2\",x=2.0)", setup="from __main__ import feval", number=10000 ) )
#print( "fibRec(10):", timeit.timeit( "fibRec(10)", setup="from __main__ import fibRec", number=5000 ) )
#print( "fib(10):", timeit.timeit( "fib(10)", setup="from __main__ import fib", number=5000 ) )
#print( "fibPy(10):", timeit.timeit( "fibPy(10)", setup="from __main__ import fibPy", number=5000 ) )
#print( "for i in range(0,10): fibRec(i):", timeit.timeit( "for i in range(0,10): fibRec(i)", setup="from __main__ import fibRec", number=1000 ) )
#print( "for i in range(0,10): fib(i):", timeit.timeit( "for i in range(0,10): fib(i)", setup="from __main__ import fib", number=1000 ) )
#print( "for i in range(0,10): fibPy(i):", timeit.timeit( "for i in range(0,10): fibPy(i)", setup="from __main__ import fibPy", number=1000 ) )
#from math import pi, sin, cos, tan, exp
#def f(x):
# return x**3 - x**2
#dfr = numRD(f)
#dfl = numLD(f)
#dfc = numCD(f)
#print( dfr(1.0) )
#print( dfl(1.0) )
#print( dfc(1.0) )
#lderivs = [ numRD(f, 1/(2**n))(1.0) for n in range(0, 5) ]
#print( lderivs )
#lcderivs = [ numCD(f, 1/(2**n))(1.0) for n in range(0, 5) ]
#print( lcderivs )
|
7d9385f4fc367d13c1a51afac0142d22266a7d7c | RedMarbleAI/RedVimana.Bunnings.ComputerVision | /Size2.py | 334 | 3.5 | 4 | class Size2(object):
def __init__(this, width, height):
this.mWidth = width
this.mHeight = height
@property
def Width(this):
return this.mWidth
@property
def Height(this):
return this.mHeight
@property
def Area(this):
return this.mWidth * this.mHeight |
5d56613f7e067437821070e45452e0a2c45df9b6 | akashmaji946/Python_May_2021_Inspire | /03_02_main.py | 314 | 3.84375 | 4 |
## Variables
x = 20
print(x)
# int -> integer
# str -> string (a seq of characters)
# dynamically typed lang
name = "Ankush"
print(name)
surname = 'Agarwal'
print(surname)
# OOP => object oriented prog.
print(type(x))
print(type(name))
# inbuilt func
# type() => datatype
print("he said 'hello'")
|
166e61865830944af3e1a6e3b9545f58c05d5a4e | laszlomerhan/Hangman | /Hangman/task/hangman/hangman.py | 1,426 | 3.84375 | 4 | import random
while True:
print('H A N G M A N\n')
choose = input('Type "play" to play the game, "exit" to quit: ')
if choose == 'play':
random_word = random.choice(['python', 'java', 'kotlin', 'javascript'])
guessed_word = "-" * len(random_word)
lst = []
count = 0
print(f'\n{guessed_word}')
while count < 9:
guess = input('Input a letter: ')
if guess == '' or len(guess) > 1:
print("You should input a single letter")
elif guess.isupper() or not guess.isalpha():
print("Please enter a lowercase English letter")
elif guess in lst:
print("You've already guessed this letter")
elif guess not in random_word:
print("That letter doesn't appear in the word")
count += 1
if count == 8:
print("You lost!\n")
break
else:
for i in range(0, len(random_word)):
if random_word[i] == guess:
guessed_word = guessed_word[:i] + guess + guessed_word[i + 1:]
if guessed_word == random_word:
print(f'You guessed the word {guessed_word}!\nYou survived!\n')
break
lst.append(guess)
print(f'\n{guessed_word}')
else:
break
|
2bb65b0a50d9a26f4e4b76761f145fcffe93c247 | frank-say/mit-python-psets | /ps1/ps1b.py | 962 | 4.21875 | 4 | annual_salary = input('Enter your annual salary: ')
annual_salary = float(annual_salary) # 获取输入的年薪
portion_saved = input(
'Enter the percent of your salary to save, as a decimal: ')
portion_saved = float(portion_saved) # 获取输入的存钱比例
total_cost = input('Enter the cost of your dream home: ')
total_cost = float(total_cost) # 获取房子总价
semi_annual_raise = input('Enter the semiannual raise, as a decimal: ')
semi_annual_raise = float(semi_annual_raise) # 每半年薪资涨幅
portion_down_payment = 0.25 # 首付比例 25%
r = 0.04 # 年化投资收益率 4%
i = 0 # 月份数
current_savings = 0 # 当前资金
month_salary = annual_salary / 12
while current_savings < total_cost * portion_down_payment:
i += 1
current_savings += current_savings * r / 12 + month_salary * portion_saved
if i % 6 == 0:
month_salary = month_salary * (1 + semi_annual_raise)
print('Number of months:', i)
|
64fb10c953c8cf61541cd7b5a2e62d828e6a538f | sevilzeynali/prepocessing-arabic-texts | /preprocessing_arabic_texts.py | 815 | 4.09375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import nltk
from nltk.stem.isri import ISRIStemmer
import re
# loading stemmer for arabic
st = ISRIStemmer()
# asking an arabic text from user
try:
while True:
print("Enter an arabic text: ")
# getting the text entered by user
text=input()
# message if user dose not enter a text
if text=="":
print("You did not enter your text !")
else:
#tokenising arabic text
tokens = nltk.word_tokenize(text)
# stemming arabic text
tok_stem=[st.stem(t) for t in tokens]
text_tok_stem=' '.join(tok_stem)
print("your text is preprocessed: ")
print(text_tok_stem)
except KeyboardInterrupt:
print (" End of the program")
|
ad48e5f3ce6899049e7cb19d5176290e0ed7d889 | Velignis/Demo-or-Repu | /tictactoe AI group project.py | 6,593 | 4.0625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[3]:
#Reference: http://www.sarathlakshman.com/2011/04/29/writing-a-tic-tac
import copy
import time
class Game(object):
"""A tic-tac-toe game."""
def __init__(self, grid):
"""Instances differ by their grid marks."""
self.grid = copy.deepcopy(grid) # No aliasing!
def display(self):
"""Print the game board."""
for row in self.grid:
print(row)
#Done by Nick
def moves(self):
"""Return a list of possible moves given the current marks."""
#Basically, check which space has - and return that this is a
#a possible move. We will use it afterwards with minimax
#returns the pair of possible locations
moveGrid = []
#fill array with possible moves based on what is blank, or '-'
for i in range(3):
for j in range(3):
if (self.grid[i][j] == '-'):
moveGrid.append([i, j])
return moveGrid
#Done by both
def neighbor(self, move, mark):
"""Return a Game instance like this one but with one move made."""
# Mark is either 'X' or 'O', move is a 2d list, needs to return self?
# fills position on board with mark and return the game state
if self.grid[move[0]][move[1]] == '-':
self.grid[move[0]][move[1]] = mark
else:
print("Position full")
return self
#Done by Victor
def utility(self):
"""Return the minimax utility value of this game:
1 = X win, -1 = O win, 0 = tie, None = not over yet."""
# for utility here, check the code from this link
#http://www.sarathlakshman.com/2011/04/29/writing-a-tic-tac
#to calculate the utility of this current board.
winPositions = [([0,0],[0,1],[0,2]), ([1,0],[1,1],[1,2]), ([2,0],[2,1],[2,2]), ([0,0],[1,0],[2,0]),([0,1],[1,1],[2,1]),([0,2],[1,2],[2,2]), ([0,0],[1,1],[2,2]), ([0,2],[1,1],[2,0])]
#interate through potential win positions to see if they are currently on the board
for i,j,k in winPositions:
if self.grid[i[0]][i[1]] == self.grid[j[0]][j[1]] == self.grid[k[0]][k[1]] and self.grid[i[0]][i[1]] != '-':
if self.grid[i[0]][i[1]] == 'X':
return 1
elif self.grid[i[0]][i[1]] == 'O':
return -1
# if there are not win positions, but possible moves left, return none, and return 0 when the board is full or when
# there are no moves left
if self.moves():
return None
else:
return 0
#returns an integer or None
class Agent(object):
"""Knows how to play tic-tac-toe."""
def __init__(self, mark):
"""Agents use either X or O."""
self.mark = mark
#Done by both
def maxvalue(self, game, opponent):
"""Compute the highest utility this game can have."""
#if state is a completed game, return its utility
#otherwise return the opponent's max(min-value(child)) over all children of state
# copy the board for possible game states, value by default is not in favor of agent
possibleGame = copy.deepcopy(game)
value = -1
move = None
# iterate through possible game moves
for i in possibleGame.moves():
#look at current move in list
possibleGame = possibleGame.neighbor(i, self.mark)
#check utility resulting from move, if there is no utility, then recurse through possible board states
utility = possibleGame.utility()
if utility != None:
possibleValue = utility
else:
# recurse through possible board states
(possibleValue, move) = opponent.minvalue(possibleGame, self)
# reset possible board states after recursion
possibleGame = copy.deepcopy(game)
#if the possible score is better than prior moves, take this move
if possibleValue > value:
value = possibleValue
move = i
return (value, move)
#Done by both
def minvalue(self, game, opponent):
"""Compute the lowest utility this game can have."""
#if state is a completed game, return its utility
#otherwise return the opponent's min(max-value(child)) over all children of state
# copy the board for possible game states, value by default is not in favor of agent
possibleGame = copy.deepcopy(game)
value = 1
move = None
# iterate through possible game moves
for i in possibleGame.moves():
#look at current move in list
possibleGame = possibleGame.neighbor(i, self.mark)
#check utility resulting from move, if there is no utility, then recurse through possible board states
utility = possibleGame.utility()
if utility != None:
possibleValue = utility
else:
# recurse through possible board states
(possibleValue, move) = opponent.maxvalue(possibleGame, self)
# reset possible board states after recursion
possibleGame = copy.deepcopy(game)
#if the possible score is better than prior moves, take this move
if possibleValue < value:
value = possibleValue
move = i
return (value, move)
def main():
"""Create a game and have two agents play it."""
game = Game([['-','-','-'], ['-','-','-'], ['-','-','-']])
game.display()
print("")
maxplayer = Agent('X')
minplayer = Agent('O')
while True:
(value, move) = maxplayer.maxvalue(game, minplayer)
game = game.neighbor(move, maxplayer.mark)
time.sleep(1)
game.display()
print("")
if game.utility() is not None:
break
(value, move) = minplayer.minvalue(game, maxplayer)
game = game.neighbor(move, minplayer.mark)
time.sleep(1)
game.display()
print("")
if game.utility() is not None:
break
if __name__ == '__main__':
main()
# In[ ]:
|
e346a05db813fd69aa2e5171f13612dcc57f9a6a | ttinning/sport_scoring_app | /tests/team_test.py | 812 | 3.578125 | 4 | import unittest
from models.team import Team
class TestTeam(unittest.TestCase):
def setUp(self):
self.team1 = Team("Eagles", "Philadelphia")
self.team2 = Team("Cowboys", "Dallas")
def test_team1_has_team_name(self):
expected = "Eagles"
actual = self.team1.name
self.assertEqual(expected, actual)
def test_team2_has_team_name(self):
expected = "Cowboys"
actual = self.team2.name
self.assertEqual(expected, actual)
def test_team1_has_team_location(self):
expected = "Philadelphia"
actual = self.team1.location
self.assertEqual(expected, actual)
def test_team2_has_team_location(self):
expected = "Dallas"
actual = self.team2.location
self.assertEqual(expected, actual)
|
f6c8c2620e3e7b7d7a4d7005157b0886fa2f6aca | stgasser/AdventOfCode2020 | /Day18/18_2.py | 1,843 | 3.71875 | 4 | def parse_input(filename):
with open(filename) as f:
return [line.replace(' ', '') for line in f.read().splitlines()]
def part1(equations):
def evaluate(eq):
stack = list()
last = ''
op = next(eq, None)
while op is not None:
if op in {'+', '*'}:
pass
elif op == '(':
op = evaluate(eq)
continue
elif op == ')':
break
else:
stack.append(int(op))
if last == '+':
stack.append(stack.pop() + stack.pop())
elif last == '*':
stack.append(stack.pop() * stack.pop())
last = op
op = next(eq, None)
return stack[0]
return sum([evaluate(iter(eq)) for eq in equations])
def part2(equations):
def evaluate(eq):
stack = list()
last = ''
op = next(eq, None)
while op is not None:
if op in {'+', '*'}:
pass
elif op == '(':
op = evaluate(eq)
continue
elif op == ')':
break
else:
stack.append(int(op))
if last == '+':
stack.append(stack.pop() + stack.pop())
elif last == '*' and len(stack) > 2: # can only multiply if 2 finished values on the stack
stack.insert(0, stack.pop(0) * stack.pop(0))
last = op
op = next(eq, None)
if len(stack) == 2:
stack.insert(0, stack.pop(0) * stack.pop(0))
return stack[0]
return sum([evaluate(iter(eq)) for eq in equations])
if __name__ == '__main__':
data = parse_input('18.in')
print("Solution to part 1:", part1(data))
print("Solution to part 2:", part2(data))
|
ea541abd209983876edec0c06842a11f1460aadd | maxzhuhl/code | /AM3.4.py | 2,579 | 3.640625 | 4 | #浏览器操作
import time
from selenium import webdriver
#浏览器操作练习
#创建一个驱动
driver = webdriver.Chrome()
#1.打开百度
driver.get('https://www.baidu.com')
# driver.find_element_by_name("tj_trhao123").click()
# 2.窗口最大化
# driver.maximize_window()
# 3.刷新,点击hao123等待5s刷新
# time.sleep(5)
# driver.refresh()
# 4.后退
# time.sleep(2)
# driver.back()
# 5.前进,回到hao123
# time.sleep(2)
# driver.forward()
# 6.等待3s后截图
# time.sleep(3)
# driver.get_screenshot_as_file("c:\\客户端\.png")
# 7.获取当前的URL标题
# url=driver.current_url
# title=driver.title
# print(url,title)
# 8.退出quit()和close()的区别
# driver.quit()
#第二章练习
# 1.通过id定位元素
#driver.find_element_by_id("kw").send_keys("12306")
# 2.通过name定位元素
# 3.通过class——name定位元素,百度一下
# 4.通过tag_name定位元素
# 5.通过link定位
# time.sleep(3)
# driver.find_element_by_partial_link_text("hao").click()
# 1.通过绝对路径做定位
#driver.find_element_by_css_selector("html body div#wrapper div#head div.head_wrapper div#u1 a+a").click()
# driver.find_element_by_xpath("/html/body/div[1]/div/div[3]/a[2]").click()
# 2.通过相对路径做定位
# driver.find_element_by_xpath("//div[3]/a[2]").click()
# driver.find_element_by_xpath("//*[@id=\"u1\"]/a[2]").click()
# 3.通过元素索引定位,索引的初始值为1
#4.使用xpath属性定位
#driver.find_element_by_xpath("//a[@name='tj_trnews']").click()
# driver.find_element_by_xpath("//a[@name='tj_trtieba']").click()
# driver.find_element_by_xpath()
#css
#1.使用绝对路径定位元素
#driver.find_element_by_css_selector("html body div#wrapper div#head div.head_wrapper div#u1 a+a").click()
#2.使用相对路径来定位元素
# driver.find_element_by_css_selector("div#u1 a+a").click()
# 3.定位下节点 +
#4.使用相对id选择来定位元素
#5.使用属性选择器来定位元素
#属性[1='值']属性2=['值']
# driver.find_element_by_css_selector("a[name='ti_trhao123']").click()
# driver.find_element_by_css_selector("a[name='tj_trhao123'][class='mnav']").click()
#6.部分属性值的匹配
#匹配开始
# driver.find_element_by_css_selector("a[name^='tj_trh'][class='mnav']").click()
#匹配结束
# driver.find_element_by_css_selector("a[name$='hao123'][class='mnav']").click()
#任意匹配
# driver.find_element_by_css_selector("a[name*='hao'][class='mnav']").click()
#7.列表选择具体的匹配(下标)
# driver.find_element_by_css_selector("a[class='mnav']:nth-of-type(3)").click()
|
406010dbd2b4904ab9878b5931d98980b650e6b4 | DevelopGadget/Basico-Python | /Recursos Profe/sets.py | 1,200 | 4.375 | 4 | #Los conjuntos son una coleccion de datos desorganizados y no indexados
#creacion de un conjunto
thisset = {"apple", "banana", "cherry"}
print(thisset)
#Acceder a los elementos del conjunto
for x in thisset:
print(x)
#Verificar si un elemento esta presente en el conjunto
print("banana" in thisset)
#Insertar(al final) un elemento en un conjunto
thisset.add("orange")
print(thisset)
#Adicionar varios elementos a un conjunto
thisset.update(["orange", "mango", "grapes"])
print(thisset)
#Determinar la longitud de un conjunto
print(len(thisset))
#Eliminacion de un elemento de un conjunto con remove(). Si el elemento no existe, genera una excepcion.
thisset.remove("banana")
print(thisset)
#Eliminacion de un elemento de un conjunto con discard(). Si el elemento no existe, no genera excepcion.
thisset.remove("mango")
print(thisset)
'''Eliminacion de un elemento de un conjunto con pop(). Este siempre elimina el ultimo elemento,
teniendo en cuenta que los conjuntos son estructuras no ordenadas, no es posible saber cual es. '''
x = thisset.pop()
print(x)
print(thisset)
#Vaciar un conjunto
thisset.clear()
print(thisset)
#Borrar un conjunto definitivamente
del thisset
print(thisset)
|
ad7aacc18a687568b540faafebb15bf1bc15d910 | ShriRachana/Python-practice | /General Practice/while_else.py | 96 | 3.96875 | 4 | x = 3
y = x
while y > 0:
print y
y = y - 1
else:
print "ye ye shall here ye"
|
83a1c32966ab2118923182797af8d71d147407e3 | yhancsx/algorithm-weekly | /cracking_the_coding_interview/8.3.py | 321 | 3.546875 | 4 | def findMagixNumber(nums):
l = 0
r = len(nums)-1
while l <= r:
m = (l+r)//2
if nums[m] == m:
return m
if nums[m] < m:
l = m + 1
else:
r = m - 1
return None
nums = [-40, -20, -1, 1, 2, 3, 7, 8, 9, 12, 13]
print(findMagixNumber(nums))
|
582172066cd45a66264ddceeb4793442e2a17941 | Roshan1115/PythonNTEL | /Week3/SelectionSort.py | 203 | 3.671875 | 4 |
#My Version of Selection sort
def selectionsort(l):
for i in range(len(l)):
for j in range(i, len(l)):
if(l[i] > l[j]):
(l[i], l[j]) = (l[j], l[i])
return(l) |
b4b80340e4445eea1522d730281a70a29739b9cc | AllieChen02/LeetcodeExercise | /BfsAndDfs/P743NetworkDelayTime/NetworkDelayTime.py | 903 | 3.546875 | 4 | import unittest
from typing import List
import collections
import heapq
class Solution:
def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:
graph = collections.defaultdict(dict)
for start, dest, cost in times:
graph[start][dest] = cost
h = [(0, k)]
visited = {}
while h:
cost, node = heapq.heappop(h)
if node not in visited:
visited[node] = cost
for neigh in graph[node]:
heapq.heappush(h, (visited[node] + graph[node][neigh], neigh))
return max(visited.values()) if len(visited) == n else -1
class UnitTest(unittest.TestCase):
def test(self):
times = [[2,1,1],[2,3,1],[3,4,1]]
n = 4
k = 2
self.assertEqual(2, Solution().networkDelayTime(times, n , k))
if __name__ == "__main__":
unittest.main() |
55dcdd2fc3039b366617b68e1cf1014e09a2e6a8 | StevenDunn/CodeEval | /FollowingInteger/py2/fi.py | 507 | 3.515625 | 4 | #following integer soln in py for code eval by steven a dunn
import sys
from itertools import permutations
def parse_digits(line):
digits = "".join(sorted(line.rstrip()))
remaining = 6 - len(digits)
padding = "0" * remaining
return padding + digits
f = open(sys.argv[1], 'r')
for line in f:
original = int(line)
digits = parse_digits(line)
for perm in permutations(digits):
val = int("".join(perm))
if val > original:
print val
break
f.close() |
9d521c9ec1b7df0683f483029e93fc99245890df | karata1975/laboratory | /Таблица сумм с -числом.py | 116 | 3.65625 | 4 | print()
for row in range(0, 10, ):
for col in range(0, -10, -1):
print(row + col, end='\t')
print()
|
6a2674ce73d12e5004d944a453cde86a96aae48c | shankarpentyala07/python | /print_example.py | 141 | 4.03125 | 4 | print("print is used to print output to std out")
print("20 days are " + str(20*24*60) + " minutes")
print(f"20 days are {20*24*60} minutes") |
15013f815cbdd9e123f34009f9912c134c675d71 | alexliyang/cardiac-segmentation-cc | /test1.py | 234 | 3.734375 | 4 | class Num123(object):
def __init__(self, i):
self.i = i
input = [1,2,3,4]
nums = map(lambda x: Num123(x), input)
print(list(nums))
def f(x):
return x*x
f_map = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
print (list(f_map)) |
66aaa1dd919ad435383d5c48b193405741e03545 | john-fitz/pairs_trading | /portfolio_management.py | 5,869 | 3.96875 | 4 | import pandas as pd
import numpy as np
from typing import Optional, Union
import pickle
DEFAULT_PURCHASE_AMT = 100
def trade_amount(coin1: str, coin2: str, hedge_ratio: float, long1: bool, fictional: bool) -> Union[float, float]:
""" checks positions for coin1 and coin2 to see the dollar amount of each coin that should be traded
Assumes that the limiting factor is the one that we have to sell and can buy up to the remaining balance on our account.
If there is no money to trade or no ability left to sell a coin, the function returns (0,0)
Parameters
----------
coin1 : string
name of coin1 to trade
coin2 : string
name of coin2 to trade
hedge_ratio : float
ratio of how much to purchase of coin1 to coin2
short1 : bool
flag if we are going long on coin1
Returns
-------
float, float
dollar values of coin1 and coin2 to purchase / sell, respectively
"""
portfolio = portfolio_positions(fictional=fictional)
max_budget = 0.90 * portfolio['balance'] # trying not to exhaust all money due to slippage
coin1_coin_amt, coin1_dollar_amt = portfolio[coin1]
coin2_coin_amt, coin2_dollar_amt = portfolio[coin2]
# print(f"trade_amt initial balance: {portfolio['balance']}, coin1_dollar_amt: {coin1_dollar_amt}, coin2_dollar_amt: {coin2_dollar_amt}")
# if we are going long on coin1, the limiting factor is how much of coin2 we have left to sell and cash reserves
if long1:
# limiting max trade to 10% of remaining balance
coin2_min_amount = coin2_dollar_amt * 0.10
# just for wiggle room, we leave 10% of balance in reserves
if coin2_dollar_amt * hedge_ratio >= max_budget:
min_amt = max_budget
else:
min_amt = coin2_min_amount
else:
# limiting max trade to 10% of remaining balance
coin1_min_amt = coin1_dollar_amt * 0.10
# just for wiggle room, we leave 10% of balance in reserves
if coin1_dollar_amt >= max_budget:
min_amt = max_budget
else:
min_amt = coin1_min_amt
if coin1_dollar_amt == 0 or coin2_dollar_amt == 0:
return (0, 0)
coin1_amt = (min_amt / coin1_dollar_amt) * coin1_coin_amt
coin2_amt = (min_amt / coin2_dollar_amt) * coin2_coin_amt * hedge_ratio
# print(f"trade_amt final balance: {portfolio['balance']}, coin1_dollar_amt: {coin1_dollar_amt}, coin2_dollar_amt: {coin2_dollar_amt}")
return (coin1_amt, coin2_amt)
def portfolio_positions(fictional: bool) -> dict:
"""returns a dataframe with the portfolio"""
# dictionary is of the form {coin_name: (number_of_coins_owned, dollar_value_of_position)} with the
# first entry being {remaining_balance: float}
file_name = portfolio_name(fictional=fictional)
portfolio = pickle.load( open( file_name, "rb" ) )
return portfolio
def save_portfolio(fictional: bool, portfolio: dict) -> None:
"""takes the portfolio as a dictionary and saves it as a pickle file"""
file_name = portfolio_name(fictional=fictional)
pickle.dump( portfolio, open( file_name, "wb" ) )
def portfolio_name(fictional: bool) -> str:
"""returns the proper name (as string) of the portfolio"""
return "fictional_crypto_positions.p" if fictional else "actual_crypto_positions.p"
def update_portfolio_positions(market_info: pd.DataFrame,) -> None:
"""Goes through the portfolio and updates values based on coin prices"""
actual_portfolio = portfolio_positions(fictional=False)
fictional_portfolio = portfolio_positions(fictional=True)
fictional = False
for portfolio in [actual_portfolio, fictional_portfolio]:
for coin in portfolio.keys():
if coin != 'balance':
# try:
coin_price = market_info[market_info['coin'] == coin]['close'].iloc[-1]
coin_amt = portfolio[coin][0]
portfolio[coin] = (coin_amt, coin_amt*coin_price)
# except:
# print("can't find information for " + str(coin))
save_portfolio(fictional=fictional, portfolio=portfolio)
fictional = True
return None
def purchase_initial_position(coin_pairs: str, market_info: pd.DataFrame) -> None:
"""loops through coin pairs and if there are any coins not in the portfolio, it add them"""
actual_portfolio = portfolio_positions(fictional=False)
fictional_portfolio = portfolio_positions(fictional=True)
coin_list = []
for coin_pair in coin_pairs:
coin1 = coin_pair[0]
coin2 = coin_pair[1]
if coin1 not in coin_list:
coin_list.append(coin1)
if coin2 not in coin_list:
coin_list.append(coin2)
fictional = False
for portfolio in [actual_portfolio, fictional_portfolio]:
for coin in coin_list:
if coin not in portfolio.keys() and portfolio['balance'] > 0:
print(f"adding ${DEFAULT_PURCHASE_AMT} of {coin} to {'fictional' if fictional else 'actual'} portfolio")
# print(len(market_info[market_info['coin'] == coin]['close']))
coin_price = market_info[market_info['coin'] == coin]['close'].iloc[-1]
portfolio[coin] = (DEFAULT_PURCHASE_AMT / coin_price, DEFAULT_PURCHASE_AMT)
# portfolio['balance'] -= DEFAULT_PURCHASE_AMT
# print(f"portfolio balance: {portfolio['balance']}")
save_portfolio(fictional=fictional, portfolio=portfolio)
fictional=True
def portfolio_value(fictional: Optional[bool]=False) -> float:
portfolio = portfolio_positions(fictional=fictional)
portfolio_value = portfolio['balance']
for coin in portfolio.keys():
if coin != 'balance':
portfolio_value += portfolio[coin][1]
return portfolio_value |
d7557c39b32e9dccabfd81f1d470b3924c40aa66 | j16949/Programming-in-Python-princeton | /3.2/interval.py | 643 | 3.71875 | 4 |
class Interval:
def __init__(self,left,right):
self._l = left
self._r = right
def contains(self,other):
if self._r >= other._r >= other._l >= self._l:
return True
return False
def intersects(self,other):
if other._r > self._r >= other._l:
return True
elif other._r >= self._l > other._r:
return True
elif self.contains(other):
return True
return False
def main():
i1 = Interval(0,5)
i2 = Interval(6,10)
print(i2.contains(i1))
print(i1.intersects(i2))
if __name__ == '__main__':
main()
|
502c14b880c3978f1da66afc5b4d9f184250a54f | rafaelperazzo/programacao-web | /moodledata/vpl_data/59/usersdata/170/40645/submittedfiles/testes.py | 34 | 3.59375 | 4 | x=1
while x<=3:
x=x+1
print(x) |
5898f8c9ca9b7cc1b481dc617493bc365e93e80d | ses1142000/python-30-days-internship | /day 2 py internship.py | 433 | 3.578125 | 4 | Python 3.9.0 (tags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> (a,b,c)=(3,4,5)
>>> print(a/10)
0.3
>>> print(b*50)
200
>>> print(c+60)
65
>>> str="sharon,sam,saji,sindhu,philip"
>>> print(str.replace("saji","g"))
sharon,sam,g,sindhu,philip
>>> (a,b)=(5,6.55)
>>> print(float(a))
5.0
>>> print(int(b))
6
>>> |
14148008a2a0286ca20034dc12688a8ee4d406a4 | Eduardo95/creative_informatics_exam | /exam_problem/2015/problem3.py | 356 | 3.53125 | 4 | with open("program.txt") as f:
sentence = f.readlines()
sentence = [i.replace("\n", "") for i in sentence]
ans = []
line_a = ""
line_b = sentence[0]
for index in range(0,len(sentence)-1):
line_a = line_b
line_b = sentence[index+1]
if line_a == line_b and (line_a not in ans):
ans.append(line_a)
for line in ans:
print(line)
|
9a5ec71a0426288e88565a48c0350994dcf05c1f | kseob/bioinfo-lecture-2021-07 | /21.07.05/005.py | 272 | 3.671875 | 4 | import sys
if len(sys.argv) != 2:
print(f"#usage: python {sys.argv[0]} [num]")
sys.exit()
num = int(sys.argv[1])
if num%3 ==0 and num%7 == 0 :
print ('3','7')
elif num%3 == 0 :
print ('3')
elif num%7 == 0 :
print ('7')
else :
print('not')
|
29093f93cd61a3fa947795e96224501d8df165db | unnunnjyann/kmeans | /readData.py | 383 | 3.578125 | 4 | import csv
def readData(fileName):
"""
:param fileName:
:return: a 2-dimensional array
"""
data = []
with open(fileName) as csvFile:
reader = csv.reader(csvFile)
for item in reader:
temp = []
for attribute in item:
temp.append(float(attribute))
data.append(temp)
return data
|
a4ec294248eb476059132d1d0d1e327f10d28e4c | alexandraback/datacollection | /solutions_2449486_0/Python/ulrikdem/codejam.py | 1,259 | 3.765625 | 4 | # Hezekiah's Code Jam Solution
# Usage: python3 codejam.py < file.in > file.out
def more(line):
return int(line.split()[0])
def solve(lines):
split = lines[0].split()
height = int(split[0])
width = int(split[1])
lawn = []
lengths = []
for row in range(0, height):
lawn.append([])
line = lines[row + 1].split()
for column in range(0, width):
length = int(line[column])
lawn[row].append(length)
if length not in lengths:
lengths.append(length)
while len(lengths):
maximum = max(lengths)
lengths.remove(maximum)
columns = []
for row in range(0, height):
if maximum in lawn[row]:
maximumColumns = []
possible = True
for column in range(0, width):
if lawn[row][column] == maximum:
if column not in columns:
maximumColumns.append(column)
elif lawn[row][column] > maximum:
possible = False
if not possible:
columns.extend(maximumColumns)
for column in columns:
for row in range(0, height):
if lawn[row][column] > maximum:
return "NO"
return "YES"
def main():
cases = int(input())
for case in range(1, cases + 1):
lines = [input()]
for line in range(0, more(lines[0])):
lines.append(input())
print("Case #" + str(case) + ": " + solve(lines))
main()
|
a082307f366bf727534b0e58e8f6ff72284b3820 | theTrio11/python-docs | /second.py | 219 | 3.640625 | 4 | #second progam
print("Enter the name of the students")
a=str(input())
b=str(input())
c=str(input())
print("Enter the marks of the three students")
x=int(input())
y=int(input())
z=int(input())
print("The sum is=",x+y+z)
|
1c7045e929f5adc6501084b3e5609470fca62da1 | airpark69/pythonStudy | /py1/test2.py | 393 | 3.890625 | 4 | a=True
print(type(a))
a=70
if a >= 80:
print("pass")
else:
print("not")
if a >= 90:
print("A")
elif a >= 80:
print("B")
elif a >= 70:
print("C")
elif a >= 60:
print("D")
else:
print("점수아님")
a=11
if 13 <= a <= 18:
print("1300")
j="901223-4234567"
if j[j.index("-") + 1] == "1" or j[j.index("-") + 1] == "3":
print("남")
else:
print("여") |
e91837cc3a948c57117f1d73830864ddfb8c440c | Slimmerd/COMP1811-Python-CW | /administrator_features/api/database_management.py | 5,015 | 3.546875 | 4 | import csv
import os
import sqlite3
import tkinter as tk
class DatabaseAPI:
def __init__(self):
self.path = os.path.dirname(os.path.dirname(__file__))
self.database_path = self.path + '/database/all_about_toys.db'
self.connection = sqlite3.connect(self.database_path)
self.cursor = self.connection.cursor()
# Makes list from database for specific column
def get_list(self, column, table, condition, list_name, list_type=1, database_type=1):
if database_type == 1:
database = self.cursor.execute(f"SELECT {column} FROM {table}")
elif database_type == 2:
database = self.cursor.execute(f"SELECT {column} FROM {table} WHERE {condition}")
num_rows = database.fetchall()
for item in num_rows:
if list_type == 1:
list_name.insert(tk.END, item[0])
elif list_type == 2:
list_name.insert(0, item[0])
self.connection.commit()
self.connection.close()
# Updates list
def update_list(self, column, table, list_name):
list_name.delete(0, tk.END)
self.get_list(column, table, 0, list_name)
# Checks if entry is already exist in the list
def repeat_checker(self, column_name, table_table, entry_data):
self.cursor.execute(f"select {column_name} from {table_table} where {column_name}=?", (entry_data,))
data = self.cursor.fetchall()
self.connection.commit()
self.connection.close()
if not data:
# Data not found returns 0
return 0
else:
# Data found returns 1
return 1
# Create category
def create_category(self, category_name):
self.cursor.execute(f"INSERT INTO Categories (CategoryName) VALUES ('{category_name}')")
self.connection.commit()
self.connection.close()
# Create product
def create_product(self, product_name, category_id, product_price, product_stock):
self.cursor.execute(
f"INSERT INTO Products (ProductName,CategoryID,ProductPrice,ProductStock) VALUES ('{product_name}',{category_id},{product_price},{product_stock})")
self.connection.commit()
self.connection.close()
# Get's id's from the table
def get_item_id(self, table_name, column_name, user_entry, user_choice):
self.cursor.execute(f"SELECT {column_name} FROM {table_name} WHERE {user_entry}=?", (user_choice,))
rows = self.cursor.fetchone()
self.connection.commit()
self.connection.close()
id_check = rows[0]
return id_check
# Delete item from database
def delete_item(self, table_name, column_name, chosen_item):
self.cursor.execute(f"DELETE FROM {table_name} WHERE {column_name}=?", (chosen_item,))
self.connection.commit()
self.connection.close()
# Edit item in database
def edit_item(self, table_name, column_name, old_value, new_value, product_name=0, new_product_name=0, type_id=1):
if type_id == 1:
self.cursor.execute(f"UPDATE {table_name} SET {column_name} = ? WHERE {column_name} = ?",
(new_value, old_value))
elif type_id == 2:
self.cursor.execute(f"UPDATE {table_name} SET {column_name} = ? WHERE {product_name} = ?",
(new_value, new_product_name))
self.connection.commit()
self.connection.close()
# Saves csv file in chosen filepath
def save_database_file(self, table_name, file_name, file_path, saving_type=1):
if saving_type == 1:
self.cursor.execute(f"select * from {table_name}")
elif saving_type == 2:
self.cursor.execute(f"SELECT ProductName FROM Products WHERE ProductStock <20")
if os.path.exists(file_path):
with open(file_path + "/" + file_name + '.csv', "w") as csv_file:
csv_writer = csv.writer(csv_file, delimiter="\t")
# Writes headers
csv_writer.writerow([i[0] for i in self.cursor.description])
# Writes other data
csv_writer.writerows(self.cursor)
else:
print('Error')
self.connection.close()
# Gets chosen item stock
def get_item_stock(self):
low_stock = self.cursor.execute(f"SELECT ProductName FROM Products WHERE ProductStock <20")
low_stock_list = []
for item in low_stock:
low_stock_list.append(item[0])
self.connection.close()
return low_stock_list
# Get item id (used for unit tests)
def tester_get_item_id(self,table_name, user_entry, user_choice):
self.cursor.execute(f"SELECT * FROM {table_name} WHERE {user_entry}=?", (user_choice,))
# rows = cursor.fetchone()
rows = self.cursor.fetchall()
self.connection.commit()
self.connection.close()
id_check = rows[0]
return id_check
|
96af4e636f01e6a8b6ff60ebf345d335ef7aec4f | nazarov-yuriy/contests | /yrrgpbqr/p0381/__init__.py | 1,737 | 3.625 | 4 | import unittest
from typing import List
import random
import collections
class RandomizedCollection:
def __init__(self):
self.hashmap = {}
self.list = []
def insert(self, val: int) -> bool:
res = val not in self.hashmap
self.hashmap.setdefault(val, set()).add(len(self.list))
self.list.append(val)
return res
def remove(self, val: int) -> bool:
if val not in self.hashmap:
return False
last_pos = len(self.list) - 1
to_move = self.list.pop()
if to_move == val:
self.hashmap[val].remove(last_pos)
else:
pos = next(iter(self.hashmap[val]))
self.hashmap[val].remove(pos)
self.list[pos] = to_move
self.hashmap[self.list[pos]].remove(last_pos)
self.hashmap[self.list[pos]].add(pos)
if len(self.hashmap[val]) == 0:
del self.hashmap[val]
return True
def getRandom(self) -> int:
pos = random.randint(0, len(self.list) - 1)
return self.list[pos]
class Test(unittest.TestCase):
def test(self):
obj = RandomizedCollection()
obj.insert(1)
obj.remove(1)
obj.insert(1)
# print(obj.hashmap, obj.list)
obj.insert(2)
# print(obj.hashmap, obj.list)
obj.remove(1)
# print(obj.hashmap, obj.list)
obj.insert(2)
# print(obj.hashmap, obj.list)
obj.insert(3)
# print(obj.hashmap, obj.list)
obj.getRandom()
c = collections.Counter()
for _ in range(10000):
num = obj.getRandom()
c[num] += 1
# print(c)
self.assertEqual(0.45 < c[3] / c[2] < 0.55, True)
|
021e522044931d8657f12c5c32569c6e19790ec2 | ShadieKamata/alx-higher_level_programming | /0x01-python-if_else_loops_functions/8-uppercase.py | 191 | 4.28125 | 4 | #!/usr/bin/python3
def uppercase(str):
for c in str:
islower = ord(c) >= 97 and ord(c) <= 122
print("{:c}".format(ord(c) - 32 if islower else ord(c)), end="")
print()
|
dd25dcf789a3baac49842673e53f36ff5daa427c | mnauman319/Snake | /app.py | 11,618 | 3.8125 | 4 | '''
------------------------Snake Rules------------------------
1. Each item eaten makes the snake longer
2. The player loses when the snake runs into the
end of the game board
3. The player loses when the snake runs into itself
'''
import tkinter
import random
from typing import List
from snake import *
#global helpful variables
segment_size = 5
food_size = 5
speed = 10
movement_freq = 200
moving = None
#helpful dictionaries
direction = {
(-speed,0): 'Left',
(speed,0): 'Right',
(0,speed): 'Down',
(0,-speed): 'Up'
}
axis_opposite = {
'Right': 'Left',
'Left': 'Right',
'Up': 'Down',
'Down': 'Up',
}
def direction_from_movement(value:str):
keys = list(direction.keys())
values = list(direction.values())
return keys[values.index(value)]
class GUI:
def __init__ (self, root:tkinter):
self.root = root
self.root.title("Snake")
self.root.geometry('1000x800')
self.my_canvas = Canvas(self.root,width=1000, height=800, bg='black')
self.my_canvas.pack()
self.head = Segment(speed,0, segment_size, self.my_canvas)
self.body = List[Segment]
self.body = [self.head]
self.food = self.my_canvas.create_rectangle(400,200,400+food_size, 200-food_size, fill='white')
def restart_game(self, e:tkinter.Event):
if(e.x>240 and e.x<760 and e.y>260 and e.y<340):
if str(e.type) == 'ButtonPress':
# cleanup the existing widgets
self.root.after_cancel(moving)
for w in range(self.body[-1].seg+2):
self.my_canvas.delete(w)
self.body = []
self.root.unbind("<Button-1>")
self.root.unbind("<Motion>")
self.my_canvas.config(cursor="")
# reset the GUI and starting state
self.food = self.my_canvas.create_rectangle(400,200,400+food_size, 200-food_size, fill='white')
self.head = Segment(speed,0, segment_size, self.my_canvas)
self.body.append(self.head)
a = self.grow_snake(self.head)
b = self.grow_snake(a)
self.grow_snake(b)
self.start()
else:
self.my_canvas.config(cursor='hand2')
else:
self.my_canvas.config(cursor='')
return "Break"
def end_game(self):
self.my_canvas.create_text(500,300,text="Game Over", fill="white", font="Times 80 bold")
self.root.bind("<Button-1>", self.restart_game)
self.root.bind("<Motion>", self.restart_game)
self.my_canvas.cursor = "hand1"
def touching_border(self):
location = self.head.canvas.coords(self.head.seg)
touching_left = location[0]+self.head.s_move_x<=0
touching_right = location[0]+self.head.s_move_x>=1000
touching_top = location[1]+self.head.s_move_y<=-5
touching_bottom = location[1]+self.head.s_move_y>=800
return touching_left or touching_right or touching_bottom or touching_top
def generate_food(self):
s_min_max = [[1000,0], [800, 0]] # [[x_min, x_max], [y_min, y_max]]
f_loc = []
# finding the max and minx for x and y from the existing snake
for seg in self.body:
s_loc = seg.canvas.coords(seg.seg)
x0 = s_loc[0]
y0 = s_loc[1]
x1 = s_loc[2]
y1 = s_loc[3]
s_min_max[0][0] = x0 if x0 < s_min_max[0][0] else s_min_max[0][0]
s_min_max[0][1] = x1 if x1 > s_min_max[0][1] else s_min_max[0][1]
s_min_max[1][0] = y0 if y0 < s_min_max[1][0] else s_min_max[1][0]
s_min_max[1][1] = y1 if y1 > s_min_max[1][1] else s_min_max[1][1]
dir = random.choice(['NE', 'NW', 'SE', 'SW'])
x = -1
y = -1
if dir == 'NE':
while x%5 !=0:
x = random.randint(2*food_size, s_min_max[0][0]) -food_size
while y%5 !=0:
y = random.randint(2*food_size, s_min_max[1][0]) -food_size
f_loc = [x,y,x+food_size,y+food_size]
self.my_canvas.coords(self.food,f_loc)
elif dir == 'NW':
while x%5 !=0:
x = random.randint(s_min_max[0][1] + food_size, 1000-2*food_size)
while y%5 !=0:
y = random.randint(2*food_size, s_min_max[1][0]) - food_size
f_loc = [x,y,x+food_size,y+food_size]
self.my_canvas.coords(self.food,f_loc)
elif dir == 'SE':
while x%5 !=0:
x = random.randint(2*food_size, s_min_max[0][0]) - food_size
while y%5 !=0:
y = random.randint(s_min_max[1][1] + food_size, 800-2*food_size)
f_loc = [x,y,x+food_size,y+food_size]
self.my_canvas.coords(self.food,f_loc)
elif dir == 'SW':
while x%5 !=0:
x = random.randint(s_min_max[0][1] + food_size, 1000-2*food_size)
while y%5 !=0:
y = random.randint(s_min_max[1][1] + food_size, 800-2*food_size)
f_loc = [x,y,x+food_size,y+food_size]
self.my_canvas.coords(self.food,f_loc)
def same_pos(self, pos1:List[float], pos2:List[float]):
for i in range(4):
if pos1[i] != pos2[i]:
return False
return True
def self_collision(self):
for seg in self.body:
if seg == self.head: continue
head_pos = self.my_canvas.coords(self.head.seg)
seg_pos = self.my_canvas.coords(seg.seg)
# if self.same_pos(head_pos, seg_pos ):
# return True
head_pos = [max(head_pos[0], head_pos[2]), max(head_pos[1], head_pos[3]), min(head_pos[0], head_pos[2]), min(head_pos[1], head_pos[3])]
seg_pos = [max(seg_pos[0], seg_pos[2]), max(seg_pos[1], seg_pos[3]), min(seg_pos[0], seg_pos[2]), min(seg_pos[1], seg_pos[3])]
if head_pos[1] > seg_pos[3] and head_pos[3] < seg_pos[3] and head_pos[0] <= seg_pos[0] and head_pos[2] >= seg_pos[2]:
return True
elif head_pos[1] > seg_pos[1] and head_pos[3] < seg_pos[1] and head_pos[0] <= seg_pos[0] and head_pos[2] >= seg_pos[2]:
return True
elif head_pos[0] > seg_pos[2] and head_pos[2] < seg_pos[2] and head_pos[1] <= seg_pos[1] and head_pos[3] >= seg_pos[3]:
return True
elif head_pos[0] > seg_pos[0] and head_pos[2] < seg_pos[0] and head_pos[1] <= seg_pos[1] and head_pos[3] >= seg_pos[3]:
return True
return False
def move_snake(self):
if self.touching_border():
self.end_game()
elif self.self_collision():
self.end_game()
else:
for seg in self.body:
cur_pos = seg.canvas.coords(seg.seg)
if len(seg.rot_dir) > 0:
if (len(seg.rot_dir) > len(self.head.rot_pos) or seg==self.head) and self.same_pos(cur_pos,seg.rot_pos[0]):
self.rotate_snake(seg.rot_dir[0],seg.cur_dir, seg)
seg.cur_dir = seg.rot_dir[0]
seg.rot_pos.pop(0)
seg.rot_dir.pop(0)
seg.canvas.move(seg.seg, seg.s_move_x, seg.s_move_y)
#Check to see if snake head is touching food
if seg == self.head:
head_loc = self.my_canvas.coords(self.head.seg)
food_loc = self.my_canvas.coords(self.food)
if (head_loc[0]==food_loc[0] and head_loc[1] == food_loc[1]) or (head_loc[2]==food_loc[2] and head_loc[3]==food_loc[3]):
self.grow_snake(self.body[len(self.body)-1])
self.generate_food()
cur_xy = direction_from_movement(seg.cur_dir)
seg.s_move_x = cur_xy[0]
seg.s_move_y = cur_xy[1]
self.root.after(movement_freq,self.move_snake)
def grow_snake(self,seg:Segment):
last_piece = self.body[len(self.body)-1]
new_piece = Segment(last_piece.s_move_x, last_piece.s_move_y, segment_size, self.my_canvas, last_piece.cur_dir, self.my_canvas.coords(last_piece.seg),last_piece.rot_pos, last_piece.rot_dir)
self.body.append(new_piece)
return new_piece
def rotate_snake(self, new_dir:str, prev_dir:str, piece:Segment):
piece.cur_dir = new_dir
body_coords = piece.canvas.coords(piece.seg)
cur_x0 = body_coords[0]
cur_y0 = body_coords[1]
cur_x1 = body_coords[2]
cur_y1 = body_coords[3]
if new_dir == 'Up':
if prev_dir == 'Left':
body_coords = [cur_x0+segment_size, cur_y0-segment_size, cur_x0+2*segment_size, cur_y1]
piece.canvas.coords(piece.seg,body_coords)
elif prev_dir == 'Right':
body_coords = [cur_x0, cur_y0-segment_size, cur_x0+segment_size, cur_y1]
piece.canvas.coords(piece.seg,body_coords)
elif new_dir == 'Down':
if prev_dir == 'Left':
body_coords = [cur_x0+segment_size, cur_y0, cur_x0+2*segment_size, cur_y1+segment_size]
piece.canvas.coords(piece.seg,body_coords)
elif prev_dir == 'Right':
body_coords = [cur_x0, cur_y0, cur_x0+segment_size, cur_y1+segment_size]
piece.canvas.coords(piece.seg,body_coords)
elif new_dir == 'Left':
if prev_dir == 'Up':
body_coords = [cur_x0+segment_size, cur_y0+segment_size, cur_x0-segment_size, cur_y0+2*segment_size]
piece.canvas.coords(piece.seg,body_coords)
elif prev_dir == 'Down':
body_coords = [cur_x0+segment_size, cur_y0, cur_x0-segment_size, cur_y0+segment_size]
piece.canvas.coords(piece.seg,body_coords)
elif new_dir == 'Right':
if prev_dir == 'Up':
body_coords = [cur_x0, cur_y0+segment_size, cur_x0+2*segment_size, cur_y0+2*segment_size]
piece.canvas.coords(piece.seg,body_coords)
elif prev_dir == 'Down':
body_coords = [cur_x0, cur_y0, cur_x0+2*segment_size, cur_y0+segment_size]
piece.canvas.coords(piece.seg,body_coords)
def key_press(self,e:tkinter.Event):
cur_pos = self.head.canvas.coords(self.head.seg)
key_pressed = str(e.char)
new_dir = ""
if key_pressed == 'w' or e.keysym=="Up":
new_dir = 'Up'
elif key_pressed == 's' or e.keysym=="Down":
new_dir = 'Down'
elif key_pressed == 'a' or e.keysym=="Left":
new_dir = 'Left'
elif key_pressed == 'd' or e.keysym=="Right":
new_dir = 'Right'
prev_direction = direction[(self.head.s_move_x,self.head.s_move_y)]
if prev_direction == new_dir or prev_direction == axis_opposite[new_dir]:
return
else:
for piece in self.body:
piece.add_rot(cur_pos,new_dir)
def start(self):
# a = GUI.grow_snake(GUI.head)
# b = GUI.grow_snake(a)
# GUI.grow_snake(b)
self.root.bind("<Key>", self.key_press)
global moving
moving = self.root.after(movement_freq, self.move_snake)
self.root.mainloop()
# initialize GUI
my_GUI = GUI(Tk())
a = my_GUI.grow_snake(my_GUI.head)
b = my_GUI.grow_snake(a)
my_GUI.grow_snake(b)
my_GUI.start()
|
cf0a6095d63a84ad5913f07260a57e485a903263 | LoisBN/python | /env/code/tme8.py | 3,611 | 3.890625 | 4 | #Tme 8
#exercice 8.2
#question 1
def moyenne(listOfNumber):
"""list[number]->float
retourne la valeur moyenne de l 'ensemble des valeurs contenues dans la liste"""
#result:float
result = 0.0
#number:number
for number in listOfNumber:
result = result + number
return result/len(listOfNumber)
#question 2
def ecart_nombre(L,x):
"""list[number]*number->list[number]
retourne la valeur absolue de la difference entre les valeurs de L et x """
#element:number
return [element - x if element-x>=0 else element-x*(-1) for element in L]
#question 3
def liste_carre(L):
"""list[number]->list[number]
retourne la liste contenant les elements au carre de L """
#element:number
return [element ** 2 for element in L]
#question 4
def variance(L):
"""list[number]->float
retourne la variance associe a la liste L """
#element:number
return moyenne(liste_carre(ecart_nombre([element for element in L], moyenne(L))))
#question 5
def variance_plus(L):
return moyenne([(element-moyenne(L))**2 if (element-moyenne(L))>=0 else (element-moyenne(L)*(-1))**2 for element in L])
#exercice 8.4
#question 1
def liste_non_multiple(n,L):
"""int*list[int]->list[int]
hyp:n>0
retourne la liste des elements de L qui ne sont pas multiple de n """
#element:int
return [element for element in L if not element % n == 0]
#question 2
def erathostene(n):
"""int->list[int]
hyp:n>0
retourne la liste des nombres premiers inferieurs a n """
#liste:list[int]
liste = [i for i in range(2, n + 1)]
#liste_erathostene:list[int]
liste_erathostene = []
while len(liste)>0:
liste_erathostene.append(liste[0])
liste = [j for j in liste if not j%liste[0] == 0]
return liste_erathostene
#question 3
def liste_facteurs_premiers(n):
"""int->list[int]
hyp:n>2
retourne la liste des facteurs premiers de n """
liste_erathostene = erathostene(n)
return [j for j in liste_erathostene if n % j == 0]
#exercice 8.6
BaseUPMC = [('GARGA', 'Amel', 20231343, [12, 8, 11, 17, 9]),
('POLO', 'Marcello', 20342241, [9, 11, 19, 3]),
('AMANGEAI', 'Hildegard', 20244229, [15, 11, 7, 14, 12]),
('DENT', 'Arthur', 42424242, [8, 4, 9, 4, 12, 5]),
('ALEZE', 'Blaise', 30012024, [17, 15, 20, 14, 18, 16, 20]),
('D2', 'R2', 10100101, [10, 10, 10, 10, 10, 10])]
#question 1
def mauvaise_note(etu):
"""etudiant->bool
retourne true si l 'etudiant a obtenu au moins une note en dessous de la moyenne sinon retourne false"""
(nom, prenom, ide, notes) = etu
for note in notes:
if note < 10:
return True
return False
#question 2
def eleve_mauvaise_note(database):
"""list[etudiant]->list[etudiant]
retourne une liste contenant les etudiants ayant eu des notes en dessous de la moyenne """
return [eleve for eleve in database if mauvaise_note(eleve)]
#question 3
def nom_eleve_mauvaise_note(database):
"""list[etudiant]->list[etudiant]
retourne une liste contenant le nom des etudiants ayant eu des notes en dessous de la moyenne """
return [eleve[0] for eleve in database if mauvaise_note(eleve) ]
#print(nom_eleve_mauvaise_note(BaseUPMC))
#question 4
def ide_eleve_bonne_note(database):
"""list[etudiant]->list[etudiant]
retourne une liste contenant les identifiants des etudiants ayant aucunes notes en dessous de la moyenne """
return [eleve[2] for eleve in database if not mauvaise_note(eleve)]
print(ide_eleve_bonne_note(BaseUPMC)) |
43117b6e7f248510e5350ba1f3a4c5fdef2b3ec1 | qpcode/smc | /smc/agent.py | 399 | 3.859375 | 4 | """ Class for Agent """
class Agent:
def __init__(self, init_x, init_y):
""" Constructor for Agent class """
self.x = init_x
self.y = init_y
class AgentTrajectories:
def __init__(self):
self.xs = []
self.ys = []
def add_point(self, x, y):
""" adds a new point to the trajectory """
self.xs.append(x)
self.ys.append(y)
|
1fa91a0b68f1bbed75ec3e43527ed3ae94838813 | SergeiLSL/Programming-course | /Глава 3 - Обработка ошибок Функции/task_3.3 - Создать функцию нахождения суммы или разности чисел.py | 465 | 3.9375 | 4 | """
Написать функцию, которая принимает на вход два аргумента.
Если аргументы больше нуля, возвращаем их сумму.
Если оба меньше - разность. Если знаки разные - возвращаем 0
"""
def result(x, y):
if a > 0 and b > 0:
return a + b
else:
return a - b
a, b = int(input()), int(input())
print(result(a, b))
|
bb5fa80c90ba0d6eb1eaf9f0e1426720fc1946d3 | Rahul-Kumar-Tiwari/PyOS | /programs/example.py | 686 | 3.765625 | 4 | # PyOS
# Made for Python 2.7
# programs/example.py
# Import the internal.extra script and give it the shortcut of 'e'.
import internal.extra as e
def app():
# This is the function that will run when the 'example' command is typed in.
# Clear the console screen
e.cls()
"""
This line of code below the BOLD text style, prints some text and resets the text style.
You can use the internal.extra.colors class to use text styles.
In this script internal.extra has been set to 'e',
so e.colors will work to access color styles.
"""
print(e.colors.BOLD + "PyOS Example Program" + e.colors.ENDC)
# Print sample text
print("Hello, World!")
|
c7bcb6a14802296993bce5620131761bbda188c2 | BielWeb/Estudando-Python | /geradorCurriculo.py | 2,382 | 3.75 | 4 | print('---------GERADOR DE CURRÍCULOS---------')
#declaracao de variaveis - INICIO
nome = str(input('Nome completo: '))
ano = int(input('Ano de Nascimento: '))
prof = str(input('Sua profissão: '))
end = str(input('Seu endereço: '))
fone = str(input('Seu telefone: '))
email = str(input('Seu email: '))
curso1 = str(input('Digite um curso: '))
escola1 = str(input('Onde você fez o 1º Curso?'))
duracao1 = str(input('Duração do primeiro curso(em horas/aula): '))
curso2 = str(input('Digite outro curso: '))
escola2 = str(input('Onde você fez o 2º Curso?'))
duracao2 = str(input('Duração do segundo curso(em horas/aula): '))
emprego1 = str(input('Digite um emprego: '))
empresa1 = str(input('Nome da empresa: '))
tempo1 = str(input('Quanto tempo você passou?(meses) '))
emprego2 = str(input('Digite outro emprego: '))
empresa2 = str(input('Nome da empresa: '))
tempo2 = str(input('Quanto tempo você passou?(meses) '))
#declaracao de variaveis - FIM
#geracao de curriculo
print('\n')
print('\033[36m//////////////////DADOS PESSOAIS//////////////////')
print('\033[34mNOME: {}'.format(nome.upper()))
#condicioanal idade - INICIO
if 2018-ano < 18:
print('{} ANOS - ESTAGIÁRIO'.format(2018-ano))
else:
print('{} ANOS'.format(2018-ano))
#condicional idade - FIM
print('PROFISSÃO: {}'.format(prof.upper()))
print('Reside em {}'.format(end))
#condicional contato - INICIO
if email != '':
print('Telefone: {} / Email: {}\n\n'.format(fone, email))
else:
print('Telefone: {}\n\n'.format(fone))
#condicional contato - FIM
print('\033[36m//////////////////////CURSOS//////////////////////')
#condicional cursos - INICIO
if curso1 != '' and escola1 != '' and duracao1 != '':
print('\033[34m{} | {} | Duração: {} horas/aula'.format(curso1,escola1,duracao1))
if curso2 != '' and escola2 != '' and duracao2 != '':
print('{} | {} | Duração: {} horas/aula'.format(curso2, escola2, duracao2))
#condicional cursos - FIM
print('\033[36m///////////EXPERIÊNCIAS PROFISSIONAIS///////////')
#condicional empregos - INICIO
if emprego1 != '' and empresa1 != '' and tempo1 != '':
print('\033[34mCargo: {} | Empresa: {} | Duração: {} meses'.format(emprego1, empresa1, tempo1))
if emprego2 != '' and empresa2 != '' and tempo2 != '':
print('\033[34mCargo: {} | Empresa: {} | Duração: {} meses'.format(emprego2, empresa2, tempo2))
#condicional empregos - FIM
|
b817cd12ee0dfc2c629bb96e7ae3f4cfc32ca886 | JBaba/PyLearn | /Scripts/classExp.py | 1,389 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Nov 16 10:56:09 2015
@author: nviradia
"""
class Robot:
""" This is robot class """
population = 0
def __init__(self,name):
""" Init the robot class """
self.name = name
print("class",self.name,"is initialized")
Robot.population += 1
def fakePop(self):
self.population +=1
def die(self):
""" destory robot """
print(self.name,"robot is destroyed")
Robot.population -= 1
def greetings(self):
print(self.name,"robot says hi")
def selfCountRobots(self):
print("we have",self.population,"self count robots.")
@classmethod
def countRobots(cls):
print("we have",cls.population,"robots.")
@classmethod
def count2Robots(self):
print("we have count2",self.population,"robots.")
print("we have count2",Robot.population,"robots.")
droid1 = Robot("R2 d1")
droid1.greetings()
droid1.fakePop()
droid1.selfCountRobots()
droid1.countRobots()
droid2 = Robot("R2 d2")
droid2.greetings()
droid2.fakePop()
droid2.selfCountRobots()
droid2.countRobots()
print("do some work.")
droid1.die()
droid1.countRobots()
droid1.count2Robots()
droid2.die()
droid1.countRobots()
droid1.count2Robots()
droid2.countRobots()
Robot.countRobots() |
97e0d6e56de983f5e223e39cf58700df77016b63 | StanislawAniola/Recruitment_task_backend_internship032021 | /currency_project/DatabaseClient.py | 6,533 | 3.8125 | 4 | import sqlite3
from sqlite3 import Error
from datetime import datetime
class DatabaseClient():
"""
establish connection to database
:return: connection object
"""
def __init__(self, start_date, end_date, currency_name="btc-bitcoin"):
self.start_date = start_date
self.end_date = end_date
self.currency_name = currency_name
def create_connection(self):
""" create a database connection to a SQLite database """
conn = None
try:
conn = sqlite3.connect("./currency_data.db")
print("connected to the database")
except Error as e:
print(e)
return conn
def create_table(self, conn):
"""
create currency_data and range_date tables
:param conn: Connection object
"""
sql_create_currency_data_table = """
CREATE TABLE IF NOT EXISTS currency_data
(
id integer PRIMARY KEY,
currency_name VARCHAR(255) NOT NULL,
date DATETIME NOT NULL,
price DOUBLE NOT NULL
);
"""
sql_create_range_date_table = """
CREATE TABLE IF NOT EXISTS range_date
(
currency_name VARCHAR(255) NOT NULL,
start_date DATETIME NOT NULL,
end_date DATETIME NOT NULL
);
"""
cursor = conn.cursor()
try:
cursor.execute(sql_create_currency_data_table)
cursor.execute(sql_create_range_date_table)
print("Tables successfully created")
except Error as e:
print(e)
finally:
cursor.close()
def check_if_data_in_database(self, conn):
"""
check if selected range already is in range_date table
:param conn: Connection object
"""
sql_get_date = """
SELECT currency_name, start_date, end_date
FROM range_date
WHERE currency_name='{currency_name}' AND start_date='{start_date}' AND end_date='{end_date}'
"""
sql_get_date = sql_get_date.format(currency_name=self.currency_name,
start_date=self.start_date, end_date=self.end_date)
cursor = conn.cursor()
try:
date_in_database = cursor.execute(sql_get_date)
selected_date_range = False
for i in date_in_database:
if len(i) == 3:
selected_date_range = True
print("Selected date range already in the database")
return selected_date_range
except Error as e:
print(e)
finally:
cursor.close()
@staticmethod
def insert_data_to_database(conn, currency_data):
"""
insert currency data to currency_data table
:param conn: Connection object
:param currency_data: currency data
"""
cursor = conn.cursor()
try:
for i in currency_data:
date = datetime.strptime(i["date"], '%Y-%m-%d')
sqlite_insert_query = """
INSERT INTO currency_data (currency_name, price, date)
SELECT '{name}', {price}, '{date}'
WHERE NOT EXISTS(SELECT *
FROM currency_data
WHERE currency_name='{name}' AND date='{date}')
"""
sqlite_insert_query = sqlite_insert_query.format(name=i["name"], price=i["price"], date=date)
cursor.execute(sqlite_insert_query)
conn.commit()
print("Records inserted successfully into table")
except Error as e:
print(e)
finally:
cursor.close()
def insert_date_data_range(self, conn):
"""
insert selected date range into range_date table
:param conn: Connection object
"""
sqlite_insert_query = """
INSERT INTO range_date (currency_name, start_date, end_date)
SELECT '{name}', '{start_date}', '{end_date}'
WHERE NOT EXISTS(SELECT *
FROM range_date
WHERE currency_name='{name}' AND start_date='{start_date}' AND end_date='{end_date}')
"""
sqlite_insert_query = sqlite_insert_query.format(name=self.currency_name,
start_date=self.start_date, end_date=self.end_date)
cursor = conn.cursor()
try:
cursor.execute(sqlite_insert_query)
conn.commit()
print("Record inserted successfully into SqliteDb_developers table ")
except Error as e:
print(e)
finally:
cursor.close()
def get_data_from_database(self, conn):
"""
get data selected data from currency_data table
:param conn: Connection object
"""
sql_get_date = """
SELECT currency_name, price, date
FROM currency_data
WHERE currency_name='{name}' AND date >= '{start_date}' AND date <= '{end_date}'
"""
sql_get_date = sql_get_date.format(name=self.currency_name, start_date=self.start_date, end_date=self.end_date)
cursor = conn.cursor()
try:
result = cursor.execute(sql_get_date)
data_from_database = []
for i in result:
dict_format = {
"name": i[0],
"price": i[1],
"date": i[2][0:10]
}
data_from_database.append(dict_format)
return data_from_database
except Error as e:
print(e)
finally:
cursor.close()
|
1dcf46d72d77e69d34b2bea1157f17ca3b714f1e | fzjawed/Snake-Game | /PetPy.py | 3,960 | 3.84375 | 4 | import turtle
import time
import random
delay = 0.1
score = 0
high_score = 0
#Setting the window for the game
wnd = turtle.Screen()
wnd.title("Snake Game by Zo")
wnd.bgcolor("light blue")
wnd.setup(width=600, height=600)
wnd.tracer(0)
#Setting the text for the game
pen = turtle.Turtle()
pen.speed(0)
pen.shape("square")
pen.color("black")
pen.penup()
pen.hideturtle()
pen.goto(0,260)
pen.write("Score: 0 High Score: 0", align = "center", font=("Courier",24,"bold"))
#Creating the snake
snake = turtle.Turtle()
snake.speed(0)
snake.shape("circle")
snake.color("yellow")
snake.penup()
snake.goto(0,0)
snake.direction = "stop"
#Creating the food for the snake
food = turtle.Turtle()
food.speed(0)
food.shape("square")
food.color("blue")
food.penup()
food.goto(0,100)
body_seg = []
#Functions for game action
#to change directions
def move_up():
if snake.direction != "down":
snake.direction = "up"
def move_down():
if snake.direction != "up" :
snake.direction = "down"
def move_left():
if snake.direction != "right":
snake.direction = "left"
def move_right():
if snake.direction != "left":
snake.direction = "right"
#defines what happens on screen on every movement
def movement():
if snake.direction == "up":
snake.sety(snake.ycor() + 20)
if snake.direction == "down":
snake.sety(snake.ycor() - 20)
if snake.direction == "left":
snake.setx(snake.xcor() - 20)
if snake.direction == "right":
snake.setx(snake.xcor() + 20)
#keyboard bindings
wnd.listen()
wnd.onkeypress(move_up, "w")
wnd.onkeypress(move_down, "s")
wnd.onkeypress(move_left, "a")
wnd.onkeypress(move_right, "d")
#Main Game loop
while True:
wnd.update()
#check for collisions
if snake.xcor()>290 or snake.xcor()<-290 or snake.ycor()>290 or snake.ycor()<-290:
time.sleep(1)
snake.goto(0,0)
snake.direction = "stop"
#hide the segment
for seg in body_seg:
seg.goto(1000,1000)
body_seg.clear()
#reset score
score = 0
delay = 0.1
pen.clear()
pen.write("Score: {} High Score: {}".format(score,high_score),align = "center", font=("Courier",24,"bold"))
#check if snake has eaten food
if snake.distance(food) < 20:
#move the food to another spot
food.goto(random.randint(-290,290),random.randint(-290,290))
#if this does happen add a segment to the snake body
new_seg = turtle.Turtle()
new_seg.speed(0)
new_seg.shape("circle")
new_seg.color("yellow")
new_seg.penup()
body_seg.append(new_seg)
delay -= 0.001
#increase score
score += 10
if score > high_score:
high_score = score
pen.clear()
pen.write("Score: {} High Score: {}".format(score,high_score),align = "center", font=("Courier",24,"bold"))
#Move the end segments to follow the others
for i in range(len(body_seg)-1,0,-1):
x = body_seg[i-1].xcor()
y = body_seg[i-1].ycor()
body_seg[i].goto(x,y)
#Move the first segment to the head
if len(body_seg) > 0:
x=snake.xcor()
y=snake.ycor()
body_seg[0].goto(x,y)
movement()
#Check for body collisions
for seg in body_seg:
if seg.distance(snake) < 20:
time.sleep(1)
snake.goto(0,0)
snake.direction = "stop"
for seg in body_seg:
seg.goto(1000,1000)
body_seg.clear()
score = 0
delay = 0.1
pen.clear()
pen.write("Score: {} High Score: {}".format(score,high_score),align = "center", font=("Courier",24,"bold"))
time.sleep(delay)
wnd.mainloop() |
b576d5bc9865fdaa4a352b2630fb318e17fcc110 | BoraxTheClean/advent-of-code-2020 | /day2/day_2.py | 653 | 3.625 | 4 | def password_validator(constraint,char,password):
start,end = parse_range(constraint)
return bool(password[start-1] == char) != bool(password[end-1] == char)
def parse_range(constraint):
constraint = constraint.split('-')
return int(constraint[0]),int(constraint[1])
def get_input():
f = open('input.txt')
lines = f.read()
lines = lines.split('\n')
lines = [i.split(' ') for i in lines if i!='']
print(lines)
total = 0
for constraint,char,password in lines:
char = char.strip(':')
if password_validator(constraint,char,password):
total += 1
print(total)
inp = get_input()
|
9e58c0d9f59a650d5a1d037fecb0dbad996fbdbb | AshFromNowOn/Hansard_sentiment | /Python/search_mockup.py | 2,402 | 3.671875 | 4 | # COMPLETELY FAKE SEARCH MOCKUP THAT DOES NOTHING
print("What would you like to do?")
print("1: Search via Member of Parliament Name \n"
"2: Search via Topic\n"
"3: Input Sentence for sentiment extraction\n"
"4: Retrain Sentiment Analysis Model(!)\n"
"Q: Quit Program")
input("Choice:")
print("--SEARCH VIA MEMBER--")
print("Member Name: Alan Jones")
print(" Searching...")
print("2 topics found for Alan Jones")
print(" TOPIC --------------------------------------------------- AVERAGE SENTIMENT")
print(" 1: Trading Schemes Bill - POSITIVE")
print(" 2: Gender Identity (Registration and Civil Status) Bill - NEGATIVE")
print("Options:\n"
"1: Select Topic\n"
"2: Search New Member\n"
"Q: Return to previous Menu")
input("Choice:")
print("Showing Speech from topic 1: Trading Schemes Bill:")
print("Pyramid selling and multi-level marketing have become great and expanding businesses. Such marketing exercises\n"
"involve more than people trading from their own homes; it has come to my notice that professional people such\n"
"as doctors, surgeons and others who see and relate to people at different levels are also now encouraging and\n"
"indulging in multi-level marketing and pyramid selling. Patients come to see doctors to get fitter and healthier,\n"
"and in that relationship they may be encouraged to buy water filters, air cleaners or filters and other things,\n"
"in the surgery. That is a remarkable development. I have come across cases in which people were encouraged to buy\n"
"in that way, and the professionally qualified doctors and accountants-I suppose even lawyers- who sell various\n"
"goods on a part-time basis to their clients are earning large amounts of money. That is a complicated matter, \n"
"and the Bill proposed by my right hon. Friend the Member for Chelsea (Sir N. Scott) is an attempt to put certain\n"
"matters right. In the late 1960s, when such trading schemes came into being, there was a great deal of demand.\n"
"There were many abuses, and successive Governments have made attempts to correct those, as the schemes have\n"
"expanded to include many millions of people.")
print("\nOptions:\n"
"1: Select Topic\n"
"2: Search New Member\n"
"Q: Return to previous Menu")
input("Choice: ") |
c8aa33cedd74a6de08899ed01c0f710aa88ef83f | BenAAndrew/AStar | /tools/vector.py | 790 | 4.1875 | 4 | class Vector:
"""
Class to represent a position on the maze.
Stores x & y and enables some useful tools.
"""
def __init__(self, tuple):
self.x = tuple[0]
self.y = tuple[1]
def __str__(self):
return f"x: {self.x}, y: {self.y}"
def get_values(self):
return self.x, self.y
def equal_to(self, vector):
return self.x == vector.x and self.y == vector.y
def distance_to(self, vector):
"""
Gets the x+y distance between itself and
another vector
Arguments:
vector {Vector} -- Vector to measure distance to
Returns:
{int} -- total distance between vectors
"""
return int(abs(self.x - vector.x) + abs(self.y - vector.y))
|
3ae0e868f8e29967e9739d7a4466961f60aa48c3 | Aasthaengg/IBMdataset | /Python_codes/p02403/s318962068.py | 95 | 3.578125 | 4 | while 1:
h,w=map(int,raw_input().split())
if (h,w)==(0,0):
break
print ("#"*w+"\n")*h |
12514f423d6f7e4d95b1781cda7da73b6bdac9aa | nnayk/PythonStuff | /61a/2021/Lab1/Q6.py | 417 | 4.15625 | 4 | def falling(n, k):
"""Compute the falling factorial of n to depth k.
>>> falling(6, 3) # 6 * 5 * 4
120
>>> falling(4, 0)
1
>>> falling(4, 3) # 4 * 3 * 2
24
>>> falling(4, 1) # 4
4
"""
"*** YOUR CODE HERE ***"
if k==0:
return 1
else:
product=k
dec=k-1
while n>1:
product*=dec
dec-=1
return product
|
4f953276889a63df2ef8eeed0802aaa340e9909b | Qiong/ycyc | /pchallengecom/equality.py | 1,026 | 3.640625 | 4 | #http://www.pythonchallenge.com/pc/def/equality.html
#http://www.pythonchallenge.com/pc/def/linkedlist.php
#http://wiki.pythonchallenge.com/index.php?title=Main_Page
#http://wiki.pythonchallenge.com/index.php?title=Level3:Main_Page
import string
import re
def main():
"""
This is testing for comments
for multiple lines
f = open('somefile.txt','r')
for line in f.readlines():
print line
f.close()
"""
upper = string.ascii_uppercase
lower = string.ascii_lowercase
result = []
fo = open('equality','r')
txt = fo.read()
res = re.findall(r'([a-z][A-Z]{3})([a-z])([A-Z]{3}[a-z])',txt)
#print res
for ch in res:
result.append(ch[1])
print ''.join(result)
"""
l = len(txt)-4
for i in range (4, l):
if txt[i] in lower:
if txt[i-3] in upper and txt[i-2] in upper and txt[i-1] in upper and txt[i+1] in upper and txt[i+2] in upper and txt[i+3] in upper:
if txt[i-4] in lower and txt[i+4] in lower:
result.append(txt[i])
print ''.join(result)
"""
if __name__=='__main__':
main()
|
170d7a6323e5df6fc018ed0063ac3155cd6622b9 | TestowanieAutomatyczneUG/laboratorium-9-cati97 | /tests/test_car.py | 1,052 | 3.5625 | 4 | import unittest
from unittest.mock import *
from src.Car import *
class TestCar(unittest.TestCase):
def setUp(self):
self.temp = Car()
def test_needsFuel_return_true(self):
self.temp.needsFuel = Mock(name='needsFuel')
self.temp.needsFuel.return_value = True
self.assertEqual(self.temp.needsFuel(), True)
def test_needsFuel_return_false(self):
self.temp.needsFuel = Mock(name='needsFuel')
self.temp.needsFuel.return_value = False
self.assertEqual(self.temp.needsFuel(), False)
@patch.object(Car, 'getEngineTemperature')
def test_getEngineTemperature_patch(self, mock_method):
mock_method.return_value = 80
result = self.temp.getEngineTemperature()
self.assertEqual(result, 80)
@patch.object(Car, 'driveTo')
def test_driveTo_patch(self, mock_method):
mock_method.return_value = "Las Vegas"
result = self.temp.driveTo("Las Vegas")
self.assertEqual(result, "Las Vegas")
if __name__ == '__main__':
unittest.main() |
e806b00d811753b564fd057d6288a2dd34de3428 | cardinalion/leetcode-medium | /998_Maximum_Binary_Tree_II.py | 672 | 3.6875 | 4 | class Solution:
def insertIntoMaxTree(self, root: 'TreeNode', val: 'int') -> 'TreeNode':
add = TreeNode(val)
if root == None:
return add
if root.val < val:
add.left = root
return add
tmp = root
while tmp != None:
if tmp.right == None:
tmp.right = add
return root
if tmp.right.val > val:
tmp = tmp.right
else:
tmp2 = tmp.right
tmp.right = add
add.left = tmp2
return root
return root
|
2061b686f9aed9382e7c160d43fada6f70c54c89 | Divyansh-03/PythoN_WorK | /leap_year.py | 402 | 4.3125 | 4 | ''' Any year is input through the keyboard. Write a program to
determine whether the year is a leap year or not.
(Hint: Use the % (modulus) operator) '''
year = int(input( " Enter an year "))
if year %4 ==0 :
if year%100==0:
if year%400==0 :
print(" It is a Leap Year ")
else :
print(" It is not a Leap year ")
else:
print(" It is a Leap year ")
else:
print(" It is not a Leap year ") |
11d9ee67f5aa71bb15048d434720d90173dc886a | akula0611/positive-number | /positive numbers.py | 193 | 3.859375 | 4 | pos=[]
InputList=list(map(int,input("Enter input list with spaces in between each number").split()))
for i in InputList:
if i>0:
pos.append(i)
print("The positive number are ",pos)
|
aa0da4713e3b2c888ff94ace67ff870d6ba92dad | JoyKrishan/Personal_Projects | /2 Web Access using Python/Regex.py | 310 | 3.609375 | 4 | import re
fname=input('Enter the file name\n')
lst=list()
try:
fhandle=open(fname)
except:
print('File could not be found',fname)
quit()
for line in fhandle:
if re.search('[0-9]+',line):
num=re.findall('[0-9]+',line)
for i in num:
lst.append(int(i))
print(sum(lst))
|
1229676ec32b6f8bb15cef4da29a06616437e672 | cliffpham/algos_data_structures | /algos/loops/unsorted_subarray.py | 746 | 3.671875 | 4 | import unittest
class Test(unittest.TestCase):
def test1(self):
self.assertEqual(
solve([2, 6, 4, 8, 10, 9, 15]),
5
),
def test2(self):
self.assertEqual(
solve([1,2,3,3,3,3]),
0
)
def solve(nums):
nums_sorted = nums[:]
nums_sorted.sort()
start = 0
end = 0
for i in range(0,len(nums)):
if nums[i] != nums_sorted[i]:
start = i
break
for n in range(len(nums)-1,-1,-1):
if nums[n] != nums_sorted[n]:
end = n
break
if (start == 0)&(end == 0):
return 0
else:
return end-start+1
if __name__ == "__main__":
unittest.main() |
14919685cb619ff2b687d908003bef0dab47adb3 | Sudo-Milin/Coursera_Crash_Course_on_Python | /Module_3/Graded_Assesment_Q02.py | 399 | 4.4375 | 4 | ### The show_letters function should print out each letter of a word on a separate line.
# Fill in the blanks to make that happen.
def show_letters(word):
# For loop interates each letter in the 'word' parameter that is passed during the function call.
for letter in word:
# For each letter encountered is printed.
print(letter)
show_letters("Hello")
# Should print one line per letter
|
2a3bd8fec4825cd9b41279431bdb6bfe1a710eef | pydupont/Massey_teaching | /LinuxAndPythonIntroductionForStaff/python2/exercise1_recursive.py | 287 | 4.125 | 4 | # answer to the exercice 1 wiht a different method
# this is called a recursive method (i.e. the function calls itself)
def fibonnaci(n):
if (n==0):
return 0
elif (n==1):
return 1
else:
return fibonnaci(n-1) + fibonnaci(n-2)
print fibonnaci(7)
|
336904cfc91ca04da3bce3ec282b20380b2641cb | bsarazin/sideways-shooter | /asteroid.py | 1,171 | 3.796875 | 4 | import pygame
from pygame.sprite import Sprite
class Asteroid(Sprite):
"""space rock!"""
def __init__(self, ai_settings, screen):
super(Asteroid, self).__init__()
self.ai_settings = ai_settings
self.screen = screen
self.speed_factor = self.ai_settings.asteroid_speed_factor
# Load the asteroid image and set its Rect attributes
self.image = pygame.image.load('images/asteroid.bmp')
self.rect = self.image.get_rect()
self.screen_rect = self.screen.get_rect()
# Start each new asteroid near the middle of the screen
self.rect.centerx = self.screen_rect.right
self.rect.centery = self.screen_rect.centery
# Store the bullet's position as a decimal value
self.x = float(self.rect.x)
def blitme(self) -> None:
"""Draw the asteroid at it's current location"""
self.screen.blit(self.image, self.rect)
def update(self) -> None:
"""Move the bullet up on the screen"""
# Update the decimal position of the bullet
self.x -= self.speed_factor
# Update the rect position
self.rect.x = self.x |
6d330e122a705d3cc7de29a7101a37950c574f00 | thiago-allue/portfolio | /02_ai/1_ml/3_data_preparation/code/chapter_26/01_define_dataset.py | 629 | 3.578125 | 4 | # example of creating a test dataset and splitting it into train and test sets
from sklearn.datasets import make_blobs
from sklearn.model_selection import train_test_split
# prepare dataset
X, y = make_blobs(n_samples=100, centers=2, n_features=2, random_state=1)
# split data into train and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=1)
# summarize the scale of each input variable
for i in range(X_test.shape[1]):
print('>%d, train: min=%.3f, max=%.3f, test: min=%.3f, max=%.3f' %
(i, X_train[:, i].min(), X_train[:, i].max(),
X_test[:, i].min(), X_test[:, i].max())) |
507dd557d8018c48f3b1a643d1871d6a2c1a5fdb | Jason-Yuan/Interview-Code | /LeetCode/Binary_Search_Tree_Iterator.py | 827 | 3.921875 | 4 | # Definition for a binary tree node
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class BSTIterator(object):
def __init__(self, root):
self.q=[]
while root:
self.q.append(root)
root=root.left
# @return a boolean, whether we have a next smallest number
def hasNext(self):
if not self.q:return False
return True
# @return an integer, the next smallest number
def next(self):
cur = self.q.pop()
node = cur.right
while node:
self.q.append(node)
node=node.left
return cur.val
# Your BSTIterator will be called like this:
# i, v = BSTIterator(root), []
# while i.hasNext(): v.append(i.next()) |
79240a2a5774e149b9b7ad897c68154f62f322bf | wangyendt/LeetCode | /Contests/301-400/week 302/2341. Maximum Number of Pairs in Array/Maximum Number of Pairs in Array.py | 685 | 3.609375 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 _*-
"""
@author: wangye(Wayne)
@license: Apache Licence
@file: Maximum Number of Pairs in Array.py
@time: 2022/07/17
@contact: wang121ye@hotmail.com
@site:
@software: PyCharm
# code is far away from bugs.
"""
import collections
from typing import *
class Solution:
def numberOfPairs(self, nums: List[int]) -> List[int]:
ret = [0, 0]
for k, v in collections.Counter(nums).items():
if v >= 2:
m, r = divmod(v, 2)
ret[0] += m
ret[1] += r
else:
ret[1] += v
return ret
so = Solution()
print(so.numberOfPairs([1, 3, 2, 1, 3, 2, 2]))
|
8900814ba83e94345c3c1b8261653dbad0ab55d8 | justRadek/pythonStudy | /recusrcion, iteration.py | 2,291 | 4.3125 | 4 | #fibonaci by using generators
"""def fib(num):
a, b = 0, 1
for i in range(0, num):
yield "{}: {}".format(i+1, a)
a, b = b, a+b
for item in fib(12):
print(item)"""
#generators for listing dictionarz items
"""myDict = {"throne": "iron", "ass": "huge", "number": "infinite"}
for key,val in myDict.items:
print("item {} is {}".format(key,val))"""
#recursive multiplication
"""def rec_mult(m, n):
#base case for recursive multiplication
if n == 0:
return 0
elif n >= 1:
return m + rec_mult(m, n-1)
elif n <= -1:
return -m + rec_mult(m, n+1)"""
#iterative multiplication - same case
"""def iter_mult(m, n):
if n == 0 or m == 0:
return 0
result = m * n
if n >= 1:
while n > 0:
result += m
n -= 1
elif n <= -1:
while n < 0:
result += -m
n += 1
return result
print("iterative multiplication: ")
print(iter_mult(3, 4))
print(iter_mult(-1, 4))
print(iter_mult(-2, 4))
print(iter_mult(2, -4))
print(iter_mult(0, 0))"""
#recursion of fibonachi
"""def rec_fib(n):
if n == 0 or n == 1:
return n
else:
return rec_fib(n -1) + rec_fib(n - 2)
print("recursive fibonachi is: ")
print(rec_fib(0))
print(rec_fib(1))
print(rec_fib(2))
print(rec_fib(3))
print(rec_fib(10))"""
#iterative of fibonachi
"""def iter_fib(n):
if n == 0 or n ==1:
return n
else:
previous_fib = 0
current_fib = 1
for iteration in range(1, n):
next_fib = current_fib + previous_fib
previous_fib = current_fib
current_fib = next_fib
return current_fib
print(iter_fib(10))"""
#faktorial
"""def f(n):
assert n >= 0
answer = 1
while n > 1:
answer *= n
n -= 1
return answer
def fact(n):
assert n >= 0
if n <= 1:
return n
else:
return n*fact(n - 1)
def g(n):
x = 0
for i in range(n):
for j in range(n):
x += 1
return x
def h(x):
assert type(x) == int and x >= 0
answer = 0
s = str(x)
for c in s:
answer += int(c)
return answer"""
|
bdb39e85ed5a155510175404197c7ca66240dd8b | iaora/ClappyBird | /quest.py | 1,199 | 3.9375 | 4 | import pygame
class QuestGame(object):
""" This class is a basic game.
This class will load data, create a pyscroll group, a hero object.
It also reads input and moves the Hero around the map.
Finally, it uses a pyscroll group to render the map and Hero.
"""
def __init__(self):
""" Init the game here
"""
def draw(self, surface):
""" Drawing code goes here
"""
def handle_input(self):
""" Handle pygame input events
"""
def update(self, dt):
""" Tasks that occur over time should be handled here
"""
def run(self):
""" Run the game loop
"""
# simple wrapper to keep the screen resizeable
def init_screen(width, height):
global temp_surface
screen = pygame.display.set_mode((width, height), pygame.RESIZABLE)
temp_surface = pygame.Surface((width / 2, height / 2)).convert()
return screen
if __name__ == "__main__":
pygame.init()
pygame.font.init()
screen = init_screen(800, 600)
pygame.display.set_caption('Quest - An epic journey.')
try:
game = QuestGame()
game.run()
except:
pygame.quit()
raise
|
cfd60d34e598c28342c70f79724b5f2fea351a76 | basimsahaf-zz/Coding-Challenges | /nthtolast.py | 1,566 | 3.921875 | 4 | """Write a function that takes a head node and an integer value n and
then returns the nth to last node in the linked list."""
class Node(object):
def __init__(self,k):
self.value = k
self.nextnode = None
#Testing Client
class TestNthToLast(object):
def TestClient(self,sol):
a = Node(1)
b = Node(2)
c = Node(3)
d = Node(4)
e = Node(5)
a.nextnode = b
b.nextnode = c
c.nextnode = d
d.nextnode = e
assert(sol(2,a)==4)
assert(sol(3,a)==3)
assert(sol(4,a)==2)
assert(sol(5,a)==1)
print("All Test Cases Correct")
#Solution:1
def nth_to_last_node(n,head):
length = 0
current = head
while current:
length += 1
current = current.nextnode
nodeIndex = length - n
current = head
while(nodeIndex != 0 and current.nextnode != None):
current = current.nextnode
nodeIndex-=1
return current.value
#Tests
t = TestNthToLast()
t.TestClient(nth_to_last_node)
#Most efficient Solution:
def nth_to_last_node_2(n,head):
left_pointer = head
right_pointer = head
for i in range(n-1):
if not right_pointer.nextnode:
raise Error('n is bigger than the length of the linked list')
right_pointer = right_pointer.nextnode
while right_pointer.nextnode:
right_pointer = right_pointer.nextnode
left_pointer = left_pointer.nextnode
return left_pointer.value
#Tests
a = TestNthToLast()
a.TestClient(nth_to_last_node_2)
|
d8a5dcf066fc8e69f35fb6647a48c1d7ab53fa56 | imnotbeno/Algorithms-and-Data-Structures | /dynamic_programming.py | 688 | 4.4375 | 4 | # !python3
# Memoization of nth fibonacci number, using a lookup table
'''
def fib(n, lookup):
# bas case
if n == 0 or n == 1:
lookup[n] = n
# if the value is not in the lookup array, calculate it and store it
if lookup[n] is None:
lookup[n] = fib(n-1, lookup) + fib(n-2, lookup)
return lookup[n]
def main():
n = 4
lookup = [None] * 101
print ("Fibonacci number is: ", fib(n, lookup))
'''
# Tabulation method of same example
def fib(n):
f = [0]*(n+1)
f[1] = 1
for i in range(2, n+1):
f[i] = f[i-1] + f[i-2]
return f[n]
def main():
n = 34
print("Fibonacci number is: ", fib(n))
main()
|
a41108c300fa310c836d5c2f225929bb02c279a2 | YMyajima/CodilityLessonPython | /lesson4-1/solution.py | 1,045 | 3.640625 | 4 | class TestValue:
def __init__(self, A, expect):
self.A = A
self.expect = expect
class Solution:
def __init__(self):
self.test_values = [
TestValue([4, 1, 3, 2], 1),
TestValue([4, 1, 3], 0),
TestValue([3, 1], 0),
TestValue([3, 3, 2], 0),
TestValue([3, 4, 2], 0),
TestValue([2], 0),
]
def solution(self, A):
raise NotImplementedError("You must implement.")
def test(self):
for test_value in self.test_values:
s = self.solution(test_value.A)
print(test_value.__dict__, 'result', s)
assert s == test_value.expect
class Solution1(Solution):
def __init__(self):
super().__init__()
def solution(self, A):
A = sorted(A)
start = 1
for a in A:
if start == a:
start += 1
else:
return 0
return 1
if __name__ == '__main__':
solution = Solution1()
solution.test()
|
c61c8f95784a8ac91a1a85f0e6b12b8552d2cc03 | alosoft/bank_app | /bank_class.py | 2,453 | 4.3125 | 4 | """Contains all Class methods and functions and their implementation"""
import random
def account_number():
"""generates account number"""
num = '300126'
for _ in range(7):
num += str(random.randint(0, 9))
return int(num)
def make_dict(string, integer):
"""makes a dictionary of Account Names and Account Numbers"""
return {string: integer}
class Account:
"""
This Class contains Balance and Name with functions like Withdraw, Deposit and Account History
"""
def __init__(self, name, balance=0, total_deposit=0, total_withdrawal=0):
"""Constructor of __init__"""
self.name = name.title()
self.balance = balance
self.records = [f'Default Balance: \t${self.balance}']
self.total_deposit = total_deposit
self.total_withdrawal = total_withdrawal
self.account = account_number()
def __str__(self):
"""returns a string when called"""
return f'Account Name:\t\t{self.name} \nAccount Balance:\t${str(self.balance)} ' \
f'\nAccount History:\t{self.records} \nAccount Number:\t\t{ self.account}'
def __len__(self):
"""returns balance"""
return self.balance
def history(self):
"""returns Account Information"""
return self.records
def print_records(self, history):
"""Prints Account Records"""
line = ' \n'
print(line.join(history) + f' \n\nTotal Deposit: \t\t${str(self.total_deposit)} '
f'\nTotal Withdrawal: \t${str(self.total_withdrawal)} '
f'\nTotal Balance: \t\t${str(self.balance)} ')
def deposit(self, amount):
"""Deposit function"""
self.total_deposit += amount
self.balance += amount
self.records.append(f'Deposited: ${amount}')
return f'Deposited: ${amount}'
def withdraw(self, amount):
"""Withdrawal function"""
if self.balance >= amount:
self.total_withdrawal += amount
self.balance -= amount
self.records.append(f'Withdrew: ${amount}')
return f'Withdrew: ${amount}'
self.records.append(
f'Balance: ${str(self.balance)} '
f'is less than intended Withdrawal Amount: ${amount}')
return f'Invalid command \nBalance: ${str(self.balance)} ' \
f'is less than intended Withdrawal Amount: ${amount}'
|
46d6976a5cd7a7b7b1ce657ac7aee54f98fc3de9 | Wambonaut/Machine-Learning-Homework | /ExerciseSheet2/Exercise1.py | 834 | 3.65625 | 4 | import numpy as np
import matplotlib.pyplot as plt
##Exercise 1: Mean-shift and K-Means
##1a) Implement the Epanechikov-Kernel
def k(x,mu=0,w=1):
return np.where(np.abs((x-mu)/w)<1, 3/(4*w)*(1-((x-mu)/w)**2), 0)
x=np.linspace(-3,3,100)
plt.plot(x, k(x))
plt.show()
##1b) Mean-shift on a 1d data set
def mean_shift_step(data_points):
for i,x0 in enumerate(data_points):
data_points[i]=sum(np.where(np.abs(x0-data_points)<1, data_points, 0))/sum(np.where(np.abs(x0-data_points)<1, 1, 0))
return data_points
data1=np.load("meanshift1d.npy")
def KDE(x, w, samples,K):
return 1/len(samples)*sum([K(x,s,w) for s in samples])
x=np.linspace(-4,4,100)
y=KDE(x,1,data1,k)
plt.plot(x,y)
data=data1
r=10
for i in range(r):
plt.scatter(data, np.zeros(len(data))+i/r)
data=mean_shift_step(data)
plt.show()
|
a5d5780a39642ab67414f3b0563dffb4be8f95de | cealicea171/todo-manager | /manager.py | 5,688 | 4.0625 | 4 | import time
import datetime
import item
class Manager(object):
print('Hi, Welcome to your Reminder App')
def startUp():
print('1 : Would you like to see your tasks?')
print('2: Would you like to create a task?')
print('3: Would you like to mark a task complete?')
decision = input('> ')
if decision == '1':
Manager.showAll()
Manager.startUp()
elif decision == '2':
Manager.createTask()
elif decision == '3':
Manager.markComplete()
else:
Manager.startUp()
def showAll():
readTask = open("todos.txt", "r")
##(file, action)
#readTask is the variable that is getting assigned to opening the text file, read only... because of the r
message = readTask.read()
#reads the file
print(message)
readTask.close()
#..
##closes the file
def markComplete():
edit = open("todos.txt").read()
##this is making the variable edit open the text file and read it
completedTask = input("What Task Did You Complete? ")
##then this making the variable completedTask and make it a input and print out the question?
s = edit.replace( completedTask, completedTask + " COMPLETE✅ " + str(True))
##(looking , action)
#(looking, getting it and putting completed beside it.)
#this is taking the variable s and having it take the user input and add completed next to it.
f2 = open("todos.txt", 'w+')
##f2 overrides (=edit) read and makes it write
f2.write(s)
##it changing the permission from read to write
f2.close()
##closes the file..
##this Prints all of the to-do items in the list.
f = open('todos.txt','r')
#(file, action)
#f is the variable that is getting assigned to opening the text file, read only... because of the r
message = f.read()
#message is being sent to f.read f is opening file, .read is taking file and reading it. message is the file
print(message) #then printing the message
##exiting it outPsy
f.close()
def createTask():
now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") # add timestamp from imported modules
#this Adds a new item to the list.
file1 = open("todos.txt","a+")#append mode
#file1 is the varaiable that is getting assigned to opening a txt file, reading and adding(appending) whatever you write
task = input("Create A New Task: ")
#this is taking variable task and assigning it to an input that prints out create a new task..
#...
file1.write("\n" + task + " " + now)
##this is saying take the file1, read it and write the new task you just entered on a new line ..
file1.close()
Manager.startUp()
##this closes the text file
Manager()
Manager.startUp()
# #Make a class called Manager. A single object of this class should be created when you run your script. It should do the following:
# #Print all of the to-do items in the list.
# #Add a new item to the list.
# #Mark an item as completed..
#inter = {
#'show_all': showAll(),
#'create_task': createTask(),
#'mark_complete': markComplete(),
#'ask_prompt': askPrompt()
#
#def askPrompt():
# question = input("Would you like to see your tasks?")
## if question == "yes":
# return 'show_all'
# elif question == "no": #
## return 'create_task'
## else:
# return 'ask_prompt'
# # class Manager
# # def print_all(f):
# # print(f.read())
# #
# #
# # print("Your tasks for this week are: ", to_do)
# #
# # #mark an item as a completed..
# # tuff = ten_things.split(' ')
# # #The split() method splits a string into a list.
# # print("Adding: ", to_do)
# # stuff.append(to_do)
# # #append Add an item to the end of the list
# # print(f"There are {len(stuff)} items now.")
#
# #this Prints all of the to-do items in the list.
#f = open('todos.txt','r') #(file, action)
# #f is the variable that is getting assigned to opening the text file, read only... because of the r
#message = f.read()
#message is being sent to f.read f is opening file, .read is taking file and reading it. message is the file
#print(message) #then printing the message
#f.close()#exiting it out
#
# #this Adds a new item to the list.
# file1 = open("todos.txt","a+")#append mode
# #file1 is the varaiable that is getting assigned to opening a txt file, reading and adding(appending) whatever you write
# task = input("Create A New Task: ")
# #this is taking variable task and assigning it to an input that prints out create a new task..
#file1.write("\n"+ task)
# #this is saying take the file1, read it and write the new task you just entered on a new line ..
#file1.close()
# #this closes the text file
#
#
# #this Marks an item as completed.
# edit = open("todos.txt").read()
# #this is making the variable edit open the text file and read it
# completedTask = input("What Task Did You Complete? ")
# #then this making the variable completedTask and make it a input and print out the question?
#s = edit.replace( completedTask, completedTask + " completed")#(looking , action)
# #(looking, getting it and putting completed beside it.)
# #this is taking the variable s and having it take the user input and add completed next to it.
#
# f2 = open("todos.txt", 'w+')
# #f2 overrides (=edit) read and makes it write
# f2.write(s)
# #it changing the permission from read to write
# f2.close()
#closes the file
|
159a822e425c79b78c16a264d76b4de610ed59a4 | YanivHollander/HashcodeDelivery | /OrderInventory.py | 3,273 | 3.84375 | 4 | from Definitions import Product
import unittest
from typing import Dict
class Order(object):
def __init__(self):
self._products: Dict[Product, int] = {} # Dictionary for frequency of each product
def __repr__(self):
return repr((self._products))
def __str__(self):
ret = "Order: "
for product in self._products:
ret += " (" + str(product) + "): " + str(self._products[product]) + "|"
return ret
def __iter__(self):
return iter(self._products)
def __getitem__(self, product: Product):
return self._products[product]
def __setitem__(self, product: Product, n: int):
self._products[product] = n
def __delitem__(self, product: Product):
del self._products[product]
def products(self) -> Dict[Product, int]:
return self._products
def clear(self) -> None:
self._products.clear()
def append(self, product: Product, n: int) -> None:
if n < 0:
raise RuntimeError ("Trying to append a negative number of items of product " + str(product))
if product in self._products:
self._products[product] += n
else:
self._products[product] = n
def remove(self, product: Product, n: int) -> None:
if product in self._products and self._products [product] >= n:
self._products [product] -= n
else:
raise RuntimeError ("Trying to remove more products " + str(product) + " than exist")
if self._products [product] == 0:
del self._products [product]
def count(self, product: Product) -> int:
if self.exist(product):
return self._products[product]
return 0
def empty(self) -> bool:
if self._products:
return False
return True
def exist(self, product: Product) -> bool:
return product in self._products
class Inventory(Order):
def __init__(self):
super().__init__()
self.__weight = 0
def __repr__(self):
return repr((self._products, self.__weight))
def __str__(self):
ret = "Inventory: "
for product in self._products:
ret += " (" + str(product) + "): " + str(self._products [product]) + "|"
ret += " total weight = " + str(self.__weight)
return ret
def clear (self) -> None:
super().clear()
self.__weight = 0
def append (self, product: Product, n: int) -> None:
super().append(product, n)
self.__weight += product.weight * n
def remove (self, product: Product, n: int) -> None:
super().remove(product, n)
self.__weight -= product.weight * n
def weight (self) -> int:
return self.__weight
class TestOrderInventory(unittest.TestCase):
def setUp(self):
self.inventory = Inventory()
def test_append_to_inventory(self):
product0 = Product(0, 5)
product1 = Product(2, 3)
self.inventory.clear()
self.inventory.append(product0, 3)
self.inventory.append(product1, 1)
print(self.inventory)
self.assertEqual(product0.weight * 3 + product1.weight * 1, self.inventory.weight())
if __name__ == '__main__':
unittest.main()
|
443803f431de9b818d4733718eb43cfd2d665d8a | lqzcf10/helloworld | /Pyhton/nine.py | 525 | 3.875 | 4 | class PrintTable(object):
'''ӡžų˷'''
def __init__(self):
print('ʼӡ9*9˷')
self.print99()
def print99(self):
#for(int i=1; i<10; i++){
# for(int j=1; j<=i; j++){
# print('%d*'+i+'%d='+j+(i*j)+' ');
# }
# println();
#}
for i in range(1,10):
for j in range(1,i+1):
print('%dx%d=%2s \t' %(i,j,i*j))
print('\n')
if __name__=='__main__':
pt=PrintTable()
|
8ea56d030bb00fc9facec5712b2c79278872b31b | Rediet8abere/leetcode | /container.py | 512 | 3.515625 | 4 | def maxArea(height):
"""
:type height: List[int]
:rtype: int
"""
maxarea = -2147483648 #minValue
area = 0
i = 0
j = len(height)-1
while i<j:
if height[i] < height[j]:
area = height[i]*(j-i)
i+=1
else:
area = height[j]*(j-i)
j-=1
if area > maxarea:
maxarea = area
return maxarea
print(maxArea([1,8,6,2,5,4,8,3,7]))
|
a2009148ed8bdf2b701e981d900fe5eb57f57464 | ShravanSk123/Data_Structures | /ProbSolvingAlgo/ValidateIP.py | 584 | 3.765625 | 4 | # validates ipv4 and ipv6 addresses
import re
def isIPV4(s):
try:
return str(int(s)) == s and 0 <= int(s) <= 255
except:
return False
def isIPV6(s):
if len(s)>4 or re.match("\W",s): # "\W" is used for special characters
return False
try:
int(s,16)
return True
except:
return False
# main
IP = input()
ipv4 = IP.split('.')
ipv6 = IP.split(':')
if len(ipv4)==4 and all(isIPV4(n) for n in ipv4):
print("IPv4")
elif len(ipv6)==8 and all(isIPV6(n) for n in ipv6):
print("IPv6")
else:
print("Neither")
|
e1ed3fe70cd61eeb94137759526a0818467b548c | davidbusch1/pythonExercises | /ex2.py | 688 | 3.984375 | 4 | #Faça um programa para calcular e exibir a porcentagem
#de comissão de vendas de um vendedor, conforme o volume
#mensal de vendas do mesmo digitado pelo usuário
vendas = float(input("Digite o valor de vendas: "))
if vendas <= 5000:
comissao = vendas * 0.02
print(f'O valor da sua comisão é de {comissao}.')
elif vendas > 5000 and vendas <= 10000:
comissao = vendas * 0.05
print(f'O valor da sua comisão é de {comissao}.')
elif vendas > 10000 and vendas <= 15000:
comissao = vendas * 0.07
print(f'O valor da sua comisão é de {comissao}.')
elif vendas > 15000:
comissao = vendas * 0.09
print(f'O valor da sua comisão é de {comissao}.') |
bb8a86b2c13d3ee77eca2a27be11894648211497 | ai2-education-fiep-turma-2/05-python | /solucoes/Sergio/ex2.py | 436 | 4.03125 | 4 | idade = int(input("Digite a sua idade: "))
if(idade >= 16 and idade <= 69):
peso = int(input("Digite o seu peso (em kg): "))
if(peso >= 50):
horas_sono = int(input("digite quantas horas dormiu na última noite: "))
if(horas_sono >= 6):
print("Tudo certo para sua doação de sangue, obrigado!")
else:
print("Horas de sono não compatível")
else:
print("Peso não compatível")
else:
print("Idade não compatível")
|
5c7b28864969b1053fe60fd9410cc11f7b41f38d | masrur-ahmed/Udacity-AI-for-Trading-Nanodegree | /quiz/m5_financial_statements/readability_solutions.py | 1,739 | 3.53125 | 4 | # solutions for readability exercises
# tokenize and clean the text
import nltk
import numpy as np
from nltk.stem import WordNetLemmatizer, SnowballStemmer
from collections import Counter
from nltk.corpus import stopwords
from nltk import word_tokenize
from syllable_count import syllable_count
nltk.download('wordnet')
nltk.download('punkt')
sno = SnowballStemmer('english')
wnl = WordNetLemmatizer()
from nltk.tokenize import RegexpTokenizer
word_tokenizer = RegexpTokenizer(r'[^\d\W]+')
def word_tokenize(sent):
return [ w for w in word_tokenizer.tokenize(sent) if w.isalpha() ]
from nltk.tokenize import sent_tokenize
def sentence_count(text):
return len(sent_tokenizer.tokenize(text))
def word_count(sent):
return len([ w for w in word_tokenize(sent)])
def hard_word_count(sent):
return len([ w for w in word_tokenize(sent) \
if syllable_count(wnl.lemmatize(w, pos='v'))>=3 ])
def flesch_index(text):
sentences = sent_tokenize(text)
total_sentences = len(sentences)
total_words = np.sum([ word_count(s) for s in sentences ])
total_syllables = np.sum([ np.sum([ syllable_count(w) for w in word_tokenize(s) ]) \
for s in sentences ])
return 0.39*(total_words/total_sentences) + \
11.8*(total_syllables/total_words) - 15.59
def fog_index(text):
sentences = sent_tokenize(text)
total_sentences = len(sentences)
total_words = np.sum([ word_count(s) for s in sentences ])
total_hard_words = np.sum([ hard_word_count(s) for s in sentences ])
return 0.4*((total_words/total_sentences) + \
100.0*(total_hard_words/total_words))
# solutions for bag-of-words, sentiments, similarity exercises |
5e96b4a4032e67a3af1abbdbdb75dc0bfa3989e2 | SalmaHassan3/8Puzzle | /8Puzzle.py | 8,470 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Mar 15 15:23:44 2018
@author: salma
"""
import heapq
import math
import timeit
#A class for nodes in search tree
class Node:
#constructor
def __init__( self, board, parent, operator, depth):
self.board= board
self.parent = parent
self.operator = operator
self.depth = depth
self.manhattan_cost = self.depth+self.Manhattan([0,1,2,3,4,5,6,7,8])
self.euclidean_cost= self.depth+self.Euclidean([0,1,2,3,4,5,6,7,8])
#A function to check if a given node(board) is a duplicate in this node's path
def checkPath(self,nodeBoard):
temp=self
while True:
if temp.board==nodeBoard:
return False
if temp.parent == None:
break
temp = temp.parent
return True
#A function to calculate Manhattan distance from goal
def Manhattan(self,goal):
distance=0
for num in range(0,9):
index1=self.board.index(num)
index2=goal.index(num)
x1=getx(index1)
y1=gety(index1)
x2=getx(index2)
y2=gety(index2)
distance+=abs(x1-x2)+abs(y1-y2)
return distance
#A function to calculate Euclidean distance from goal
def Euclidean(self,goal):
distance=0
for num in range(0,9):
index1=self.board.index(num)
index2=goal.index(num)
x1=getx(index1)
y1=gety(index1)
x2=getx(index2)
y2=gety(index2)
distance+=math.sqrt((x1-x2)**2+(y1-y2)**2)
return distance
#Less than function to compare nodes according to their costs(used by heap in A* search)
# def __lt__(self, other):
# return self.manhattan_cost < other.manhattan_cost
def __lt__(self, other):
return self.euclidean_cost < other.euclidean_cost
#Takes index of element in board reprsented by 1-D array and returns its X co-ordinate in 2-D board
def getx(index):
if index in [0,1,2]:
return 0
elif index in [3,4,5]:
return 1
else:
return 2
#Takes index of element in board reprsented by 1-D array and returns its Y co-ordinate in 2-D board
def gety(index):
if index in [0,3,6]:
return 0
elif index in [1,4,7]:
return 1
else:
return 2
def displayBoard( state ):
print ("-------------")
print ("| %d | %d | %d |" % (state[0], state[1], state[2]))
print ("-------------")
print ("| %d | %d | %d |" % (state[3], state[4], state[5]))
print ("-------------")
print ("| %d | %d | %d |" % (state[6], state[7], state[8]))
print ("-------------")
#Move functions in four directions
def moveLeft( board ):
indexZero = board.index( 0 )
if indexZero not in [0, 3, 6]:
newBoard = board[:]
temp = newBoard[indexZero - 1]
newBoard[indexZero - 1] = newBoard[indexZero]
newBoard[indexZero] = temp
return newBoard
else:
return None
def moveRight( board ):
indexZero = board.index( 0 )
if indexZero not in [2, 5, 8]:
newBoard = board[:]
temp = newBoard[indexZero + 1]
newBoard[indexZero + 1] = newBoard[indexZero]
newBoard[indexZero] = temp
return newBoard
else:
return None
def moveUp( board ):
indexZero = board.index( 0 )
if indexZero not in [0, 1, 2]:
newBoard = board[:]
temp = newBoard[indexZero - 3]
newBoard[indexZero - 3] = newBoard[indexZero]
newBoard[indexZero] = temp
return newBoard
else:
return None
def moveDown( board ):
indexZero = board.index( 0 )
if indexZero not in [6, 7, 8]:
newBoard = board[:]
temp = newBoard[indexZero + 3]
newBoard[indexZero + 3] = newBoard[indexZero]
newBoard[indexZero] = temp
return newBoard
else:
return None
def createNode( board, parent, operator, depth):
return Node( board, parent, operator, depth)
def expandNode( node ):
children = []
if moveRight(node.board) != None:
newNode=createNode( moveRight( node.board), node, "r", node.depth + 1)
if node.checkPath(newNode.board):
children.append(newNode)
if moveDown(node.board) != None:
newNode=createNode( moveDown( node.board ), node, "d", node.depth + 1 )
if node.checkPath(newNode.board):
children.append(newNode)
if moveLeft(node.board) != None:
newNode=createNode( moveLeft( node.board ), node, "l", node.depth + 1)
if node.checkPath(newNode.board):
children.append(newNode)
if moveUp(node.board) != None:
newNode=createNode( moveUp( node.board ), node, "u", node.depth + 1)
if node.checkPath(newNode.board):
children.append(newNode)
return children
nodes_Expanded=0
#BFS search
def BFS(start,goal):
print("Visited Nodes:")
global nodes_Expanded
frontier =[]
frontier.append( createNode( start, None, None, 0))
while True:
if len( frontier ) == 0:
return None
node = frontier.pop(0)
displayBoard(node.board)
if node.board == goal:
moves = []
moves.insert(0, node)
temp = node
while True:
if temp.parent == None:
break
moves.insert(0, temp.parent)
temp = temp.parent
return moves
children= expandNode(node)
nodes_Expanded=nodes_Expanded+len(children)
frontier.extend(children)
#DFS search
def DFS(start,goal):
print("Visited Nodes:")
global nodes_Expanded
frontier =[]
frontier.append( createNode( start, None, None, 0) )
while True:
if len( frontier ) == 0:
return None
node = frontier.pop()
displayBoard(node.board)
if node.board == goal:
moves = []
moves.insert(0, node)
temp = node
while True:
if temp.parent == None:
break
moves.insert(0, temp.parent)
temp = temp.parent
return moves
children= expandNode(node)
nodes_Expanded=nodes_Expanded+len(children)
frontier.extend(children)
#A* search
def A_star(start,goal):
print("Visited Nodes:")
global nodes_Expanded
frontier=[]
start=createNode(start, None, None, 0)
heapq.heappush(frontier,start)
while True:
if len( frontier ) == 0:
return None
node=heapq.heappop(frontier)
displayBoard(node.board)
if node.board == goal:
moves = []
moves.insert(0, node)
temp = node
while True:
if temp.parent == None:
break
moves.insert(0, temp.parent)
temp = temp.parent
return moves
children= expandNode(node)
nodes_Expanded=nodes_Expanded+len(children)
for num in range(0,len(children)):
heapq.heappush(frontier,children[num])
def main():
start=stop=0
# startState=[]
# print('Enter start state element by element:')
# for i in range(9):
# x = int(input('-->'))
# startState.append(x)
# print (startState)
startState=[1,2,3,4,0,5,6,7,8]
goal = [0,1,2,3,4,5,6,7,8]
method=int(input("Choose method:1-bfs 2-dfs 3-a-star :"))
if method==1:
start = timeit.default_timer()
moves = BFS(startState,goal)
stop = timeit.default_timer()
if method==2:
start = timeit.default_timer()
moves = DFS(startState,goal)
stop = timeit.default_timer()
if method==3:
start = timeit.default_timer()
moves = A_star(startState,goal)
stop = timeit.default_timer()
print("Moves are:")
for num in range(0,len(moves)):
displayBoard(moves[num].board)
print("Cost of path is: %d" %moves[len(moves)-1].depth)
print("Depth of path is: %d" %moves[len(moves)-1].depth)
print("Number of nodes expanded is: %d "%(nodes_Expanded+1))
print ("Running time is: %d s" %(stop - start ))
if __name__ == "__main__":
main() |
6ea073999482bceaf7bbd23336bbd8bf6379f288 | DanLesman/euler | /p4.py | 323 | 3.8125 | 4 | def is_palindrome(n):
for k in range (1,len(str(n))/2+1):
if str(n)[k-1] is not str(n)[len(str(n))-k]:
return False
return True
largest_palindrome = 0
for i in range (100,1000):
for j in range (100,1000):
if is_palindrome(i*j) and i*j > largest_palindrome:
largest_palindrome = i*j
print (largest_palindrome) |
6ed262c90acd762b453335f6b558d55a7fa39566 | alectar/Study_Python | /WORKDIR/Calc_1.py | 475 | 3.765625 | 4 | #! Python3
import sys
A = int(sys.argv[1])
B = int(sys.argv[3])
Opr = sys.argv[2]
print(str(A) + ' and '+ str(B))
if Opr == '+':
print (str(A) + ' ' + Opr + ' ' + str(B) + ' = ' + str(A+B))
elif Opr == '-':
print(str(A) + ' ' + Opr + ' ' + str(B) + ' = ' + str(A-B))
elif (Opr == 'x') or (Opr == '*'):
print(str(A) + ' * ' + str(B) + ' = ' + str(A*B))
elif (Opr == '/'):
print(str(A) + ' ' + Opr + ' ' + str(B) + ' = ' + str(A/B))
else:
print('ERROR )=') |
10f40c4a02e45a8e36f03458a4d27882aaaa16e3 | NoSuchThingAsRandom/Arcade-Games | /Snake/Snake.py | 6,400 | 3.734375 | 4 | import random
import time
import pygame
def play(increase_speed):
# Colours
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# Dimensions
rows = 25
columns = 25
cell_width = 20
cell_height = 20
offset_height = 0.1
offset_width = 0.05
width = int(columns * cell_width * (1 + offset_width))
height = int(rows * cell_height * (1 + offset_height))
size = (width, height)
grid = [x[:] for x in [[""] * columns] * rows]
# Snake
length = 1
bearing = "N"
preserve_tail = False
headx = int(columns / 2)
heady = int(rows / 2)
tailx = int(columns / 2)
taily = int(rows / 2)
grid[headx][heady] = "H"
# Food
foodx = random.randint(0, rows - 1)
foody = random.randint(0, columns - 1)
grid[foodx][foody] = "F"
# User Options
"""
print("Please select your difficulty:")
print("Easy (E)")
print("Medium (M)")
print("Hard (H)")
diff = "M"
if diff == "E":
speed = 1
elif diff == "M":
speed = 5
elif diff == "H":
speed = 10
else:
speed = 5
"""
if increase_speed:
speed=5
else:
speed = 10
# Scoring
score = 0
previous_time = time.time()
# Pygame Setup
pygame.init()
pygame.font.init()
font = pygame.font.SysFont('Comic Sans MS', 15)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Snake")
finished = False
clock = pygame.time.Clock()
start = time.time()
start_game = False
while not finished:
# User Input
while not start_game:
text_start = font.render(
"Press any key to start", False, RED)
screen.blit(text_start, (int(width * 0.5 * offset_width), 0))
pygame.draw.rect(screen, WHITE, [int(width * 0.5 * offset_width), int(
height * 0.5 * offset_height), (columns * cell_width), (rows * cell_height)])
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
start_game = True
for event in pygame.event.get():
if event.type == pygame.QUIT:
finished = True
continue
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
bearing = "N"
if event.key == pygame.K_DOWN:
bearing = "S"
if event.key == pygame.K_LEFT:
bearing = "W"
if event.key == pygame.K_RIGHT:
bearing = "E"
# GRID
# Moves head
grid[headx][heady] = bearing
if bearing == "N":
heady -= 1
elif bearing == "E":
headx += 1
elif bearing == "S":
heady += 1
elif bearing == "W":
headx -= 1
if headx >= rows or headx < 0 or heady >= columns or heady < 0:
print("Out of grid!")
finished = True
continue
if grid[headx][heady] != "":
if grid[headx][heady] != "F":
finished = True
continue
grid[headx][heady] = "H"
# Detects food
if (headx == foodx) and (heady == foody):
time_scored = time.time()
score += round((100 * ((time_scored - previous_time) ** -0.8) + 1), None)
# print(str(round((time_scored - previous_time), 2)) + " : " + str(
# round((100 * ((time_scored - previous_time) ** -0.8) + 1), None)))
previous_time = time_scored
length += 1
preserve_tail = True
while grid[foodx][foody] != "":
foodx = random.randint(0, rows - 1)
foody = random.randint(0, columns - 1)
grid[foodx][foody] = "F"
if increase_speed:
speed+=2
if preserve_tail:
preserve_tail = False
else:
tail_bearing = grid[tailx][taily]
grid[tailx][taily] = ""
if tail_bearing == "N":
taily -= 1
elif tail_bearing == "E":
tailx += 1
elif tail_bearing == "S":
taily += 1
elif tail_bearing == "W":
tailx -= 1
# GRAPHICS
screen.fill(BLACK)
# Draws Map
# Text
display = "Score: " + str(score) + " Length: " + str(length) + " Time: +" + str(
round((time.time() - start), 2))+" Speed: "+str(speed)
textsurface = font.render(
display, False, WHITE)
screen.blit(textsurface, (int(width * 0.5 * offset_width), 0))
pygame.draw.rect(screen, WHITE, [int(width * 0.5 * offset_width), int(
height * 0.5 * offset_height), (columns * cell_width), (rows * cell_height)])
# rect[x,y,width,heigth]
# Draws Grid
for x in range(0, columns):
for y in range(0, rows):
if grid[x][y] != "":
if grid[x][y] == "F": # Food
pygame.draw.rect(screen, RED, [int(width * 0.5 * offset_width + (x * cell_width)), int(
height * 0.5 * offset_height + (y * cell_height)), cell_width, cell_height])
elif grid[x][y] == "H": # Food
pygame.draw.rect(screen, BLUE, [int(width * 0.5 * offset_width + (x * cell_width)), int(
height * 0.5 * offset_height + (y * cell_height)), cell_width, cell_height])
else: # Snake
pygame.draw.rect(screen, GREEN, [int(width * 0.5 * offset_width + (x * cell_width)), int(
height * 0.5 * offset_height + (y * cell_height)), cell_width, cell_height])
# Updates
pygame.display.flip()
clock.tick(speed)
pygame.display.quit()
pygame.quit()
print("\n"*3)
print("Score: " + str(score) + "\nLength: " + str(length) + "\nTime: +" + str(
round((time.time() - start), 2)) + "\nSpeed: " + str(speed))
return [str(score), str(length), str(round((time.time() - start), 2)), str(speed)]
# play()
def standard():
return play(False)
def speed():
return play(True)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.