blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
6ab32412fd38d034e07222b198ab45e80ff4e10c | pondycrane/algorithms | /python/tree/convert_sorted_array_to_binary_search_tree.py | 1,089 | 4.09375 | 4 | import collections
import typing
import base.solution
from lib.ds_collections.treenode import TreeNode
class Solution(base.solution.Solution):
def convert_sorted_array_to_binary_search_tree(self, nums: typing.List[int]) -> TreeNode:
if not nums: return None
def dfs(l, r):
if l > r: return None
mid = (r - l) // 2 + l
root = TreeNode(nums[mid])
root.left = dfs(l, mid - 1)
root.right = dfs(mid + 1, r)
return root
return dfs(0, len(nums) - 1)
"""
108. Convert Sorted Array to Binary Search Tree
Easy
2342
208
Add to List
Share
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example:
Given the sorted array: [-10,-3,0,5,9],
One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
0
/ \
-3 9
/ /
-10 5
"""
|
d529d539a406b7b4ac25a123554e3582ed53847e | Zemke/euler100 | /20.py | 189 | 3.8125 | 4 | #!/usr/bin/env python
def fact(n):
product = 1
while n > 0:
product *= n
n -= 1
return product
fact10 = fact(100)
summ = sum([int(i) for i in str(fact10)])
print(summ)
|
e40dc758e1bbc7da9545da627703262cdf179b11 | jdanray/leetcode | /reverse.py | 395 | 3.515625 | 4 | # https://leetcode.com/problems/reverse-integer/
class Solution(object):
def reverse(self, x):
neg = False
if x < 0:
neg = True
x = -x
p = -1
y = x
while y > 0:
p += 1
y //= 10
p = 10 ** p
r = 0
while x > 0:
d = x % 10
r += (d * p)
p //= 10
x //= 10
if neg:
r = -r
lim = 2 ** 31
if r < -lim or r > lim - 1:
return 0
else:
return r
|
14c940a9f124d6ca2b2e355e2c0db8e266a613fe | aCatasaurus/ProjectEuler | /p4/four.py | 913 | 4.25 | 4 | #!/usr/bin/env python3
# Find the largest palindrome made from the product of two 3-digit numbers.
# brute force method
def is_palindrome(num):
s = str(num)
for i in range(0, len(s) // 2):
if s[i] != s[-i - 1]:
return False
return True
def palindromes(digits, base=10):
t = 0
for a in reversed(range(base**(digits - 1), base**digits)):
if a < t:
break
for b in reversed(range(base**(digits - 1), base**digits)):
if is_palindrome(a * b):
t = b
yield a, b
break
def largest_palindrome(digits, base=10):
return max(palindromes(digits, base), key=lambda pair: pair[0] * pair[1])
# end brute force method
def p(digits, base=10):
a = [base - 1] * digits
b = [base - 1] * digits
if __name__ == '__main__':
a, b = largest_palindrome(3)
print(a, '*', b, '=', a * b)
|
d9c42d7f5b0f0c81b0780e72c225583c495057d8 | samer2point0/uni | /FOC/exc1/part1.py | 1,043 | 4 | 4 | """This module should filter and sort uk phone numbers from the text file provided. """
import re
def isValid(num): #returns true if the passed number starts with 44 and has 12 numbers
if len(num)==12 and num[:2]=='44':
return True
else:
return False
def formatNum(num): #transform number formats from 44XXXXXXXXXX => 0XXXX XXXXXX
return '0'+num[2:6]+' '+num[6:]
if __name__ == "__main__":
#file read
nF= open('phone_log.txt','r')
log=nF.read()
nF.close()
#use regex to remove alphabet characters and spaces
regEx=re.compile(r'[a-z]+|[\s]+',re.I)
log=regEx.sub( '', log)
#given every numbr starts with + split the numbers on +
nList=log.split('+')
validList=[]
#going through the nList and creating a new list (validList) with only valid numbers with the right format
for num in nList:
if isValid(num):
validList.append(formatNum(num))
#sort the list and print numbers
validList.sort()
for num in validList:
print(num)
|
f2c028622728491d34467fb3ac4c1c445627b0f3 | gsahinpi/pythodmidterm2 | /triangle.py | 989 | 3.859375 | 4 | import turtle
def drawTriangle(points,color,turtle):
turtle.up()
turtle.goto(points[0][0],points[0][1])
turtle.down()
turtle.goto(points[1][0],points[1][1])
turtle.goto(points[2][0],points[2][1])
turtle.goto(points[0][0],points[0][1])
def midpoint(p1,p2):
return [(p1[0]+p2[0])/2,(p1[1]+p2[1])/2]
def serp(points,degree,turtle):
drawTriangle(points,"",turtle)
if degree>0:
newpoints1=[points[0],midpoint(points[0],points[1]),midpoint(points[0],points[2])]
serp(newpoints1,degree-1,turtle)
newpoints2=[points[1],midpoint(points[1],points[0]),midpoint(points[1],points[2])]
serp(newpoints2,degree-1,turtle)
newpoints3=[points[2],midpoint(points[2],points[0]),midpoint(points[2],points[1])]
serp(newpoints3,degree-1,turtle)
myTurtle = turtle.Turtle()
myWin = turtle.Screen()
myPoints = [[-200,-100],[0,200],[200,-100]]
#drawTriangle(myPoints,"blue",myTurtle)
serp(myPoints,5,myTurtle)
myWin.exitonclick()
|
c5b844a832b38508b90382daed280756dda9b0d9 | pyKis/GeekB | /Lesson-2/Lesson-2 task-2.py | 594 | 3.609375 | 4 | def get_sign(x):
if x[0] in '+-':
return x[0]
my_list = ['в', '5', 'часов', '17', 'минут', 'температура', 'воздуха', 'была', '+5', 'градусов']
i = 0
while i < len(my_list):
sign = get_sign(my_list[i])
if my_list[i].isdigit() or (sign and my_list[i][1:].isdigit()):
if sign:
my_list[i] = sign + my_list[i][1:].zfill(2)
else:
my_list[i] = my_list[i].zfill(2)
my_list.insert(i, '"')
my_list.insert(i + 2, '"')
i += 2
i += 1
print(my_list)
|
5dcded01ded23fc00547ef6a6a5cac3392b7dbde | akash1601/algorithms_leetcode_solution | /solutions/numberOfIslands.py | 499 | 3.609375 | 4 | def numberOfIslands(nums):
count = 0
for i in range(len(nums)):
for j in range(len(nums[0])):
if nums[i][i] == '1':
self.dfs(nums, i, j)
count += 1
return count
def dfs(self, nums, i, j):
if i < 0 or j < 0 or i >= len(nums) or j >= len(nums[0]) or nums[i][j] != '1':
return
nums[i][j] = '#'
self.dfs(nums, i+1, j)
self.dfs(nums, i-1, j)
self.dfs(nums, i, j+1)
self.dfs(nums, i, j-1)
numberOfIslands([1,1,1,1,1,1],
[1,1,1,0,0,0],
[1,1,1,1,0,0],
[1,1,1,1,1,1])
|
1f55d7e64f1dbcab01c7534e67b36d0033b1ae6d | rrkas/Exercism-Python | /29_meetup/meetup.py | 825 | 4 | 4 | import calendar
from datetime import date
class MeetupDayException(Exception):
pass
def meetup(year: int, month: int, week: str, day_of_week: str) -> date:
cal: calendar.Calendar = calendar.Calendar()
# all those days in month
matching_days: list[date] = [d for w in cal.monthdatescalendar(year, month) for d in w
if d.month == month and d.weekday() == list(calendar.day_name).index(day_of_week)]
if week.endswith("teenth"):
return [d for d in matching_days if 13 <= d.day <= 19][0]
elif week == "last":
return matching_days[-1]
elif week[0].isdigit() and int(week[0]) <= len(matching_days):
return matching_days[int(week[0]) - 1]
else:
raise MeetupDayException("No match found")
print(meetup(2013, 5, "teenth", "Monday")) |
e58dadc4bcbaa0bd49978a936f08702fd2ad9f2b | stefanGT44/Math-Expression-Interpreter | /lexer.py | 8,942 | 3.9375 | 4 | INTEGER, PLUS, MINUS, MUL, DIV, EOF, LEFT, RIGHT, LOG, SIN, COS, TAN, CTG, SQRT, POW, COMMA, GREATER, LESS\
, GREATER_E, LESS_E, EQUALS, EQUALS_I, EQUALS_NOT, VAR, D_VAR, FLOAT, TRUE, FALSE = (
'INTEGER', 'PLUS', 'MINUS', 'MUL', 'DIV', 'EOF', 'LEFT', 'RIGHT',
'LOG', 'SIN', 'COS', 'TAN', 'CTG', 'SQRT', 'POW', ',', '>', '<',
'>=', '<=', '=', '==', '!=', 'VAR', 'D_VAR', 'FLOAT', 'True', 'False'
)
class Token(object):
def __init__(self, type, value):
# token type: INTEGER, PLUS, MINUS, MUL, DIV, or EOF
self.type = type
# token value: non-negative integer value, '+', '-', '*', '/', or None
self.value = value
def __str__(self):
"""String representation of the class instance.
Examples:
Token(INTEGER, 3)
Token(PLUS, '+')
Token(MUL, '*')
"""
return 'Token({type}, {value})'.format(
type=self.type,
value=repr(self.value)
)
def __repr__(self):
return self.__str__()
class Lexer(object):
def __init__(self, text):
# client string input, e.g. "3 * 5", "12 / 3 * 4", etc
self.text = text
# self.pos is an index into self.text
self.pos = 0
self.current_char = self.text[self.pos]
def error(self):
raise Exception('Invalid character')
def advance(self):
"""Advance the `pos` pointer and set the `current_char` variable."""
self.pos += 1
if self.pos > len(self.text) - 1:
self.current_char = None # Indicates end of input
else:
self.current_char = self.text[self.pos]
def skip_whitespace(self):
while self.current_char is not None and self.current_char.isspace():
self.advance()
def integer(self):
"""Return a (multidigit) integer consumed from the input."""
result = ''
while self.current_char is not None and self.current_char.isdigit():
result += self.current_char
self.advance()
if self.current_char == '.':
result += '.'
self.advance()
while self.current_char is not None and self.current_char.isdigit():
result += self.current_char
self.advance()
db = float(result)
return round(db, 3)
else:
return int(result)
def getFunToken(self, fun, length):
i = 0;
result = ''
while (i<length):
result += self.current_char
self.advance()
i+=1
if fun == 'C':
if result.upper() == 'COS' or result.upper() == 'CTG':
return result.upper()
else:
self.error()
return 0
if fun == 'S':
if result.upper() == 'SIN':
return result.upper()
elif result.upper() == 'SQR':
result += self.current_char
self.advance()
if result.upper() == 'SQRT':
return result.upper();
else:
return 0
else:
return 0
if result.upper() == fun:
return fun
else:
self.error()
return 0
def getIdentityToken(self, identity):
if self.pos + 1 < len(self.text):
self.advance()
if self.current_char == '=':
return identity+'='
else:
return identity
else:
return 0
def getVar(self):
startPos = self.pos
tempPos = 0
result = ''
test = 0
while self.current_char!=None and self.current_char.isalpha():
result += self.current_char
self.advance()
tempPos = self.pos
self.skip_whitespace()
if self.current_char == '=':
test += 1
self.advance()
self.skip_whitespace()
if self.current_char == '=':
test += 1
if test == 1:
return result+'='
elif test == 0:
if result.upper() in ('SIN', 'COS', 'CTG', 'TAN', 'LOG', 'SQRT', 'POW') and self.current_char == '(':
self.pos = startPos
self.current_char = self.text[self.pos]
return 0
else:
return result
elif test == 2:
self.pos = tempPos
self.current_char = self.text[self.pos]
return result
def get_next_token(self):
"""Lexical analyzer (also known as scanner or tokenizer)
This method is responsible for breaking a sentence
apart into tokens. One token at a time.
"""
while self.current_char is not None:
if self.current_char.isspace():
self.skip_whitespace()
continue
if self.current_char.isdigit():
test = self.integer()
if isinstance(test, int):
return Token(INTEGER, test)
elif isinstance(test, float):
return Token(FLOAT, test)
if self.current_char == '+':
self.advance()
return Token(PLUS, '+')
if self.current_char == '-':
self.advance()
return Token(MINUS, '-')
if self.current_char == '*':
self.advance()
return Token(MUL, '*')
if self.current_char == '/':
self.advance()
return Token(DIV, '/')
if self.current_char == '(':
self.advance()
return Token(LEFT, '(')
if self.current_char == ')':
self.advance()
return Token(RIGHT, ')')
if self.current_char == '>':
result = self.getIdentityToken('>')
if result == '>':
return Token(GREATER, '>')
elif result == '>=':
self.advance()
return Token(GREATER_E, '>=')
if self.current_char == '<':
result = self.getIdentityToken('<')
if result == '<':
return Token(LESS, '<')
elif result == '<=':
self.advance()
return Token(LESS_E, '>=')
if self.current_char != None and self.current_char.isalpha():
result = self.getVar()
if result != 0 and result[len(result)-1] == '=':
result = result[:len(result)-1]
return Token(D_VAR, result)
elif result != 0:
if result == 'True':
return Token(TRUE, 'True')
elif result == 'False':
return Token(FALSE, 'False')
else:
return Token(VAR, result)
if self.current_char == 'L' or self.current_char == 'l':
return Token(LOG, self.getFunToken('LOG', 3))
if self.current_char == 'S' or self.current_char =='s':
result = self.getFunToken('S', 3)
if result == 'SIN':
return Token(SIN, result)
else:
return Token(SQRT, result)
if self.current_char == 'C' or self.current_char == 'c':
result = self.getFunToken('C', 3)
if result == 'COS':
return Token(COS, result)
else:
return Token(CTG, result)
if self.current_char == 'T' or self.current_char == 't':
return Token(TAN, self.getFunToken('TAN', 3))
if self.current_char == ',':
self.advance()
return Token(COMMA, ',')
if self.current_char == 'P' or self.current_char == 'p':
return Token(POW, self.getFunToken('POW', 3))
if self.current_char == '=':
self.advance()
if self.current_char == '=':
self.advance()
return Token(EQUALS_I, '==')
else:
return Token(EQUALS, '=')
if self.current_char == '!':
self.advance()
if self.current_char == '=':
self.advance()
return Token(EQUALS_NOT, '!=')
else:
self.error()
self.error()
return Token(EOF, None) |
f9535f2853f7d7de41d61d24984692141c40d0e4 | prtk94/cec-rest-api | /test.py | 500 | 3.5625 | 4 | import pandas as pd
import numpy as np
months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
year_data= []
for i in months:
print(f"reading excel for solar data in month {i}")
month_df = pd.read_excel(f"Datasets/Solar {i}.xlsx")
print(f"file read: Datasets/Solar {i}.xlsx")
month_df.set_index('Unnamed: 0',inplace=True)
solar_data = month_df[136.05].iloc[6]
print(f"fetched data => {solar_data}")
year_data.append(solar_data)
print("full data:")
print(year_data)
|
dbc38bb54f545d7f17a2b55b14d6ec397257ea24 | here0009/LeetCode | /Python/726_NumberofAtoms.py | 5,294 | 4.4375 | 4 | """
Given a chemical formula (given as a string), return the count of each atom.
The atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name.
One or more digits representing that element's count may follow if the count is greater than 1. If the count is 1, no digits will follow. For example, H2O and H2O2 are possible, but H1O2 is impossible.
Two formulas concatenated together to produce another formula. For example, H2O2He3Mg4 is also a formula.
A formula placed in parentheses, and a count (optionally added) is also a formula. For example, (H2O2) and (H2O2)3 are formulas.
Given a formula, return the count of all elements as a string in the following form: the first name (in sorted order), followed by its count (if that count is more than 1), followed by the second name (in sorted order), followed by its count (if that count is more than 1), and so on.
Example 1:
Input: formula = "H2O"
Output: "H2O"
Explanation: The count of elements are {'H': 2, 'O': 1}.
Example 2:
Input: formula = "Mg(OH)2"
Output: "H2MgO2"
Explanation: The count of elements are {'H': 2, 'Mg': 1, 'O': 2}.
Example 3:
Input: formula = "K4(ON(SO3)2)2"
Output: "K4N2O14S4"
Explanation: The count of elements are {'K': 4, 'N': 2, 'O': 14, 'S': 4}.
Example 4:
Input: formula = "Be32"
Output: "Be32"
Constraints:
1 <= formula.length <= 1000
formula consists of English letters, digits, '(', and ')'.
formula is always valid.
"""
class Solution:
def countOfAtoms(self, formula: str) -> str:
index = 0
length = len(formula)
formula += '$'
tmp, d = '', ''
res = []
while index < length:
s = formula[index]
print(index, formula[index])
index += 1
if s.isdigit():
d += s
if formula[index].isdigit():
continue
else:
res.append(tmp+d)
if s == '(':
left = index
p = 1
while index < length:
if formula[index] == ')':
p -= 1
elif formula[index] == '(':
p += 1
if p == 0:
break
index += 1
lst = self.countOfAtoms(formula[left:index])
res.extend(x+d for x in lst)
index += 1 # skip ')'
elif s.isalpha():
tmp += s
if formula[index].islower() or formula[index].isdigit():
continue
else:
res.append(tmp+d)
tmp, d = '', ''
print(formula, res)
return res
from collections import Counter
class Solution:
def countOfAtoms(self, formula: str) -> str:
def format_formula(formula):
index = 0
length = len(formula)
formula += '$'
f_formula = '' # add 1 to the end of elment
while index < length:
s = formula[index]
f_formula += s
index += 1
if (s.isalpha() or s == ')') and not (formula[index].isdigit() or formula[index].islower()):
f_formula += '1'
return f_formula
def unpack(formula):
length = len(formula)
formula += '$'
tmp, d = '', ''
res = []
lst = []
index = 0
while index < length:
s = formula[index]
index += 1
if s.isdigit():
d += s
if formula[index].isdigit():
continue
else:
d = int(d)
if tmp:
res.append((tmp,d))
tmp, d = '', ''
elif lst:
res.extend((x, c*d) for x,c in lst)
lst, d = [], ''
if s == '(':
left = index
p = 1
while index < length:
if formula[index] == ')':
p -= 1
elif formula[index] == '(':
p += 1
if p == 0:
break
index += 1
lst = unpack(formula[left:index])
index += 1 # skip ')'
elif s.isalpha():
tmp += s
return res
f_formula = format_formula(formula)
res = unpack(f_formula)
counts = Counter()
for k,v in res:
counts[k] += v
keys = sorted(counts.keys())
res_string = ''
for key in keys:
v = counts[key]
res_string += key
if v > 1:
res_string += str(v)
return res_string
S = Solution()
formula = "H2O"
print(S.countOfAtoms(formula))
formula = "Mg(OH)2"
print(S.countOfAtoms(formula))
formula = "K4(ON(SO3)2)2"
print(S.countOfAtoms(formula))
formula = "Be32"
print(S.countOfAtoms(formula))
|
a3ece277966e38c0de5d242c8115d8e2ba870c48 | saigono/leetcode | /981.time_based_key_value_store.py | 836 | 3.546875 | 4 | # https://leetcode.com/problems/time-based-key-value-store/
from bisect import bisect
from collections import defaultdict
class TimeMap:
def __init__(self):
"""
Initialize your data structure here.
"""
self._timestamps = defaultdict(list)
self._data = defaultdict(list)
def set(self, key: str, value: str, timestamp: int) -> None:
self._timestamps[key].append(timestamp)
self._data[key].append(value)
def get(self, key: str, timestamp: int) -> str:
idx = bisect(self._timestamps[key], timestamp) - 1
if idx < 0:
return ''
else:
return self._data[key][idx]
# Your TimeMap object will be instantiated and called as such:
# obj = TimeMap()
# obj.set(key,value,timestamp)
# param_2 = obj.get(key,timestamp)
|
f794b2aca859f63da22f2f57851e98689a237acf | Ethan0507/Algorithmic-Toolbox | /week1_programming_challenges/3_16_diagonals/16-diagonals.py | 2,242 | 3.703125 | 4 | def check_up(grid,index,n):
up_ele = grid[index - n]
if up_ele != '_':
return grid[index] == up_ele
else:
return True
def check_up_left(grid, index, n):
up_left_ele = grid[index - (n + 1)]
if up_left_ele != '_':
return grid[index] != up_left_ele
else:
return True
def check_up_right(grid, index, n):
up_right_ele = grid[index - (n - 1)]
if up_right_ele != '_':
return grid[index] != up_right_ele
else:
return True
def check_left(grid, index):
left_ele = grid[index - 1]
if left_ele != '_':
return grid[index] == left_ele
else:
return True
def check_if_conflict_does_not_exist(grid, n):
index = len(grid) - 1
if len(grid) == 1 or grid[index] == '_':
return True
if int(index / n) != 0:
if index % n == 0:
if grid[index] == '/':
return check_up(grid, index, n) and check_up_right(grid, index, n)
else:
return check_up(grid, index, n)
elif index % n == (n - 1):
if grid[index] == '/':
return (check_up(grid, index, n) and check_left(grid, index))
else:
return (check_up(grid, index, n) and check_up_left(grid, index, n) and check_left(grid, index))
elif 0 < index % n < (n - 1):
if grid[index] == '/':
return (check_up(grid, index, n) and check_up_right(grid, index, n) and check_left(grid, index))
else:
return (check_up(grid, index, n) and check_up_left(grid, index, n) and check_left(grid, index))
else:
return check_left(grid, index)
def extend_grid(grid, n, m):
if len(grid) == n * n:
if grid.count("/") + grid.count("\\") == m:
print(grid)
for i in range(n):
grid_str = ''
for j in range(n):
grid_str += grid[n * i + j]
print(grid_str)
return
else:
return
for k in ['/', '\\', '_']:
grid.append(k)
if check_if_conflict_does_not_exist(grid, n):
extend_grid(grid, n, m)
grid.pop()
extend_grid([], 4, 10) |
3351169269a91ac145037e008260591bb4718a8a | michaelhuang/LintCode_Python | /Flip_Bits.py | 397 | 3.796875 | 4 | import ctypes
class Solution:
"""
@param a, b: Two integer
return: An integer
"""
def bitSwapRequired(self, a, b):
c = ctypes.c_uint32(a ^ b).value # both a and b are 32-bit integers
count = 0
while c:
c &= c - 1
count += 1
return count
if __name__ == '__main__':
a = Solution()
print a.bitSwapRequired(1, -1)
|
61dcdb00b9ac69a04567bcb083d03c1f93c0ac49 | alphaf52/document-qa | /docqa/data_processing/span_data.py | 7,647 | 3.703125 | 4 | from typing import List
import numpy as np
from docqa.data_processing.qa_training_data import Answer
"""
Utility methods for dealing with span data, and span question answers
"""
def span_len(span):
return span[1] - span[0] + 1
def span_f1(true_span, pred_span):
start = max(true_span[0], pred_span[0])
stop = min(true_span[1], pred_span[1])
if start > stop:
return 0
overlap_len = span_len((start, stop))
p = overlap_len / span_len(pred_span)
r = overlap_len / span_len(true_span)
return 2 * p * r / (p + r)
def get_best_span(word_start_probs, word_end_probs):
max_val = -1
best_word_span = None
span_start = -1
span_start_val = -1
for word_ix in range(0, len(word_start_probs)):
# Move `span_start` forward iff that would improve our score
# Thus span_start will always be the largest valued start between
# [0, `word_ix`]
if span_start_val < word_start_probs[word_ix]:
span_start_val = word_start_probs[word_ix]
span_start = word_ix
# Check if the new span is the best one yet
if span_start_val * word_end_probs[word_ix] > max_val:
best_word_span = (span_start, word_ix)
max_val = span_start_val * word_end_probs[word_ix]
return best_word_span, max_val
def get_best_span_bounded(word_start_probs, word_end_probs, bound):
max_val = -1
best_word_span = None
span_start = -1
span_start_val = -1
for word_ix in range(0, len(word_start_probs)):
# Move `span_start` forward iff that would improve our score
if span_start_val < word_start_probs[word_ix]:
span_start_val = word_start_probs[word_ix]
span_start = word_ix
# Jump to the next largest span start iff we reach the boundary limit
if (word_ix - span_start + 1) > bound:
span_start += 1 + np.argmax(word_start_probs[span_start+1:word_ix+1])
span_start_val = word_start_probs[span_start]
# Check if the new span is the best one yet
if span_start_val * word_end_probs[word_ix] > max_val:
best_word_span = (span_start, word_ix)
max_val = span_start_val * word_end_probs[word_ix]
return best_word_span, max_val
def get_best_in_sentence_span(start_probs, end_probs, sent_lens):
max_val = -1
best_word_span = None
span_start = 0
span_start_val = start_probs[0]
on_sent = 0
sent_end = sent_lens[0]
for word_ix in range(0, len(start_probs)):
if word_ix == sent_end:
# reached the start of the next sentence, reset the span_start pointer
on_sent += 1
if on_sent >= len(sent_lens):
break
sent_end += sent_lens[on_sent]
span_start = word_ix
span_start_val = start_probs[word_ix]
else:
if span_start_val < start_probs[word_ix]:
span_start_val = start_probs[word_ix]
span_start = word_ix
# Check if the new span is the best one yet
if span_start_val * end_probs[word_ix] > max_val:
best_word_span = (span_start, word_ix)
max_val = span_start_val * end_probs[word_ix]
return best_word_span, max_val
def get_best_span_from_sent_predictions(per_sent_start_pred, per_sent_end_pred, sent_lens):
max_val = -1
best_word_span = None
word_offset = 0
# Min in case the the # of sentences was truncated
for sent_ix in range(min(len(sent_lens), len(per_sent_start_pred))):
sent_len = sent_lens[sent_ix]
start_pred = per_sent_start_pred[sent_ix]
end_pred = per_sent_end_pred[sent_ix]
span_start = 0
span_start_val = start_pred[0]
# Min in case the # of sentence predictions was truncated
for word_ix in range(0, min(sent_len, len(start_pred))):
if span_start_val < start_pred[word_ix]:
span_start_val = start_pred[word_ix]
span_start = word_ix
if span_start_val * end_pred[word_ix] > max_val:
best_word_span = (word_offset + span_start, word_offset + word_ix)
max_val = span_start_val * end_pred[word_ix]
word_offset += sent_len
return best_word_span, max_val
def top_disjoint_spans(span_scores, bound: int, n_spans: int, spans):
"""
Given a n_token x n_tokens matrix of spans scores, return the top-n non-overlapping spans
and their scores
"""
sorted_ux = np.argsort(span_scores.ravel())[::-1]
sorted_ux = np.stack([sorted_ux // len(span_scores), sorted_ux % len(span_scores)], axis=1)
lens = sorted_ux[:, 1] - sorted_ux[:, 0]
sorted_ux = sorted_ux[np.logical_and(lens >= 0, lens < bound)]
cur_scores = np.zeros(n_spans, dtype=np.float32)
cur_spans = np.zeros((n_spans, 2), dtype=np.int32)
spans_found = 0
for s, e in sorted_ux:
# the span must either start after or end before each existing spans
if np.all(np.logical_or(cur_spans[:spans_found, 0] > e, cur_spans[:spans_found, 1] < s)):
if spans[s][0] < spans[e][1]: # Don't select zero length spans
cur_spans[spans_found, 0] = s
cur_spans[spans_found, 1] = e
cur_scores[spans_found] = span_scores[s, e]
spans_found += 1
if spans_found == n_spans:
break
return cur_spans[:spans_found], cur_scores[:spans_found]
def compute_span_f1(true_span, pred_span):
start = max(true_span[0], pred_span[0])
stop = min(true_span[1], pred_span[1])
if start > stop:
return 0
overlap_len = span_len((start, stop))
p = overlap_len / span_len(pred_span)
r = overlap_len / span_len(true_span)
return 2 * p * r / (p + r)
class ParagraphSpan(object):
def __init__(self,
sent_start: int, word_start: int, char_start: int,
sent_end: int, word_end: int, char_end: int,
para_word_start: int, para_word_end: int,
text: str):
self.sent_start = sent_start
self.word_start = word_start
self.char_start = char_start
self.sent_end = sent_end
self.word_end = word_end
self.char_end = char_end
self.para_word_start = para_word_start
self.para_word_end = para_word_end # inclusive
self.text = text
def as_tuple(self):
return self.sent_start, self.word_start, self.char_start, self.sent_end, \
self.word_end, self.char_end, self.para_word_start, self.para_word_end, self.text
class ParagraphSpans(Answer):
def __init__(self, spans: List[ParagraphSpan]):
self.spans = spans
def get_vocab(self):
return []
def __getitem__(self, item):
return self.spans[item]
def __iter__(self):
return iter(self.spans)
def __len__(self) -> int:
return len(self.spans)
@property
def answer_text(self):
return [x.text for x in self.spans]
@property
def answer_spans(self):
return np.array([(x.para_word_start, x.para_word_end) for x in self.spans])
class TokenSpans(Answer):
__slots__ = ["answer_text", "answer_spans"]
def __init__(self, answer_text: List[str], answer_spans: np.ndarray):
"""
:param answer_text: list of text answers
:param answer_spans: (n, 2) array of inclusive (start, end) occurrences of an answer
"""
self.answer_text = answer_text
self.answer_spans = answer_spans
def get_vocab(self):
return []
|
ef890521122c285a618371657d37da6cbe5344eb | Aasthaengg/IBMdataset | /Python_codes/p02723/s209599494.py | 99 | 3.53125 | 4 | import sys
s = input().strip()
if s[2] == s[3] and s[4] == s[5]:
print("Yes")
else : print("No") |
5ab518a635636197d60d67aa4cb562e5c060f7b8 | Lawrence-tng/Sudoku-Solver | /Solver.py | 5,268 | 3.578125 | 4 | import pygame
import time
pygame.font.init()
board = [
[7, 8, 0, 4, 0, 0, 1, 2, 0],
[6, 0, 0, 0, 7, 5, 0, 0, 9],
[0, 0, 0, 6, 0, 1, 0, 7, 8],
[0, 0, 7, 0, 4, 0, 2, 6, 0],
[0, 0, 1, 0, 5, 0, 9, 3, 0],
[9, 0, 4, 0, 6, 0, 0, 0, 5],
[0, 7, 0, 3, 0, 0, 0, 1, 2],
[1, 2, 0, 0, 0, 7, 4, 0, 0],
[0, 4, 9, 2, 0, 6, 0, 0, 7],
]
def solve(bo):
find = find_empty(bo)
if not find:
return True
else:
row, col = find
for i in range(1, 10):
if valid(bo, i, (row, col)):
bo[row][col] = i
if solve(bo):
return True
bo[row][col] = 0
return False
def valid(bo, num, pos):
# check row
for i in range(len(bo[0])):
if bo[pos[0]][i].value == num and pos[1] != i:
return False
# check col
for i in range(len(bo)):
if bo[i][pos[1]].value == num and pos[0] != i:
return False
# check box
box_x = pos[1] // 3
box_y = pos[0] // 3
for i in range(box_y * 3, box_y * 3 + 3):
for j in range(box_x * 3, box_x * 3 + 3):
if bo[i][j].value == num and (i, j) != pos:
return False
return True
def print_board(bo):
for i in range(len(bo)):
if i % 3 == 0 and i != 0:
print("- - - - - - - - - - - - - - ")
for j in range(len(bo[0])):
if j % 3 == 0:
print(" | ", end="")
if j == 8:
print(bo[i][j])
else:
print(str(bo[i][j]) + " ", end="")
def find_empty(bo):
for i in range(9):
for j in range(9):
print(bo[i][j].value)
if bo[i][j].value == 0:
return (i,j) # row, col
return None
board_width = 540
board_height = 540
gap = board_width / 9
pygame.init()
win = pygame.display.set_mode((board_width, board_height))
pygame.display.set_caption("SudokuSolver")
class Grids:
def __init__(self):
self.grids = [[Grid(board[i][j], i, j, ) for j in range(9)] for i in range(9)]
self.win = win
def solve_grids(self):
find = find_empty(self.grids)
if not find:
return True
else:
row, col = find
print(find)
for i in range(1, 10):
if valid(self.grids, i, (row, col)):
self.grids[row][col].value = i
self.grids[row][col].draw_grid(self.win, True)
pygame.display.update()
pygame.time.delay(100)
if self.solve_grids():
return True
self.grids[row][col].value = 0
self.grids[row][col].draw_grid(self.win, False)
pygame.display.update()
pygame.time.delay(100)
return False
class Grid:
def __init__(self, value, row, col):
self.value = value
self.col = col
self.row = row
self.selected = False
def select(self):
pygame.draw.rect(win, (0, 0, 255), (self.col * gap, self.row * gap, gap, gap))
pygame.display.update()
draw_initial_brd()
def unselect(self):
pygame.draw.rect(win, (255, 255, 255), (self.col * gap, self.row * gap, gap, gap))
pygame.display.update()
draw_initial_brd()
def draw_grid(self, win, valid=True):
fnt = pygame.font.SysFont("comicsans", 40)
x = self.col * gap
y = self.row * gap
pygame.draw.rect(win, (255, 255, 255), (x, y, gap, gap), 0)
text = fnt.render(str(self.value), 1, (0, 0, 0))
win.blit(text, (x + (gap / 2 - text.get_width() / 2), y + (gap/2 - text.get_height() / 2)))
if valid:
pygame.draw.rect(win, (0, 255, 0), (x, y, gap, gap), 3)
else:
pygame.draw.rect(win, (255, 0, 0), (x, y, gap, gap), 3)
def draw_initial_brd():
square_length = board_width / 9
for i in range(9):
if i % 3 == 0 and i != 0:
line_size = 4
else:
line_size = 1
pygame.draw.line(win, (0, 0, 0), (0, i * square_length), (board_width, i * square_length), line_size)
pygame.draw.line(win, (0, 0, 0), (i * square_length, 0), (i * square_length, board_height), line_size)
pygame.display.update()
def draw_brd(bo):
fnt = pygame.font.SysFont("comicsans", 40)
space = board_width / 9
for i in range(9):
for j in range(9):
x = i * space
y = j * space
if bo[i][j] != 0:
text = fnt.render(str(bo[i][j]), 1, (0, 0, 0))
win.blit(text, (y + (space / 2 - text.get_height() / 2), x + (space / 2 - text.get_width() / 2)))
#run to start visualier
def main():
win.fill((255, 255, 255))
run = True
while run:
pygame.time.delay(100)
draw_initial_brd()
draw_brd(board)
game_grid = Grids()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
if event.key == pygame.K_SPACE:
game_grid.solve_grids()
pygame.quit()
main()
|
654a82405b581296580c3b8579bd24536c71a357 | jepebe/aoc2018 | /aoc2017/day4.py | 1,330 | 3.8125 | 4 | import itertools
def passphrase_is_valid(line):
words = line.split()
valid_words = []
for word in words:
if word in valid_words:
return False
else:
valid_words.append(word)
return True
def passphrase_is_valid_wo_anagram(line):
words = line.split()
used_words = []
for word in words:
if word in used_words:
return False
else:
perm = itertools.permutations(word, len(word))
perm = [''.join(p) for p in perm]
used_words.extend(perm)
return True
def count(exp):
return len(list(exp))
if __name__ == '__main__':
assert passphrase_is_valid('aa bb cc dd ee')
assert not passphrase_is_valid('aa bb cc dd aa')
assert passphrase_is_valid('aa bb cc dd aaa')
assert passphrase_is_valid_wo_anagram('abcde fghij')
assert not passphrase_is_valid_wo_anagram('abcde xyz ecdab')
assert passphrase_is_valid_wo_anagram('a ab abc abd abf abj')
assert passphrase_is_valid_wo_anagram('iiii oiii ooii oooi oooo')
assert not passphrase_is_valid_wo_anagram('oiii ioii iioi iiio')
with open('day4.txt', 'r') as f:
data = f.read()
lines = data.splitlines()
print(count(line for line in lines if passphrase_is_valid(line)))
print(count(line for line in lines if passphrase_is_valid_wo_anagram(line)))
|
6dd7949f4dc1de5c249f6e99dcb79dee1b8ec86a | anderssv49/python-course-gbg | /extralab/symbolic.py | 2,217 | 3.6875 | 4 | from parse_symbolic import *
#########################################################################
### part 1: derivatives of polynomials and more general expressions #####
#########################################################################
def derivative(exp): # TODO: return the derivative exp of an arbitrary exp
print("cannot differentiate this function yet")
def exp2polynom(exp): # TODO: all the way from Exp to a polynomial
print("cannot convert this function to polynomialyet")
def deriv_polynom(p): # TODO: return the derivative polynomial of p
print("cannot differentiate this polynomial yet")
###############################################
## part 2: printing and parsing expressions ###
###############################################
def show_exp_infix(level,exp): # TODO: infix printing of expressions, minimizing parentheses
return show_exp_prefix(exp) # default behaviour, to be replaced
def show_polynom(p): # TODO printing polynomials: use + or - between terms, ignore 0 terms, 1 coefficients, and * signs
return p # default behaviour, to be replaced
###############################################
## The main function: test with your own input
###############################################
# the main function: input infix expression, show tree, polynomial, 1st and 2nd derivatives, and the graph
def main(): # given, don't change
s = input("enter expression> ")
toks = insert_mul(lex(s))
exp = top_parse(toks)
print("tree:", show_exp_prefix(exp))
print("infix:", show_exp_infix(0,exp))
try:
dert = derivative(exp)
print("derivative:", show_exp_infix(0,dert))
except:
print("derivative not available")
try:
poly = exp2polynom(exp)
print("polynomial:", show_polynom(poly))
der = deriv_polynom(poly)
print("derivative of polynomial:", show_polynom(der))
polydert = exp2polynom(dert)
print("polynomial of derivative:", show_polynom(polydert))
der2 = deriv_polynom(der)
print("second derivative:", show_polynom(der2))
except:
print("polynomial not defined")
show_graph(exp)
if __name__ == "__main__":
main()
|
cc1cc1045ee9e6b42b28f0bcb7fa1a1a6247f285 | charmip09/Python_Training | /TASK2_Range.py | 206 | 3.96875 | 4 | '''
Write a program in Python which will find all such numbers which are divisible
by 7 but are not a multiple of 5, between 2000 and 3200.
'''
print(*[x for x in range(2000, 3201) if not(x%7) and x%5])
|
d2a10980ac0ff133e06916cfd5e9cab29ab8b947 | Chakyllfcu/Pythonprojects | /Unidad 2/Ejercicio 9.py | 497 | 3.796875 | 4 | import math
print("Para hacer una hamburguesa se necesita 1 pan, 2 carnes, 1/5 de libra de tocineta. Calcule cuantas haburguesas se pueden hacer segun la cantidad de estas materias primas que existen en un almacén.")
p = input("Inserte el numero de panes en almacen: ")
c = input("Inserte el numero de carnes en almacen: ")
t = input("Inserte las libras de tocinetas en almacen: ")
hp = int(p)
hc = int(c)/2
ht = int(t)/0.2
h=[hp,hc,ht]
print("Se pueden hacer",math.floor(min(h)),"hamburguesas.") |
c835639ed2b77b529034947ca338752581217d40 | wusanpi825117918/study | /Day01/p_12类型转换.py | 775 | 4.03125 | 4 | '''
类型转换
'''
# 转换成整数类型
print(int(1))
print(int(1.1))
print(int('1'))
# print(int('1.1')) # 转换错误
# print(int('abc')) # 转换错误
# 转换成浮点类型
print(float(1))
print(float(1.1))
print(float('1.1'))
print(float('1'))
# print(float('abc')) # 转换错误
# 转换成字符串类型
print('| ' + str(1) + ' |')
print('| ' + str(1.1) + ' |')
print('| ' + str('1') + ' |')
print('| ' + str('1.1') + ' |')
print('| ' + str('abc') + ' |')
print('| ' + str(True) + ' |')
# chr 函数
# 将一个数字转换成字符
print(chr(48)) # '0'
print(chr(65)) # 'A'
print(chr(97)) # 'a'
# ord 函数
# 转换一个字符转换对应的数字编码
print(ord('0'))
print(ord('A'))
print(ord('a'))
|
836626458194c0c848e7c96f520da5a4e74f47ab | essanhaji/python-3-tp | /exo/trening/2.py | 374 | 4.28125 | 4 |
firstName = str(input("enter your first name :"))
middleName = str(input("enter your middle name :"))
lastName = str(input("enter your last name :"))
firstName = firstName.capitalize()
middleName = middleName.capitalize()
lastName = lastName.capitalize()
fullName = "{first} {middle:.1s} {last}"
print(fullName.format(first=firstName, middle=middleName, last=lastName))
|
539f1f967c50ad7d2e9a59e371ec13685258b421 | itdevline/process_vs_thread | /threadTest.py | 1,092 | 4.1875 | 4 | import random
import threading
"""
*** MULTITHREADING ***
Advantage:
- Shared memory
- low memory usage
- I/O-bound applications (For example: networking)
- Easy UI (user interface) communications
- Access global variables.
Disadvantages:
- Not killable the child threads
- If you have one CPU core then not faster the code.
- Hard debug code.
"""
def list_append(count, id, out_list):
for i in range(count):
out_list.append(random.random())
if __name__ == "__main__":
for xx in range(0, 5):
# thread
size = 3000000
threads = 8 # We will run 8 threads
jobs = [] # We will store all threads in a list.
for i in range(0, threads):
out_list = list()
thread = threading.Thread(target=list_append(size, i, out_list)) # Create a thread object and set the constructor.
jobs.append(thread) # Append threads to list.
for j in jobs:
j.start() # Start all threads
for j in jobs:
j.join() # If we use join, then the main thread will be block.
|
267afbe2b2f792eb06e3dbb88adcc62e962fa31d | Sumitsami14/NAI | /Coding games/Power of Thor.py | 664 | 3.65625 | 4 | #https://www.codingame.com/training/easy/power-of-thor-episode-1
#Dominika Stryjewska s16722
import sys
import math
north= "N"
south = "S"
east = "E"
west = "W"
light_x, light_y, initial_tx, initial_ty = [int(i) for i in input().split()]
while True:
remaining_turns = int(input())
walk = ""
if initial_ty > light_y:
initial_ty -= 1
walk += north
elif initial_ty < light_y:
initial_ty += 1
walk += south
if initial_tx < light_x:
initial_tx += 1
walk += east
elif initial_tx > light_x:
initial_tx -= 1
walk += west
print(walk)
|
171c68799ffe5446a522dc8d32fa8bbcc187f94c | markanson25/python-fundamentals | /09_exceptions/09_04_files_exceptions.py | 3,137 | 4.34375 | 4 | '''
In this exercise, you will practice both File I/O as well as using Exceptions
in a real-world scenario.
You have a folder containing three text files of books from Project Gutenberg:
- war_and_peace.txt
- pride_and_prejudice.txt
- crime_and_punishment.txt
1) Open war_and_peace.txt, read the whole file content and store it in a variable
2) Open crime_and_punishment.txt and overwrite the whole content with an empty string
3) Loop over all three files and print out only the first character of each. Your program
should NEVER terminate with a Traceback.
a) Which Exception can you expect to encounter? Why?
b) How do you catch it to avoid the program from terminating with a Traceback?
BONUS CHALLENGE: write a custom Exception that inherits from Exception and raise it if the
first 100 characters of any of the files contain the string "Prince".
UnicodeDecodeError
'''
counter = 0
error_free = False
text_files_list = []
first_characters_list = []
war_and_peace = []
pride_and_prejudice = []
crime_and_punishment = []
class Prince(Exception):
def print_exception(self):
return f"Can you believe that the word 'Prince' was used within the first 100 words of this text!?!?"
with open("Books/war_and_peace.txt", "r", errors='ignore') as war_and_peace_text:
for word in war_and_peace_text.readlines():
word = word.strip()
word = word.replace(',','')
word = word.split(' ')
war_and_peace.append(word)
text_files_list.append(war_and_peace)
with open("Books/pride_and_prejudice.txt", "r", errors='ignore') as pride_and_prejudice_text:
for word in pride_and_prejudice_text.readlines():
word = word.strip()
word = word.replace(',','')
word = word.split(' ')
pride_and_prejudice.append(word)
text_files_list.append(pride_and_prejudice)
with open("Books/crime_and_punishment.txt", "w", errors='ignore') as crime_and_punishment_text:
crime_and_punishment_text.write('')
with open("Books/crime_and_punishment.txt", "r", errors='ignore') as crime_and_punishment_text:
for word in crime_and_punishment_text.readlines():
word = word.strip()
word = word.replace(',','')
word = word.split(' ')
crime_and_punishment.append(word)
text_files_list.append(crime_and_punishment)
while error_free == False:
try:
first_file = first_characters_list.append(text_files_list[0][0])
except IndexError as error:
first_file = first_characters_list.append('null')
try:
second_file = first_characters_list.append(text_files_list[1][0])
except IndexError as error:
second_file = first_characters_list.append('null')
try:
third_file = first_characters_list.append(text_files_list[2][0])
except IndexError as error:
third_file = first_characters_list.append('null')
error_free = True
print(first_characters_list)
while counter < 100:
for file in text_files_list:
for file_list in file:
for word in file_list:
if word == "Prince":
raise Prince()
counter += 1
|
c008b2121ea3e072925bd5ccb895257bbcd87be0 | hristoboyadzhiev/course-robotics-npmg | /word-counting-demo/word-counting.py | 558 | 3.625 | 4 | import re
def myFunc(item):
return item[1]
if __name__ == "__main__":
file = open("wikipedia.txt", "rt", encoding="utf-8")
counts = dict()
for line in file:
words = set(re.split("[\s\.,?!\[\]\(\)\'\"=:;]+", line))
# print(words)
for w in words:
if(len(w) <= 3):
continue
if(w in counts):
counts[w] = counts[w] + 1
else:
counts[w] = 1
wlist = list(counts.items())
wlist.sort(reverse=True, key=myFunc)
print(wlist[:10]) |
3645ab2a746909fb25afe1afddaef94d43516a06 | Subham6240/college-python-assignment | /python 2nd assignment/temperature coonversion.py | 321 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Sep 10 12:37:39 2020
@author: SUBHAM
"""
x=float(input("enter temp."))
u=input("enter unit c/f ")
if u=='c':
temp=float((9*x/5)+32)
print("temp. is",str(temp),"F")
elif u=='f':
temp=float(5*(x-32)/9)
print("temp is :",str(temp),"C")
else : print("wrong unit") |
3813e0283506c63781f71de04a08b785555be8bf | abhiwalia15/practice-programs | /multiplication_table.py | 139 | 3.828125 | 4 | def table():
n=int(input("ENTER ANY NUMBER\n"))
for i in range(1,11):
p = n*i
print(str(n)+' * '+str(i)+' = '+str(p))
table()
|
f4dd7f39fb1c767711a6fc0dfdaf2562c2f0b07c | dinneel002/derekUdemyPython | /moreonstrings/acronmyn.py | 188 | 4.1875 | 4 | original_string = input('convert to acronmy :')
original_string=original_string.upper()
list_of_words = original_string.split()
for word in list_of_words:
print(word[0],end="")
print() |
c37ff9a8813a9492ab7c71b1b9dd8756947e49cd | cdeepakait/MonkVisitsCoderland | /MonkNiceString.py | 440 | 3.609375 | 4 | total = int(input())
def niceness(letter, allstring):
print("letter, allstring", letter, allstring)
if len(allstring) == 0:
print(0)
else:
allstring.append(letter)
allstring.sort()
try:
print(allstring.index(letter))
except ValueError:
print(0)
lst = []
for i in range(total):
lst.append(input())
for i in range(total):
niceness(lst[i], lst[0:i + 1])
|
ed3c86bf6246400138f57db4c8b3cb0919c2288c | poojakancherla/Problem-Solving | /HackerRank Problem Solving/PrintLinkedList.py | 369 | 4.15625 | 4 | import LinkedListBase as l
# Function to print the elements of a linked list
def printLinkedList(head):
curr = head
while(curr):
print(curr.data)
curr = curr.next
llist_count = int(input())
llist = l.SinglyLinkedList()
for _ in range(llist_count):
llist_item = int(input())
llist.insert_node(llist_item)
printLinkedList(llist.head)
|
283a21a625ae91698351bbd4377443ab521d99b0 | eazapata/python | /Ejercicios python/PE3/PE3E3.py | 323 | 4 | 4 | #PE3E3 Eduardo Antonio Zapata Valero
#¿Qué función te informa del tipo de dato tiene almacenado una variable?
#Haz una prueba con los distintos tipos de datos que conoces.
a=int(input("Escriba un numero entero "))
print (type (a))
b=float(input("Escriba un número decimal "))
print (type (b))
c=input("Escriba un nombre ")
print (type (c))
|
9982a3aa8852aa457b8f43cb8097b331240d9e15 | Percygu/my_leetcode | /链表/反转链表/92.反转链表-ii.py | 781 | 3.671875 | 4 | #
# @lc app=leetcode.cn id=92 lang=python3
#
# [92] 反转链表 II
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
pre = None
current = head
while current:
stamp = current.next
current.next = pre
pre = current #pre 和 current 同时后移一个单位
current = stamp
return pre
# @lc code=end
'''
在遍历是,当前节点要指向前一节点,所以指向了前一节点后,就到不了后一节点了,要用一个暂存节点存下其后一个节点的值
''' |
ef3f7526a507cc2519a9c319bb70f21c12f322dd | rafhaeldeandrade/learning-python | /2 - Variáveis e tipos de dados em Python/Exercicios/ex43.py | 846 | 3.9375 | 4 | """
43. Escreva um programa de ajuda para vendedores. A partir de um valor total lido, mostre:
* o total a pagar com desconto de 10%;
* o valor de cada parcela, no parcelamento de 3x sem juros;
* a comissão do vendedor, no caso da venda ser a vista (5% sobre o valor com des¬conto)
* a comissão do vendedor, no caso da venda ser parcelada (5% sobre o valor total)
"""
valor_venda = float(input('Digite um valor: '))
valor_pagar_desconto = valor_venda * 0.9
valor_parcela = valor_venda / 3.0
comissao_vendedor_a_vista = valor_pagar_desconto * 0.05
comissao_vendedor_parcelado = valor_venda * 0.05
print(f"""Total a pagar com desconto: {valor_pagar_desconto}
Valor de cada parcela (3x): {valor_parcela:.2f}
Comissão do vendedor, venda a vista: {comissao_vendedor_a_vista}
Comissão do vendedor, venda a prazo: {comissao_vendedor_parcelado}""")
|
11eb2cf5905bbfeac586ba7e51bc6c5e1534af25 | Crown0815/ESB-simulations | /critical_angle_simulation.py | 918 | 3.828125 | 4 | from math import *
def critical_angle(candy_radius, rod_length, rod_radius):
angle = 0
old_result = 0
while angle < pi/2:
result = critical_angle_equation(candy_radius, rod_length, rod_radius, angle)
if old_result * result < 0:
break
old_result = result
angle += pi / 100000
if rod_radius >= candy_radius:
return 0
return angle
def critical_angle_degrees(candy_radius, rod_length, rod_radius):
return critical_angle(candy_radius, rod_length, rod_radius) / pi * 180
def critical_angle_equation(candy_radius, rod_length, rod_radius, angle):
return 1 / 2 * (rod_length + candy_radius) * sin(2 * angle) - candy_radius * cos(angle) + rod_radius * cos(
angle) ** 2
if __name__ == "__main__":
for radius in range(10, 101, 1):
print(str(radius/10) + " " + str(critical_angle_degrees(radius/10, 100, 3.9)) + "\\\\")
|
92b9c87cd086770fa062605887c8cbff31873cf7 | swapnilz30/python | /examples/area_of_circle.py | 129 | 4.3125 | 4 | #!/usr/bin/python3.6
pi = 3.142
r = input("Enter the radius: ")
area = pi * int(r) * int(r)
print("The area of circle: ", area) |
d550221b1acfb3558ebfd94d52b95f4c56d90458 | karanguptak9/pythonPractice | /12.py | 96 | 3.703125 | 4 | my_range = range(1, 21)
print([10 * x for x in my_range])
#we use a for loop inside the range
|
f37243482f8658e9a81d08013268fa2ad521bb6b | Ansh-Kumar/Ansh-Fun-and-Learn | /Ansh Learn/WeatherWearer.py | 455 | 4.1875 | 4 | rainy = input("How is the weather? Is it raining? (y/n)").lower()
cold = input("Is it cold outside? (y/n)").lower()
if (rainy == 'y' and cold == 'y'):
print("You should wear something extra warm and take an umbrella.")
elif (rainy == 'y' and cold != 'y'):
print("Just take an umbrella.")
elif (rainy != 'y' and cold == 'y'):
print("Take something warm")
elif(rainy != 'y' and cold != 'y'):
print("Wear anything you want")
|
893127b37b101f853ee3c1cfab593cfa27d84529 | Go-Trojans/trojan-go | /code/goboard/game_winner.py | 4,215 | 3.671875 | 4 | """
Author : Puranjay Rajvanshi
Date : June 9th 2020
File : game_winner.py
Description : Decides the game winner.
"""
"""
Big Idea for the code written in this file:
===========================================
Assuming any go board size.
Given: given a board state, determine who's the winner
0 : blank site
1 : black piece
2 : White piece
These are the rules to calculate the winner:
First all the dead stones of both sides are removed from the board. Then one side's living stones are counted,
including the vacant points enclosed by those stones. Vacant points situated between both sides' living stones
are shared equally. A vacant point counts as one stone.
The winner is determined by comparison with 180-1/2, which is half the number of points on the board. If the total
of one side's living stones and enclosed vacant points is larger than 180-1/2, then that side is the winner. If the
total is less than 180-1/2, then that side loses. If the total is equal to 180-1/2, the game is a draw.
In games with compensation, the comparison is made with different numbers, according to separate rules.
Removal of dead stones will be a separate function since it'll be needed for both Suicide an KO functions
"""
import numpy as np
def game_winner(board):
"""
:param: board: A 2-Dimensional numpy array
:return: 0: Draw
1: Black wins
2: White wins
Basic intuition:
if black piece is encountered increase points for black by 1
if white piece is encountered increase points for white by 1
if blank sites is encountered we try to find the size of the cluster of blank sites
if blank sites are completely surrounded by black then points for black increases by the group size
if blank sites are completely surrounded by white then points for white increases by the group size
if blank sites are completely surrounded by both then points for both increases by (group size)/2
"""
visited = set()
m = board.shape[0]
n = board.shape[1]
if m == 19:
komi = 3.75
else:
komi = (m/2) - 1
count_black = -komi
count_white = komi
offset = np.array([[1,0],[0,1],[-1,0],[0,-1]])
for i in range(m):
for j in range(n):
if (i,j) in visited:
continue
elif board[i][j] == 1:
count_black+=1
elif board[i][j] == 2:
count_white+=1
elif board[i][j] == 0:
queue = set()
queue.add((i,j))
black_neighbour = False
white_neighbour = False
group_count = 0
while queue:
node_x,node_y = queue.pop()
if (node_x,node_y) in visited:
continue
visited.add((node_x,node_y))
group_count+=1
neighbours = offset+np.array([node_x,node_y])
for neighbour in neighbours:
if (neighbour[0],neighbour[1]) in visited:
continue
elif 0<=neighbour[0]<m and 0<=neighbour[1]<n:
val = board[neighbour[0]][neighbour[1]]
if val == 1:
black_neighbour = True
elif val == 2:
white_neighbour = True
elif val == 0:
queue.add((neighbour[0],neighbour[1]))
if black_neighbour and white_neighbour:
count_black+=(group_count/2)
count_white+=(group_count/2)
elif black_neighbour:
count_black+=group_count
elif white_neighbour:
count_white+=group_count
if count_white>count_black:
return 2
elif count_black>count_white:
return 1
else:
return 0
if __name__ == "__main__":
board = np.zeros((19,19))
board[15][8] = 1
board[5][6] = 2
print(board)
print(game_winner(board))
|
de3db976b72ed65f536307efdb5363fda277e30e | afrizaldm/latihan-python | /latihan2.py | 1,845 | 3.953125 | 4 | # nilai < 90 dan nilai > 80 A
# nilai < 80 dan nilai > 70 B
# nilai < 70 dan nilai > 60 C
# D
nilai = 76
if nilai > 80 and nilai < 90:
print("A")
elif nilai >70 and nilai < 80:
print("B")
elif nilai >60 and nilai < 70:
print("C")
else:
print("D")
# jika nilai > 80 dan absen kurang dari 3 maka lulus selain itu remidi
nilai = 70
absen = 2
if nilai >80 and absen <3 :
print("lulus")
else:
print("tidak lulus")
# Menulis bilangan 10 sd 1
angka = 10
while angka >0 :
print(angka)
angka = angka - 1
# Menulis bilangan bulat dari 2 sd 10
angka = 2
while angka <= 10:
print(angka)
angka = angka + 2
# Menulis bilangan bulat dari 2 sd 10
angka = 1
while angka <= 10:
if (angka % 2) == 0:
print(angka)
angka = angka + 1
# Menulis bilangan ganjil dari 20 sd 0
angka = 20
while angka >= 0 :
if (angka % 2) != 0:
print (angka)
angka = angka - 1
# Variable Tipe Data List
gender = ["laki-laki", "perempuan"]
print(gender[0])
# Mencetak list dengan mengguankan while
bulan = ["januari", "febuari", "maret"]
index = 0
while index <= 2 :
print (bulan[index])
index += 1
print("*")
print("*" * 2)
print("*" * 3)
# Mencetak bintang membentuk segitiga
angka = 1
while angka <= 3 :
print ("*" * angka)
angka += 1
# Mencetak bintang dengan spasi
angka = 1
while angka <= 3:
cetak = (" " * (3 - angka)) + ("*" * angka)
print(cetak)
angka += 1
# Mencetak bintang terbalik
angka = 3
while angka >=1 :
print ("*" * (angka))
angka -= 1
# Mencetak bintang terbalik dengan spasi
angka = 3
while angka >= 1:
cetak = (" " * (3 - angka)) + ("*" * angka)
print(cetak)
angka -= 1
# Mencetak list dengan menggunakan for
bulans = ["januari", "febuari", "maret"]
for bulan in bulans:
print(bulan)
bulans[0] = 1
print(bulans[0])
|
077c64dd9a48db72a5f0ad6abe5c7e96f8f93079 | courtneycampbell15/ProjectGutenberg | /methods.py | 625 | 4.0625 | 4 | # this method takes in a .txt file and returns the number of words in the file
def get_total_number_of_words(file):
wordCount = 0
f = open(file, "r")
# read first line
line = f.readline()
while line:
# do whatever
line = f.readline()
wordCount = wordCount + 1
f.close()
return wordCount
# getTotalUniqueWords()
# this method returns the number of unique words in the novel
def get_total_unique_words(file):
# get20MostFrequentWords()
# get20MostInterestingFrequentWords()
# get20LeastFrequentWords()
# getFrequencyOfWord()
# getChapterQuoteAppears()
# generateSentence()
|
1560e2212321e69391810b05dea2fab1501a8b39 | tloszabno/tl_en | /tlen/parser.py | 554 | 3.6875 | 4 | __SEPARATOR__ = "-"
def parse_file(file_path):
result = []
with open(file_path) as fs:
for entry in fs:
chunks = entry.split(__SEPARATOR__)
if len(chunks) == 0:
continue
english_word = chunks[0].strip()
if len(english_word) == 0:
continue
translation = chunks[1].strip() if len(chunks) > 1 else ""
sample = "\n".join([x.strip() for x in chunks[2:]])
result.append((english_word, translation, sample))
return result
|
6099a21cda4297fe3a54bf2f514b325591678e9f | curiousboey/Learning-Python | /Logical operators.py | 265 | 4.03125 | 4 | print(10 > 5)
print(10 >= 5)
print(10 <= 5)
print(10 != 5) #not equal to
print(10 == 5)
print((10 > 5) and (1 > 3))
print((10 > 5) and (1 < 3))
print("and operation = ",(10 > 5) and (1 < 3) and "A" == "c")
print((10 > 5) or (1 > 3))
print(not("james" == "Maria")) |
cfe26137917dfbae3d4880909af70441b81f9fbf | Xomia4iwe/lesson_005 | /Drawing_tools/house.py | 1,117 | 3.59375 | 4 | import simple_draw as sd
def triangle(point, length, angle=0):
for _ in range(3):
v = sd.get_vector(start_point=point, length=length, angle=angle, width=3)
v.draw()
angle += 120
point = v.end_point
def house(point_x, point_y, color, length, height, row):
sd.rectangle(right_top=sd.get_point(point_x + length / 2, point_y), left_bottom=sd.get_point(300, 0), color=color,
width=2)
triangle(point=sd.get_point(300, point_y), length=(length * 6.5))
circle_x = (300 + length * 6.5 / 2)
h = int(((length * 6.5) ** 2 - (length * 6.5 / 2) ** 2) ** 0.5)
circle_y = point_y + h / 4
sd.circle(center_position=sd.get_point(circle_x, circle_y), radius=(h / 8), color=color, width=5)
for y in range(0, point_y, height):
row += 1
for x in range(300, point_x, length):
x_0 = x if row % 2 else x + length // 2
left_bottom = sd.get_point(x_0, y)
right_top = sd.get_point(x_0 + length, y + height)
sd.rectangle(left_bottom=left_bottom, right_top=right_top, color=color, width=2)
|
e3657982e304e98ea3ce2a1df049a3e65a89d7ad | francoistourlonnias/MesFonctions | /Python/Formation Python/formationPython2017_2/Ex5-3/Ex5-3-Done.py | 8,108 | 3.734375 | 4 | """
Exercise 5.3 Polymorphism
"""
class Trip:
def __init__(self, departCity=None, arriveCity=None,
departTime=None, departDay=None,
arriveTime=None, arriveDay=None):
self.departCity = departCity
self.arriveCity = arriveCity
self.departTime = departTime
self.departDay = departDay
self.arriveTime = arriveTime
self.arriveDay = arriveDay
caribList = [ 'CUR', 'GCM' ]
hawaiiList = [ 'HNL', 'ITO' ]
def isRoundTrip(self):
if self.arriveCity == self.departCity and self.departDay == self.arriveDay:
return True
else:
return False
def isCarribean(self):
if self.arriveCity in Trip.caribList:
return True
else:
return False
def isHawaiian(self):
if self.arriveCity in Trip.hawaiiList:
return True
else:
return False
def isOverNight(self):
if self.arriveDay != self.departDay:
return True
else:
return False
def isInterIsland(self):
if self.arriveCity in Trip.hawaiiList and self.departCity in Trip.hawaiiList:
return True
else:
return False
class Flight(Trip):
def __init__(self, flightnum=0, departCity=None, arriveCity=None,
departTime=None, departDay=None,
arriveTime=None, arriveDay=None,
cost=0.0, code=0):
self.flightnum = flightnum
self.cost = cost
self.code = code
Trip.__init__(self,departCity=departCity, arriveCity=arriveCity,
departTime=departTime, departDay=departDay,
arriveTime=arriveTime, arriveDay=arriveDay)
def discount(self):
discount = 0.0
if self.isInterIsland():
discount += 0.05
elif self.isHawaiian():
discount += 0.10
elif self.isCarribean():
discount += 0.15
self.cost -= ( self.cost * discount )
# Part A
class Cruise(Trip):
def __init__(self, cruisenum=0, departCity=None, arriveCity=None,
departTime=None, departDay=None,
arriveTime=None, arriveDay=None,
cost=0.0, code=0):
self.cruisenum = cruisenum
self.cost = cost
self.code = code
Trip.__init__(self,departCity, arriveCity,
departTime, departDay,
arriveTime, arriveDay)
def discount(self):
discount = 0
if self.isInterIsland():
discount += 0.10
elif self.isHawaiian():
discount += 0.20
self.cost -= ( self.cost * discount )
# Part B
cruise1 = Cruise( cruisenum = 201, departCity = "HNL", arriveCity = "ITO",
departTime = "08:00", departDay = "Monday",arriveTime = "23:00",
arriveDay = "Monday", cost = 199.99, code = "I" )
flight1 = Flight( flightnum = 336, departCity = "HKG", arriveCity = "GCM",
departTime = "12:00", departDay = "Monday", arriveTime = "20:00",
arriveDay = "Monday", cost = 299.99, code = 4 )
print 'Before discount cruise', cruise1.cruisenum, cruise1.departCity, cruise1.arriveCity, cruise1.cost
print 'Before discount flight', flight1.flightnum, flight1.departCity, flight1.arriveCity, flight1.cost
cruise1.discount()
flight1.discount()
print 'After discount cruise', cruise1.cruisenum, cruise1.departCity, cruise1.arriveCity, cruise1.cost
print 'After discount flight', flight1.flightnum, flight1.departCity, flight1.arriveCity, flight1.cost
# Part C
def genDiscount(obj):
# if isinstance(obj,Flight):
# Flight.discount(obj)
# elif isinstance(obj,Cruise):
# Cruise.discount(obj)
# else:
# print 'object is not a Flight or Cruise'
if (isintance(obj,Fligh) or isinstance(obj, Cruise)):
obj.discount()
else:
print 'object is not a Flight or a Cruise.'
cruise2 = Cruise( cruisenum = 202, departCity = "HNL", arriveCity = "ITO",
departTime = "05:00", departDay = "Sunday", arriveTime = "21:30",
arriveDay = "Sunday", cost = 99.99, code = "O" )
flight2 = Flight( flightnum = 337, departCity = "HNL", arriveCity = "ITO",
departTime = "8:00", departDay = "Monday", arriveTime = "14:00",
arriveDay = "Monday", cost = 199.99, code = 2 )
print 'Before genDiscount cruise', cruise2.cruisenum, cruise2.departCity, cruise2.arriveCity, cruise2.cost
print 'Before genDiscount flight', flight2.flightnum, flight2.departCity, flight2.arriveCity, flight2.cost
genDiscount(cruise2)
genDiscount(flight2)
print 'After genDiscount cruise', cruise2.cruisenum, cruise2.departCity, cruise2.arriveCity, cruise2.cost
print 'After genDiscount flight', flight2.flightnum, flight2.departCity, flight2.arriveCity, flight2.cost
# Part D
flight1 = Flight( flightnum = 336, departCity = "HKG", arriveCity = "GCM",
departTime = "12:00", departDay = "Monday", arriveTime = "20:00",
arriveDay = "Monday", cost = 299.99, code = 4 )
flight2 = Flight( flightnum = 337, departCity = "HNL", arriveCity = "ITO",
departTime = "8:00", departDay = "Monday", arriveTime = "14:00",
arriveDay = "Monday", cost = 199.99, code = 2 )
flight3 = Flight( flightnum = 660, departCity = "CDG", arriveCity = "GCM",
departTime = "14:00", departDay = "Monday", arriveTime = "0:00",
arriveDay = "Tuesday", cost = 199.99, code = 2 )
flight4 = Flight( flightnum = 681, departCity = "CDG", arriveCity = "ITO",
departTime = "6:00", departDay = "Monday", arriveTime = "11:00",
arriveDay = "Monday", cost = 209.89, code = 1 )
flight5 = Flight( flightnum = 753, departCity = "LHR", arriveCity = "HKG",
departTime = "10:00", departDay = "Monday", arriveTime = "18:00",
arriveDay = "Monday", cost = 199.99, code = 2 )
cruise1 = Cruise( cruisenum = 201, departCity = "HNL", arriveCity = "ITO",
departTime = "08:00", departDay = "Monday",arriveTime = "23:00",
arriveDay = "Monday", cost = 199.99, code = "I" )
cruise2 = Cruise( cruisenum = 202, departCity = "HNL", arriveCity = "ITO",
departTime = "05:00", departDay = "Sunday", arriveTime = "21:30",
arriveDay = "Sunday", cost = 99.99, code = "O" )
cruise3 = Cruise( cruisenum = 206, departCity = "HNL", arriveCity = "ITO",
departTime = "06:00", departDay = "Tuesday", arriveTime = "22:00",
arriveDay = "Tuesday", cost = 199.99, code = "I" )
cruise4 = Cruise( cruisenum = 208, departCity = "HNL", arriveCity = "ITO",
departTime = "16:00", departDay = "Thursday", arriveTime = "08:00",
arriveDay = "Friday", cost = 299.99, code = "I" )
cruise5 = Cruise( cruisenum = 210, departCity = "HNL", arriveCity = "ITO",
departTime = "15:00", departDay = "Friday", arriveTime = "09:00",
arriveDay = "Saturday", cost = 299.99, code = "O" )
fList = [ flight1, flight2, flight3, flight4, flight5 ]
cList = [ cruise1, cruise2, cruise3, cruise4, cruise5 ]
for f in fList:
print 'Before genDiscount flight', f.flightnum, f.cost
genDiscount(f)
print 'After genDiscount flight', f.flightnum, f.cost
for c in cList:
print 'Before genDiscount cruise', c.cruisenum, c.cost
genDiscount(c)
print 'After genDiscount cruise', c.cruisenum, c.cost
def printRebate(obj):
if isinstance(obj,Flight):
if obj.code == 2:
print obj.flightnum, obj.code, 'Frebate'
elif isinstance(obj,Cruise):
if obj.code == "I":
print obj.cruisenum, obj.code, 'Crebate'
else:
print obj, 'is not a Flight or Cruise'
for f in fList:
printRebate(f)
for c in cList:
printRebate(c)
for junk in [ 'a' , 1.5, -7, { 'key':'value' }, True, Trip ]:
printRebate(junk) |
493fa8342af9aab2c5d1efcd56759f0b6f29f9a1 | lemonnader/LeetCode-Solution-Well-Formed | /math/Python/0066-加一.py | 983 | 3.59375 | 4 | # 66. 加一
# 给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。
#
# 最高位数字存放在数组的首位, 数组中每个元素只存储一个数字。
#
# 你可以假设除了整数 0 之外,这个整数不会以零开头。
class Solution(object):
def plusOne(self, digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
if len(digits) == 0:
return []
# 进位标识
carry = 1
for i in range(len(digits) - 1, -1, -1):
s = digits[i] + carry
digits[i] = s % 10
# 注意:整除要使用 //
carry = s // 10
if carry == 0:
return digits
print(digits, carry)
if carry == 1:
return [1] + digits
if __name__ == '__main__':
digits = [9, 9, 9, 9]
solution = Solution()
result = solution.plusOne(digits)
print(result)
|
ef8e90e95f6ffa4096f8422a33e56503796d7005 | fxalban8/Python-FOR_Loop | /Printing_elements_of_a_list.py | 228 | 4.5 | 4 | #The FOR command can be used to show the elementos of a list
#let's create a list
people=["M1","M2","F1","F2","F3"]
#let's print each element of the list in one single line each other
for item in people:
print(item)
|
14ef5daf0727532527ec2a3d5a7bdd9fb8dec33a | joshwassum/cse210-student-batter | /batter/game/handle_collisions_action.py | 4,782 | 3.5625 | 4 | import random
import sys
from game import constants
from game.action import Action
from game.point import Point
class HandleCollisionsAction(Action):
"""A code template for handling collisions. The responsibility of this class of objects is to update the game state when actors collide.
Stereotype:
Controller
"""
# Vanessa
def execute(self, cast):
"""Executes the action using the given actors.
Args:
cast (dict): The game actors {key: tag, value: list}.
"""
ball = cast["ball"][0]
paddle = cast["paddle"][0]
bricks = cast["brick"]
marquee = cast["marquee"][0]
self._handle_bricks(bricks, ball, marquee)
self._handle_paddle(paddle, ball)
self._handle_ball_constraints(ball)
self._handle_paddle_constraints(paddle)
# Brian
def _handle_paddle(self, paddle, ball):
"""This function loops through the paddle text's quadrants and the ball's quadrants to see if they are the same. If True the ball velocity is changed.
Args:
paddle (Actor): An instance of the Actor class.
self (Handle_collisions_Action): An instance of Handle_Collisions_Action
ball (Actor): is an instance of the Actor class
"""
for i in range(0, len(paddle.get_text())):
paddle_position = paddle.get_position().add(Point(i, 0))
# if ball.get_position().equals(paddle_position):
# ball.set_velocity(ball.get_velocity().reverse())
if ball.get_position().equals(paddle_position) and i < 5:
ball.set_velocity(Point(-1,-1))
elif ball.get_position().equals(paddle_position) and i > 5:
ball.set_velocity(Point(1,-1))
elif ball.get_position().equals(paddle_position) and i == 5:
ball.set_velocity(Point(0,-1))
# Vanessa
def _handle_bricks(self, bricks, ball, marquee):
"""handle_brick first loops through all the bricks and if the ball touches a brick
the brick is removed.
Then the ball will get the velocity to a reverse or reverse_y randomly to change ball direction.
Args:
Self (instance): Is an instance of HandleCollisionsAction class.
Brick (list):Is an instance of the brick list.
Ball (instance): Is an instance of Actor.
marquee (instance): Is an istance of Actor.
"""
for brick in bricks:
if ball.get_position().equals(brick.get_position()):
random_number = random.randint(1,10)
bricks.remove(brick)
self._update_score(brick, marquee)
if random_number > 5:
ball.set_velocity(ball.get_velocity().reverse())
else:
ball.set_velocity(ball.get_velocity().reverse_y())
# Brian
def _handle_ball_constraints(self, ball):
"""
This function determines if the ball hits the walls,ceiling, or floor and reverse the direction of the ball or ends the game.
Args:
ball (Actor): is an instance of the Actor class
self (Handle_collisions_Action): An instance of Handle_Collisions_Action
"""
position = ball.get_position()
x = position.get_x()
y = position.get_y()
if x == 0 or x == constants.MAX_X:
ball.set_velocity(ball.get_velocity().reverse_x())
if y == 0:
ball.set_velocity(ball.get_velocity().reverse_y())
if y == constants.MAX_Y:
sys.exit()
# Brian
def _handle_paddle_constraints(self, paddle):
"""This function keeps the paddle inside the walls of the game.
Args:
paddle (Actor): An instance of the Actor class.
self (Handle_collisions_Action): An instance of Handle_Collisions_Action
"""
position = paddle.get_position()
x = position.get_x()
if x < 0:
paddle.set_position(Point(0, constants.MAX_Y - 1))
if x > constants.MAX_X - len(paddle.get_text()):
paddle.set_position(Point(constants.MAX_X - len(paddle.get_text()), constants.MAX_Y - 1))
def _update_score(self, brick, marquee):
"""This function gets the point value from the brick and adds it to the score. Then sets value of points
to the marquee.
Args:
marquee (Actor): marquee is an instance of Actor
brick (Actor): brick is an instance of Actor
points (integer): point value from Actor
"""
points = brick.get_points()
marquee.add_points(points)
marquee.set_text(marquee.get_points())
|
bafab7a5d5777d6582d6d51dda7795a83a20fa69 | AndersonFSP/Curso-em-V-deo-Python | /010-ConvertendoMoedas.py | 155 | 3.625 | 4 | real = float(input('Digite o valor em R$ a ser convertido: '))
dolar = real / 3.76
print('Com R${:.2f} você pode comprar US${:.2f} '.format(real, dolar))
|
ff938f135473154417ca946abc7ecac6d2b2c57e | Aasthaengg/IBMdataset | /Python_codes/p03679/s700974907.py | 130 | 3.546875 | 4 | x,a,b=map(int,input().split())
if 1<=(b-a)<=x:
print('safe')
elif (b-a)>x:
print('dangerous')
else:
print('delicious') |
a718e57efa86b5ce435f2670b14063dabd95691f | jvanvari/LeetCode | /python-solutions/sorting/selection_sort.py | 714 | 4.03125 | 4 | from typing import List
# compare 1 element with all
# find the smallest element in unsorted list
# second time we locate the smallest item in the list starting from the second element in the list
def selection_sort(nums: List[int]):
l = len(nums)
for i in range(l-1): # works with l also
for j in range(i+1, l):
if nums[i] > nums[j]:
nums[i], nums[j] = nums[j], nums[i]
n = [4, 5, 9, 8, 6, 7, 3, 2]
selection_sort(n)
print(n)
'''
for i in range(len(A)):
min_idx = i # assume first is min
for j in range(i+1, len(A)):
if A[min_idx] > A[j]:
min_idx = j # find mind
A[i], A[min_idx] = A[min_idx], A[i]
'''
|
9c9c7e304f8339acef5ac83f021279b768be0c26 | shasank-shah/pycharmProjects | /pythonProjects/learningClasses/demo_inherirance.py | 694 | 3.953125 | 4 | # to get methods of other class into current class
# single level inheritance
class A: # super class
def feature1(self):
print("feature 1")
def feature2(self):
print("feature 2")
class B(): # sub class
def feature3(self):
print("feature 3")
def feature4(self):
print("feature 4")
# multi level inheritance
class C(B): # mutilevel sub class
def feature5(self):
print("feature 5")
# multiple inheritance
class D(A, B): # removing A super class from B class to obtain mutiple level inheritance
def feature6(self):
print("feature 5")
a1 = D()
a1.feature6() |
a2150ca2209bfc404f2b6770784846b18368fe1b | DhruvGodambe/python_oop | /encapsulation.py | 981 | 4.28125 | 4 | # creating a class with a private variable 'origin'
class Company:
def __init__(self, name, net_worth, rating):
self.name = name
self.net_worth = net_worth
self.rating = rating
self.__origin = "India" # adding __ makes it a private variable
print(" __origin from init function : {}".format(self.__origin))
def get_data(self):
return {
"name": self.name,
"net_worth": self.net_worth,
"rating": self.rating,
"origin": self.__origin
}
def set_origin(self, val):
self.__origin = val
#creating a company object
comp1 = Company("Apple", "20000000000", 5)
# changing origin from the class function
comp1.set_origin("Indonesia")
print(comp1.get_data())
#changing private variable from outside of the class
comp1.__origin = "Pakistan"
print(comp1.get_data())
#changing other variables from outside of the class
comp1.name = "Microsoft"
print(comp1.get_data()) |
af84a03c1ecf8b39c288adfd1d309cdb243036e4 | G-M-C/War-Card-Game | /war.py | 2,207 | 3.859375 | 4 | from deck import Deck
from player import Player
player_one = Player(input("Enter Name of Player 1 : "))
player_two = Player(input("Enter Name of Player 2 : "))
new_deck = Deck()
new_deck.shuffle_cards()
for i in range(26):
player_one.add_cards(new_deck.deal_one())
player_two.add_cards(new_deck.deal_one())
game_on = True
round_num=0
while game_on:
round_num += 1
print(f"Round {round_num}")
if len(player_one.all_cards) == 0:
print(f"{player_one.name} is out of Cards !!!! {player_two.name} is the winner !")
game_on = False
break
if len(player_two.all_cards) == 0:
print(f"{player_two.name} is out of Cards !!!! {player_one.name} is the winner !")
game_on = False
break
player_one_cards = []
player_one_cards.append(player_one.remove_one())
player_two_cards = []
player_two_cards.append(player_two.remove_one())
at_war = True
while at_war:
if player_one_cards[-1].value > player_two_cards[-1].value:
player_one.add_cards(player_one_cards)
player_one.add_cards(player_two_cards)
at_war = False
elif player_one_cards[-1].value < player_two_cards[-1].value:
player_two.add_cards(player_one_cards)
player_two.add_cards(player_two_cards)
at_war = False
else:
print("@ WAR !!!")
"""
The number of cards that have to be drawn is set to 5 here , This can be varied
according to the player's choice....
"""
if len(player_one.all_cards) < 5:
print(f"{player_one.name} can't declare war")
print(f"{player_two.name} wins !!!!")
game_on = False
break
elif len(player_two.all_cards) < 5:
print(f"{player_two.name} can't declare war")
print(f"{player_one.name} wins !!!!")
game_on = False
break
else:
for i in range(5):
player_one_cards.append(player_one.remove_one())
player_two_cards.append(player_two.remove_one())
|
3ec384fafbbe4a4ae0ad2264976e99b1a2916265 | axisonliner/0502_project | /lesson2_homework.py | 1,551 | 4.03125 | 4 | from datetime import date
import random
date_now = date.today()
def input_data(date_now):
while True:
input_name = raw_input("Enter your name: ")
if input_name:
break
while True:
input_year = raw_input("Enter your birth year: ")
if input_year.isdigit() and len(input_year) < 5:
if int(input_year) < date_now.year and int(input_year) > 1900:
break
else:
print ("wrong year, please enter again")
age_now = date_now.year - int(input_year)
print "{0}, your age is {1}".format(input_name, age_now)
result(input_name, age_now)
def result(input_name, age_now):
print
if age_now < 18:
print "Ubderage, your age less then 18"
else:
print "Adult"
input_data(date_now)
# nubers generator
numb_range = []
for x in range(10):
numb_range.append(random.randint(1, 10))
print "Random numbers = ", numb_range
# finding the sum of even numbers and odd numbers
add_list = 0
even_list = 0
for numb in numb_range:
if numb % 2:
add_list = add_list + numb
else:
even_list = even_list + numb
print "sum of odd numbers is: ", add_list
print "sum of even numbers is: ", even_list
# sorted numbers
numb_range.sort(reverse=False)
print "Sorted numbers = ", numb_range
numb_range.sort(reverse=True)
print "Reversed numbers = ", numb_range
# sum min and max numbers
sum_min_max = min(numb_range) + max(numb_range)
print "Sum min and max = ", sum_min_max
#test jkdfhgkjdhg
new = range(12)
for i in new:
print i |
a2b8f1f6d1557f483af767f7c5c2948df1e29631 | xerifeazeitona/PCC_Basics | /chapter_02/exercises/07_stripping_names.py | 534 | 4.5625 | 5 | # 2-7. Stripping Names
# Use a variable to represent a person’s name, and include some whitespace
# characters at the beginning and end of the name. Make sure you use each
# character combination, "\t" and "\n" , at least once.
# Print the name once, so the whitespace around the name is displayed.
# Then print the name using each of the three stripping functions, lstrip(), rstrip(), and strip().
name = "\n\t John Doe \n \t "
print(f"'{name}'")
print(f"'{name.lstrip()}'")
print(f"'{name.rstrip()}'")
print(f"'{name.strip()}'")
|
2c2912ec2aa50d2dac67938d47a77b8c3fbd3872 | Bak4riba/zombieDice | /ZombieDice.py | 1,772 | 3.515625 | 4 | """
PUCPR - ANALISE E DESENVOLVIMENTO DE SISTEMAS
ALUNO: MATHEUS BAKAUS BRUNO
MATERIA: RACIOCÍNIO COMPUTACIONAL
"""
from random import randint
shots = 0
brains = 0
steps = 0
# DEFININDO DADOS
# T = TIROS, C = CEREBROS, P = PASSOS
diceGreen = 'CPCTPC'
diceYellow = 'TPCTPC'
diceRed = 'TPTCPT'
copo = []
pontos = []
for i in range(0, 6):
copo.append(diceGreen)
for i in range(0, 4):
copo.append(diceYellow)
for i in range(0, 3):
copo.append(diceRed)
print('Mostrar dados no copo')
for i in copo:
# print(i)
while True:
numPlayer = int(input('Quantos players nessa rodada, caro aventureiro?\n'))
if numPlayer > 1:
print('================================INICIANDO JOGO=========================================')
listPlayers = []
for ind in range(0, numPlayer):
nome = input('Como se chama, caro aventureiro?\n')
cerebros = 0
tiros = 0
player = [ind, nome, cerebros, tiros]
listPlayers.append(player)
for x in range(0, 3):
# INDICE ALEATÓRIO
randomNumber = randint(0, 12)
# DADO SORTEADO
dicePlayer = copo[randomNumber]
# FACE DADO
diceFace = randint(0, 5)
if dicePlayer[diceFace] == "C":
print('--------------------------------\n\n\n... CEREBRO!... \n Você comeu um cérebro')
brains = brains+1
elif dicePlayer[diceFace] == "T":
print('--------------------------------\n\n\n... TIRO!... \n Você levou um tiro!')
shots = shots + 1
else:
print('--------------------------------\n\n\n... PASSOS!... \n a vitima escapou')
steps = steps + 1
|
162f4c2fd3e416492f8b6bb0e4f002cc05d9a25b | RRoundTable/CPPS | /array_and_string/Reorder_Data_in_Log_Files.py | 1,625 | 3.75 | 4 |
'''
link: https://leetcode.com/problems/reorder-data-in-log-files/
You have an array of logs. Each log is a space delimited string of words.
For each log, the first word in each log is an alphanumeric identifier. Then, either:
Each word after the identifier will consist only of lowercase letters, or;
Each word after the identifier will consist only of digits.
We will call these two varieties of logs letter-logs and digit-logs. It is guaranteed that each log has at least one word after its identifier.
Reorder the logs so that all of the letter-logs come before any digit-log. The letter-logs are ordered lexicographically ignoring identifier, with the identifier used in case of ties. The digit-logs should be put in their original order.
Return the final order of the logs.
Example 1:
Input: logs = ["dig1 8 1 5 1","let1 art can","dig2 3 6","let2 own kit dig","let3 art zero"]
Output: ["let1 art can","let3 art zero","let2 own kit dig","dig1 8 1 5 1","dig2 3 6"]
Constraints:
0 <= logs.length <= 100
3 <= logs[i].length <= 100
logs[i] is guaranteed to have an identifier, and a word after the identifier.
- time complexity:
- space complexity:
'''
from typing import List
class Solution:
def reorderLogFiles(self, logs: List[str]) -> List[str]:
let, dig = [], []
for ele in logs:
if ele[-1] in '0123456789':
dig.append(ele)
else:
let.append(ele)
def compose(s):
s = s.split()
return s[1:] + [s[0]]
let = sorted(let, key=lambda x: compose(x))
return let + dig
|
1f86763ac124049c5dc4fd0740bb79df6e060a13 | jonnysassoon/Projects | /DataStructuresAndAlgorithms/DataStructures/ArrayStack.py | 592 | 3.546875 | 4 | """
Author: Jonny Sassoon
Program: Stack
Implementation of LIFO Data Structure
"""
class Empty(Exception):
pass
class ArrayStack:
def __init__(self):
self.data = []
def __len__(self):
return len(self.data)
def is_empty(self):
return (len(self) == 0)
def push(self, element):
self.data.append(element)
def pop(self):
if self.is_empty():
raise Empty("Stack is empty.")
return self.data.pop()
def top(self):
if self.is_empty():
raise Empty("Stack is empty.")
return self.data[-1] |
fda0276e0631b8652d53ceab36d9622c95bac2a1 | vivekjha1213/Algorithms-practice.py | /data structure using python.py/array_question/problem_8.py | 333 | 3.78125 | 4 | def Min(arr,n):
res = arr[0]
for i in range(1,n):
res= min(res,arr[i])
return res
def Max(arr,n):
res=arr[0]
for i in range(1,n):
res = max(res,arr[i])
return res
arr =[15, 16, 10, 9, 6, 7, 17]
n=len(arr)
MIN=Min(arr,n)
MAX=Max(arr,n)
print(MIN)
print(MAX)
Range=MAX-MIN
print(Range) |
06b46838e6f5d845be8ad4e6330311b3a6682364 | Vimvimvim/gittutorial | /Test.py | 135 | 3.703125 | 4 | def validation():
name = input("What is your name?")
print("Hello",name,",you are a beautiful fucking bastard.")
validation()
|
2fea15e492274c3d85248a7081883cbb8798aa88 | jonghoonok/Algorithm_Study | /Implementation/Resorting.py | 628 | 3.640625 | 4 | def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[0]
tail = arr[1:]
left = [x for x in tail if x < pivot]
right = [x for x in tail if x >= pivot]
return quick_sort(left) + [pivot] + quick_sort(right)
chars = list(input())
alphas = []
nums = []
for char in chars:
word_to_num = ord(char)
if 65 <= word_to_num < 91:
alphas.append(word_to_num)
else:
nums.append(int(char))
new_alphas = quick_sort(alphas)
num = sum(nums)
for i in range(len(new_alphas)):
new_alphas[i] = chr(new_alphas[i])
result = ''.join(new_alphas) + str(num)
print(result) |
b789d3c6d1b8fef2f113b0a264f0c2e92b60fff1 | CarlosFer27/Python | /ValidaUsiarioContraseña/ValidacionUsuarios/valida_usuario.py | 480 | 4.15625 | 4 | contador = 1
while(contador == 1):
nombre = input("\nIngresa tu usuario: ")
caracteres = len(nombre)
alfanumerico = nombre.isalnum()
if(caracteres < 6):
print("\nEl nombre de usuario debe contener al menos 6 caracteres")
elif(caracteres > 12):
print("\nEl nombre de usuario no puede contener más de 12 caracteres")
elif(alfanumerico == False):
print("\nEl nombre de usuario puede contener solo letras y números")
else:
print(True)
contador = 2
|
201a8ce0ca1f599eeb6ce7996733d6dd14b41ba4 | rdasxy/programming-autograder | /problems/CS101/0038/solution.py | 207 | 3.671875 | 4 | # solution.py
from divider import Divider
x = int(raw_input())
y = int(raw_input())
d = Divider()
try:
print "Quotient is %d" % d.divide(x, y)
except ValueError:
print "Cannot divide by zero"
|
3cb46797192c9281b3b8bf3cd05a2c521dca6d06 | jbmaillet/cpu_cgroup_calc | /cpu_cgroup_calc.py | 2,529 | 3.78125 | 4 | #!/usr/bin/python3
import sys
import argparse
def percent_to_share(percent_list):
total_percent = sum(percent_list)
if total_percent < 100:
added_group_share_percent = 100 - total_percent
print("Adding a group with {0}% of shares to reach mandatory 100%..."
.format(added_group_share_percent))
percent_list.append(added_group_share_percent)
elif total_percent > 100:
print("Total is {0}% cpu shares - reconsider your figures, we only have 100% CPU at best!"
.format(total_percent))
sys.exit(1)
percent_list.sort(reverse=True)
one_percent_cpu_share = 1024 / percent_list[0]
for share_percent in percent_list:
print("Group with {0:3d}% of CPU shares should be setup with a 'cpu.shares' of {1:4d}"
.format(share_percent,
int(share_percent * one_percent_cpu_share)))
def share_to_percent(share_list):
total_share = sum(share_list)
share_list.sort(reverse=True)
for share in share_list:
print("group with {0:4d} 'cpu.shares' have {1:3d}% of CPU shares"
.format(share,
round((share / total_share) * 100)))
def strictly_positive_integer(value):
error_msg = "'%s' is not a positive integer value" % value
try:
ivalue = int(value)
except ValueError:
raise argparse.ArgumentTypeError(error_msg)
if ivalue <= 0:
raise argparse.ArgumentTypeError(error_msg)
return ivalue
def main():
parser = argparse.ArgumentParser(description="Compute cgroup cpu.shares values from a list of CPU %, and the reverse.")
group = parser.add_mutually_exclusive_group()
group.add_argument("-p2s",
"--percent_to_share",
help="from CPU %% to cpu.shares",
metavar='percent',
type=strictly_positive_integer,
nargs='+')
group.add_argument("-s2p",
"--share_to_percent",
help="from cpu.shares to CPU %%",
metavar='share',
type=strictly_positive_integer,
nargs='+')
if len(sys.argv) == 1:
parser.print_help()
sys.exit(1)
args = parser.parse_args()
if args.percent_to_share:
percent_to_share(args.percent_to_share)
if args.share_to_percent:
share_to_percent(args.share_to_percent)
sys.exit(0)
if __name__ == "__main__":
main()
|
35a5ded7d1e074aab70c394573bab617a126df88 | randompyslices/randomslices | /a_random_sample_of_python/sample_no_repeats.py | 827 | 3.796875 | 4 | #!/usr/bin/env python
from random import randint
import numpy as np
from timeit import timeit
def sample_without_repeats(M,N):
while True:
s = [randint(0,M) for i in xrange(0,2*N)][:N]
if len(set(s)) == N:
return s
def sample_no_repeats(M,N):
while True:
s = np.random.randint(0,M,N)
if len(set(s)) == N:
return s
print 'Timing 3 approaches to obtaining a sample without repeats...'
print 'randint: ', timeit('sample_without_repeats(1000,100)',
setup = 'from __main__ import sample_without_repeats',number=100)
print 'NumPy: ', timeit('sample_no_repeats(1000,100)',
setup='from __main__ import sample_no_repeats',number=100)
print 'random.sample: ', timeit('random.sample(xrange(0,1000),100)',
setup='import random',number=100)
|
8966dd253242fe974e2c463d44f75383af7b03ac | Aaryan-R-S/Python-Tutorials | /Practice Problems/x+y.py | 392 | 3.65625 | 4 | def move(mylist):
for i in range(len(mylist)-1):
if mylist[i] == '1':
mylist[i] = '0'
if mylist[i+1] == '0':
mylist[i+1] = '1'
else:
mylist[i+1] == '0'
return mylist
if __name__ == "__main__":
a = list('1011111111111')
print(a)
while a != move(a.copy()):
a = move(a.copy())
print(a) |
dfe934033830d20983bdcb0d5746598b937b224a | Antohnio123/Python | /Practice/a.makarov/Lection8-ExamWork/Task6-finished.py | 2,108 | 3.671875 | 4 | def myformat (string, *args):
simple = False
numerate = False
class WrongPositions(Exception):
pass
def Poscheck():
if simple == numerate == True:
raise WrongPositions()
if not isinstance(string, str):
print("Введённые аргументы не являются строками, передайте строки в функцию.")
return (1)
A=list(args)
S=list(string) # Перевели строку в лист знаков
Pos = []
i=0
while "{" in S and "}" in S:
Ind1 = S.index('{')
Ind2 = S.index('}')
# print(str(Ind1)+ " " + str(Ind2)) # Проверка 1 - индексы
p = ''.join((S[Ind1:(Ind2 + 1)]))
# print(p) # Проверка 2
if p == "{}":
simple = True
try:
Poscheck()
except WrongPositions:
print(
"В строке пристутствуют нумерованные и простые позиции, должно быть что-то одно, программа закрывается.")
exit(code=1)
S[Ind1:(Ind2 + 1)] = A[i]
i+=1
k = p.replace("{", "")
k = k.replace("}", "")
if k.isdigit():
numerate = True
try:
Poscheck()
except WrongPositions:
print(
"В строке пристутствуют нумерованные и простые позиции, должно быть что-то одно, программа закрывается.")
exit(code=1)
S[Ind1:(Ind2 + 1)] = A[int(k)]
Res = ''.join(S)
return Res
# Код завершён! Ниже - проверка --------------------------------------------------------------------------
s = "dfghdhsh {} jfsfjh {} shgs {} hsg hfdgdfg"
print(s.format('AAAA', 'BBBB', 'CCCC', 'DDDD'))
print(myformat(s, 'AAAA', 'BBBB', 'CCCC', 'DDDD'))
|
9c4e73ad9212216daf7e9320b854da6ba61be4ca | jingong171/jingong-homework | /闫凡/2017310390-闫凡-第五次作业-金融工程17-1/10-6加法运算.py | 400 | 3.78125 | 4 | #使用try-excpet代码块来处理异常
try:
#输入第一个数
num1=input('请输入两个数字,计算他们的和,请输入第一个数字')
#输入第二个数
num2=input('请输入第二个数字')
#执行计算并打印
num=float(num1)+float(num2)
print('他们的和为'+str(num))
#处理异常
except ValueError:
print('请输入两个数字,不要输入文本')
|
363a6223e3af958569cc18ec2975261a400701af | lollinim/date-a-scientist | /capstone/dating_skeleton_Question1.py | 3,955 | 3.5 | 4 | import pandas as pd
from matplotlib import pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import MultinomialNB
#1.) Import Data to Dataframe:
df = pd.read_csv("profiles.csv")
'''Extract Ethinicty/Religion Name from first word of the string, create map based on religion_mapping and insert this
back into the dataframe as a new column.
*Note ethnicity can be a list, we are only using the first listed ethnicity assuming users listed them in order of
importance to them.
'''
religions = df['religion'].str.extract(r'^(\w+)')
ethnicity = df['ethnicity'].str.extract(r'([\w ]+)')
# Mappings
religion_mapping = {'atheism': 0, 'agnosticism': 1, 'christianity': 2, 'catholicism': 3, 'judaism': 4, 'buddhism': 5,
'hinduism': 6, 'islam': 7, 'other': 8}
ethnicity_mapping = {'asian': 0, 'black': 1, 'hispanic ': 2, 'indian': 3, 'middle eastern': 4, 'native american': 5,
'pacific islander': 6, 'white': 7, 'other': 8}
drug_mapping = {"never": 0, "sometimes": 1, "often": 2}
alcohol_mapping = {'not at all': 0, 'rarely': 1, 'socially': 2, 'often': 3, 'very often': 4, 'desperately': 5}
# Pull used data/mappings into a centralized dataframe.
data = pd.DataFrame()
data['religion_map'] = religions[0].map(religion_mapping)
data['ethnicity_map'] = ethnicity[0].map(ethnicity_mapping)
data['drug_map'] = df.drugs.map(drug_mapping)
data['alcohol_map'] = df.drinks.map(alcohol_mapping)
data = data.dropna()
# Look at Freqency of each religion based on Ethnicity
relg_freq = data.groupby(['ethnicity_map','religion_map']).size().reset_index(name='relg_frequency')
drug_freq = data.groupby(['drug_map','religion_map']).size().reset_index(name='relg_frequency')
alc_freq = data.groupby(['alcohol_map','religion_map']).size().reset_index(name='relg_frequency')
drug_counts = data.drug_map.value_counts()
relg_counts = data.ethnicity_map.value_counts()
alc_counts = data.alcohol_map.value_counts()
# Rather than frequency look at the percentage of religion occurrence in each subset.
p_list = []
for i in range(len(relg_freq)):
percentage = round(100 * (relg_freq['relg_frequency'][i] / relg_counts[relg_freq['ethnicity_map'][i]]), 2)
p_list.append(percentage)
relg_freq['relg_percentage'] = p_list
p_list = []
for i in range(len(drug_freq)):
percentage = round(100 * (drug_freq['relg_frequency'][i] / drug_counts[drug_freq['drug_map'][i]]), 2)
p_list.append(percentage)
drug_freq['relg_percentage'] = p_list
p_list = []
for i in range(len(alc_freq)):
percentage = round(100 * (alc_freq['relg_frequency'][i] / alc_counts[alc_freq['alcohol_map'][i]]), 2)
p_list.append(percentage)
alc_freq['relg_percentage'] = p_list
# Plot graphs showing the religion vs mapped field where size of the data point is based on percentage of occurrence.
plt.subplot(221)
plt.scatter(relg_freq['ethnicity_map'], relg_freq['religion_map'], s=relg_freq['relg_percentage']**2)
plt.xlabel("Ethnicity")
plt.ylabel("Religion")
plt.subplot(222)
plt.scatter(drug_freq['drug_map'], drug_freq['religion_map'], s=drug_freq['relg_percentage']**2)
plt.xlabel("drug_usage")
plt.ylabel("Religion")
plt.subplot(223)
plt.scatter(alc_freq['alcohol_map'], alc_freq['religion_map'], s=alc_freq['relg_percentage']**2)
plt.xlabel("alcohol_usage")
plt.ylabel("Religion")
X_train, X_test, y_train, y_test = train_test_split(data[data.columns[-3:]], data['religion_map'], random_state=42)
#KNN Classification
accuracies = []
for k in range(1, 50):
Classifier = KNeighborsClassifier(n_neighbors=k)
Classifier.fit(X_train, y_train)
accuracies.append(Classifier.score(X_test, y_test))
plt.subplot(224)
plt.plot(range(1, 50), accuracies)
plt.xlabel('K')
plt.ylabel('Validation Accuracy')
plt.title('Religion Classifier Accuracy')
plt.show()
#Naive Bayes Classification
Classifier = MultinomialNB()
Classifier.fit(X_train,y_train)
score = Classifier.score(X_test, y_test)
print(score) |
4a9532569b20b98c6489c2af042e6a0da955999b | shashwatkathuria/Data-Structures-And-Algorithms | /Shortest Path - Bellman Ford - All Sources/allpairsbellman.py | 7,303 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jul 9 07:31:55 2018
@author: Shashwat Kathuria
"""
# BELLMAN FORD ALL PAIRS SHORTEST PATH ALGORITHM - USING DYNAMIC PROGRAMMING
# ALL PAIRS SHORTEST PATHS
# Assignment answers
# g3 = -19
# g2, g1 = negative cycle
def main():
# Reading the input file and saving corresponding graph and
# edges info inside graph object
file = open("g1.txt", "r")
graphInfo = file.readline().split(" ")
noOfVertices, noOfEdges1 = int(graphInfo[0]), int(graphInfo[1])
directedGraph = DirectedGraph(noOfVertices = noOfVertices, noOfEdges = noOfEdges1)
# For loop for g1.txt, g2.txt and g3.txt
for i in range(noOfEdges1):
s = file.readline().split(" ")
edge = DirectedEdge( startVertex = int(s[0]), endVertex = int(s[1]), edgeWeight = int(s[2]) )
print(edge)
directedGraph.addEdge(edge)
directedGraph.graph[edge.startVertex].append(edge.endVertex)
## For loop for dijkstraDataCopy.txt
## Only 1 for loop is to be used at a time, other is to be commented
# file = open("dijkstraDataCopy.txt", 'r')
# noOfVertices = 200
#
# directedGraph = DirectedGraph(noOfVertices = 200, noOfEdges = 0)
# for i in range(noOfVertices):
#
# vertexAndEdgesInfo = file.readline().split('\t')
# vertex = int( vertexAndEdgesInfo[0] )
# edgesInfo = vertexAndEdgesInfo[1 : -1]
#
# for edge in edgesInfo:
#
# edgeInfo = edge.split(',')
# directedEdge = DirectedEdge(startVertex = vertex, endVertex = int( edgeInfo[0] ), edgeWeight = int( edgeInfo[1] ))
# print("ADDED EDGE : " + str(directedEdge) )
# directedGraph.addEdge( directedEdge )
# directedGraph.graph[directedEdge.startVertex].append(directedEdge.endVertex)
# Computing the indegree neighbours for each vertex in graph
directedGraph.computeInDegreeNeighbours()
# Calling bellman ford algorithm on graph
bellmanFord(directedGraph)
def bellmanFord(directedGraph):
"""Bellman Ford Algorithm function to compute all shortest paths.Inpuut is the directed graph."""
n = directedGraph.noOfVertices # -1 <- if sure that no negative cycle is present
# Boolean for keeping track for any negative cycle's presence
negativeCycle = False
# Looping for each source
for source in range(1, directedGraph.noOfVertices + 1):
# Initializing shortest paths of graphs with standard values
for destination in range(1, directedGraph.noOfVertices + 1):
for noOfEdgesTraversed in range(0, n + 1):
if source == destination:
directedGraph.shortestPaths[source, destination, noOfEdgesTraversed] = 0
else:
directedGraph.shortestPaths[source, destination, noOfEdgesTraversed] = 9999999
# Looping for maximum number of edges allowed in the current path concerned
for noOfEdgesTraversed in range(1, n + 1):
print("COMPUTING SHORTEST PATHS FROM SOURCE VERTEX : " + str(source) + " EDGES TRAVERSED COUNTER : " + str(noOfEdgesTraversed) )
# Looping for each possible destination
for vertex in range(1, directedGraph.noOfVertices + 1):
# Storing previous value
path1 = directedGraph.shortestPaths[source, vertex,noOfEdgesTraversed - 1]
# List to store new candidates possible
path2Candidates = []
for neighbour in directedGraph.inDegreeNeighbours[vertex]:
path2Candidates.append( directedGraph.shortestPaths[source, neighbour, noOfEdgesTraversed - 1] + directedGraph.edges[neighbour, vertex] )
# if new candidate paths are present, shortest path is the minimum of
# the number of edges - 1 path and mimum of path2 candidates
if path2Candidates != []:
minimumPath2Candidate = min(path2Candidates)
directedGraph.shortestPaths[source, vertex, noOfEdgesTraversed] = min(path1, minimumPath2Candidate)
# else shortest path is the number of edges - 1 graph
else:
directedGraph.shortestPaths[source, vertex, noOfEdgesTraversed] = path1
# if the value of shortest path for any vertex changes from n - 1 to n edges,
# it means the directed graph concerned has a negative cycle
if directedGraph.shortestPaths[source, vertex, n] != directedGraph.shortestPaths[source, vertex, n - 1]:
print("\n\nThis graph has a Negative Cycle present. Therefore, shortest path has no meaning for this graph.\n\n")
negativeCycle = True
break
# if no negative cycles, go ahead and print the shortest path for each vertex and destination
if negativeCycle == False:
print("\n\nTHE SHORTEST PATHS ARE : \n\n")
# Printing shortest paths for each source and destination
for i in range(1, directedGraph.noOfVertices + 1):
for j in range(1, directedGraph.noOfVertices + 1):
print("The shortest path from " + str(i) + " to " + str(j) + " has distance : " + str(directedGraph.shortestPaths[i, j, n - 1]) )
print("\n")
class DirectedEdge:
def __init__(self, startVertex, endVertex, edgeWeight):
"""Function to initialize edge.Inputs are the start vertex, end vertex and the edge weight."""
self.startVertex = startVertex
self.endVertex = endVertex
self.edgeWeight = edgeWeight
def __str__(self):
"""Function to print the edge."""
return "Edge from " + str(self.startVertex) + " to " + str(self.endVertex) + " Weight " + str(self.edgeWeight)
class DirectedGraph:
def __init__(self,noOfVertices, noOfEdges):
"""Function to initialize the graph. Inputs are the number of vertices and number of edges."""
self.edges = {}
self.noOfVertices = noOfVertices
self.noOfEdges = noOfEdges
self.graph = {}
for vertex in range(1, self.noOfVertices + 1):
self.graph[vertex] = [False]# self.graph[vertex]=[Visited or Not,neighbour1,neighour2,..]
self.inDegreeNeighbours = {}
self.shortestPaths = {}
def addEdge(self,directedEdge):
"""Funtion to add a directed edge to the graph list of edges."""
self.edges[directedEdge.startVertex, directedEdge.endVertex] = directedEdge.edgeWeight
def computeInDegreeNeighbours(self):
"""Computes the indegree neighbours of all the vertices of the graph
and stores it in the format [vertexVisitedOrNotVisited,indegreeneighbour1,indegreeneighbour2,...]"""
for vertex in range(1, self.noOfVertices + 1):
print("COMPUTING IN DEGREE NEIGHBOURS ON VERTEX NUMBER : " + str(vertex))
self.inDegreeNeighbours[vertex] = []
for key in self.graph:
if vertex in self.graph[key][1:]:
self.inDegreeNeighbours[vertex].append(key)
if __name__ == "__main__":
main()
|
28b488720006468617062d6ba12271f80022c42c | copycat123/Vending_machine | /Vending_machine.py | 680 | 4.125 | 4 | sodas = ["pepsi", "cherry coke", "sprite"]
chips = ["Doritos", "chetoz"]
candy = ["Snickers", "M&M", "Twizz"]
while True:
choice = input("Would you like a SODAS, some CHIPS , or a CANDY? ").lower()
try:
if choice == "sodas":
snack = sodas.pop()
elif choice == "chips":
snack = chips.pop()
elif choice == "candy":
snack = candy.pop()
else:
print("Sorry i didn't understand that.")
continue
except IndexError:
print("Sorry all out of {}".format(choice))
else:
print("Here is your {}: {}".format(choice, snack))
# complete
|
04b8548da41d9f7bde9040cd120b5d245e05e782 | RobertoRGM/Curso_Python | /ex014.py | 191 | 3.953125 | 4 | #Conversor de temperaturas
t = float(input('Informe a temperatura em °C:'))
f = ((9 * t) / 5) + 32
print('A temperatura de {:.2f}°C convertida em Farenheit é {:.2f}°F'.format(t,f))
|
6dab702837eb43e69c7a42247755da14a706e034 | MrHamdulay/csc3-capstone | /examples/data/Assignment_5/prmkov001/question1.py | 1,484 | 3.640625 | 4 | #Kovlin Perumal
#Print Menu
print("Welcome to UCT BBS")
print("MENU")
print("(E)nter a message")
print("(V)iew message")
print("(L)ist files")
print("(D)isplay file")
print("e(X)it")
message = "no message yet"
#initialize selection variable
sel = input("Enter your selection:\n")
#Close if sel = X
if sel == 'X' or sel == 'x':
print("Goodbye!")
while(sel!='X' and sel!='x') :
if sel == 'E' or sel == 'e':
message = input("Enter the message:\n")#Enter message
if sel == 'V' or sel == 'v':
print("The message is:", message)#View message
if sel == 'L' or sel == 'l' :
print("List of files: 42.txt, 1015.txt")
if sel == 'D' or sel == 'd': #Display contents of text files
fName = input("Enter the filename:\n")
if fName == '42.txt':
myfile = open("42.txt", 'r')
for line in myfile: print(line,end = '')
print()
elif fName == '1015.txt':
myfile = open("1015.txt", 'r')
for line in myfile: print(line,end = '')
print()
else:
print("File not found")
print("Welcome to UCT BBS")
print("MENU")
print("(E)nter a message")
print("(V)iew message")
print("(L)ist files")
print("(D)isplay file")
print("e(X)it")
sel = input("Enter your selection:\n")
if sel == 'X' or sel == 'x':
print("Goodbye!")
|
8e2ad9dfd7fd7a7073ce65d65c2607b07bff010b | nnar2201/python1 | /Nayanarrays.py | 1,589 | 3.890625 | 4 | '''
JDoe_JSmith_1_4_2: Read and show an image.
'''
import matplotlib.pyplot as plt
import os.path
import numpy as np # “as” lets us use standard abbreviations
'''Read the image data'''
# Get the directory of this python script
directory = os.path.dirname(os.path.abspath(__file__))
# Build an absolute filename from directory + filename
filename = os.path.join(directory, 'woman.jpg')
# Read the image data into an array
img = plt.imread(filename)
'''Show the image data'''
# Create figure with 1 subplot
fig, ax = plt.subplots(1, 1)
# Show the image data in a subplot
ax.imshow(img, interpolation='none')
# Show the figure on the screen
fig.show()
# Read the data into an array
img = plt.imread(filename)
###
# Make a rectangle of pixels yellow
###
height = len(img)
width = len(img[0])
for row in range(420, 470):
for column in range(135, 162):
img[row][column] = [0, 255, 0] # red + green = yellow
img = plt.imread(filename)
###
# Change a region if condition is True
###
height = len(img)
width = len(img[0])
for r in range(155):
for c in range(width):
if sum(img[r][c])>500: # brightness R+G+B goes up to 3*255=765
img[r][c]=[255,0,255] # R + B = magenta
for r in range(420,470):
for c in range(width):
if sum(img[r][c])>300: # brightness R+G+B goes up to 3*255=765
img[r][c]=[255,0,255] # R + B = magenta
if __name__ == ¨__main__¨:
image = make_mask(100,70,10)
fig, ax = plt.subplots(1, 1)
ax.imshow(image)
fig.show()
|
c12fe8deb91d2c168b0f17766ea0dac4f8b0edca | StuQAlgorithm/AlgorithmHomework | /3rd/homework_1/id_69/103-BinaryTreeZigzagLevelOrderTraversal.py | 1,468 | 4.09375 | 4 | # Given a binary tree, return the zigzag level order traversal of
# its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
# For example:
# Given binary tree [3,9,20,null,null,15,7],
# 3
# / \
# 9 20
# / \
# 15 7
# return its zigzag level order traversal as:
# [
# [3],
# [20,9],
# [15,7]
# ]
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque
class Solution(object):
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if root is None: return []
direction = 1
last_size = 1
queue = deque()
queue.append(root)
res = []
while queue:
level = []
for i in range(last_size):
node = queue.popleft()
level.append(node.val)
if direction < 0:
if node.right: queue.append(node.right)
if node.left: queue.append(node.left)
else:
if node.left: queue.append(node.left)
if node.right: queue.append(node.right)
res.append(level)
direction = -direction
queue.reverse()
last_size = len(queue)
return res
|
456afc6db24ba6806a1b0f2017fabb808a342c6c | brez/yijing | /yijing/iching.py | 1,685 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
"Countless words count less than the silent balance between yin and yang"
- Lao Tzu, Tao Te Ching
"""
import random
YIN = 0
YANG = 1
TAILS = 2
HEADS = 3
THREE = 3
HEXAGRAMS = {
1: '䷁', 2: '䷖', 3: '䷇', 4: '䷓', 5: '䷏', 6: '䷢', 7: '䷬', 8: '䷋', 9: '䷎', 10: '䷳', 11: '䷦', 12: '䷴',
13: '䷽', 14: '䷷', 15: '䷞', 16: '䷠', 17: '䷆', 18: '䷃', 19: '䷜', 20: '䷺', 21: '䷧', 22: '䷿', 23: '䷮',
24: '䷅', 25: '䷭', 26: '䷑', 27: '䷯', 28: '䷸', 29: '䷟', 30: '䷱', 31: '䷛', 32: '䷫', 33: '䷗', 34: '䷚',
35: '䷂', 36: '䷩', 37: '䷲', 38: '䷔', 39: '䷐', 40: '䷘', 41: '䷣', 42: '䷕', 43: '䷾', 44: '䷤', 45: '䷶',
46: '䷝', 47: '䷰', 48: '䷍', 49: '䷒', 50: '䷨', 51: '䷻', 52: '䷼', 53: '䷵', 54: '䷥', 55: '䷹', 56: '䷉',
57: '䷊', 58: '䷙', 59: '䷄', 60: '䷈', 61: '䷡', 63: '䷪', 64: '䷀'
}
def _heads_or_tails():
return random.randint(TAILS, HEADS)
# rolls three coins and sums the total, even are yin, odd are yang
def _line():
six_thru_nine = 0
for coin in range(THREE):
six_thru_nine += _heads_or_tails()
return (six_thru_nine % 2)
def _convert_bitmap_to_int_and_add_offset(bitmap):
return int(bitmap, 2) + 1
# main prediction method, requires a seed, reversed because they grow from the bottom
def predict(seed):
random.seed(seed)
hexagram = []
for line in range(6):
hexagram.append(str(_line()))
return _convert_bitmap_to_int_and_add_offset("".join(reversed(hexagram)))
# lastly get the unicode value if interested
def lookup(hexagram_base10):
return HEXAGRAMS[hexagram_base10]
|
e928dea8a91e45e1c2dce549d81edd3622a93c5c | Fisher-Wang/ps_image_alignment | /points.py | 1,038 | 3.59375 | 4 | import pygame
import math
class Points:
def __init__(self, screen):
self.screen = screen
self.points = []
self.RADIUS = 10
def update(self, events):
for event in events:
if event.type == pygame.MOUSEBUTTONDOWN and event.button == pygame.BUTTON_LEFT:
pos = pygame.mouse.get_pos()
print(pos)
in_circle = False
for idx, point in enumerate(self.points):
dx = pos[0] - point[0]
dy = pos[1] - point[1]
r = math.sqrt(dx**2 + dy**2)
if r < self.RADIUS:
in_circle = True
del self.points[idx]
break
if not in_circle:
self.points.append(pos)
def draw(self):
for point in self.points:
pygame.draw.circle(self.screen, (255,0,0), point, self.RADIUS, width=1)
pygame.draw.circle(self.screen, (255,0,0), point, 1) |
b2615c0b9f8e0e7565497568bea9defc6745bc66 | raghulrage/Python-programs | /Basic-programs/balancing scale.py | 1,926 | 3.734375 | 4 | l=[[3,4],[1,2,7,7]]
l=[[13,4],[1, 2, 3, 6, 14]]
l=[[5,9],[1, 2, 6, 7]]
m=max(l[0])
n=min(l[0])
d=m-n
l2,l3,l4,l5=l[1],[],[],[]
for i in range(len(l2)-1):
if(l2[i]+l2[i+1]==d):
l3.append([l2[i],l2[i+1]])
if(l3==[]):
for i in l2:
l4.append(l[0][0]+i)
l5.append(l[0][1]+i)
for i in range(len(l4)):
if(l4[i] in l5):
s=[l[1][l4.index(l4[i])],l[1][l5.index(l4[i])]]
if(d is min(s)):
print(d)
else:
print(s)
break
else:
print ('No')
else:
print(l3[0])
'''Have the function ScaleBalancing(strArr) read strArr which will contain two elements,
the first being the two positive integer weights on a balance scale (left and right sides) and
the second element being a list of available weights as positive integers.
Your goal is to determine if you can balance the scale by using the least amount of weights from the list,
but using at most only 2 weights. For example: if strArr is ["[5, 9]", "[1, 2, 6, 7]"]
then this means there is a balance scale with a weight of 5 on the left side and 9 on the right side.
It is in fact possible to balance this scale by adding a 6 to the left side from the list of weights and
adding a 2 to the right side. Both scales will now equal 11 and they are perfectly balanced.
Your program should return a comma separated string of the weights that were used from the list in ascending order,
so for this example your program should return the string 2,6
There will only ever be one unique solution and the list of available weights will not be empty.
It is also possible to add two weights to only one side of the scale to balance it.
If it is not possible to balance the scale then your program should return the string not possible.
Examples
Input: ["[3, 4]", "[1, 2, 7, 7]"]
Output: 1
Input: ["[13, 4]", "[1, 2, 3, 6, 14]"]
Output: 3,6
'''
|
d7024b91bea18daffaecba5828334af17e6a8135 | giuliana-marquesi/estudo-python | /coursera/decomposicao_fatores.py | 704 | 3.84375 | 4 | def main():
num = int(input("Digite um numero: "))
primo = 2
multiplicidade = 0
while num > 1:
while num % primo == 0:
num = num // primo
multiplicidade = multiplicidade + 1
if multiplicidade > 0:
print("Fator", primo, "multiplicidade", multiplicidade)
primo = primo + 1
multiplicidade = 0
def proximo_primo(primo):
primo = primo + 1
while not confere_numero(primo):
primo = primo + 1
return primo
def confere_numero(primo):
n = 2
while n < primo:
if primo % n == 0:
return False
else:
n = n + 1
return True
main()
|
408092919abea01fd0d181587703f22ff8e7af4b | abhisoniks/interviewbit | /tree/symmetricBinaryTree.py | 615 | 3.921875 | 4 | # Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param A : root node of tree
# @return an integer
def isSymmetric(self, A):
return self.areChildSymmetric(A.left,A.right)
def areChildSymmetric(self, A, B):
if A==B:
return 1
if A==None or B==None:
return 0
if A.val!=B.val:
return 0
p=self.areChildSymmetric(A.left,B.right)
q=self.areChildSymmetric(A.right,B.left)
return p and q
|
a8cb5666101f28a519e21286012130267e1b12ef | ParkerCS/ch-web-scraping-bernhardtjj | /weather_scrape.py | 1,240 | 4.0625 | 4 | # Below is a link to a 10-day weather forecast at weather.com
url = "https://weather.com/weather/tenday/l/USIL0225:1:US"
# Use urllib and BeautifulSoup to scrape data from the weather table.
import urllib.request
from bs4 import BeautifulSoup
# Print a brief synopsis of the weather for the next 10 days.
# Include the day, date, high temp, low temp, and chance of rain.
# You can customize the text as you like, but it should be readable
# for the user. You will need to target specific classes or other
# attributes to pull some parts of the data.
# (e.g. Wednesday, March 22: the high temp will be 48 with a low of 35, and a 20% chance of rain). (25pts)
page = urllib.request.urlopen(url)
soup = BeautifulSoup(page.read(), "lxml")
if soup.find("table"):
data_list = [[y.text.strip() for y in x.findAll("td")][1:] for x in soup.find("table").findAll("tr")][1:]
data_list[0][0] = "Now" + data_list[0][0][5:]
for day in data_list:
print(day[0][:3] + ", " + day[0][3:] + ": will be " + day[1] + ". The high temp will be " +
day[2].split("°")[0] + " with a low of " +
day[2].split("°")[0] + ", and a " + day[3] + " chance of rain.")
else:
print("Try again -- your connection is bad.")
|
9c653e97fde549a940aeceaf7ef0cfa8f8f2b419 | kunalverma75/AprioriAlgorithm | /Apriori_Algorithm_for_Generating_Frequent_Itemsets.py | 12,188 | 4.15625 | 4 | #!/usr/bin/env python
# coding: utf-8
# # Apriori Algorithm for Generating Frequent Itemsets
# ##### by Kunal Verma
# ## Introduction
# Apriori invented by Rakesh Agarwal and Ramakrishnan Srikant in 1994 is
# a well known algorithm in data mining. Apriori Algorithm is used in finding frequent itemsets. Identifying associations between items in a dataset of transactions can be useful in various data mining tasks. The challenge is that given a dataset D having T transactions each with n number of attributes, how to find itemsets that appear frequently in D?
#
#
# Using this algorithm we are trying to find significant terms obtained from a collection of electronic document which can be further used for text classification, topic finding and many other applications.
# ## Definitions
#
# 1) Let T = {$t_i, t2,..., t_N $} be the set of all transactions and I = {$h, h i_d$} be the set of all items in a transaction database. Each transaction $t_j$ consists of items which are subsets of I.
#
#
# 2) Itemset: It is defined as a collection of zero or more items in a transaction. If an itemset has no items in it then it is termed as a null itemset, and if it contains k items then it is referred as a k-itemset.
#
# 3) Support count: Support count is defined as the number of transactions that contain a particular itemset. It is the most important property of an itemset.
#
#
# Now using the rules of association and concepts of support and confidence, we are going to describe how the Apriori actually works.
#
# ## Apriori Algorithm
# Apriori works on the following principle which is also known as apriori property:
#
# If an itemset is frequent, then all of its subsets must also be frequent.
#
# The Apriori algorithm needs a minimum support level as an input and a data set. The algorithm will generate a list of all candidate itemsets with one item. The transaction data set will then be scanned to see which sets meet the minimum support level. The sets which are below the specified minimum support level are removed from further computations.
# Now we will demonstrate the step-by-step approach of the algorithm using an example.
# | TID | Items |
# |-----|---------|
# | 100 | 1,3,4 |
# | 200 | 1,3,4 |
# | 300 | 1,2,3,5 |
# | 400 | 2,5 |
# Our dataset contains four transactions which could be sentences in case of documents with above particulars (sets/words in that sentence)
# #### Step 1: Generating 1-itemset table
# Generate the 1-itemset table by enumerating all the unique elements of items. Correspondingly calculate their support
# | Itemset | Support |
# |---------|---------|
# | {1} | 2 |
# | {2} | 3 |
# | {3} | 3 |
# | {4} | 1 |
# | {5} | 3 |
# Support value is calculated as support ($a -> b$) = $\frac{\text{Number of transactions a and b appear}} {\text{total transactions}}$. But for the sake of simplicity we use support value as number of times each transaction appears. We also assume support threshold = 2.
# Now as we can see the support of Itemset 4 is 1 which is less then our threshold of 2. So we remove that itemset.
# Now we create the 2-itemset table
# #### Step 2 : Generate 2-itemsets table
# From the above 1-itemset table, we look at the different combinations of size 2 itemsets, not considering the eliminated itemsets. Correspondingly calculating the support of each 2-itemset
# | Itemset | Support |
# |---------|---------|
# | {1,2} | 1 |
# | {1,3} | 2 |
# | {1,5} | 1 |
# | {2,3} | 2 |
# | {2,5} | 3 |
# | {3,5} | 2 |
# Now repeat the above process of removing itemsets with support less than 2. and using the new 2-itemset create 3-itemset table. In this example {1,2} and {1,5} are removed.
# #### Step 3 : Generate 3-itemsets table
# The corresponding 3-itemseet table would be formed using all combinations of above accepted size 2 itemsets
# | Itemset | Support |
# |---------|---------|
# | {2,3,5} | 2 |
# Now we have to stop because 4-itemsets cannot be generated as there are only three items left.
#
# Following are the frequent itemsets that we have generated and which are above support threshold: {1}, {2}, {3}, {5}, {1, 3}, {2, 3}, {2, 5}, {3, 5} and {2, 3, 5}
# ### Pseudo-code for the whole Apriori algorithm
# 
# 1) Create a list of candidate itemsets of length k
#
# 2) Scan the dataset to see if each itemset is frequent
#
# 3) Keep frequent itemsets to create itemsets of length k+1
# ## Association analysis
# Looking for hidden relationships in large datasets is known as association analysis or association rule learning. The problem is, finding different combinations of items can be a time-consuming task and prohibitively expensive in terms of computing power.
#
# Association rules suggest that a strong relationship exists between two items.
# The support and confidence are ways we can quantify the success of our association analysis.
#
# The support of an itemset is defined as the percentage of the dataset that contains this itemset.
#
#
# The confidence for a rule P ➞ H is defined as support(P | H)/ support(P). Remember, in Python, the | symbol is the set union; the mathematical symbol is U. P | H means all the items in set P or in set H.
# 1) To find association rules, we first start with a frequent itemset. We know this set of items is unique, but we want to see if there is anything else we can get out of these items. One item or one set of items can imply another item.
# 2) We use this to find association between the above generated frequent itemsets. Also we calculate confidence for each association and prune those with confidence below the minimum threshold
# This gives you three rules: {1} ➞ {3},{5} ➞ {2},and {2} ➞ {5}. It’s interesting to see that the rule with 2 and 5 can be flipped around but not the rule with 1 and 3
# ## Code for the Apriori Algorithm and Association Rules
# ## Apriori algorithm
# 
# The following code is referenced from the blog on Apriori Algorithm on adataanlyst.com
# Scanning the dataset
# For each transaction in the dataset:
#
# For each candidate itemset, can:
#
# Check to see if can is a subset of tran
#
# If so increment the count of can
#
# For each candidate itemset:
#
# If the support meets the minimum, keep this item
#
# Return list of frequent itemsets
# In[20]:
from IPython.display import Latex
# In[10]:
from numpy import *
# Dataset for testing
# In[13]:
def loadDataSet():
return [[1, 3, 4], [2, 3, 5], [1, 2, 3, 5], [2, 5]]
# This creates 1-itemset table(C1). we’ll scan the dataset to see if these one itemsets meet our minimum support requirements. The itemsets that do meet our minimum requirements become L1. L1 then gets combined to become C2 and C2 will get filtered to become L2.
#
# Frozensets are sets that are frozen, which means they’re immutable; you can’t change them. You need to use the type frozenset instead of set because you’ll later use these sets as the key in a dictionary.
# In[8]:
def createC1(dataSet):
C1 = []
for transaction in dataSet:
for item in transaction:
if not [item] in C1:
C1.append([item])
C1.sort()
return list(map(frozenset, C1))
# Next function takes three arguments: a dataset, Ck, a list of candidate sets, and minSupport, which is the minimum support you’re interested in. This is the function you’ll use to generate L1 from C1.
# In[11]:
def scanD(D, Ck, minSupport):
ssCnt = {}
for tid in D:
for can in Ck:
if can.issubset(tid):
if not can in ssCnt: ssCnt[can]=1
else: ssCnt[can] += 1
numItems = float(len(D))
retList = []
supportData = {}
for key in ssCnt:
support = ssCnt[key]/numItems
if support >= minSupport:
retList.insert(0,key)
supportData[key] = support
return retList, supportData
# In[14]:
dataSet = loadDataSet()
dataSet
# In[15]:
C1 = createC1(dataSet)
C1
# In[17]:
#D is a dataset in the setform.
D = list(map(set,dataSet))
D
# Now that you have everything in set form, you can remove items that don’t meet our minimum support.
# In[18]:
L1,suppDat0 = scanD(D,C1,0.5)
L1
# Creating candidate itemsets: Ck
#
# The function aprioriGen() will take a list of frequent itemsets, Lk, and the size of the itemsets, k, to produce Ck
# In[19]:
def aprioriGen(Lk, k): #creates Ck
retList = []
lenLk = len(Lk)
for i in range(lenLk):
for j in range(i+1, lenLk):
L1 = list(Lk[i])[:k-2]; L2 = list(Lk[j])[:k-2]
L1.sort(); L2.sort()
if L1==L2: #if first k-2 elements are equal
retList.append(Lk[i] | Lk[j]) #set union
return retList
# it will take the itemsets {0}, {1}, {2} and so on and produce {0,1} {0,2}, and {1,2}
# In[26]:
def apriori(dataSet, minSupport = 0.5):
C1 = createC1(dataSet)
D = list(map(set, dataSet))
L1, supportData = scanD(D, C1, minSupport)
L = [L1]
k = 2
while (len(L[k-2]) > 0):
Ck = aprioriGen(L[k-2], k)
Lk, supK = scanD(D, Ck, minSupport)#scan DB to get Lk
supportData.update(supK)
L.append(Lk)
k += 1
return L, supportData
# Now we run this main function apriori for implementing the apriori algorithm.
# ## Mining association rules
# The generateRules() function takes three inputs: a list of frequent itemsets, a dictionary of support data for those itemsets, and a minimum confidence threshold.
# In[21]:
def generateRules(L, supportData, minConf=0.7): #supportData is a dict coming from scanD
bigRuleList = []
for i in range(1, len(L)):#only get the sets with two or more items
for freqSet in L[i]:
H1 = [frozenset([item]) for item in freqSet]
if (i > 1):
rulesFromConseq(freqSet, H1, supportData, bigRuleList, minConf)
else:
calcConf(freqSet, H1, supportData, bigRuleList, minConf)
return bigRuleList
# calcConf() calculates the confidence of the rule and then find out the which rules meet the minimum confidence.
# In[24]:
def calcConf(freqSet, H, supportData, brl, minConf=0.7):
prunedH = [] #create new list to return
for conseq in H:
conf = supportData[freqSet]/supportData[freqSet-conseq] #calc confidence
if conf >= minConf:
print (freqSet-conseq,'-->',conseq,'conf:',conf)
brl.append((freqSet-conseq, conseq, conf))
prunedH.append(conseq)
return prunedH
# rulesFromConseq() generates more association rules from our initial dataset. This takes a frequent itemset and H, which is a list of items that could be on the right-hand side of a rule.
# In[27]:
def rulesFromConseq(freqSet, H, supportData, brl, minConf=0.7):
m = len(H[0])
if (len(freqSet) > (m + 1)): #try further merging
Hmp1 = aprioriGen(H, m+1)#create Hm+1 new candidates
Hmp1 = calcConf(freqSet, Hmp1, supportData, brl, minConf)
if (len(Hmp1) > 1): #need at least two sets to merge
rulesFromConseq(freqSet, Hmp1, supportData, brl, minConf)
L,suppData= apriori(dataSet,minSupport=0.5)
rules= generateRules(L,suppData, minConf=0.7)
# ## Limitations
# 1) Apriori algorithms can be very slow on very large datasets
#
# 2) If the transaction datababse has 10,000 frequent 1-itemsets, they will generate $10^7$ candidate 2-itemsets even after employing the downward closure.
#
# 3) Computing support and comparing with minimum support, the database needs to scanned at every level.
# ## Methods for Improving
# 1) Hash-based itemset counting
#
# 2) Transaction reduction
#
# 3) Partitioning
#
# 4) Sampling
#
# 5) Dynamic itemset counting
# ## Advantages/Disadvantages
# Pros:
#
# 1) Uses large itemset property
#
# 2) Easilly parallelized
#
# 3) Easily implementable
#
# Cons:
#
# 1) Assumes transaction database is memory resident.
#
# 2) Requires many database scans
#
#
# In[ ]:
|
48f628e97bec99fbff3f16c7a3c4b04d21377e3a | bilalc97/LeetCodePractice | /is_permutation.py | 843 | 4.03125 | 4 | def is_permutation(s1, s2):
"""
Return True is s1 and s2 are permutations of each other and False otherwise.
:param s1: str
:param s2: str
:return: bool
"""
if len(s1) != len(s2):
return False
else:
s1_dict = {}
for i in range(len(s1)):
if s1[i] in s1_dict:
s1_dict[s1[i]] += 1
else:
s1_dict[s1[i]] = 1
for i in range(len(s2)):
if s2[i] in s1_dict and s1_dict[s2[i]] > 0:
s1_dict[s2[i]] -= 1
else:
return False
for key in s1_dict.keys():
if s1_dict[key] != 0:
return False
return True
if __name__ == "__main__":
print(is_permutation("abcdefghijklmno", "onmlkjihgfedcba"))
print(is_permutation("hello", "helo")) |
14a9fe882f17a6e409ceb8498cad8514f7163abe | erauner12/python-scripting | /Linux/Python-Essentials/9-python-modules.py | 2,109 | 4.15625 | 4 | #!/usr/bin/python3.6
# nothing
print("")
# functions
# create first function:
def sayHello():
print("Hello")
sayHello()
print("--")
usernames = [
{
'name' :'bcranston',
'priv' :'admin',
'password' :'millennium'
},
{
'name' :'agunn',
'priv' :'user',
'password' :'abc123'
}
]
# create authenticate function to take arguments of username and password
#adding an additional parameter. Defaulting it to user. Ensures that the function calling it will have something to put in if nothing is supplied
#this is acalled an optional argument
def authenticate(username,password,priv="user"):
for u in usernames:
if u['name'] == username and u['password'] == password:
return True
return False
# call function
# mixing both positional arguments and inserted the others in regardless of order
#*Need to put the positional argument first since it is called first
if authenticate(password = 'bcranston',username = 'millennium',priv="admin"):
print("Welcome!")
print("Your privelege is",)
else:
print("Sorry, wrong or non-existent credentials")
print("--")
# Let's say you want to create a user and take metadata (undefined amount of arguments)
#need to insert positional data first and then arbritary lists
def createUser(usernames,password,**meta):
# create empty dictionary
user = {}
# populate with whatever was supplied
user["username"] = usernames
user["password"] = password
#adding items method to dictionary to enable us to loop through it
#each value in the key pair is being assigned for every additional argument that was not gathered before
for k,v in meta.items():
user[k] = v
return user
#dictionary key pairs allow us to add as many arguments as we want to a dictionary
user = createUser("Evan","password123",job = "Devops Engineer", age = "26", country = "US", lang = "English")
print(user)
#use dictionary instead
|
515c1352dec92a056848bd742aa365a1d2b0dde2 | AdriaSalvado/M03 | /ejercicio-pares.py | 154 | 4.03125 | 4 | # coding: utf8
# Adrià Salvadó
#
numero=input ("Escribe un numero ")
if (numero%2==0):
print "Que bonito número par"
else:
print "Que número mas vulgar"
|
59b3ebd4baa6d21e90fbb186377fbf6ff688dda0 | nkmeng/python_examples | /0021/0021.py | 683 | 3.53125 | 4 | # -*- coding: utf-8 -*-
"""
第 0021 题: 通常,登陆某个网站或者 APP,需要使用用户名和密码。密码是如何加密后存储起来的呢?请使用 Python 对密码加密。
"""
import hashlib
SALT = '8#@ia0o'
def encrypt_password(password):
sha1 = hashlib.sha1()
password = password + SALT
sha1.update(password.encode('utf-8'))
return sha1.hexdigest()[3:33]
def validate_password(password, hashed):
return encrypt_password(password) == hashed
def test():
p = input('Password:')
hashed = encrypt_password(p)
print(hashed)
print('Validation: %s' % validate_password(p, hashed))
if __name__ == '__main__':
test() |
660a7fb51832d409d2fb3705a9daad463a890c2a | ifmylove2011/student | /exercise/ex16.py | 296 | 3.84375 | 4 | # 输出指定格式的日期
import time
print(time.time())
localtime = time.localtime(time.time())
print("本地时间为 :", localtime)
localtime = time.asctime(time.localtime(time.time()))
print("本地时间为 :", localtime)
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
|
49a94908210ded0a914afbbc754bd396f7bd2ec9 | arnauddesombre/Asteroids | /Asteroids.py | 41,175 | 3.59375 | 4 | # ---------------------------------------------------------------- #
# Asteroids #
# Developped by Arnaud Desombre (arnauddesombre@yahoo.com) #
# ---------------------------------------------------------------- #
# Open source ** PLEASE DISTRIBUTE ** and give credit when due #
# ---------------------------------------------------------------- #
"""
Coursera project requirements:
https://class.coursera.org/interactivepython-002/human_grading/view/courses/970391/assessments/35/submissions
(all requirements are fully met and/or exceeded)
Additions:
* Handling of all explosions
* Rocks bounce off each other:
- Elastic collision
- The mass of each rock is proportional to its rate of rotation
- The rocks spin faster as the score increases
* Ship pulls gravitationally on rocks:
- Newtonian gravity. The trajectory of heavier (fast spinning) rocks is therefore more affected.
* To avoid the "death blossom" strategy of spinning in place and hammering the space bar, rocks will be thrown
directly at the ship after a period of stillness, with increasing spin and velocity.
* Hyperspace:
- Pressing 'H' puts the ship at the 'safest' place (cost points).
Play responsibly, and enjoy!!
Note: submitted entry for Coursera was:
http://www.codeskulptor.org/#user16_JQRgHi0SN7Djoym.py
This is a later update with anti-"death blossom" (with 'ship_stillness') and Olivier PIRSON's SimpleGUICS2Pygame addition.
The original source was developped during Coursera's course
"An Introduction to Interactive Programming in Python"
by Joe Warren, John Greiner, Stephen Wong, Scott Rixner
This version of the game can be played:
in Codeskulptor: as is
locally with Python: create local .\_img\ and .\_snd\ directories for image and sound files
command line: python -O -OO asteroids.py --stop-timers [--no-controlpanel]
use --no-controlpanel to remove the control panel from the left side of the canvas
(configuration buttons are accessible by keyboard (b -> bounce / m -> music / s -> sound))
"""
##################################################################
# replace CodeSkulptor's simplegui import with Olivier PIRSON's module, downloaded from:
# https://bitbucket.org/OPiMedia/simpleguics2pygame
# documentation:
# http://www.opimedia.be/DS/SimpleGUICS2Pygame/doc_html/
try:
import simplegui
www = True
except:
import SimpleGUICS2Pygame.simpleguics2pygame as simplegui
www = True
import math
import random
# declaration of global variables for user interface
# size of the canvas (can be changed, but the location for number of lives, score and help screen would not resize)
WIDTH = 800
HEIGHT = 600
# initialize sound on/off defaults
sound_on = True
music_on = False
# rocks bounce off each other or not
# original Asteroids' mode was False, but True is much cooler (but slows down the game)
bounce_mode = True
# number of lives per game
MAX_LIVES = 3
# Security perimeter (in number of ship radius) around the ship
SHIP_SECURITY_PERIMETER = 5.0
# constants for ship / rocks / missiles
SHIP_ANGLE_INCREMENT = (2.0 * math.pi) / 54.0
SHIP_ACCELERATION = 0.2
SHIP_GRAVITY_PULL = 1500.0
SPACE_FRICTION = 0.04
VELOCITY_MAX_SHIP = 20.0
ROCK_MAX_NUMBER = 10
VELOCITY_MIN_ROCK = 0.5
VELOCITY_MAX_ROCK = 3.0
ROTATION_MAX_ROCK = 1.0
ROTATION_MIN_ROCK = 0.25
VELOCITY_MISSILE = 4.0
# lifespan of missiles
# if the ship fires at rest, a missile disappears after travelling about 0.35 of the canvas width
MISSILE_LIFE = (0.35 * WIDTH) // VELOCITY_MISSILE
# number of allowed missile at one time (can actually be somehow redundant with MISSILE_LIFE)
MISSILE_MAX_NUMBER = 10
# 1: game not started / 2: game in play (normal) / 3: game paused / 4: game over
game_in_play = 1
# declare all other global variables
score = 0
lives = 0
time = 0
ship_stillness = 0.0
rock_group = set()
missile_group = set()
explosion_group = set()
text_group = set()
# 'my_ship' global variable is declared after the 'Class ship():' declaration
##################################################################
# Hyperspace grid:
# define elementary cell for hyperspace (no need to make it much smaller than the ship)
hyper_cell = [40, 40]
# define grid
HYPER_GRID = []
for i in range(0, WIDTH // hyper_cell[0]):
for j in range(0, HEIGHT // hyper_cell[1]):
HYPER_GRID += [(hyper_cell[0] * (i + 1/2),
hyper_cell[1] * (j + 1/2))]
##################################################################
# Image class
class ImageInfo:
def __init__(self, center, size, radius = 0, lifespan = None, animated = False):
self.center = center
self.size = size
self.radius = radius
if lifespan:
self.lifespan = lifespan
else:
self.lifespan = float('inf')
self.animated = animated
return
def get_center(self):
return self.center
def get_size(self):
return self.size
def get_radius(self):
return self.radius
def get_lifespan(self):
return self.lifespan
def get_animated(self):
return self.animated
##################################################################
# Art assets created by Kim Lathrop
# may be freely re-used in non-commercial projects, please credit Kim
# SimpleGUICS2Pygame requirement:
# local images or sounds (.ogg format) must be placed .\_img\ and .\_snd\ directories
# debris images - debris1_brown.png, debris2_brown.png, debris3_brown.png, debris4_brown.png
# debris1_blue.png, debris2_blue.png, debris3_blue.png, debris4_blue.png, debris_blend.png
debris_info = ImageInfo([320, 240], [640, 480])
if www:
debris_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/debris2_blue.png")
else:
debris_image = simplegui.load_image("_img\debris2_blue.png")
# nebula images - nebula_brown.png, nebula_blue.png
nebula_info = ImageInfo([400, 300], [800, 600])
if www:
nebula_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/nebula_blue.png")
else:
nebula_image = simplegui.load_image("_img\nebula_blue.png")
# ship image
ship_info = ImageInfo([45, 45], [90, 90], 35)
if www:
ship_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/double_ship.png")
else:
ship_image = simplegui.load_image("_img\double_ship.png")
# missile image - shot1.png, shot2.png, shot3.png
# Note that these images have different sizes:
# missile_info = ImageInfo([5,5], [10, 10], 3, life) for shot1.png and shot2.png
# missile_info = ImageInfo([10,10], [20, 20], 3, life) for shot3.png
missile_info = ImageInfo([10, 10], [20, 20], 3, MISSILE_LIFE)
if www:
missile_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/shot3.png")
else:
missile_image = simplegui.load_image("_img\shot3.png")
# asteroid images - asteroid_blue.png, asteroid_brown.png, asteroid_blend.png
asteroid_info = ImageInfo([45, 45], [90, 90], 40)
if www:
asteroid_image = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/asteroid_blue.png")
else:
asteroid_image = simplegui.load_image("_img\asteroid_blue.png")
# animated explosion - explosion_orange.png, explosion_blue.png, explosion_blue2.png, explosion_alpha.png
explosion_info = ImageInfo([64, 64], [128, 128], 17, 24, True)
if www:
explosion_image1 = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/explosion_alpha.png")
explosion_image2 = simplegui.load_image("http://commondatastorage.googleapis.com/codeskulptor-assets/lathrop/explosion_orange.png")
else:
explosion_image1 = simplegui.load_image("_img\explosion_alpha.png")
explosion_image2 = simplegui.load_image("_img\explosion_orange.png")
# sound assets purchased from sounddogs.com
# please do not redistribute!
if www:
soundtrack = simplegui.load_sound("http://commondatastorage.googleapis.com/codeskulptor-assets/sounddogs/soundtrack.ogg")
missile_sound = simplegui.load_sound("http://commondatastorage.googleapis.com/codeskulptor-assets/sounddogs/missile.ogg")
ship_thrust_sound = simplegui.load_sound("http://commondatastorage.googleapis.com/codeskulptor-assets/sounddogs/thrust.ogg")
explosion_sound = simplegui.load_sound("http://commondatastorage.googleapis.com/codeskulptor-assets/sounddogs/explosion.ogg")
else:
soundtrack = simplegui.load_sound("_snd\soundtrack.ogg")
missile_sound = simplegui.load_sound("_snd\missile.ogg")
ship_thrust_sound = simplegui.load_sound("_snd\thrust.ogg")
explosion_sound = simplegui.load_sound("_snd\explosion.ogg")
missile_sound.set_volume(.5)
##################################################################
def angle_to_vector(ang):
# transformation angle (in radian) -> vector ([x,y])
return [math.cos(ang), math.sin(ang)]
def dist_squared(p, q):
# distance between 2 points p and q squared
return ((p[0] - q[0]) ** 2 + (p[1] - q[1]) ** 2)
def dist(p, q, curved_space = True):
# distance between 2 points p and q
if curved_space:
# opposites side of the canvas are actually connected
# and this 'dist' calculation takes this into account
return min(math.sqrt((p[0] - q[0]) ** 2 + (p[1] - q[1]) ** 2),
math.sqrt((WIDTH - abs(p[0] - q[0])) ** 2 + (p[1] - q[1]) ** 2),
math.sqrt((p[0] - q[0]) ** 2 + (HEIGHT - abs(p[1] - q[1])) ** 2),
math.sqrt((WIDTH - abs(p[0] - q[0])) ** 2 + (HEIGHT - abs(p[1] - q[1])) ** 2))
else:
# return simple (Euclidian) distance
# (this is only used for missile/rock distance calculation for collision)
return math.sqrt((p[0] - q[0]) ** 2 + (p[1] - q[1]) ** 2)
def norm(p):
# return the norm of vector p
return math.sqrt(p[0] ** 2 + p[1] ** 2)
def sign(x):
# return the sign of x
if x > 0:
return 1
elif x < 0:
return -1
else:
return 0
##################################################################
# Ship class
class Ship:
def __init__(self, pos, vel, angle, image, info):
self.pos = [pos[0], pos[1]]
self.vel = [vel[0], vel[1]]
self.thrust = False
self.angle = angle
self.angle_vel = 0.0
self.image = image
self.image_center = info.get_center()
self.image_size = info.get_size()
self.radius = info.get_radius()
return
def draw(self, canvas):
if self.thrust:
# thrust => use second image (with thrust flames)
center = (self.image_center[0] + self.image_size[0], self.image_center[1])
else:
# no thrust => use first image (without thrust flames)
center = (self.image_center[0], self.image_center[1])
canvas.draw_image(self.image, center, self.image_size, self.pos, self.image_size, self.angle)
if self.thrust and sound_on:
ship_thrust_sound.play()
else:
ship_thrust_sound.pause()
ship_thrust_sound.rewind()
return
def update(self):
self.angle += self.angle_vel
if self.thrust:
# manage acceleration
vect = angle_to_vector(self.angle)
self.vel[0] += SHIP_ACCELERATION * vect[0]
self.vel[1] += SHIP_ACCELERATION * vect[1]
# respect speed limit for ship
if self.get_speed() > VELOCITY_MAX_SHIP:
self.vel[0] = VELOCITY_MAX_SHIP * vect[0]
self.vel[1] = VELOCITY_MAX_SHIP * vect[1]
else:
# deceleration through friction
self.vel[0] *= (1.0 - SPACE_FRICTION)
self.vel[1] *= (1.0 - SPACE_FRICTION)
# update position + remain within canvas (modulo WIDTH and HEIGHT)
self.pos[0] = (self.pos[0] + self.vel[0]) % WIDTH
self.pos[1] = (self.pos[1] + self.vel[1]) % HEIGHT
return
def get_speed(self):
# returns speed of ship
return norm(self.vel)
def get_angle(self):
# returns angle of ship
return self.angle
def get_position(self):
# return position of ship
return self.pos
def get_radius(self):
# return radius of ship
return self.radius
def get_mass(self):
# return mass of ship (for consistancy only, mass of the ship is irrelevant but cannot be zero)
return 1.0
def shoot(self):
# shoot one missile from ship
global missile_group
vect = angle_to_vector(self.angle)
# initial position is: top of the ship
pos = (self.pos[0] + self.radius * vect[0],
self.pos[1] + self.radius * vect[1])
# initial velocity is: speed of ship + VELOCITY_MISSILE + bonus for speed of ship
# Note: the ship is not necessarily oriented in the direction of its speed
bonus = 1.0 + 1.5 * self.get_speed() / VELOCITY_MAX_SHIP
vel = (self.vel[0] + VELOCITY_MISSILE * vect[0] * bonus,
self.vel[1] + VELOCITY_MISSILE * vect[1] * bonus)
# angle: is the same as the ship
vect = angle_to_vector(self.angle)
a_missile = Sprite(pos, vel, 0.0, self.angle, 0.0, missile_image, missile_info, missile_sound)
missile_group.add(a_missile)
return
# declare global variable 'my_ship'
my_ship = Ship([WIDTH // 2, HEIGHT // 2], [0, 0], -math.pi / 2.0, ship_image, ship_info)
##################################################################
# Sprite class
class Sprite:
def __init__(self, pos, vel, mass, ang, ang_vel, image, info, sound = None):
self.pos = [pos[0], pos[1]]
self.vel = [vel[0], vel[1]]
self.mass = mass
self.angle = ang
self.angle_vel = ang_vel
self.image = image
self.image_center = info.get_center()
self.image_size = info.get_size()
self.radius = info.get_radius()
self.lifespan = info.get_lifespan()
self.animated = info.get_animated()
self.age = 0
if sound and sound_on:
sound.rewind()
sound.play()
return
def get_position(self):
# return position of sprite
return self.pos
def get_mass(self):
# return mass of sprite
return self.mass
def get_velocity(self):
# return velocity of sprite
return self.vel
def get_radius(self):
# return radius of sprite
return self.radius
def collide(self, other_object):
# return True if self and other_object collide
if self.mass == 0.0 or other_object.get_mass() == 0.0:
# use euclidian distance if one of the object is a missile (for quicker calculation)
# missiles are the only Sprite with zero mass
return (dist(self.get_position(), other_object.get_position(), False) <= self.get_radius() + other_object.get_radius())
else:
return (dist(self.get_position(), other_object.get_position()) <= self.get_radius() + other_object.get_radius())
def draw(self, canvas):
self.age += 1
canvas.draw_image(self.image, self.image_center, self.image_size, self.pos, self.image_size, self.angle)
return
def is_dead(self):
return (self.age > self.lifespan)
def update(self):
# update angle
self.angle += self.angle_vel
# update speed: if mass != 0, Sprite is gravitationally attracted to the ship
if self.get_mass() > 0.0:
# define a normalized vector self -> my_ship
vect = (my_ship.get_position()[0] - self.pos[0],
my_ship.get_position()[1] - self.pos[1])
n = norm(vect)
vect = (vect[0] / n, vect[1] / n)
# calculate Newtonian gravity
gravity_pull = SHIP_GRAVITY_PULL * self.mass / dist_squared(my_ship.get_position(), self.get_position())
self.vel[0] += vect[0] * gravity_pull
self.vel[1] += vect[1] * gravity_pull
# update position + remain within canvas
self.pos[0] = (self.pos[0] + self.vel[0]) % WIDTH
self.pos[1] = (self.pos[1] + self.vel[1]) % HEIGHT
return
##################################################################
# Explosion class
# NOTE: The draw method of this class contains '.remove()'
class Explosion:
def __init__(self, pos, scale, image, info, sound = None):
self.pos = [pos[0], pos[1]]
self.age = 0
self.scale = scale
self.image = image
self.image_center = info.get_center()
self.image_size = info.get_size()
self.radius = info.get_radius()
self.lifespan = info.get_lifespan()
self.animated = info.get_animated()
self.age = 0
if sound and sound_on:
sound.rewind()
sound.play()
return
def draw(self, canvas):
global explosion_group
center = (self.image_center[0] + self.age * self.image_size[0], self.image_center[1])
output = [self.image_size[0] * self.scale, self.image_size[1] * self.scale]
canvas.draw_image(self.image, center, self.image_size, self.pos, output, 0)
self.age += 1
if self.age > self.lifespan:
explosion_group.remove(self)
return
##################################################################
# Text class (write temporary information on the screen)
# NOTE: the draw method of this class contains '.remove()'
class Text:
def __init__(self, text, line, lifespan):
self.text = text
self.y = line
self.age = 0
self.lifespan = lifespan
return
def draw(self, canvas):
global text_group
message_size = frame.get_canvas_textwidth(self.text, 40)
canvas.draw_text(self.text, ((WIDTH - message_size) // 2, self.y), 40, "Red")
self.age += 1
if self.age > self.lifespan:
text_group.remove(self)
return
##################################################################
# button managed functions
def music_handler(flag = 1):
# toggle background music on/off
global music_on
if flag == 1:
music_on = not music_on
if music_on:
music_button.set_text("[m]usic = ON")
soundtrack.rewind()
soundtrack.play()
else:
music_button.set_text("[m]usic = OFF")
soundtrack.pause()
return
def sound_handler(flag = 1):
# toggle sound on/off
global sound_on
if flag == 1:
sound_on = not sound_on
if sound_on:
sound_button.set_text("[s]ound = ON")
else:
sound_button.set_text("[s]ound = OFF")
return
def bounce_handler(flag = 1):
# toggle bounce mode true/false
global bounce_mode
if flag == 1:
bounce_mode = not bounce_mode
if bounce_mode:
bounce_button.set_text("[b]ounce = ON")
else:
bounce_button.set_text("[b]ounce = OFF")
return
##################################################################
# helper functions for keyboard managed functions
def fire_missile(flag):
if flag == 1:
if len(missile_group) < MISSILE_MAX_NUMBER:
my_ship.shoot()
return
def ship_thrust(flag):
my_ship.thrust = (flag == 1)
return
def ship_rotate_left(flag):
ship_rotate(flag, -1)
return
def ship_rotate_right(flag):
ship_rotate(flag, 1)
return
def ship_rotate(flag, direction):
# flag == 1 -> rotate the ship: direction == 1 -> right
# direction == -1 -> left
# flag == 0 -> stop rotation if the ship was turning in the relevant direction
# for example: Left Down / Right Down / Left Up -> does not stop rotation
if flag == 1:
# key down
my_ship.angle_vel = direction * SHIP_ANGLE_INCREMENT
else:
# key up
if sign(my_ship.angle_vel) == direction:
my_ship.angle_vel = 0
return
def hyperspace(flag):
global score
if flag == 1:
if score < 100:
text_group.add(Text("NO CREDIT FOR HYPERSPACE", 70, 30))
else:
# put the ship outside of the screen (so it cannot be destroyed during calculation)
old_pos = my_ship.pos
my_ship.pos = [WIDTH + my_ship.get_radius() + 1, HEIGHT + my_ship.get_radius() + 1]
# calculate the distance of all the HYPER_GRID points to their respective nearest rock
distance_to_rock = []
for i in range(0, len(HYPER_GRID)):
d_min = float('inf')
for rock in list(rock_group):
d = dist(HYPER_GRID[i], rock.get_position())
if d < d_min:
d_min = d
distance_to_rock.append(d_min)
# calculate point within HYPER_GRID further from all the rocks
d_max = 0.0
hyper_point = -1
for i in range(0, len(distance_to_rock)):
if distance_to_rock[i] > d_max:
d_max = distance_to_rock[i]
hyper_point = i
# hyper_point is the index in HYPER_GRID where the ship will emerge
if dist(HYPER_GRID[hyper_point], my_ship.get_position()) < (SHIP_SECURITY_PERIMETER / 2.0) * my_ship.get_radius():
text_group.add(Text("POSITION CANNOT BE IMPROVED", 70, 30))
my_ship.pos = old_pos
else:
text_group.add(Text("** HYPERSPACE **", 70, 30))
my_ship.pos[0] = HYPER_GRID[hyper_point][0]
my_ship.pos[1] = HYPER_GRID[hyper_point][1]
my_ship.vel[0] = 0.0
my_ship.vel[1] = 0.0
my_ship.angle = -math.pi / 2.0
clean_area_around_ship()
score -= 100
if sound_on:
# insert 'hyperspace sound' sound here...
pass
return
# keyboard functions
key_inputs = {"space": fire_missile,
"up": ship_thrust,
"left": ship_rotate_left,
"right": ship_rotate_right,
"h": hyperspace,
"b": bounce_handler,
"m": music_handler,
"s": sound_handler}
def key_down_handler(key):
global game_in_play
exception = False
if game_in_play == 4:
if key == 13: # <Enter> key
game_init()
game_in_play = 2
elif game_in_play != 2:
# the game is resumed from non play status on any key except b, m, s (configuration button)
if key != simplegui.KEY_MAP["b"] and key != simplegui.KEY_MAP["m"] and key != simplegui.KEY_MAP["s"]:
game_in_play = 2
else:
exception = True
elif key == 27: # <Esc> key
game_in_play = 3
# No 'else:' used here, so that the key pressed
# to un-pause the game is handled immediately...
if game_in_play == 2 or exception:
for i in key_inputs:
if key == simplegui.KEY_MAP[i]:
key_inputs[i](1)
return
def key_up_handler(key):
for i in key_inputs:
if key == simplegui.KEY_MAP[i]:
key_inputs[i](0)
return
##################################################################
def game_init():
# initialize variables for a new game
global score, lives, time, ship_stillness, my_ship, rock_group, missile_group, explosion_group, text_group
score = 0
lives = MAX_LIVES
time = 0
ship_stillness = 0.0
if music_on:
soundtrack.rewind()
soundtrack.play()
# initialize ship
my_ship = Ship([WIDTH // 2, HEIGHT // 2], [0, 0], -math.pi / 2.0, ship_image, ship_info)
# initialize rock set
rock_group = set()
# initialize missile set
missile_group = set()
# initialize explosion set
explosion_group = set()
# initialiaze text set
text_group = set()
return
def update_score(increase_score):
# update scores, and add 1 life every 2.000 points
global score, lives
old_score = score
score += increase_score
if (old_score // 2000) != (score // 2000):
# x2.000 points crossed!
lives += 1
text_group.add(Text("** EXTRA LIFE! **", 110, 30))
return
def rock_spawner():
# timer handler that spawns a rock
# this function is called every 1 second and is used to increase the score due to survival rate
global rock_group, ship_stillness
if game_in_play == 2:
# increase score from +1 (at speed = 0) to +10 (at speed = VELOCITY_MAX_SHIP)
speed_ratio = 9.0 * my_ship.get_speed() / VELOCITY_MAX_SHIP
update_score(1 + round(speed_ratio))
# update ship stillness
if speed_ratio >= 2.0:
ship_stillness = 0.0
elif speed_ratio >= 1.0:
if ship_stillness < 15.0:
ship_stillness += 0.5
else:
ship_stillness -= 1.0
else:
ship_stillness += 1.0
if len(rock_group) < ROCK_MAX_NUMBER and game_in_play == 2:
# generate a rock (from a random side of the canvas only / never from the middle)
overlap = True
while overlap:
# rules for ship_stillness penalty:
# 0 to 15 = nothing
# 15 to 25 = rock spawn towards ship
# 25 to 35 = rock spawn towards ship from behind
# 35 to 45 = rock spawn towards ship from behind + at increased spin
# 45 to 60 = rock spawn towards ship from behind + at increased spin + at maximum velocity
# above 60 = rock spawn towards ship from behind + at maximum spin + at maximum velocity
#
# random speed between VELOCITY_MIN_ROCK and VELOCITY_MAX_ROCK
if ship_stillness > 45.0:
velocity = VELOCITY_MAX_ROCK
else:
velocity = VELOCITY_MIN_ROCK + random.random() * (VELOCITY_MAX_ROCK - VELOCITY_MIN_ROCK)
if ship_stillness > 25.0:
angle = my_ship.get_angle() % (2.0 * math.pi)
if math.pi / 4.0 <= angle <= 3.0 * math.pi / 4.0:
center = (random.randint(0, WIDTH - 1), 0)
elif 3.0 * math.pi / 4.0 <= angle <= 5.0 * math.pi / 4.0:
center = (WIDTH - 1, random.randint(0, HEIGHT - 1))
elif 5.0 * math.pi / 4.0 <= angle <= 7.0 * math.pi / 4.0:
center = (random.randint(0, WIDTH - 1), HEIGHT - 1)
else:
center = (0, random.randint(0, HEIGHT - 1))
else:
if random.choice([0, 1]) == 0:
center = (0, random.randint(0, HEIGHT - 1))
else:
center = (random.randint(0, WIDTH - 1), 0)
# random trajectory angle between 0 and 2 * PI
# though generated on left or top side, the rock can enter from right or bottom side, depending on angle:
# also, adjust angle to target ship after 15 seconds of stillness
if ship_stillness > 15.0:
s = my_ship.get_position()
angle = (s[0] - center[0], s[1] - center[1])
n = norm(angle)
angle = (angle[0] / n, angle[1] / n)
else:
angle = angle_to_vector(random.random() * 2.0 * math.pi)
velocity_vect = (angle[0] * velocity, angle[1] * velocity)
# random rotation between ROTATION_MIN_ROCK and ROTATION_MAX_ROCK turns per
# second, increasing with the score (min = +15% every 5.000 points / max = +30%)
spin_min = ROTATION_MIN_ROCK * (1.0 + 0.15 * (score / 5000.0))
spin_max = ROTATION_MAX_ROCK * (1.0 + 0.30 * (score / 5000.0))
if ship_stillness > 60.0:
spin_min = spin_max
elif ship_stillness > 35.0:
spin_min = (spin_max + spin_min) / 2.0
rotation = random.choice([-1, 1]) * (spin_min + random.random() * (spin_max - spin_min)) * (2.0 * math.pi / 60.0)
# mass of rock is proportional to its spin rate
mass = abs(rotation)
new_rock = Sprite(center, velocity_vect, mass, 0.0, rotation, asteroid_image, asteroid_info)
# Overlap rules for rock generation:
# a new rock cannot be too close from the ship (not within SHIP_SECURITY_PERIMETER ship radius)
# a new rock cannot overlap an existing rock if bounce_mode == True
overlap = False
if dist(new_rock.get_position(), my_ship.get_position()) <= SHIP_SECURITY_PERIMETER * my_ship.get_radius():
overlap = True
if bounce_mode and not overlap:
for rock in list(rock_group):
if new_rock.collide(rock):
overlap = True
break
rock_group.add(new_rock)
return
def bounce_rock(m1, v1, m2, v2):
# elastic collision between:
# rock #1: mass m1 (float) and speed v1 (tuple (v_x, v_y))
# rock #2: mass m1 (float) and speed v2 (tuple (v_x, v_y))
# some math and comments for elastic collision equations can be found at:
# http://batesvilleinschools.com/physics/apphynet/Dynamics/Collisions/elastic_deriv.htm
# Ref2 is the referential where ball #2 is fixed before the collision
v1_ref2 = (v1[0] - v2[0], v1[1] - v2[1])
# after choc, in Ref2
v1_after_ref2 = (((m1 - m2) / (m1 + m2)) * v1_ref2[0],
((m1 - m2) / (m1 + m2)) * v1_ref2[1])
v2_after_ref2 = (2.0 * m1 / (m1 + m2) * v1_ref2[0],
2.0 * m1 / (m1 + m2) * v1_ref2[1])
# back to initial referential
v1_after = (v1_after_ref2[0] + v2[0],
v1_after_ref2[1] + v2[1])
v2_after = (v2_after_ref2[0] + v2[0],
v2_after_ref2[1] + v2[1])
return (v1_after, v2_after)
def group_collide(group, sprite):
# test for collision between all members of 'group' (group of sprites) vs. 'sprite' (one sprite)
g = set()
num_collision = 0
for member in list(group):
if member.collide(sprite):
num_collision += 1
g.add(member)
# explosion is centered on 'member' (not 'sprite')
new_explosion = Explosion(member.get_position(), 1, explosion_image1, explosion_info, explosion_sound)
explosion_group.add(new_explosion)
group.difference_update(g)
return num_collision
def group_group_collide(group1, group2):
# test for collision between all members of 'group1' (group of sprites) vs. 'group2' (group of sprites)
# group1 -> missiles
# group2 -> rocks
g1 = set()
num_collision = 0
for member1 in list(group1):
n = group_collide(group2, member1)
if n > 0:
g1.add(member1)
num_collision += n
group1.difference_update(g1)
return num_collision
def clean_area_around_ship():
# eliminate all rocks whithin SHIP_SECURITY_PERIMETER radius of the ship
# (no points added to score)
global rock_group
for rock in list(rock_group):
if dist(rock.get_position(), my_ship.get_position()) <= SHIP_SECURITY_PERIMETER * my_ship.get_radius():
# the rocks within ship perimeter explode with a different explosion (scaled 30%) image & no sound & no score
new_explosion = Explosion(rock.get_position(), 0.30, explosion_image2, explosion_info)
explosion_group.add(new_explosion)
rock_group.remove(rock)
return
##################################################################
# update canvas
def help_display(canvas, offset):
# help screen (display)
if offset == 2:
color = "Black"
color_special = color
elif offset == 1:
color = "Blue"
color_special = "White"
else:
color = "White"
color_special = "Red"
canvas.draw_text("<Left arrow>", (50+offset, 130+offset), 40, color)
canvas.draw_text("<Right arrow>", (50+offset, 180+offset), 40, color)
canvas.draw_text("<Up arrow>", (50+offset, 230+offset), 40, color)
canvas.draw_text("<Space bar>", (50+offset, 280+offset), 40, color)
canvas.draw_text("<Esc>", (50+offset, 330+offset), 40, color)
canvas.draw_text("<H>", (50+offset, 380+offset), 40, color)
canvas.draw_text("turn ship counter-clockwise", (325+offset, 130+offset), 40, color)
canvas.draw_text("turn ship clockwise", (325+offset, 180+offset), 40, color)
canvas.draw_text("accelerate ship forward", (325+offset, 230+offset), 40, color)
canvas.draw_text("fire missile", (325+offset, 280+offset), 40, color)
canvas.draw_text("pause game", (325+offset, 330+offset), 40, color)
canvas.draw_text("hyperspace", (325+offset, 380+offset), 40, color)
canvas.draw_text("(Transport & stop ship in a 'safer' place. Cost 100 points)", (325+offset, 410+offset), 20, color)
# bounce message from left to right of the canvas
if game_in_play == 1:
message = "welcome to Asteroids!"
elif game_in_play == 4:
message = "game over!"
else:
message = "== game paused =="
pos1 = (WIDTH - frame.get_canvas_textwidth(message, 40))
pos2 = time % pos1
if (time // pos1) % 2 == 0:
pos = pos2
else:
pos = pos1 - pos2
canvas.draw_text(message, (pos+offset, 70+offset), 40, color_special)
if game_in_play == 1:
canvas.draw_text("== Press any key to start the game ==", (100+offset, 460+offset), 40, color_special)
elif game_in_play == 4:
canvas.draw_text("== Press [Enter] to start a new game ==", ( 90+offset, 460+offset), 40, color_special)
else:
canvas.draw_text("== Press any key to resume the game ==", ( 95+offset, 460+offset), 40, color_special)
canvas.draw_text("Each rock destroyed = +50 points", (95+offset, 500+offset), 20, color)
canvas.draw_text("Survival bonus = from +1 (at low speed) to +10 points (at high speed) per second", (95+offset, 525+offset), 20, color)
canvas.draw_text("Extra life every 2,000 points!", (95+offset, 550+offset), 20, color)
canvas.draw_text("Heavier rocks spin faster - Rotation increases with time - The ship exerts gravitational pull", (40+offset, 580+offset), 20, color)
return
def process_sprite_group(canvas, group, update):
# update and draw each sprite in the group
dead = set()
for sprite in list(group):
if update:
sprite.update()
if sprite.is_dead():
dead.add(sprite)
sprite.draw(canvas)
group.difference_update(dead)
return
def process_rock_collision(group):
# handle collision rock-rock
g = list(group)
for rock1 in range(0, len(g)):
for rock2 in range(rock1+1, len(g)):
if g[rock1].collide(g[rock2]):
# elastic collision between rock1 & rock2. Because mass1 != mass 2, after the collision
# the speed of 1 rock may be over VELOCITY_MAX_ROCK. This is intentionally not adjusted!
new_vel = bounce_rock(g[rock1].get_mass(), g[rock1].get_velocity(), g[rock2].get_mass(), g[rock2].get_velocity())
g[rock1].vel[0], g[rock1].vel[1] = new_vel[0][0], new_vel[0][1]
g[rock2].vel[0], g[rock2].vel[1] = new_vel[1][0], new_vel[1][1]
if sound_on:
# insert 'rock bouncing off one another' sound here...
pass
def process_explosion(canvas):
# display explosions
for explosion in list(explosion_group):
explosion.draw(canvas)
return
def process_text(canvas):
# display text
for text in list(text_group):
text.draw(canvas)
return
def help(canvas):
# help screen / text is shaded in different colors for 3D illusion
# display text 1st shade (black)
help_display(canvas, 2)
# display text 2nd shade (blue)
help_display(canvas, 1)
# display text 3rd shade (white)
help_display(canvas, 0)
return
def draw(canvas):
global time, lives, game_in_play, ship_stillness
# animate background
time += 1
center = debris_info.get_center()
size = debris_info.get_size()
wtime = (time / 8.0) % center[0]
canvas.draw_image(nebula_image, nebula_info.get_center(), nebula_info.get_size(), [WIDTH // 2, HEIGHT // 2], [WIDTH, HEIGHT])
canvas.draw_image(debris_image, [center[0] - wtime, center[1]], [size[0] - 2 * wtime, size[1]],
[WIDTH / 2 + 1.25 * wtime, HEIGHT // 2], [WIDTH - 2.5 * wtime, HEIGHT])
canvas.draw_image(debris_image, [size[0] - wtime, center[1]], [2 * wtime, size[1]],
[1.25 * wtime, HEIGHT // 2], [2.5 * wtime, HEIGHT])
if game_in_play != 2:
# draw ship and sprites (game is not in play -> not started or paused)
process_sprite_group(canvas, rock_group, False)
process_sprite_group(canvas, missile_group, False)
process_explosion(canvas)
my_ship.draw(canvas)
help(canvas)
elif lives < 0:
# game has ended ('Live = 0' has been played => lives = -1)
game_in_play = 4
process_sprite_group(canvas, rock_group, False)
process_sprite_group(canvas, missile_group, False)
process_explosion(canvas)
my_ship.draw(canvas)
help(canvas)
else:
# draw ship and sprites (game is in play -> normal mode)
# process rocks
process_sprite_group(canvas, rock_group, True)
# handle rock collisions
if bounce_mode:
process_rock_collision(rock_group)
# process missiles
process_sprite_group(canvas, missile_group, True)
# update ship
my_ship.update()
my_ship.draw(canvas)
# check if the ship has hit a rock
if group_collide(rock_group, my_ship) > 0:
# the ship explodes with a large explosion (scaled 4x) image & no sound
new_explosion = Explosion(my_ship.get_position(), 4, explosion_image1, explosion_info)
explosion_group.add(new_explosion)
clean_area_around_ship()
# stop ship
my_ship.vel = [0.0, 0.0]
if sound_on:
explosion_sound.rewind()
explosion_sound.play()
# lose 1 life but score 50 points...
lives -= 1
ship_stillness = 0.0
update_score(50)
# indicative display (0.5 second)
text_group.add(Text("** SHIP DESTROYED! **", 150, 30))
# check if a missile has hit a rock
hit = group_group_collide(missile_group, rock_group)
update_score(50 * hit)
# explosions
process_explosion(canvas)
# display informational text
process_text(canvas)
# display number of lives (number & visual information), score, and ship stillness light
if lives == 1:
message_lives = "1 life"
else:
message_lives = str(max(lives, 0)) + " lives"
canvas.draw_text(message_lives, (10, 25), 25, "White")
for i in range(0, lives):
canvas.draw_image(ship_image, ship_info.get_center(), ship_info.get_size(), [95 + i*25, 20], [30, 30], -math.pi/2)
message_score = "Score: " + str(int(score)) + " "
message_size = frame.get_canvas_textwidth(message_score, 25)
canvas.draw_text(message_score, (WIDTH - 10 - message_size, 25), 25, "White")
if ship_stillness >= 40.0:
r = 255
g = 0
if ship_stillness % 2 == 1:
# makes light blink each second
r = -1
else:
# creates a gradient color from green to red
if ship_stillness < 20:
r = int((255 * ship_stillness) / 20)
g = 255
else:
r = 255
g = int((255 * (40 - ship_stillness)) / 20)
if r >= 0:
color = "rgb(" + str(r) + ", " + str(g) + ", 0)"
canvas.draw_circle((WIDTH - 10, 16), 5, 1, color, color)
return
##################################################################
# initialize frame
frame = simplegui.create_frame("Asteroids", WIDTH, HEIGHT)
if sound_on:
soundtrack.rewind
soundtrack.play()
# register handlers
frame.set_draw_handler(draw)
frame.set_keydown_handler(key_down_handler)
frame.set_keyup_handler(key_up_handler)
frame.set_draw_handler(draw)
music_button = frame.add_button("", music_handler, 125)
music_on = not music_on
music_handler()
sound_button = frame.add_button("", sound_handler, 125)
sound_on = not sound_on
sound_handler()
bounce_button = frame.add_button("", bounce_handler, 125)
bounce_mode = not bounce_mode
bounce_handler()
# initialize timer rock_spawner() every 1 second
timer = simplegui.create_timer(1000.0, rock_spawner)
# get things rolling
game_init()
timer.start()
frame.start()
|
1f638e8c4d8c6e0787d9cbad7ae7dcb4fc5156a7 | mauro-20/The_python_workbook | /chap2/ex48.py | 1,304 | 4.3125 | 4 | # BirthDate to Astrological Sign
day = int(input('enter your day of birthday: '))
month = input('enter your month of birthday: ')
sign = ''
if month == 'dec' and day >= 22 or month == 'jan' and day <= 19:
sign = 'capricorn'
elif month == 'jan' and day >= 20 or month == 'feb' and day <= 18:
sign = 'aquarius'
elif month == 'feb' and day >= 19 or month == 'mar' and day <= 20:
sign = 'pisces'
elif month == 'mar' and day >= 21 or month == 'apr' and day <= 19:
sign = 'aries'
elif month == 'apr' and day >= 20 or month == 'may' and day <= 20:
sign = 'taurus'
elif month == 'may' and day >= 21 or month == 'jun' and day <= 20:
sign = 'gemini'
elif month == 'jun' and day >= 21 or month == 'jul' and day <= 22:
sign = 'cancer'
elif month == 'jul' and day >= 23 or month == 'aug' and day <= 22:
sign = 'leo'
elif month == 'aug' and day >= 23 or month == 'sep' and day <= 22:
sign = 'virgo'
elif month == 'sep' and day >= 23 or month == 'oct' and day <= 22:
sign = 'libra'
elif month == 'oct' and day >= 23 or month == 'nov' and day <= 21:
sign = 'scorpio'
elif month == 'nov' and day >= 22 or month == 'dec' and day <= 21:
sign = 'sagittarius'
if sign == '':
print('error')
else:
print('your zodiac sign is', sign)
|
9eed33de4070fed698e27654832995b1b47905d4 | rogeriosilva-ifpi/teaching-tds-course | /programacao_estruturada/20192_166/Bimestral2_166_20192/Parte_1/Renato_Wilames/segunda questão.py | 464 | 3.953125 | 4 | def main():
senha = input('digite sua senha: ')
cara = 8
maiu = 1
minu = 1
nume = 1
quanti = len(senha)
lma = 'ABCDEFGHIJKLMNOPQRSTUVXWYZ'
lmi = 'abcdefghijklmnopqrstuvxwyz'
if quanti >= 8:
print('sua senha é segura')
elif quanti < 8:
print('sua senha não é segura, faltou a quantidade de caracteres maior que oito(8)')
elif senha == lma:
print('sua senha é segura')
main() |
b4eed4041a09e97220584b3b3bcafaf1e1fb3de0 | KuyaKen/1jazzymonkey | /python_work/animals.py | 132 | 3.6875 | 4 | animals = ['Dog','Cat','Whale','Mouse']
for animal in animals:
print(animal)
print(f"\tA {animal.lower()}, is not an object\n") |
eecdf39a6eb0d7f6ec881419716bcea7350a57f8 | Sibinvarghese/PythonPrograms | /object oriented programming/student constructor.py | 672 | 4 | 4 | class Student():
college_name="lumniar"
def __init__(self,id,name,course,total):
self.id=id
self.name=name
self.course=course
self.total=total
def printValues(self):
print("Roll No=",self.id)
print("name=",self.name)
print("College_Name=", Student.college_name )
print("Course=", self.course)
print("total=",self.total)
def __str__(self):
return self.name
#return self.name + str(self.total)
# obj=Student(101,"Sibin","MCA",78)
# obj.printValues()
#using method overriding
obj=Student(101,"Sibin","MCA",78)
obj1=Student(101,"COdexW","MCA",98)
print(obj)
print(obj1)
|
5de3448e681412859c7c07fa93302cf8dea13051 | MikaPY/HomeworkPY | /hw5.py | 1,705 | 3.71875 | 4 | # Импорт одного модуля.
import time
# Импорт нескольких модулей.
import random, os
# Импорт некоторых методов или же переменных.
from math import ceil # Импорт метода ceil
# Псевдонимы для модулей(сокращения).
import Template as tem # Обращение к модулю,как tem.
# Импорт из модуля math, pi и ceil
from math import pi, ceil as c
# Модуль os для получения текущей директории.
import os
os.getcwd()
# Импортирование из модуля math число pi.
from math import pi
r = int(input("Enter a nun: "))
s = pi * r ** 2
print(s)
# Импортирование созданного модуля.
from myModule import summ
print(summ)
Импорт модуля и добавление псевдонима.
from datetime import datetime as dt
print(dt.now()) # Метод now.
# Угадайка с рандоным числом.
from random import randint
rand = randint(0, 20)
user_num = int(input("Введите число от 0 до 20: "))
while (user_num != rand):
print("Вы не угадали! ")
if user_num > rand:
print("Число,что вы пытайтесь угадать меньше. ")
else:
print("Число что вы пытайтесь угадать больше. ")
user_num = int(input("Введите число от 0 до 20: "))
print("Вы угадали!")
# Прикол
import this
# функция sqrt импортируется из модуля math исп. ключевое слово from
from math import sqrt |
ebf0a9d82c03eb4273aba54333ed9f2e97ac34d0 | sarthak-789/CP1_CIPHERSCHOOLS | /1431_Kids With the Greatest Number of Candies.py | 360 | 3.546875 | 4 | # link : https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/
class Solution:
def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]:
m=max(candies)
l=[True]*len(candies)
for i in range(len(candies)):
if candies[i]+extraCandies < m:
l[i]=False
return l |
5c27d12642f5f71274dfb0e4966a7597e510f795 | miseop25/Back_Jun_Code_Study | /back_joon/문자열처리/back_joon_1769_3의배수/back_joon_1769_ver1.py | 301 | 3.8125 | 4 | if __name__ == "__main__":
N = (input())
cnt = 0
while int(N) > 9 :
temp = 0
for i in N :
temp += int(i)
N = str(temp)
cnt += 1
if int(N)%3 == 0 :
answer = "YES"
else :
answer = "NO"
print(cnt)
print(answer) |
e77c434d3fd1c2c251370144e61360e3655b4be4 | byhwdy/learning-ml | /my_algorithm/gd_1.py | 491 | 4.0625 | 4 | """
用梯度下降最小化一些简单函数
"""
def f1(x):
"""
待最小化的函数
"""
return x**2
def d1(x):
"""
导数
"""
return 2 * x
def train(x, f, d, learn_rate, epochs):
"""
Args:
x: 自变量
f: 函数
d: 导数
learn_rate: 学习率
epochs: 迭代次数
Returns:
"""
for epoch in range(epochs):
x -= learn_rate * d(x)
return x, f(x)
if __name__ == '__main__':
x = 10
learn_rate = 0.01
epochs = 1000
print(train(x, f1, d1, learn_rate, epochs)) |
660c9ade0cf1114e9249868b83514b0d77cd1de7 | Michael-Nath-HS/MKS21X | /ai/testers/newlinkedlists.py | 2,636 | 4.09375 | 4 | class Node:
#Init object
def __init__(self,data):
self.data = data
self.next = None
def __str__(self):
return "NODE VALUE: %d" % self.data
class LinkedList:
def __init__(self):
self.head = None
def printlist(self): # Prints contents of a linked list
# Sets the first node as the node to start traversing
temp = self.head
# will loop until hits a None
while temp:
print(temp.data)
# Change the node to the next node
temp = temp.next
def insertfront(self, value):
anode = Node(value)
anode.next = self.head
self.head = anode
def insertend(self,value):
anode = Node(value)
if self.head is None:
self.head = anode
return
temp = self.head
while temp:
if temp.next is None:
temp.next = anode
return
else:
temp = temp.next
def insertafter(self, prevnode, value):
if prevnode is None:
return "Previous Node has to be in linked list"
anode = Node(value)
anode.next = prevnode.next
prevnode.next = anode
def delete(self,value):
anode = Node(value)
temp = self.head
if temp is not None:
if temp.data == value:
self.head = temp.next
temp = None
return
while temp is not None:
if temp.data == value:
break
prev = temp
temp = temp.next
if temp is None:
return "Cannot delete. Key not in linked list"
prev.next = temp.next
temp = None
def deletelist(self):
cur = self.head
while cur:
prev = cur.next
del(cur.data)
cur = prev
def length(self):
lengthy = []
cur = self.head
if cur.data is None:
return 0
def helper(node):
if node is not None:
lengthy.append(1)
helper(node.next)
else:
return
helper(cur)
return len(lengthy)
linked = LinkedList()
linked.head = Node(1)
second = Node(2)
third = Node(3)
# Links the first node to the second
linked.head.next = second
# Links the second node to the third
second.next = third
# adds a node to the front of a linked list
linked.insertend(8)
linked.insertend(9)
linked.insertafter(third, 57)
# linked.printlist()
linked.delete(8)
print("New List:")
linked.printlist()
print(linked.length())
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.