text
stringlengths 37
1.41M
|
---|
#!/usr/bin/env python
from __future__ import division
from sys import stdin
from copy import copy
"""
Strategies to implement:
* Create a list of high priority planets for me and for the enemy
* expansion phase when the enemy does not have that many planets (i.e., at beginning) or when the enemy does not have much strength
* Calculate the potential growth rate and cost of taking over any planet
* Calculate the risk of any of my planets, based on the fleets coming in. Determine if I should "save" the planet or evacuate the planet.
* Move headquarters if needed (maybe at every stage, any planet with more than X ships could move 3/4 of them to another planet to try to take over it?)
Done
* Using the knowledge about fleets, predict the game state in the future
* evacuate planet if it is doomed
* Calculate the growth rate for me for every planet (i.e., how many ships it is producing for me). Enemy planets count as negative growth rate. Neutral planets count as 0 growth rate.
Philosophies:
* Getting a planet to produce is more important than battling enemy ships.
* Prevent the enemy from becoming too strong
"""
from PlanetWars import PlanetWars, log, predict_state
def do_turn(pw):
log('planets: %s'%[(p.id, p.num_ships) for p in pw.my_planets])
log('fleets: %s'%[(f.num_ships, f.source, f.destination) for f in pw.my_fleets])
pw_future=predict_state(pw,MAX_TURNS)
for p in pw.planets:
p.future=[i.planets[p.id].num_ships if i.planets[p.id].owner==1 \
else -i.planets[p.id].num_ships for i in pw_future]
if pw.my_production >= 1.5*pw.enemy_production:
num_fleets=2
else:
num_fleets=4
if len(pw.my_fleets) >= num_fleets:
return
#log('finding source')
# (2) Find my strongest planet.
source = -1
source_score = -999999.0
source_num_ships = 0
s=None
dest=None
for p in pw.my_planets:
score = float(p.num_ships)/(1+p.growth_rate)
if score > source_score:
source_score = score
source = p.id
s=p
source_num_ships = p.num_ships
if s is not None:
#log('finding dest')
# (3) Find the weakest enemy or neutral planet.
dest = -1
dest_score = -999999.0
not_my_planets=set(pw.planets)-pw.my_planets
for p in not_my_planets:
score = float(1+p.growth_rate) / (1+p.num_ships)/(1+pw.distance(s,p))
if score > dest_score and not any(f.destination==p.id for f in pw.my_fleets):
dest_score = score
dest = p.id
#log('sending')
# (4) Send half the ships from my strongest planet to the weakest
# planet that I do not own.
num_ships=0
if source >= 0 and dest >= 0:
num_ships = source_num_ships / 2
pw.order(source, dest, num_ships)
my_planets=copy(pw.my_planets)
evacuate=set()
# if any of my planets is dying on the next turn, evacuate
for p in my_planets:
new_owner=pw_future[1].planets[p.id].owner
if new_owner!=1:
evacuate.add(p)
my_planets-=evacuate
if len(my_planets)==0:
my_planets=set([pw.planets[0]])
for p in evacuate:
log('evacuating %d to %d'%(p.id,dest))
if source==p.id:
p.num_ships-=num_ships
if p.num_ships>0:
dest=min(my_planets, key=lambda x: pw.distance(p,x))
pw.order(p.id, dest.id, p.num_ships)
MAX_TURNS=None
#from itertools import product
# needed because they only support python 2.5!
def product(*args, **kwds):
# product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
# product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
pools = map(tuple, args) * kwds.get('repeat', 1)
result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]
for prod in result:
yield tuple(prod)
def main():
global MAX_TURNS
map_data = ''
log('*'*30)
turn=0
while True:
current_line = stdin.readline()
if len(current_line) >= 2 and current_line.startswith("go"):
log('Turn %d '%turn+'='*30+'Turn %d'%turn)
pw = PlanetWars()
pw.parse_game_state(map_data)
if MAX_TURNS is None:
for p,q in product(pw.planets,repeat=2):
d=pw.distance(p,q)
if d>MAX_TURNS:
MAX_TURNS=d
if MAX_TURNS>10:
MAX_TURNS=10
log("predicting %s turns in the future"%MAX_TURNS)
do_turn(pw)
pw.finish()
map_data = ''
turn+=1
else:
map_data += current_line
if __name__ == '__main__':
try:
import psyco
psyco.full()
except ImportError:
pass
try:
main()
except KeyboardInterrupt:
print 'ctrl-c, leaving ...'
|
""" Documentation for misc_utils
A collection of various useful function to be reused outside class"""
import datetime
import logging
from logging.handlers import RotatingFileHandler
class funcLogger():
"""This is a class to manage file logging"""
_func_count = {}
def __init__(self, filename="timings.txt", level=logging.INFO):
self.log = logging.getLogger("func_logger")
self.handler = RotatingFileHandler(filename=filename, backupCount=5)
self.log.addHandler(self.handler)
self.log.setLevel(level=level)
def count_up(self, function_name):
self._func_count.update({function_name: self._func_count.get(function_name, 0) + 1})
@property
def counts(self):
return self._func_count
flog = funcLogger()
def func_timer(func):
"""time a function, record how many times called"""
def inner(*args, **kwargs):
start = datetime.datetime.now()
result = func(*args, **kwargs)
end = datetime.datetime.now() - start
flog.count_up(function_name=func.__name__)
flog.log.info(f"TIMER: {func.__name__}() -> {end} | "
f"COUNT: {flog.counts.get(func.__name__)}")
return result
return inner
|
def sumofdiv(number):
divisors = [1]
for i in range(2, number+1):
if (number % i)==0:
divisors.append(i)
return sum(divisors)
t = int(input())
for i in range(t):
c = int(input())
for i in range(1,c):
if c == sumofdiv(i):
print(i)
else:
print(-1)
print('Hello, World')
print('testing git commits')
print('tesing new branch')
print('testing rebase')
print('hi')
print('Hello')
print('Python id Fun')
|
import util
"""
Data sturctures we will use are stack, queue and priority queue.
Stack: first in last out
Queue: first in first out
collection.push(element): insert element
element = collection.pop() get and remove element from collection
Priority queue:
pq.update('eat', 2)
pq.update('study', 1)
pq.update('sleep', 3)
pq.pop() will return 'study' because it has highest priority 1.
"""
"""
problem is a object has 3 methods related to search state:
problem.getStartState()
Returns the start state for the search problem.
problem.isGoalState(state)
Returns True if and only if the state is a valid goal state.
problem.getChildren(state)
For a given state, this should return a list of tuples, (next_state,
step_cost), where 'next_state' is a child to the current state,
and 'step_cost' is the incremental cost of expanding to that child.
"""
def myDepthFirstSearch(problem):
visited = {}
frontier = util.Stack()
frontier.push((problem.getStartState(), None))
while not frontier.isEmpty():
state, prev_state = frontier.pop()
if problem.isGoalState(state):
solution = [state]
while prev_state != None:
solution.append(prev_state)
prev_state = visited[prev_state]
return solution[::-1]
if state not in visited:
visited[state] = prev_state
for next_state, step_cost in problem.getChildren(state):
frontier.push((next_state, state))
return []
def myBreadthFirstSearch(problem):
# YOUR CODE HERE
visited = {}
frontier = util.Queue()
frontier.push((problem.getStartState(), None))
while not frontier.isEmpty():
state, prev_state = frontier.pop()
if problem.isGoalState(state):
solution = [state]
while prev_state != None:
solution.append(prev_state)
prev_state = visited[prev_state]
return solution[::-1]
if state not in visited:
visited[state] = prev_state
for next_state, step_cost in problem.getChildren(state):
frontier.push((next_state, state))
#util.raiseNotDefined()
return []
def myAStarSearch(problem, heuristic):
# YOUR CODE HERE
frontier = util.PriorityQueue()
start = [problem.getStartState(), heuristic(problem.getStartState()), []]
p = 0
frontier.push(start, p) # queue push at index_0
closed = []
while not frontier.isEmpty():
[state, cost, path] = frontier.pop()
# print(state)
if problem.isGoalState(state):
# print(path)
return path+[state] # here is a deep first algorithm in a sense
if state not in closed:
closed.append(state)
for child_state, child_cost in problem.getChildren(state):
new_cost = cost + child_cost
new_path = path + [state]
frontier.push([child_state, new_cost, new_path], new_cost + heuristic(child_state))
#util.raiseNotDefined()
return []
"""
Game state has 4 methods we can use.
state.isTerminated()
Return True if the state is terminated. We should not continue to search if the state is terminated.
state.isMe()
Return True if it's time for the desired agent to take action. We should check this function to determine whether an agent should maximum or minimum the score.
state.getChildren()
Returns a list of legal state after an agent takes an action.
state.evaluateScore()
Return the score of the state. We should maximum the score for the desired agent.
"""
class MyMinimaxAgent():
def __init__(self, depth):
self.depth = depth
def minimax(self, state, depth):
if depth==0 or state.isTerminated():
return None, state.evaluateScore()
best_state, best_score = None, -float('inf') if state.isMe() else float('inf')
def Max_s(a,b,c,d):
if(a>c):
return a,b
else:
return c,d
def Min_s(a,b,c,d):
if(a<c):
return a,b
else:
return c,d
for child in state.getChildren():
# YOUR CODE HERE
#util.raiseNotDefined()
if state.isMe():
ghost,min_score=self.minimax(child,depth)
best_score,best_state=Max_s(best_score,best_state,min_score,child)
elif child.isMe():
agent,max_score=self.minimax(child,depth-1)
best_score,best_state=Min_s(best_score,best_state,max_score,child)
else:
ghost,min_score=self.minimax(child,depth)
best_score,best_state=Min_s(best_score,best_state,min_score,child)
return best_state, best_score
def getNextState(self, state):
best_state, _ = self.minimax(state, self.depth)
return best_state
class MyAlphaBetaAgent():
def __init__(self, depth):
self.depth = depth
def minimax(self, state, depth,a,b):
if depth==0 or state.isTerminated():
return None, state.evaluateScore()
best_state, best_score = None, -float('inf') if state.isMe() else float('inf')
def Max_s(a,b,c,d):
if(a>c):
return a,b
else:
return c,d
def Min_s(a,b,c,d):
if(a<c):
return a,b
else:
return c,d
for child in state.getChildren():
# YOUR CODE HERE
#util.raiseNotDefined()
if state.isMe():
ghost,min_score=self.minimax(child,depth,a,b)
best_score,best_state=Max_s(best_score,best_state,min_score,child)
if best_score > b:
return best_state, best_score
a = max(a, best_score)
elif child.isMe():
agent,max_score=self.minimax(child,depth-1,a,b)
best_score,best_state=Min_s(best_score,best_state,max_score,child)
if best_score < a:
return best_state, best_score
b = min(b, best_score)
else:
ghost,min_score=self.minimax(child,depth,a,b)
best_score,best_state=Min_s(best_score,best_state,min_score,child)
if best_score < a:
return best_state, best_score
b = min(b, best_score)
return best_state, best_score
def getNextState(self, state):
# YOUR CODE HERE
#util.raiseNotDefined()
best_state, _ = self.minimax(state, self.depth,-float('inf'), float('inf'))
return best_state
|
class Solution:
def rotate(self, matrix):
import math
"""
Do not return anything, modify matrix in-place instead.
"""
n=len(matrix)
half=math.ceil(n/2)
print(n,half)
for i in range(n):
for j in range(i,n):
matrix[i][j],matrix[j][i]=matrix[j][i],matrix[i][j]
for k in range(half,n):
matrix[i][k],matrix[i][n-k-1]=matrix[i][n-k-1],matrix[i][k]
print(matrix)
matrix = \
[
[1,2,3],
[4,5,6],
[7,8,9]
]
a=Solution()
#a.rotate(matrix)
a.rotate([[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]])
|
'''
1367. 二叉树中的列表
'''
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSubPath(self, head, root):
self.head=head
self.res=0
def dfs(root,head):
if root==None:
return
if root.val==head.val:
if head.next==None:
self.res=1
else:
dfs(root.left, head.next)
dfs(root.right, head.next)
elif head!=self.head:
dfs(root,self.head)
else:
dfs(root.left,self.head)
dfs(root.right,self.head)
dfs(root,head)
if self.res==0:
return False
else:
return True |
"""
Representation of some objects used in regex.
"""
class Node: # pylint: disable=too-few-public-methods
""" Represents a node in the tree representation of a regex
Parameters
----------
value : str
The value of the node
"""
def __init__(self, value):
self._value = value
@property
def value(self):
""" Give the value of the node
Returns
----------
value : str
The value of the node
"""
return self._value
def get_str_repr(self, sons_repr):
"""
The string representation of the node
Parameters
----------
sons_repr : iterable of str
The sons representations
Returns
-------
repr : str
The representation of this node
"""
raise NotImplementedError
CONCATENATION_SYMBOLS = ["."]
UNION_SYMBOLS = ["|", "+"]
KLEENE_STAR_SYMBOLS = ["*"]
EPSILON_SYMBOLS = ["epsilon", "$"]
PARENTHESIS = ["(", ")"]
SPECIAL_SYMBOLS = CONCATENATION_SYMBOLS + \
UNION_SYMBOLS + \
KLEENE_STAR_SYMBOLS + \
EPSILON_SYMBOLS + \
PARENTHESIS
def to_node(value: str) -> Node:
""" Transforms a given value into a node """
if not value:
res = Empty()
elif value in CONCATENATION_SYMBOLS:
res = Concatenation()
elif value in UNION_SYMBOLS:
res = Union()
elif value in KLEENE_STAR_SYMBOLS:
res = KleeneStar()
elif value in EPSILON_SYMBOLS:
res = Epsilon()
elif value[0] == "\\":
res = Symbol(value[1:])
else:
res = Symbol(value)
return res
class Operator(Node): # pylint: disable=too-few-public-methods
""" Represents an operator
Parameters
----------
value : str
The value of the operator
"""
def get_str_repr(self, sons_repr):
raise NotImplementedError
def __repr__(self):
return "Operator(" + str(self._value) + ")"
class Symbol(Node): # pylint: disable=too-few-public-methods
""" Represents a symbol
Parameters
----------
value : str
The value of the symbol
"""
def get_str_repr(self, sons_repr):
return str(self.value)
def __repr__(self):
return "Symbol(" + str(self._value) + ")"
class Concatenation(Operator): # pylint: disable=too-few-public-methods
""" Represents a concatenation
"""
def get_str_repr(self, sons_repr):
return "(" + ".".join(sons_repr) + ")"
def __init__(self):
super().__init__("Concatenation")
class Union(Operator): # pylint: disable=too-few-public-methods
""" Represents a union
"""
def get_str_repr(self, sons_repr):
return "(" + "|".join(sons_repr) + ")"
def __init__(self):
super().__init__("Union")
class KleeneStar(Operator): # pylint: disable=too-few-public-methods
""" Represents an epsilon symbol
"""
def get_str_repr(self, sons_repr):
return "(" + ".".join(sons_repr) + ")*"
def __init__(self):
super().__init__("Kleene Star")
class Epsilon(Symbol): # pylint: disable=too-few-public-methods
""" Represents an epsilon symbol
"""
def get_str_repr(self, sons_repr):
return "$"
def __init__(self):
super().__init__("Epsilon")
class Empty(Symbol): # pylint: disable=too-few-public-methods
""" Represents an empty symbol
"""
def __init__(self):
super().__init__("Empty")
class MisformedRegexError(Exception):
""" Error for misformed regex """
def __init__(self, message: str, regex: str):
super().__init__(message + " Regex: " + regex)
self._regex = regex
|
"""Provides the HTTP request handling interface."""
from typing import TYPE_CHECKING, Any, Optional
import requests
from .const import TIMEOUT, __version__
from .exceptions import InvalidInvocation, RequestException
if TYPE_CHECKING:
from requests.models import Response
from .sessions import Session
class Requestor(object):
"""Requestor provides an interface to HTTP requests."""
def __getattr__(self, attribute: str) -> Any:
"""Pass all undefined attributes to the ``_http`` attribute."""
if attribute.startswith("__"):
raise AttributeError
return getattr(self._http, attribute)
def __init__(
self,
user_agent: str,
oauth_url: str = "https://oauth.reddit.com",
reddit_url: str = "https://www.reddit.com",
session: Optional["Session"] = None,
timeout: float = TIMEOUT,
) -> None:
"""Create an instance of the Requestor class.
:param user_agent: The user-agent for your application. Please follow Reddit's
user-agent guidelines: https://github.com/reddit/reddit/wiki/API#rules
:param oauth_url: The URL used to make OAuth requests to the Reddit site
(default: ``"https://oauth.reddit.com"``).
:param reddit_url: The URL used when obtaining access tokens (default:
``"https://www.reddit.com"``).
:param session: A session to handle requests, compatible with
``requests.Session()`` (default: ``None``).
:param timeout: How many seconds to wait for the server to send data before
giving up (default: ``prawcore.const.TIMEOUT``).
"""
if user_agent is None or len(user_agent) < 7:
raise InvalidInvocation("user_agent is not descriptive")
self._http = session or requests.Session()
self._http.headers["User-Agent"] = f"{user_agent} prawcore/{__version__}"
self.oauth_url = oauth_url
self.reddit_url = reddit_url
self.timeout = timeout
def close(self) -> None:
"""Call close on the underlying session."""
return self._http.close()
def request(self, *args, timeout: Optional[float] = None, **kwargs) -> "Response":
"""Issue the HTTP request capturing any errors that may occur."""
try:
return self._http.request(*args, timeout=timeout or self.timeout, **kwargs)
except Exception as exc:
raise RequestException(exc, args, kwargs)
|
# Написати клас Army, для того щоб оптимізувати код. І від нього спадкувати класи OrcArmy та ElfArmy
class Army:
def __init__(self, warrior_amount, damage_per_orc, warrior_health, shield=0):
self.warrior_amount = warrior_amount
self.damage_per_orc = damage_per_orc
self.warrior_health = warrior_health
self.shield = shield
def __str__(self):
if not self.warrior_amount:
return f'Army {self.__class__.__name__} is dead'
return f'{self.__class__.__name__} {self.warrior_amount} {self.damage_per_orc} {self.warrior_health}' \
f' {self.shield}'
def __add__(self, other):
new_amount = self.warrior_amount + other.warrior_amount
new_damage = (self.warrior_amount * self.damage_per_orc + other.warrior_amount * other.damage_per_orc) /\
(self.warrior_amount + other.warrior_amount)
new_health = (self.warrior_amount * self.warrior_health + other.warrior_amount * other.warrior_health) /\
(self.warrior_amount + other.warrior_amount)
new_shield = (self.warrior_amount * self.shield + other.warrior_amount * other.shield) / \
(self.warrior_amount + other.warrior_amount)
return self.__class__(new_amount, round(new_damage, 2), round(new_health, 2), round(new_shield, 2))
def __sub__(self, other):
sub = self.warrior_amount - other.warrior_amount
return self.__class__(0 if sub <= 0 else sub, self.damage_per_orc, self.warrior_health, self.shield)
def receive_damage(self, damage: int):
damage = (damage - self.shield) // self.warrior_health
self.warrior_amount = self.warrior_amount - damage
if self.warrior_amount < 0:
self.warrior_amount = 0
class ElfArmy(Army):
def __init__(self, warrior_amount, damage_per_orc, warrior_health, shield):
super().__init__(warrior_amount, damage_per_orc, warrior_health, shield)
class OrcArmy(Army):
def __init__(self, warrior_amount, damage_per_orc, warrior_health, shield=0):
super().__init__(warrior_amount, damage_per_orc, warrior_health)
if __name__ == "__main__":
enemy = OrcArmy(70, 15, 5)
enemy_1 = ElfArmy(155, 20, 17, 8)
big_enemy = enemy_1 + enemy
print(big_enemy)
down_enemy = enemy - enemy_1
print(down_enemy)
enemy.receive_damage(100)
print(enemy)
print(enemy.receive_damage(50))
|
def get_next_multiple(num):
result = 0
while True:
result += num
yield result
gen_multiple_of_two = get_next_multiple(2)
print(next(gen_multiple_of_two))
print(next(gen_multiple_of_two))
print(next(gen_multiple_of_two))
print(next(gen_multiple_of_two))
gen_multiple_of_thirteen = get_next_multiple(13)
print(next(gen_multiple_of_thirteen))
print(next(gen_multiple_of_thirteen))
print(next(gen_multiple_of_thirteen))
print(next(gen_multiple_of_thirteen))
|
rainbow_colors = ("RED", "ORANGE", "YELLOW", "GREEN", "BLUE", "INDIGO", "PURPLE")
user_color = (input("Введите цвет: ")).upper()
if user_color in rainbow_colors:
index = rainbow_colors.index(user_color)
if index != 0:
print(rainbow_colors[index - 1])
if index != 6:
print(rainbow_colors[index + 1])
|
# Напишіть функцію beautiful_list_generator, що приймає список, символ (маркер)
# та назву файлу. Функція створить файл з назвою, що в неї передали і маркером
# та помістить цей список в сприйнятний для більшості формі.
def beautiful_list_generator(lst: list, marker: str, file_name: str) -> bool:
try:
with open(file_name, 'w', encoding='utf-8') as f:
for i in lst:
f.write(marker + ' ' + i + '\n')
return True
except:
return False
if __name__ == "__main__":
dc_heroes = [
"Batman",
"Superman",
"Flash",
"Green Lantern",
"Wonder Woman",
]
print(beautiful_list_generator(dc_heroes, "\u2713", "heroes.txt"))
|
week_days = {"1": "monday",
"2": "tuesday",
"3": "wednesday",
"4": "thursday",
"5": "friday",
"6": "saturday",
"7": "sunday"
}
daily_routine = {"monday": ["wash and put away dishes", "wipe down mirrors"],
"tuesday": ["sort clothes to keep out", "change air filter"],
"wednesday": ["wash windows", "wash out trash can"],
"thursday": ["polish wood floors", "clean out dryer vents"],
"friday": ["wash rugs", "wash out garbage can"],
"saturday": ["go to the cinema"],
"sunday": ["at 8 pm meeting with friends"]
}
while True:
user_day = (input("Введите день недели: ").lower())
if user_day == "exit":
break
week_day = week_days.get(user_day)
if not week_day:
print(*daily_routine.get(user_day) or ["Нет такого дня недели"], sep="\n")
else:
print(*daily_routine.get(week_day), sep="\n")
|
data = input("Enter your text: ")
flag = False
result = ''
for symbol in data:
if symbol == '.':
flag = True
if flag and symbol.isalpha():
symbol = symbol.upper()
flag = False
result += symbol
print(result)
|
# Реалізуйте клас Apartment, який буде мати властивості номер квартири, кількість жителів квартири,
# поверх та площа квартири. Використайте property, для задання та зміни параметрів.
class Apartment:
def __init__(self, number_flat, inhabitants, number_floor, area_flat):
self.number_flat = number_flat
self.inhabitants = inhabitants
self.number_floor = number_floor
self.area_flat = area_flat
@property
def number_flat(self):
return self.__number_flat
@number_flat.setter
def number_flat(self, value):
if value.isdigit():
self.__number_flat = value
else:
raise ValueError('Use digit')
@number_flat.deleter
def number_flat(self):
del self.__number_flat
@property
def inhabitants(self):
return self.__inhabitants
@inhabitants.setter
def inhabitants(self, value):
if value.isdigit():
self.__inhabitants = value
else:
raise ValueError('Use digit')
@inhabitants.deleter
def inhabitants(self):
del self.__inhabitants
@property
def number_floor(self):
return self.__number_floor
@number_floor.setter
def number_floor(self, value):
if value.isdigit():
self.__number_floor = value
else:
raise ValueError('Use digit')
@number_floor.deleter
def number_floor(self):
del self.__number_floor
@property
def area_flat(self):
return self.__area_flat
@area_flat.setter
def area_flat(self, value):
if value.isdigit():
self.__area_flat = value
else:
raise ValueError('Use digit')
@area_flat.deleter
def area_flat(self):
del self.__area_flat
|
def draw_board(board):
print("-------------")
for i in range(3):
print("|", board[0+i*3], "|", board[1+i*3], "|", board[2+i*3], "|")
print("-------------")
def validation(move, board):
try:
move = int(move)
except:
return False
if move not in board:
return False
return True
def check_win(board):
win_coord = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6))
for each in win_coord:
if board[each[0]] == board[each[1]] == board[each[2]]:
return True, board[each[0]]
return False, None
def main():
board = list(range(1, 10))
player = 'X'
while True:
draw_board(board)
move = input(f"Make your move for '{player}': ")
valid = validation(move, board)
if valid:
move = int(move)
board[move-1] = player
is_win, user = check_win(board)
if is_win:
draw_board(board)
print(f'Congratulation the player {user} is winner!')
break
elif all(isinstance(i, str) for i in board):
draw_board(board)
print('There is no winner! The game has ended as Draw!')
break
player = 'O' if player == 'X' else 'X'
continue
else:
print('Make a right move')
continue
# if __name__ == '__main__':
main()
|
### Created on 25-05-2019
def input_matrix(matrix, row, col):
for i in range(row): # Loop for row entries
r = []
for j in range(col): # Loop for column entries
r.append(int(input('Entry in row ' + str(i+1) + ' col ' + str(j+1) + ': ')))
matrix.append(r)
def add_matrix(matrix1, matrix2, result):
for i in range(len(matrix1)):
r = []
for j in range(len(matrix1[0])):
r.append(matrix1[i][j] + matrix2[i][j])
result.append(r)
def sub_matrix(matrix1, matrix2, result):
for i in range(len(matrix1)):
r = []
for j in range(len(matrix1[0])):
r.append(matrix1[i][j] - matrix2[i][j])
result.append(r)
def display_matrix(matrix):
for i in range(len(matrix)):
for j in range(len(matrix[0])):
print(matrix[i][j], end=' ')
print('')
def main():
matrix1 = []
matrix2 = []
result = []
print('====================================')
print(' Operation: + Add | - Subtract ')
print('====================================')
row1 = int(input('\nEnter number of rows of matrix 1: '))
col1 = int(input('Enter number of columns of matrix 1: '))
row2 = int(input('\nEnter number of rows of matrix 2: '))
col2 = int(input('Enter number of columns of matrix 2: '))
if (row1 != row2) or (col1 != col2):
print('\nBoth matrices must be of the same size.')
else:
print('\n### Matrix 1 ###')
input_matrix(matrix1, row1, col1)
print('\n### Matrix 2 ###')
input_matrix(matrix2, row2, col2)
op = input('\nSelect operation (+, -): ')
if op == '+':
add_matrix(matrix1, matrix2, result)
print('\nThe addition of the matrices:')
display_matrix(result)
elif op == '-':
sub_matrix(matrix1, matrix2, result)
print('\nThe subtraction of the matrices:')
display_matrix(result)
else:
print('Invalid choice\n')
if __name__ == '__main__':
main()
|
### Created on 12-05-2019
nums = input('Enter some numbers (separate by space): ').split()
# Calculate the average
sum_of_nums = 0
for num in nums:
sum_of_nums += float(num)
avg = sum_of_nums / len(nums)
# Display the numbers & the average
print('\nYou entered:', *nums, end=' ')
print('\nThe average:', avg)
|
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn import preprocessing
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
chocolate = pd.read_csv("C:\choco.csv", delimiter=',')
data_random = chocolate.sample(frac=1)
keep_col = ['Company', 'Cocoa Percent', 'Company Location', 'Broad Bean Origin']
rating_col = ['Rating']
data_keep = data_random[keep_col]
ratings = data_random[rating_col]
for index, row in ratings.iterrows():
if(row['Rating']>3.7):
row['Rating']=1.0
else:
row['Rating']=0.0
encoder = preprocessing.LabelEncoder()
ratings_encoded = encoder.fit_transform(ratings)
data_dummies = pd.get_dummies(data_keep)
X_train, X_test, y_train, y_test = train_test_split(data_dummies, ratings_encoded)
forest = RandomForestClassifier(n_estimators=500, n_jobs=-1, max_features=50, min_samples_leaf=50)
forest.fit(X_train, np.ravel(y_train))
print("Classification forest:")
print(forest.score(X_train, y_train))
print(forest.score(X_test, y_test))
featuresArray = []
sum1features = [1, 414]
sum2features = [415,475]
sum3features = [476,575]
featuresArray.append(forest.feature_importances_[0])
featuresArray.append(sum(forest.feature_importances_[sum1features]))
featuresArray.append(sum(forest.feature_importances_[sum2features]))
featuresArray.append(sum(forest.feature_importances_[sum3features]))
npArray = np.asarray(featuresArray)
labels = ['Cocoa Percent','Company', 'Company Location', 'Broad Bean Origin']
n_features = npArray.shape[0]
plt.barh(range(n_features),npArray,align='center')
plt.yticks(np.arange(n_features),labels)
plt.xlabel('Feature Importance')
plt.ylabel('Feature')
plt.show() |
#coding:utf-8
import re
#需求 :从下面的字符串吧c#替换成GO语言
a = 'C|C++|Java|C#|Python|Javascript|PythonC#C#'
def convert(value):
matched = value.group()
return '!!' +matched +'!!'
# r = re.sub('C#','Go',a) #运行:C|C++|Java|Go|Python|Javascript|PythonGoGo 默认是0
# r = re.sub('C#','Go',a ,0) #运行:C|C++|Java|Go|Python|Javascript|PythonGoGo 0表示这样的替换无限制替换下去
# r = re.sub('C#','Go',a ,1) #运行:C|C++|Java|Go|Python|Javascript|PythonC#C# 1表示1次
r = re.sub('C#',convert,a ,0) #运行:C|C++|Java|Go|Python|Javascript|PythonC#C# 1表示1次
#其实这个跟replace函数也是一样的 这就是sub的简化版
#r = r.replace('C#','Go') #运行:C|C++|Java|Go|Python|Javascript|PythonGoGo
#print(r)
#需求:找出这里面所有的数字 凡是大于等于6的就替换成9
s = "A8C342D86"
def replace_dali(value):
matched = value.group()
if int(matched) >= 6:
return "9"
else:
return "0"
#\d找到[0-9] \D(等于[^0-9])
s2 =re.sub('\d',replace_dali,s)
print(s2) #输出来A9C000D99
#需求:找出这里面所有的数字 凡是大于等于50的就替换成100 小于10的替换成0
s2 = "A812C34132D81236E1"
def replace_da(value):
matched = value.group()
if int(matched) >= 6:
return "9"
else:
return "0"
#\d找到[0-9] \D(等于[^0-9])
s2 =re.sub('\d',replace_da,s2)
print(s2)
|
#coding:utf-8
# CONDITION = True
# i=1
# while i <= 10:
# i=i+1
# print(i)
# else:
# print("玩了这么多把终于打到了最强王者")
#while的使用场景 上王者使用while 设定一个目标 达到目标就不执行了
#递归算法里面用while是非常合适的
#for的使用场景 遍历序列或者集合 或者字典
a = ['apple','orange','banna','grage']
c = [['apple','orange','banna','grage'],(1,2,4)]
b = {'达理',"2",34}
for x in c:
for y in x:
print(y,end='\n')
else:
print("当遍历结束的时候就会被执行")
a= [1,2,3,4]
for x in a:
print(x)
if x==3:
break
print("循环结束啦")
for x in a:
print(x)
if x==3:
continue
print("循环结束啦") |
#!/usr/bin/python
import sys
import os
import requests
if len(sys.argv) < 2:
print """
args are ip_address [param_name....]
if no params are specifed, all are shown
if one is requested, then its value is shown
if more than one is requested, then they results are shown as
param_name<tab>param_value
...
"""
sys.exit(0)
RESERVATION_SERVER = os.getenv('RESERVATION_SERVER', 'http://reservation.eng.riftio.com:80')
url = RESERVATION_SERVER + '/testlab/REST/GetSystem/%s/' % sys.argv[1]
response = requests.get(url)
if response.status_code != 200:
raise Exception("error %d retrieving testbed defintion from %s" % (response.status_code, url))
data = response.json()
if len(sys.argv) == 3:
print data[sys.argv[2]]
elif len(sys.argv) > 3:
for param in sys.argv[2:]:
print "%s %s" % ( param, data[param] )
else:
print data
|
print("Hallo Selamat datang bebey")
print("-----------------------")
kondisi = int(input("Sekarang jam berapa iya?(ex: 13, format 24 jam): "))
print(" ")
if 1<=kondisi<=4:
print("Kamu belum tidur? Begadang? tidur lah bebey 😢")
elif 5<=kondisi<=11:
print("Selamat Pagi Bebey ❤ ❤ ❤")
elif 12<=kondisi<=15:
print("Selamat Siang Bebey ❤ ❤ ❤")
elif 16<=kondisi<=18:
print("Selamat Sore Bebey ❤ ❤ ❤")
elif 19<=kondisi<=24:
print("Selamat Malam Bebey ❤ ❤ ❤")
else:
print("Masukan jam yang benar dong ❤")
print("nggk jadi deh ucap salamnya")
print(" ")
print(" ")
ngapain = input("Kamu lagi apa bebey? ❤ :")
print(" ")
print("ohh, Kalo aku sedang mikirin kamoo ❤ ❤ ❤")
print(" ")
print(" ")
makan = input("Kamu sudah makan belum bebey? (sudah/belum): ")
print(" ")
sudah_makan = "sudah"
belum_makan = "belum"
if makan == sudah_makan:
print("Allhamdulilah bebey 😘")
elif makan == belum_makan:
print("Makan lah bebey 😢")
else:
print("yah dijawab dengan jawaban berbeda :(")
print(" ")
print(" ")
tanya_makan = input("tanyakan kembali ke saya apakah saya sudah makan atau belum: ")
print(" ")
print("Alhamdulillah aku sudah makan bebey")
print(" ")
print(" ")
print("Have A Good Day bebey? 😘")
print(" ")
input("says: ")
print(" ")
print("dadahhhhh") |
# two-part exercise
from cs115 import map
'''
Part 0
Here is a memoized version of edit distance.
Your task: make it trace the calls to fastED_help, indented
according to recursion depth. Hint: add a parameter to fastED_help.
'''
def fastED(first, second):
'''Returns the edit distance between the strings first and second. Uses
memoization to speed up the process.'''
def fastED_help(first, second, memo, tabs):
if (first, second) in memo:
return memo[(first, second)]
elif first == '':
result = len(second)
elif second == '':
result = len(first)
elif first[0] == second[0]:
print(tabs*(' ')+'fastED_help('+first[1:]+','+second[1:]+')')
tabs+=1
result = fastED_help(first[1:], second[1:], memo, tabs)
else:
print(tabs*(' ')+'fastED_help('+first[1:]+','+second[1:]+')')
print(tabs*(' ')+'fastED_help('+first[1:]+','+second+')')
print(tabs*(' ')+'fastED_help('+first+','+second[1:]+')')
tabs+=1
substitution = 1 + fastED_help(first[1:], second[1:], memo, tabs)
deletion = 1 + fastED_help(first[1:], second, memo, tabs)
insertion = 1 + fastED_help(first, second[1:], memo, tabs)
result = min(substitution, deletion, insertion)
memo[(first, second)] = result
return result
return fastED_help(first, second, {}, 0)
'''
Part 1
Complete the following function. You may use the functions
numToBinary and increment from lab 6, provided below.
Start by sketching your design in psuedo-code.
'''
def numToTC(N):
'''Assume N is an integer.
If N can be represented in 8 bits using two's complement, return
that representation as a string of exactly 8 bits.
Otherwise return the string 'Error'.
'''
if N >= 128 or N < -128:
return 'Error'
elif N < 128 and N >= 0:
b = numToBinary(N)
return prefixZeroes(b)
else:
b = numToBinary(-N)
b8 = prefixZeroes(b)
flipped = helperino(b8)
print(flipped)
added = add(flipped,'1')
return added
'''
Examples:
NumToTc(1) ---> '00000001'
NumToTc(-128) ---> '10000000'
NumToTc(200) ---> 'Error'
'''
def add(S, T):
'''converts to base 10 and then adds and converts back'''
STen=baseBToNum(S, 2)
TTen=baseBToNum(T, 2)
newNum = STen + TTen
answer = numToBaseB(newNum, 2)
return answer
def numToBaseB(N, B):
'''Precondition: integer argument is non-negative.
Returns the string with the number N converted into whatever base B'''
def inner(N, B):
if N==0:
return ''
else:
return inner(N//B,B)+str(N%B)
if N == 0:
return '0'
else:
return inner(N,B)
def baseBToNum(S, B):
'''Precondition: s is a string of 0s and 1s.
Returns the integer corresponding to the base B representation in S.
Note: the empty string represents 0.'''
biterinos = len(S)
if S=='':
return 0
elif S[0] == '0':
return baseBToNum(S[1:], B)
else:
return ((B**(biterinos-1))*int(S[0])) + baseBToNum(S[1:], B)
def helperino(x):
def inhelperino(x,newx):
if x == '':
return newx
elif x[0]=='0':
newx+='1'
return inhelperino(x[1:],newx)
else:
newx+='0'
return inhelperino(x[1:],newx)
return inhelperino(x,'')
def prefixZeroes(s):
'''fills up empty spaces with 0s to get 5 total numbers in each 'chunk' '''
binary = s
len_binary = len(binary)
return ('0'*(8-len_binary)) + binary
def numToBinary(N):
'''Assuming N is a non-negative integer, return its base 2
representation as a string of bits.'''
if N == 0:
return ''
if isOdd(N):
return numToBinary(N//2) + '1'
else:
return numToBinary(N//2) + '0'
def increment(s):
'''Assuming s is a string of 8 bits, return the binary representation
of the next larger number takes an 8 bit string of 1's and 0's and
returns the next largest number in base 2'''
num = binaryToNum(s) + 1
if num == 256:
return '00000000'
zeros = (len(s)-len(numToBinary(num))) * '0'
return zeros + numToBinary(num)
def binaryToNum(s):
'''Assuming s is a string of bits, interpret it as an unsigned binary
number and return that number (as a python integer).
'''
def binaryToNumHelp(s, index):
if s == '':
return 0
elif s[0] == '0':
index -= 1
return 0 + binaryToNumHelp(s[1:], index)
else:
index -= 1
return 2**index + binaryToNumHelp(s[1:], index)
return binaryToNumHelp(s, len(s))
def isOdd(n):
'''returns whether a number is odd or not'''
if n % 2 == 0:
return False
else:
return True
|
from cs115 import *
def div(k):
return n % k == 0
def divides(n):
'checks if there is a remainder'
def div(k):
return n % k == 0
return div
def divisibles(n,L):
'assume L is a list of integers; return a list of the one divisible by n'
if L==[]:
return []
else:
if divides(L[0])(n):
return [L[0]] + divisibles(n, L[1:])
else:
return divisibles(n,L[1:])
def make_len(n):
def pad_it(word):
x = len(word)
return word + ((n-x)*'*')
return pad_it
def pad(words):
'Assume words is a non-empty list of strings. Let n be the'
'length of the longest. Write * after the shorter to make them the same length'
m= max(map(len,words))
return map(make_len(m), words)
|
from cs115 import *
import math
def inverse(n):
'''returns the reciprocal'''
return 1/n
def add(x,y):
'''adds 2 inputted variables'''
return x+y
def divideByFact(x):
'''divides 1 by the inputted variales factorial'''
return 1/math.factorial(x)
def e(n):
'''uses a taylor series to approximate e'''
'''n is how many terms there are in the series'''
M = range(1,n+1)
return reduce(add,map(divideByFact, M))+1
def error(n):
'''finds the error in the approximation'''
M = range(1,n+1)
myE=e(n)
return abs(math.e - myE)
|
def skill_agility(answer, person): # меняет ловкость use the 1 option as negative in question
while person['skills']["luck"] > 0 and person['skills']["agility"] > 0:
if answer == '1':
person['skills']["luck"] = person['skills']["luck"] - person['cargo']["risk_precent"]
person['skills']['agility'] = person['skills']['agility'] - person['cargo']["risk_precent"]
return print('Your luck: ', person['skills']["luck"], 'Your eloquence: ', person['skills']["luck"],
'Your agility: ', person['skills']["luck"])
if answer == '2':
person['skills']["luck"] = person['skills']["luck"] + person['cargo']["risk_precent"]
person['skills']["agility"] = person['skills']['agility'] + person['cargo']["risk_precent"]
return print('Your luck: ', person['skills']["luck"], 'Your eloquence: ', person['skills']["luck"],
'Your agility: ', person['skills']["luck"])
def skill_eloquence(answer, person): # use the 2 option as negative in question
while person['skills']["luck"] > 0 and person['skills']["eloquence"] > 0:
if answer == '2':
person['skills']["luck"] = person['skills']["luck"] - person['cargo']["risk_precent"]
person['skills']['eloquence'] = person['skills']['eloquence'] - person['cargo']["risk_precent"]
return print('Your luck: ', person['skills']["luck"], 'Your eloquence: ', person['skills']["luck"],
'Your agility: ', person['skills']["luck"])
if answer == '1':
person['skills']["luck"] = person['skills']["luck"] + person['cargo']["risk_precent"]
person['skills']["eloquence"] = person['skills']['eloquence'] + person['cargo']["risk_precent"]
return print('Your luck: ', person['skills']["luck"], 'Your eloquence: ', person['skills']["luck"],
'Your agility: ', person['skills']["luck"])
def positive_1(person): # try skill_eloquence for answer
answer = input('Print your answer here:', )
return skill_eloquence(answer, person)
def positive_2(person): # try skill_agility for answer
answer = input('Print your answer here:', )
return skill_agility(answer, person)
# if answer != '1' and answer != '2':
# print('Please choose variant 1 or 2')
def question(lucky_person):
lucky_person['name'] = input('Hello! Welcome to custom! May I know your name? ', )
print('Do you have illegal items?\n Choose your option:\n 1. Yes \n 2. No')
positive_2(lucky_person)
print('We will need to exam your luggage, sir.\n Choose your option:\n'
' 1. Maybe we can avoid this somehow? \n '
'2. Ok, here is my bag.')
positive_1(lucky_person)
if lucky_person['cargo']["type"] == "technique":
print('Oh, what is this? There are some phones. Do you have docs for them?\n Choose your option:\n'
' 1. No, unfortunately \n '
'2. Seems I left them at home.')
positive_2(lucky_person)
if lucky_person['cargo']["type"] == "cigarette":
print('Oh, what is this? There are some packs of sigarettes. You have too many.\n Choose your option:\n '
'1. I will leave some if required \n'
' 2. I do not care about the law')
positive_1(lucky_person)
if lucky_person['cargo']["type"] == "jewelry":
print('Oh, what is this? There are some brilliants. \n Choose your option:'
'\n 1. I do not want to go to prison!!!'
' \n 2. I hope we can resolve such the situation if you understand.')
positive_2(lucky_person)
if lucky_person['cargo']["type"] == "alcohol":
print('Oh, what is this? Whiskie? \n Choose your option:\n '
'1. That is all for me. \n '
'2. Just bring one bottle.')
positive_2(lucky_person)
print('Did you have any issues with law before?\n Choose your option:\n'
'1. No, never. \n '
'2. To be honest, yes. I stole a heart of one girl. Just jocking.')
positive_1(lucky_person)
|
Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:43:08) [MSC v.1926 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> print("number\tsquare\tcube")
number square cube
>>> for i in range(6):
print(i,"\t",pow(i,2),"\t",pow(i,3))
0 0 0
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
>>>
>>> celsius = float(input('Enter temperature in Celsius: '))
Enter temperature in Celsius: -40
>>> fahrenheit = (celsius * 9/5) +32
>>> print('%0.1f Celsius is equal to %0.1f degree Fahrenheit'%(celsius,fahrenheit))
-40.0 Celsius is equal to -40.0 degree Fahrenheit
>>> Celsius = float(input('Enter temperature in Celsius: '))
Enter temperature in Celsius: 0
>>> fahrenheit = (celsius * 9/5) +32
>>> print('%0.1f Celsius is equal to %0.1f degree Fahrenheit'%(celsius,fahrenheit))
-40.0 Celsius is equal to -40.0 degree Fahrenheit
>>> celsius = float(input('Enter temperature in Celsius: '))
Enter temperature in Celsius: 0
>>> fahrenheit = (celsius * 9/5) + 32
>>> print('%0.1f Celsius is equal to %0.1f degree Fahrenheit'%(celsius,fahrenheit))
0.0 Celsius is equal to 32.0 degree Fahrenheit
>>> celsius = float(input('Enter temperature in Celsius: '))
Enter temperature in Celsius: 40
>>> fahrenheit = (celsius * 9/5) + 32
>>> print('%0.1f Celsius is equal to %0.1f degree Fahrenheit'%(celsius,fahrenheit))
40.0 Celsius is equal to 104.0 degree Fahrenheit
>>> celsius = float(input('Enter temperature in Celsius: '))
Enter temperature in Celsius: 100
>>> fahrenheit = (celsius * 9/5) + 32
>>> print('%0.1f Celsius is equal to %0.1f degree Fahrenheit'%(celsius,fahrenheit))
100.0 Celsius is equal to 212.0 degree Fahrenheit
>>>
==================== RESTART: C:/Users/Owner/Desktop/sum.py ====================
Enter the value of a:1000
Enter the value of b:2000
Enter the value of c:4000
Sum is = 7000
>>>
================== RESTART: C:/Users/Owner/Desktop/average.py ==================
Enter the value of a:1000
Enter the value of b:2000
Enter the value of c:4000
Average is = 2333.3333333333335
>>> |
# pycal.functions.py
from pprint import pprint
import math
class Trigonometry:
def __init__(self, name:str=None, *args, **kwargs):
'''
Trigonometry is a branch of mathematics that studies relationships
between the sides and angles of triangles.
'''
if name:
self.trig_name = name
@property
def pi(self):
return math.pi
def sqr(self, num:float=None):
if num:
return num * num
return
def sqrt(self, num:float=None):
""" Does not accept negative numbers"""
if num and num > 0 :
return math.sqrt(num)
return
def radian(self, degree:float=None):
'''
Return the Aangular radians given a degrees.
'''
if degree and degree < 361:
return math.radians(degree)
return 'You have exceded the maximimum circular degree of a true circle'
def degree(self, radian:float=None):
'''
Return the Aangular degrees radians given a radian.
'''
if radian and radian < self.radian(360):
return math.degrees(radian)
return 'You have exceded the maximimum radei of a true circle'
def hypothenuse(self, height:float=None, base:float=None):
'''
Return the length the hypothenuse of a triangle given its rise and run distance.
'''
if height and base:
return self.sqrt( self.sqr(height) + self.sqr(base) )
return
class Geometry(
# Plugins
Trigonometry
):
def __init__(self, name:str=None, *args, **kwargs):
'''
Geometry is a branch of mathematics that studies the size,
shapes, angles, positions and dimensions of things.
'''
if name:
self.geo_name = name
# Calculator Functions Here
def rcircle(self, radius:float=None):
'''
Return the Area of a circle given its radius.
In geometry, the area enclosed by a circle of radius r is π r².
Here the Greek letter π represents a constant, approximately equal to 3.14159, which is equal to
the ratio of the circumference of any circle to its diameter. Source: wikipedia.com.
A = \pi r^2
A = area
r = radius
Usage:
In [3]: cal.area_r(2)
Out[3]: 12.566370614359172
'''
if radius:
return self.sqr(radius) * self.pi
pprint(self.rcircle.__doc__, depth=1, width=60)
return
def dcircle(self, diameter:float=None):
'''
Return the Area of a circle given its diameter.
'''
if diameter:
return (self.rcircle(diameter / 2))
return
def rectangle(self, length:float=None, width:float=None):
'''
Identifies and Return the Area and perimeter of a rectangle or square.
'''
if length and width:
objectr = {
"area": length * width,
"perimeter": (2 * length) + (2 * width)
}
if length == width:
objectr['figure'] = 'Square'
else:
objectr['figure'] = 'Rectangle'
return objectr
return
def triangle(self, base:float=None, height:float=None):
'''
Identifies and Return the Area and perimeter of a rectangle or square.
'''
if base and height:
return (base / 2) * height
return
def trapezoid(self, toplength:float=None, baselength:float=None, height:float=None):
'''
Return the area of a Trapezium or Quadrilateral given the length of
its two paralell sides and the distance between them.
'''
if toplength and baselength and height:
return ((toplength + baselength) / 2) * height
return
def quadrilateral(self, toplength:float=None, baselength:float=None, height:float=None):
return self.trapezoid(toplength, baselength, height)
|
#a=int(input())
#if (a==4):
# print("this is down. you win ")
#if (a!=4):
#else:
# print("oops, your gues is wrong")
#x=input()
#y=input()
#if (x>y):
# print(x+("is greater"))
#else:
# print(y+("the number is greater"))
x=int(input())
y=int(input())
if (x>y):
print(str(x)+("is greater"))
else:
print(str(y)+("the number is greater"))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
from ..find_anagram import find_anagrams
class TestFindAnagrams(unittest.TestCase):
def test_should_find_anagram_with_list_arg(self):
result = find_anagrams('roma', ['amor', 'teste', 'mora'])
self.assertEqual(len(result), 2)
def test_should_find_anagram_with_special_chars(self):
result = find_anagrams('leão', ['oãel', '', 'mora', 'ãããos'])
self.assertEqual(len(result), 1)
def test_should_find_anagram_with_tuple_arg(self):
result = find_anagrams('leão', ('oãel', '', 'mora', 'ãããos'))
self.assertEqual(len(result), 1)
def test_should_find_anagram_with_empty_string(self):
result = find_anagrams('', ('oãel', '', 'mora', 'ãããos'))
self.assertEqual(len(result), 1)
def test_should_find_anagram_with_number_on_string(self):
result = find_anagrams(1, ('oãel', '', 'mora', 'ãããos'))
self.assertFalse(result)
|
class Node:
def __init__(self, data):
self.data = data
self.next = None
class SinglyLinkedList:
def __init__(self):
self.head = None
def __len__(self):
node = self.head
length = 0
while node:
node = node.next
length += 1
return length
def add_at_head(self, data):
node = Node(data)
if self.head == None:
self.head = node
else:
node.next = self.head
self.head = node
def add_at_end(self,data):
node = Node(data)
if self.head == None:
self.head = node
else:
p = self.head
while p.next:
p = p.next
p.next = node
def echo(self):
node = self.head
while node:
print(node.data,end=" ")
node = node.next
def length(self):
return len(self)
def is_empty(self):
return len(self) == 0
if __name__ == '__main__':
l1 = SinglyLinkedList()
l1.add_at_end(1)
l1.add_at_end(2)
l1.add_at_end(3)
l1.add_at_end(4)
print(l1.length())
print(l1.is_empty())
l1.echo()
|
t = int(input())
if (t%3==1):
print((t//3 -1)*7 + 4)
else:
if (t%3 ==2):
print((t//3)*7 +1 )
else:
print(t // 3 * 7) |
# Question: Calculate the sum of the values of keys a and b .
d = {"a": 1, "b": 2, "c": 3}
# Expected output:
# 3
# Answer
print(d['a'] + d['b'])
# Explanation:
# It's as easy as that. However, if you want to do the sum of all dictionary values you need to take another approach instead of accessing all values one by one. We're going through that approach later on in another exercise. |
"""
use Monte Carlo method for simulation which uses random sampling to evaluate possible outcomes.
this program will determine the probability of certain outcomes when rolling dice.
Input: variable number of arguments for sides of dice
Output: table of possible outcome
example: roll_dice(4, 6, 6) => useing 4 side die and two 6 sided dice
"""
import random
def sort_dict(dictionary):
new_dict = {}
lst = [k for k in dictionary.keys()]
lst.sort()
for key in lst:
new_dict[key] = dictionary[key]
return new_dict
def roll_dice(*args):
number_of_simulations = int(1e6) # a million times
sides_tracker = {}
sum_tracker = {}
for sim in range(number_of_simulations):
total_sum = 0
for roll in args:
side_of_dice = random.randint(1, roll)
# Counting Sides
side_count = sides_tracker.get(side_of_dice, 0) + 1 # check and update the counter for each side
sides_tracker[side_of_dice] = side_count
# Counting sum of dice
total_sum += side_of_dice
sum_count = sum_tracker.get(total_sum, 0) + 1
sum_tracker[total_sum] = sum_count
print("----- OUTCOME PROBABILITY for Each Side -----")
for key,value in sort_dict(sides_tracker).items():
probability = (sides_tracker[key] / (number_of_simulations * len(args))) * 100
print("side {} : {:0.2f}%".format(key, probability))
print("\n----- OUTCOME PROBABILITY for Sum -----")
for key,value in sort_dict(sum_tracker).items():
probability = (sum_tracker[key] / number_of_simulations) * 100
print("{} : {:0.2f}%".format(key, probability))
if __name__ == "__main__":
roll_dice(4, 6, 6)
roll_dice(4, 6, 6, 20) |
# Question: Use Python to calculate the distance in kilometers between Jupiter and Sun
# on January 1, 1230.
# Hint 1: Use the ephem Python third party library.
# Hint 2: Note that the units of ephem are in Astronomical Units (AU).
# You need to convert them to kilometers.
# Expected output:
# 758085657.5026425
# Answer:
import ephem
date = '1230/1/1'
jupiter = ephem.Jupiter()
jupiter.compute(date)
distance_AU = jupiter.sun_distance
distance_km = distance_AU * 149597870.691
print(f"distance in kilometers between Jupiter and Sun on January 1, 1230: {distance_km}")
# Explanation:
# This solution required some internet research to find out about the ephem library which is used for astronomy computations. The library can be installed with pip install ephem, but if that doesn't work on Windows then download a precompiled version from here and install it again with pip like pip install ephem‑3.7.6.0‑cp36‑cp36m‑win_amd64.whl
# In the ephem webpage you can find an example to start off. The above solution was developed based on that example.
|
class Account:
def __init__(self, name, balance, min_balance):
self.name = name
self.balance = balance
self.min_balance = min_balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if self.balance - amount >= self.min_balance:
self.balance -= amount
else:
print("No Sufficient Funds!")
def show_statement(self):
print(f"Balance: $ {float(self.balance)}")
class Current(Account):
def __init__(self, name, balance):
super().__init__(name, balance, min_balance=-1000)
def __str__(self):
return f"{self.name}'s Current account is $ {self.balance}"
class Saving(Account):
def __init__(self, name, balance):
super().__init__(name, balance, min_balance=0)
def __str__(self):
return f"{self.name}'s Saving account is $ {self.balance}"
def main():
c1 = Current("Richard", 500)
print(c1)
c1.deposit(100)
c1.withdraw(50)
c1.show_statement()
c1.withdraw(500)
c1.show_statement()
c1.withdraw(100)
c1.show_statement()
s1 = Saving("Vivian", 1000)
print(s1)
s1.deposit(200)
s1.withdraw(50)
s1.show_statement()
s1.withdraw(100)
s1.show_statement()
s1.withdraw(500)
if __name__ == "__main__":
main() |
# download the attached ZIP file and extract its files in a folder.
# Then, write a script that counts and prints out the number of .py files in that folder.
import pathlib
count = 0;
for path in pathlib.Path('./92_files').iterdir():
if path.is_file() and path.suffix == '.py':
count += 1;
print(f'Number of files {count}');
#alternative way
# import glob
# file_list=glob.glob1("files","*.py")
# print(len(file_list))
|
import configparser
def main():
print("***** Welcome to Your Weights on differnt Planets ***** ")
user_answer = 'Y'
try:
while user_answer == "Y":
weight = input("\nPlease enter your weight(lbs) on EARTH : ")
if weight != "":
weight_converter(int(weight))
user_answer = input("\nWould you like to try again (Y/N)? ")
except Exception as err:
print(f"\nYou have provided an invalid input. The program will quit now !")
def weight_converter(weight):
"""convert earth weight to 9 different planets weights"""
config = configparser.RawConfigParser()
config.read("planets.properties")
print(f"Your weight on MERCURY is {round(float(config.get('WeightsSection','MERCURY')) * weight,2)}")
print(f"Your weight on VENUS is {round(float(config.get('WeightsSection','VENUS')) * weight,2)}")
print(f"Your weight on MOON is {round(float(config.get('WeightsSection','MOON')) * weight,2)}")
print(f"Your weight on MARS is {round(float(config.get('WeightsSection','MARS')) * weight,2)}")
print(f"Your weight on JUPITER is {round(float(config.get('WeightsSection','JUPITER')) * weight,2)}")
print(f"Your weight on SATURN is {round(float(config.get('WeightsSection','SATURN')) * weight,2)}")
print(f"Your weight on URANUS is {round(float(config.get('WeightsSection','URANUS')) * weight,2)}")
print(f"Your weight on NEPTUNE is {round(float(config.get('WeightsSection','NEPTUNE')) * weight,2)}")
print(f"Your weight on PLUTO is {round(float(config.get('WeightsSection','PLUTO')) * weight,2)}")
if __name__ == "__main__":
main() |
# Question: Make a script that prints out numbers from 1 to 10
# Expected output:
# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9
# 10
# Answer:
for item in range(1,11):
print(item)
# Explanation:
# A for loop is used to repeat an action (i.e. print ) until the iterating sequence (i.e. range ) is consumed. In our case it would print all items of the range one by one.
|
import pickle
class Animal:
def __init__(self, name, species):
self.name = name
self.species = species
def __repr__(self):
return f"{self.name} is a {self.species}"
def make_sound(self, sound):
print(f"this animal says {sound}")
class Cat(Animal):
def __init__(self, name, breed, toy):
super().__init__(name, species="Cat") # Call init on parent class
self.breed = breed
self.toy = toy
def play(self):
print(f"{self.name} plays with {self.toy}")
conny = Cat("Conny", "Burmese Shorthair", "Yo Yo")
# pickling the object will store the object as binary, so next time you can unpickl it and continue where you left of
# pickling comes from same concept of making something last long and use it later when you need it
# To pickle an object:
# wb: write binary
with open("pets.pickle", "wb") as file:
pickle.dump(conny, file)
# To unpickle something:
# rb: read binary
# with open("pets.pickle", "rb") as file:
# zombie_conny = pickle.load(file)
# print(zombie_conny)
# print(zombie_conny.play())
|
collection = ["gold", "silver", "bronze"]
# list comprehension
new_list = [item.upper for item in collection]
# generator expression
# it is similar to list comprehension, but use () round brackets
my_gen = (item.upper for item in collection) |
# Input: A list / array with integers. For example:
# [3, 4, 1, 2, 9]
# Returns:
# Nothing. However, this function will print out
# a pair of numbers that adds up to 10. For example,
# 1, 9. If no such pair is found, it should print
# "There is no pair that adds up to 10.".
def pair10(given_list):
numbers_seen = {}
for item in given_list:
if (10 - item) in numbers_seen:
return [(10-item), item]
else:
numbers_seen[item] = 1
if __name__ == "__main__":
print("""
Which pair adds up to 10? (Should print 1, 9)
[3, 4, 1, 2, 9]
""")
result = pair10([3, 4, 1, 2, 9])
print(result)
print("""
Which pair adds up to 10? (Should print -20, 30)
[-11, -20, 2, 4, 30]
""")
result = pair10([-11, -20, 2, 4, 30])
print(result)
print("""
Which pair adds up to 10? (Should print 1, 9 or 2, 8)
[1, 2, 9, 8]
""")
result = pair10([1, 2, 9, 8])
print(result)
print("""
Which pair adds up to 10? (Should print 1, 9)
[1, 1, 1, 2, 3, 9]
""")
result = pair10([1, 1, 1, 2, 3, 9])
print(result)
print("""
Which pair adds up to 10? (Should print "There is no pair that adds up to 10.")
[1, 1, 1, 2, 3, 4, 5]
""")
result = pair10([1, 1, 1, 2, 3, 4, 5])
print(result) |
def count_up(x, maximum):
if x > maximum:
print("Done!")
return
print(x)
count_up(x+1, maximum)
count_up(1, 10)
|
# Two nested loops are O(n^2)
my_favourite_desserts = ["chocolate", "ice cream", "crackers"]
quantities = [10, 20, 30]
for item in my_favourite_desserts:
for q in quantities:
print(item, " - ", q) |
import json
people_string ='''
{
"people":[
{
"name":"John-Smith",
"phone":"123-456-789",
"emails":["[email protected]","[email protected]"],
"has_license":false
},
{
"name":"Doey Timberlake",
"phone":"444-555-666",
"emails":null,
"has_license":true
}
]
}
'''
#load string into object
data = json.loads(people_string)
# print(type(data['people']))
# print(data)
for person in data["people"]:
del person["phone"] #delete phone keys and values
new_string = json.dumps(data, indent=2)
print(new_string) |
import random
import configparser
def main():
user_answer = 'Y'
print("******* Welcome to Magic 8 Balls *******")
while user_answer == 'Y':
question = input("What would you like to know? please ask me your question.\n")
if question == "":
print("Seem like you have nothing to ask. Good bye!")
user_answer = "N"
else:
answer_number = random.randint(1,20)
answer = get_answer(answer_number)
print(answer)
#ask user to whether he/she likes to answer more question.
user_answer = input("Would you like to ask again? (Y/N) : ")
#function to get answer
def get_answer(answer_number):
#load the properties file
config = configparser.RawConfigParser()
config.read('answers.properties')
"""give the magic 8 balls answers """
if answer_number == 1:
answer = config.get('AnswersSection','answer1')
elif answer_number == 2:
answer = config.get('AnswersSection','answer2')
elif answer_number == 3:
answer = config.get('AnswersSection','answer3')
elif answer_number == 4:
answer = config.get('AnswersSection','answer4')
elif answer_number == 5:
answer = config.get('AnswersSection','answer5')
elif answer_number == 6:
answer = config.get('AnswersSection','answer6')
elif answer_number == 7:
answer = config.get('AnswersSection','answer7')
elif answer_number == 8:
answer = config.get('AnswersSection','answer8')
elif answer_number == 9:
answer = config.get('AnswersSection','answer9')
elif answer_number == 10:
answer = config.get('AnswersSection','answer10')
elif answer_number == 11:
answer = config.get('AnswersSection','answer11')
elif answer_number == 12:
answer = config.get('AnswersSection','answer12')
elif answer_number == 13:
answer = config.get('AnswersSection','answer13')
elif answer_number == 14:
answer = config.get('AnswersSection','answer14')
elif answer_number == 15:
answer = config.get('AnswersSection','answer15')
elif answer_number == 16:
answer = config.get('AnswersSection','answer16')
elif answer_number == 17:
answer = config.get('AnswersSection','answer17')
elif answer_number == 18:
answer = config.get('AnswersSection','answer18')
elif answer_number == 19:
answer = config.get('AnswersSection','answer19')
else:
answer = config.get('AnswersSection','answer20')
return answer
#main
if __name__ == "__main__":
main() |
# Python Object Oriented Programming by Joe Marini course example
# Using composition to build complex objects
class Book:
def __init__(self, title, price, author):
self.title = title
self.price = price
self.author = author
self.chapters = []
def addchapter(self, chapter):
self.chapters.append(chapter)
def getbookpagecount(self):
total_pages = 0
for ch in self.chapters:
total_pages += ch.pages
return total_pages
class Author():
def __init__(self, authorfname, authorlname):
self.authorfname = authorfname
self.authorlname = authorlname
def __str__(self):
return f"{self.authorfname} {self.authorlname}"
class Chapter():
def __init__(self, name, pages):
self.name = name
self.pages = pages
author = Author("Leo", "Tolstoy")
b1 = Book("War and Peace", 39.0, author)
ch1 = Chapter("Chapter 1", 125)
ch2 = Chapter("Chapter 2", 97)
ch3 = Chapter("Chapter 3", 143)
b1.addchapter(ch1)
b1.addchapter(ch2)
b1.addchapter(ch3)
print(b1.title)
print(b1.author)
print(b1.getbookpagecount())
|
def bubble_sort(items, ascending = True):
n = len(items)
is_sorted = True
for i in range(n):
for j in range(1, n - i):
if ascending:
if items[j] < items[j-1]:
items[j], items[j-1] = items[j-1], items[j]
is_sorted = False
else:
if items[j] > items[j-1]:
items[j], items[j-1] = items[j-1], items[j]
is_sorted = False
# immediate return for already sorted ones
if is_sorted:
return items
return items
if __name__ == "__main__":
items = [8, 2, 4, 1, 3]
# items = [8, 2, 4]
# items = [8, 2]
# items = [8]
# items = []
# items = [1, 2, 3, 4, 8]
print("items: ", items)
sorted_one = bubble_sort(items)
print("After ascending, sorted items: ", sorted_one)
sorted_one = bubble_sort(items, ascending = False)
print("After decending, sorted items: ", sorted_one) |
"""
Palindrome: word or phrase that reads the same forwards as backwards
Input: string of word or phrase
Output: True/False
Only consider letters (A-Z)
Ignore Capital Letters
Example: level => Palindrome
Example: Racecar => Palindrome
Example: Go hang a salami - I'm a lasagna hog => Palindrome
"""
import re
def is_palindrome(st):
forwards = "".join(re.findall("[A-Za-z]+", st.lower()))
backwards = forwards[::-1]
return forwards == backwards
if __name__ == "__main__":
st = input("Enter a string: ")
result = is_palindrome(st)
print("It is a Palindrome." if result else "It is NOT a Palindrome.") |
import unittest
import addition
class TestMain(unittest.TestCase):
def setUp(self):
print("about to run a function.")
def test_add_1(self):
'''Sample doc string'''
test_param1 = 10
test_param2 = 20
result = addition.add(test_param1,test_param2)
self.assertEqual(result,30)
def test_add_2(self):
test_param1 = "abcdefg"
test_param2 = 20
result = addition.add(test_param1,test_param2)
# self.assertTrue(isinstance(result,ValueError))
self.assertIsInstance(result,ValueError)
def test_add_3(self):
test_param1 = None
test_param2 = 20
result = addition.add(test_param1, test_param2)
self.assertEqual(result,"Please enter numbers.")
def test_add4(self):
test_param1 = ""
test_param2 = 20
result = addition.add(test_param1, test_param2)
self.assertEqual(result,"Please enter numbers.")
def test_add5(self):
test_param1 = 0
test_param2 = 0
result = addition.add(test_param1, test_param2)
self.assertEqual(result, 0)
def tearDown(self):
print('cleaning up !!!')
if __name__ == "__main__":
unittest.main()
|
def fibonacci(n):
'''Return nth number of fibonacci sequence'''
if n < 2:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)
if __name__ == "__main__":
for i in range(1, 10):
print(fibonacci(i))
|
from time import perf_counter
from functools import wraps
def timer(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = perf_counter()
result = func(*args, **kwargs)
end = perf_counter()
duration = end - start
args = str(*args)
print(f"{func.__name__}({args}) = {result} => Duration: {duration:.8f}seconds")
return result
return wrapper
@timer
def fib(n):
'''return nth value from Fibonacci sequence '''
if n < 2:
return n
else:
return fib(n-1) + fib(n-2)
if __name__ == "__main__":
print(fib(20))
|
# This is generator function which will return generator object
def even_integers_function(n):
for i in range(n):
if i%2 == 0:
yield i
if __name__ == "__main__":
even_gen = even_integers_function(10)
print(even_gen) #generator object got returned.
print(list(even_gen)) #now generator object yeild the results |
"""Reterive and print words from a URL.
Usage:
python3 words.py <URL>
Example: python words.py http://sixty-north.com/c/t.txt
"""
import requests
import sys
def fetch_words(url):
"""Fetch a list of string from URL.
Args:
url: The URL of a UTF-8 text document.
Returns:
A list of strings containing words from the document.
"""
user_agents = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36'
headers = {'User-Agents':user_agents}
response = requests.get(url,headers = headers)
story_word = []
for line in response.text.split('\n'):
line_word = line.split()
for word in line_word:
story_word.append(word)
return story_word
def print_words(story_word):
"""Print items one per line.
Args:
An iterable series of printable items.
"""
for word in story_word:
print(word)
def main(url):
"""Print each word from a text document from at a URL.
Args:
url: The URL of a UTF-8 text document.
"""
words = fetch_words(url)
print_words(words)
if __name__ == "__main__":
url = sys.argv[1] # The 0th arg is the module filename.
main(url) |
#from database.db, print out those countries with an area of greater than 2,000, 000.
import sqlite3
conn = sqlite3.connect('database/database.db');
c = conn.cursor();
c.execute('SELECT * FROM countries WHERE area >= 2000000;');
results = c.fetchall();
for country in results:
print(",".join(str(data) for data in country))
c.close();
|
# Question: The script is supposed to output the cosine of angle 1 radian, but instead it is throwing an error. Please fix the code so that it prints out the expected output.
# import math
# print(math.cosine(1))
# Expected output:
# 0.5403023058681397
# Answer:
import math
print(math.cos(1))
print(dir(math))
# Hint: You could get a list of all available methods of the math module with dir(math) and see whether cosine is there or not. |
#
# Example file for variables
#
# Declare a variable and initialize it
x = 100
print(x)
# # re-declaring the variable works
x = "abc"
print(x)
# # ERROR: variables of different types cannot be combined
# print("hello" + 123)
print("hello" + str(123))
# Global vs. local variables in functions
def some_func():
# global x
x = 999
print(x)
some_func()
print(x)
|
from functools import reduce
# def accumulator(acc, item):
# print(acc, item)
# return acc + item # acc gets assign this result on next run
# items = [1, 2, 3]
# print("Result: ", reduce(accumulator, items, 10))
#reducing list of string into total word length
def word_length(acc, item):
# return len(item) + acc
return {item: len(item)}
items = ["list", "of", "words"]
print("Total Length: ", reduce(word_length, items, 0)) |
# Python Essential Libraries by Joe Marini course example
# Example file for using Requests library
import requests
# use a timeout value for a request
resp = requests.get("https://httpbin.org/delay/0.5", timeout=1.0)
print(resp.status_code)
# simulating timeout error => website took 2.0 seconds to response, our program only wait for 1.0 seconds otherwise throw timeout error
resp = requests.get("https://httpbin.org/delay/2.0", timeout=1.0)
print(resp.status_code)
# introspect the redirection history
resp = requests.get("http://github.com") # github redirects http request to more secure https
print(resp.url)
print(resp.history)
print()
original = resp.history.pop()
print(original.url)
print(original.status_code)
print(original.reason)
# Use a session object to group requests and settings
sess = requests.Session()
sess.get("https://httpbin.org/cookies/set/sample/123456789")
resp = sess.get("https://httpbin.org/cookies")
print(resp.text)
# Customize the user-agent to simulate different browsers
# Set the user-agent to be Firefox
sess.headers.update({
"User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0"
})
resp = sess.get("http://google.com")
print(len(resp.content))
# Set the user-agent to be an iPhone
sess.headers.update({
"User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 13_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) relesys_web_client/1.3.10.0 (RelesysApp/1.3.43 net.relesysapp.nettoenterprise)"
})
resp = sess.get("http://google.com")
print(len(resp.content)) |
#create a program that generate a password of 6 random alphanumeric characters in the range
#abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()?
# Answer 1:
import random
st = 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()?'
password = ''
for i in range(6):
password += random.choice(st)
print(password)
# Answer 2:
characters = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()?"
chosen = random.sample(characters, 6)
password = "".join(chosen)
print(password)
# Explanation:
# We're importing the random module and using its sample method which picks 6 random items from the characters sequence. The items are stored in list chosen . Then we use a string join method to join the list items to a string.
|
# 1 What would be the output of the below 4 print statements?
#Try to answer these before you click RUN!
print("Hello {}, your balance is {}.".format("Cindy", 50))
print("Hello {0}, your balance is {1}.".format("Cindy", 50))
print("Hello {name}, your balance is {amount}.".format(name="Cindy", amount=50))
print("Hello {0}, your balance is {amount}.".format("Cindy", amount=50))
# 2 How would you write this using f-string? (Scroll down for answer) |
# Question: Create a program that prints out Hello every two seconds.
# Expected output:
# ...
# Hello
# Hello
# Hello
# Hello
# Hello
# Hello
# ...
# Answer:
import time
while True:
print('Hello')
time.sleep(2)
# Explanation:
# The sleep method of the built-in time module suspends the execution of the script for the given number of seconds. |
#create a script that lets user submit a password until they have satisifed three conditions.
#1) Password contains at least one number
#2) Contains one upper letter
#3) It is at least 5 chars long
# Print out message 'password is not fine' if the user didn't create a correctly satisfied password
# Answer (using regex):
import re
pattern = '(?=.*[0-9])(?=.*[A-Z])([a-zA-Z0-9!@#$%^&*()?]+){5,}'
user_password = input('Enter your password to check condition: ')
match = re.search(pattern, user_password)
if match:
print('Your password satisfy the conditions. Good Job !')
else:
print('password is not fine.')
# Answer 2:
while True:
psw = input("Enter new password: ")
if any(i.isdigit() for i in psw) and any(i.isupper() for i in psw) and len(psw) >= 5:
print("Password is fine")
break
else:
print("Password is not fine")
# Explanation:
# We're using a while loop here because we need to keep the program running until the user submits a password that satisfies all three conditions. Line 3 contains the three conditions connected with an and operator. Line 3 becomes True only when all three conditions are True . If that happens, Password is fine is generated, and the break statement will break the loop, and the program will stop. If at least one of the conditions in Line 3 is False , Line 3 evaluates to False and the print statement under else is executed and the loop starts over again. |
#filter
def only_odd(item):
return item % 2 != 0
my_list = [1,2,3]
print(my_list)
print(list(filter(only_odd, my_list)))
|
import random
CHOICE = ["Rock", "Paper", "Scissor"]
DRAW = 0
WIN = 1
LOSE = 2
def get_result(user_choice, computer_choice):
if user_choice == "R" and computer_choice.startswith("P"):
return 2
elif user_choice == "R" and computer_choice.startswith("S"):
return 1
elif user_choice == "P" and computer_choice.startswith("R"):
return 1
elif user_choice == "P" and computer_choice.startswith("S"):
return 2
elif user_choice == "S" and computer_choice.startswith("R"):
return 2
elif user_choice == "S" and computer_choice.startswith("P"):
return 1
else:
return 0
def rock_paper_scissor():
user_wins = 0
computer_wins = 0
number_of_wins = 3
print("*** Welcome to Rock Paper Scissor ***")
print("to quit: type q")
print("how to play - Enter r for ROCK | Paper: p | Scissor: s")
while user_wins < number_of_wins and computer_wins < number_of_wins:
computer_choice = random.choice(CHOICE)
user_choice = input("\nEnter your choice: ").upper()
if user_choice not in ["R", "P", "S", "Q"]:
print("you enter invalid choice. please try again.")
continue
if user_choice == "Q":
break
print(f"Computer plays: {computer_choice}")
result = get_result(user_choice, computer_choice)
if result == 1:
user_wins +=1
print("You wins!")
elif result == 2:
computer_wins +=1
print("Computer wins!")
else:
print("It's a draw!")
print(f"Your Score: {user_wins} vs Computer Score: {computer_wins}")
print("\nThanks for playing!")
print("\n--- Final Score ---")
print(f"Your Score: {user_wins} vs Computer Score: {computer_wins}")
if user_wins > computer_wins:
print("Congrats.. You win!")
elif user_wins < computer_wins:
print("Sorry.. Computer wins!")
else:
print("It's a tie!")
if __name__ == "__main__":
rock_paper_scissor() |
import pprint
message = "Today is quite cloudy in Yangon. I just watched #Alive korean zombie moive which is pretty good."
count = {}
for character in message.upper():
count.setdefault(character, 0) #if key doesn't exist in dict, set 0 as default value
count[character] = count[character] + 1
#pprint.pprint(count)
text = pprint.pformat(count) #if we want the output string to do further manipulation
print(text) |
""""
print the picture of the lists in terms of grid as below shape
..OO.OO..
.OOOOOOO.
.OOOOOOO.
..OOOOO..
...OOO...
....O....
""""
grid = [['.', '.', '.', '.', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['O', 'O', 'O', 'O', 'O', '.'],
['.', 'O', 'O', 'O', 'O', 'O'],
['O', 'O', 'O', 'O', 'O', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['.', '.', '.', '.', '.', '.']]
for y in range(len(grid[0])):
for x in range(len(grid)):
print(grid[x][y], end="")
print("") |
#!/usr/local/bin/python3
import sys
import os
SearchDir = "/"
SearchExt = ".mp3" # Default extension.
numargs = len(sys.argv)
if numargs > 3:
print("Error - too many arguments supplied.")
sys.exit()
elif numargs == 2:
if sys.argv[1][0] == ".":
SearchExt = sys.argv[1]
else:
if os.path.isdir(sys.argv[1]):
SearchDir = sys.argv[1]
else:
print("Error - name is not a valid directory")
sys.exit()
elif numargs == 3:
if sys.argv[1][0] == ".":
SearchExt = sys.argv[1]
if os.path.isdir(sys.argv[2]):
SearchDir = sys.argv[2]
else :
print("Error - name is not a valid directory")
sys.exit()
else :
if os.path.isdir(sys.argv[1]):
SearchDir = sys.argv[1]
else :
print("Error - name is not a valid directory")
sys.exit()
if sys.argv[2][0] == ".":
SearchExt = sys.argv[2]
else :
print("Error - search extension does not contain a period.")
sys.exit()
def findfile (searchdir, searchext):
print("Searchdir = ", searchdir, "Searchext = ", searchext)
foundfiles = []
contents = os.listdir(searchdir)
# print(contents)
for name in contents :
if os.path.isfile(os.path.join(searchdir, name)):
# print("found a file", name)
if name.endswith(searchext):
foundfiles.append(os.path.join(searchdir, name))
elif os.path.isdir(os.path.join(searchdir, name)):
# print("found a directory", name)
tempfiles = findfile(os.path.join(searchdir, name), searchext)
foundfiles.extend(tempfiles)
return foundfiles
def findfile2(searchdir, searchext):
os.chdir(searchdir)
print("Searchdir = ", os.getcwd(), "Searchext = ", searchext)
foundfiles = []
contents = os.listdir(".")
# print(contents)
for name in contents:
if os.path.isfile(name):
# print("found a file", name)
if name.endswith(searchext):
foundfiles.append(os.path.join(os.getcwd(), name))
elif os.path.isdir(name):
# print("found a directory", name)
tempfiles = findfile2(name, searchext)
foundfiles.extend(tempfiles)
os.chdir("..")
return foundfiles
# allfiles = findfile(SearchDir, SearchExt)
allfiles = findfile2(SearchDir, SearchExt)
for name in allfiles:
print(name)
|
"""contient les méthodes d'accès aux fichiers"""
import pickle
class Files:
def fopen(path):
file = open(path, 'r')
content = file.read()
file.close()
return content
fopen = staticmethod(fopen)
def dic_saver(origin, map, dictionnary):
with open(origin+map, 'wb') as fichier:
mon_pickler = pickle.Pickler(fichier)
mon_pickler.dump(dictionnary)
dic_saver = staticmethod(dic_saver)
def dic_recuperator(origin, map):
with open(origin+map, 'rb') as fichier:
mon_depickler = pickle.Unpickler(fichier)
return mon_depickler.load()
dic_recuperator = staticmethod(dic_recuperator) |
#####################################################################################################################
# AUTHOR:
# Gabrielle Talavera
#
# DESCRIPTION: This project simulates a mesh network where nodes and links may fail. Nodes may fail intermittently,
# and as an input to the simulation, each node and link will have a certain probability to fail. When such failure
# occurs, the network must adapt and re-route to avoid the faulty node.
#
# RUNNING THE PROGRAM:
# 1. Make sure Python is installed preferrably 3.7.4
# 2. Make sure numpy and networkx packages are downloaded
# 3. Run the program using 'python sim.py'
#
# OUTPUT:
# - Original Path
# - Number of hops with no node failures
# - Total Cost of Path
# - Updates:
# - Nodes that fail every cycle.
# - Updated path from source node to destination node
# - Number of hops (how many links it has to pass over)
# - Total Cost of path (all the weights on links added up)
# - If the Dijkstra and Bellman-Ford feature is activated, then the
# path, hops, and total cost would be printed for these algorithms
######################################################################################################################
import networkx as nx
import random
import numpy as np
# this gets a user input of how many nodes that are wanted
# returns an integer of the amount of nodes
def nodeAmount():
# An input is requested and stored in a variable
text = input("Enter number of nodes: ")
# Converts the string into a integer.
nodes = int(text)
return nodes
# this gets a user input of the probability of node failure
# returns a float which is the probability of failure
def nodeFailure():
failProb = -1
while failProb < 0 or failProb > 1:
text = input("Enter probability of node failure (0-1): ")
failProb = float(text)
return failProb
# this gets a user input of the starting node
# returns an integer which is the source node
def srcNode(nodeAmount):
src = -1
while src > (nodeAmount-1) or src < 0:
text = input("Enter source node (possible values from 0 to the number of nodes - 1): ")
src = int(text)
return src
# this gets a user input of the ending node
# returns an integer which is the destination node
def destNode(nodeAmount):
dest = -1
while dest > (nodeAmount-1) or dest < 0:
text = input("Enter destination node (possible values from 0 to the number of nodes - 1): ")
dest = int(text)
return dest
# this generates the graph
# Parameters: n = node amount (based on user input)
# returns the graph (network)
def generateGraph(n):
# finds the max amount of edges that can exist
maxEdges = (n * (n - 1)) / 2
# based on the max amount of edges, it randomizes a number of edges that our graph will have
e = random.randint(n, maxEdges)
# this generates a random graph using the amount of nodes and edges
g = nx.gnm_random_graph(n, e)
# this randomly assigns weights to the edges
for (u, v) in g.edges():
g.edges[u, v]['weight'] = random.randint(1, 10)
return g
# this finds the shortest path using the Floyd-Warshall function which was imported from networkx
# if you want to compare Floyd-Warshall with Dijkstra's uncomment lines: 107, 112, 122
# if you want to compare Floyd-Warshall with Bellman-Ford uncomment lines: 108, 113, 123
def findPath(graph, src, dest):
# finds node predecessors using a function imported from networkx
predecessors, _ = nx.floyd_warshall_predecessor_and_distance(graph)
try:
# finds the shortest path through the Floyd-Warshall algorithm by using a function imported from networkx
path = nx.reconstruct_path(src, dest, predecessors)
dpath = nx.dijkstra_path(graph, src, dest)
bfpath = nx.bellman_ford_path(graph, src, dest)
# prints the shortest path
print("Path:", path)
# print("Dijkstra's Path:", dpath)
# print("Bellman-Ford Path:", bfpath)
# prints the number of hops from source to destination
print("Number of Hops:", len(path)-1)
# print("Dijkstra's Number of Hops:", len(dpath)-1)
# print("Bellman-Ford Number of Hops:", len(bfpath)-1)
# gets the total cost
edge = 0
for i in range(1, len(path)):
edge += graph.edges[path[i - 1], path[i]]['weight']
dpathcost = nx.dijkstra_path_length(graph, src, dest)
bfpathcost = nx.bellman_ford_path_length(graph, src, dest)
print("Total Cost:", edge)
# print("Dijkstra's Total Cost:", dpathcost)
# print("Bellman-Ford Total Cost:", bfpathcost)
print()
except:
# Print to the terminal if no path exists.
print("ERROR: No available path from source: node", src, "to destination: node", dest)
# this is to calculate which nodes are failing
# parameters: nodeAmount = amount of nodes
# nodeProbs = probabilities that were assigned to each node to fail
# failProb = the probabily of node failure based on user input
# src = starting node
# dest = ending node
# returns a list of the nodes that failed
def calculateFailure(nodeAmount, nodeProbs, failProb, src, dest):
# calculates the amount of nodes that can fail
failAmount = round(failProb / (1 / nodeAmount))
# this randomly generates the nodes that could fail
holder = {random.randint(0, nodeAmount) for x in range(0, failAmount)}
failure = []
# this goes through the nodes that could fail and if their probability is lower than the failProb, then the node
# will be added to the fail list
for x in holder:
if nodeProbs[x - 1] < failProb and x != src: #and x != dest:
failure.append(x)
return failure
# this updates the path and graph based on the node failures
def update(graph, nodeAmount, nodeProbs, failProb, src, dest):
print("Updates: ")
# uses the calculateFailure to get the failed nodes
failure = calculateFailure(nodeAmount, nodeProbs, failProb, src, dest)
print("Nodes that failed: ", failure)
# removes the nodes that failed from the graph
graph.remove_nodes_from(failure)
# finds the new shortest path
findPath(graph, src, dest)
def main():
# get user inputs
n = nodeAmount()
src = srcNode(n)
dest = destNode(n)
f = nodeFailure()
# randomly generates a list of the probability of each node failing
nodeProbs = np.random.rand(n)
# generates the graph
g = generateGraph(n)
# finds the shortest path
findPath(g, src, dest)
# automatically does one case of failed nodes, so user can see what happens
update(g, n, nodeProbs, f, src, dest)
# will keep executing update until user enters a q
q = ''
while q != 'q':
print('Enter q to exit, or enter any other key to continue to update the graph with failed nodes: ')
q = input()
if q != 'q':
update(g, n, nodeProbs, f, src, dest)
if __name__ == "__main__":
main()
|
#!/bin/python
def sort2arrays(a,b):
l = []
pta, ptb, ptl = 0,0,0
while pta < len(a) and ptb < len(b):
if a[pta] < b[ptb]:
l.append(a[i])
pta+=1
print sort2arrays([2,4,6,8,10], [1,3,5,7,9])
|
#!/usr/bin/python
def insertion_sort(items):
""" Implementation of insertion sort """
for i in range(1, len(items)):
j = i
while j > 0 and items[j] > items[j-1]:
items[j], items[j-1] = items[j-1], items[j]
print items
j -= 1
return items
lst = insertion_sort([8,3,7,9,2,5,6])
print lst
|
"Show-off the Circuitous code from the user's point of view"
from __future__ import division
from circuitous import Circle
print u'Tutorial for Circuitous\N{trade mark sign}'
print 'Circle class version %d.%d' % Circle.version[:2]
c = Circle(10)
print 'a circle with a radius of', c.radius
print 'has an area of', c.area()
print
## Academia ########################################################
from pprint import pprint
from random import random, seed
n = 10000
jenny = 8675309
seed(jenny)
print 'DARPA Grant Proposal to study the average area of random circles'
print 'using Circuitous(tm) version %d.%d' % Circle.version[:2]
print 'preliminary study of {n} random circles'.format(n=n)
print "seeded using Jenny's number: {jenny}".format(jenny=jenny)
circles = [Circle(random()) for i in xrange(n)]
areas = [circle.area() for circle in circles]
average_area = sum(areas) / n
print 'The average area is %.5f' % average_area
print
## Rubber Sheet Company ###############################################
cut_template = [0.1, 0.2, 0.7]
print 'Specification sheet for the cut template:', cut_template
circles = [Circle(cut_radius) for cut_radius in cut_template]
for i, c in enumerate(circles, start=1):
print 'Circle number #%d' % i
print 'A rubber circle with a cut radius of', c.radius
print 'has a perimeter of', c.perimeter()
print 'and a cold area of', c.area()
c.radius *= 1.1
# c.set_radius(c.get_radius() * 1.1)
print 'and a warm area of', c.area()
print
## National Tire Company ##############################################
class Tire(Circle):
'Circle analytics on a rubber tire'
RUBBER_RATIO = 1.25
def perimeter(self):
'Circumference corrected for the rubber on the tire'
return Circle.perimeter(self) * self.RUBBER_RATIO # Extending
return 2.0 * math.pi * self.radius * self.RUBBER_RATIO # Overriding
__perimeter = perimeter
class MonsterTire(Tire):
RUBBER_RATIO = 1.50
t = Tire(30)
print 'A tire with an inner radius of', t.radius
print 'has an inner area of', t.area()
print 'and an outer perimeter of', t.perimeter()
print
m = MonsterTire(30)
print 'A tire with an inner radius of', m.radius
print 'has an inner area of', m.area()
print 'and an outer perimeter of', m.perimeter()
print
## National Trucking Company ###############################
print u'An inclinometer reading of 5\N{degree sign}',
print 'is a %.1f%% grade.' % Circle.angle_to_grade(5)
print
## National Graphics Company ###############################
c = Circle.from_bbd(30)
print 'A circle with a bounding box diagonal of 30'
print 'has a radius of', c.radius
print 'an area of', c.area()
print 'and perimeter of', c.perimeter()
print
## US Government ###########################################
# No circle software shall compute the area() directly from
# instance variables. It MUST first call perimeter() and
# infer the radius indirectly.
# No circle software shall store a radius. It MUST store
# the diameter and ONLY the diameter.
|
#!/usr/bin/python
fib_dict = {}
def cache_fib(fib_func):
print 'inside cache_fib'
def fib_wrapper(n):
if n not in fib_dict:
fib_dict[n] = fib_func(n)
return fib_dict[n]
return fib_wrapper
@cache_fib
def fib(n):
print 'aparna looses'
if n == 0 or n ==1:
return n
return fib(n-1)+fib(n-2)
#fib = cache_fib(fib)
result = fib(10)
print result
|
import random
def main():
print('Guessing game')
print('Guess a number between 1 and 100')
m,c = start()
if c == 0:
print(m)
else:
print(m+' in '+str(c)+' tries')
def start():
guess = -1
c=0
f=True
rannum = random.randint(1,100)
print(rannum)
while True:
n = input("Guess your number: ")
if len(n) == 0:
continue
if f:
if int(n) == rannum:
return 'Out of bounds',c
elif int(n) > rannum - 10 and int(n) < rannum + 10:
print("WARM")
guess = n
else:
print("Cold")
guess = n
else:
if int(n) == rannum:
return 'Number guessed',c
elif abs(int(n)-rannum) < abs(int(guess)-rannum):
print("Warmer")
guess = n
else:
print("Colder")
guess = n
c+=1
f=False
main()
|
# 列表推导式
# 计算从1到10的所有偶数的2次幂
# 第一种方式
alist = [] # 定义一个存放2次幂的列表
for i in range(1, 11):
if i % 2 == 0:
alist.append(i * i)
print(alist)
# 第二种方式,使用列表推导式
blist = [i * i for i in range(1, 11) if i % 2 == 0]
print(blist)
|
price = 10
pen = 0.38
rain = True
name = 'kevin'
print(price, pen, rain, name)
name = input('请输入名字:')
print('Hello,' , name)
height = input('请输入身高:')
weight = input('input your weight:')
print('你的身高是:' , height)
print('你的体重是:' , weight, '该减肥了')
major = input('input your major:')
print('your major:' , major) |
def bubble_sort(arr):
def swap(i, j):
arr[i], arr[j] = arr[j], arr[i]
n = len(arr)
swapped = True
x = -1
while swapped:
swapped = False
x = x + 1
for i in range(1, n - x):
if arr[i - 1] > arr[i]:
swap(i - 1, i)
swapped = True
return arr
print(bubble_sort([12,12,11,23,45,65,76,9]))
def bubble_Sort(arr):
x=0
l = len(arr)
h = l//2
while x != h +1:
h=h+1
for i in range(l):
if arr[i] > arr[i+1]:
arr[i],arr[i+1]=arr[i+1],arr[i]
return arr
print([12,12,11,23,45,65,76,9])
|
import pandas as pd
import numpy as np
class dataPandas:
def __init__(self):
self.fields = ['season', 'week', 'away_team', 'a_score', 'away_elo_i', 'home_elo_i','away_elo_f', 'home_elo_f']
self.df = pd.read_csv('nfl_results.csv', usecols=self.fields, low_memory=False)
self.away_team = self.season = self.week = 0
# Verify number of arguments, if necesary filter or not
def setArgs(self, args):
if len(args) >= 2 and len(args) <= 4:
try:
self.away_team = args[1]
except Exception as e:
self.away_team = ""
try:
self.season = args[2]
except Exception as e:
self.season = ""
try:
self.week = args[3]
except Exception as e:
self.week = ""
print 'Valid arguments'
self.setFilter()
elif len(args) >= 1 and len(args) <= 2:
self.getData()
else:
print 'Invalid arguments'
# If not filter, display all data
def getData(self):
print self.df.to_string()
# if necesary filter, depend of arguments we apply an specific filter
def setFilter(self):
print "\nFound Elements"
print "--------"
# Filter by away_team
if len( self.away_team ) > 0:
filterBy = ( self.df.away_team == self.away_team.strip() )
# Filter by season
if len( self.away_team ) > 0 and len( self.season ) > 0:
filterBy = ( self.df.away_team == self.away_team.strip() ) & ( self.df.season == int(self.season) )
# Filter by week
if len( self.away_team ) > 0 and len( self.season ) > 0 and len( self.week ) > 0:
filterBy = ( self.df.away_team == self.away_team.strip() ) & ( self.df.season == int(self.season) ) & ( self.df.week == int(self.week) )
findData = self.df[ filterBy ]
print("Number of found elements: {0}".format(len(findData)))
print findData.to_string()
|
pizzas = ['New York','chicago','Pan','Thick','Cracker'];
message = 'The first three items in the list are:';
print(message);
print(pizzas[:3]);
print('Three items from the middle of the list are:');
print(pizzas[1:4]);
print('The last three items in the list are:');
print(pizzas[-3:]);
friend_pizzas = [];
pizzas.append('ice');
friend_pizzas.append('naiyou');
print('My favorite pizzas are:');
for pizza in pizzas:
print(pizza);
print("My friend's favorite pizzas are:");
for friend_pizza in friend_pizzas:
print(friend_pizza);
print('=========================================================');
my_foods = ['pizza','falafel','carrot cake'];
for my_food in my_foods:
print(my_food);
|
#coding=gbk
print('=========================ֵѵʼ=========================================');
friend = {'first_name':'Ma', 'last_name':'Yuhua', 'age':'25', 'city':''};
print(friend);
print();
likeNum = {'Mayh':'2','Mazh':'4','Magy':'8','Vsky':'5','fly':'9'};
print(likeNum);
course = {'var':'','str':'ַ','num':'','list':'б','dict':'ֵ'};
print();
print('var:' + course['var']);
print('str:' + course['str']);
print('num:' + course['num']);
print('list:' + course['list']);
print('dict:' + course['dict']);
|
#coding=gbk
print('=========================ָ==========================');
class Resturaurant():
def __init__(self, restaurant_name, cuisine_type):
"""ʼrestaurant_name,cuisine_type"""
self.restaurant_name = restaurant_name;
self.cuisine_type = cuisine_type;
self.number_served = 0;
def describe_restaurant(self):
"""ӡ"""
print(self.restaurant_name);
print(self.cuisine_type);
def open_restaurant(self):
"""Ӫҵ"""
print('Open for business!');
def set_number_served(self, number_served):
self.number_served = number_served;
def increment_number_served(self, number_served):
self.number_served += number_served;
rest = Resturaurant('','');
print(rest.number_served);
rest.number_served = 2;
print(rest.number_served);
rest.set_number_served(6);
print(rest.number_served);
rest.increment_number_served(300);
print(rest.number_served);
print('=========================ָ==========================');
class User():
def __init__(self,first_name,last_name,summary):
self.first_name = first_name;
self.last_name = last_name;
self.summary = summary;
self.login_attempts = 0;
def describe_user(self):
print(self.summary);
def greet_user(self):
print('Welcome,' + self.first_name.title() + ' ' + self.last_name.title());
def increment_login_attempts(self):
self.login_attempts += 1;
def reset_login_attempts(self):
self.login_attempts = 0;
user = User('guoying','ma','');
user.increment_login_attempts();
user.increment_login_attempts();
user.increment_login_attempts();
print('ӡ½');
print(user.login_attempts);
user.reset_login_attempts();
print('úĵ¼');
print(user.login_attempts);
|
import sqlite3
import json
#Read data from json (Socrata Database)
f = open("testjson.txt", "r")
content = f.read()
dict_all = json.loads(content)
#Connection to SQLite Database
conn = sqlite3.connect('testing3.db',isolation_level=None)
c = conn.cursor()
#Get count of all tables in the database
c.execute("SELECT name FROM sqlite_master WHERE type='table';")
tables = c.fetchall()
# for table in tables:
# print(table)
# print(len(tables))
#Get the actual columns dynamically from the json and get the count of columns
allEntryColumns = []
for data in dict_all:
for data2 in data.items():
allEntryColumns.append(data2[0])
columns = []
for x in allEntryColumns:
if x not in columns:
columns.append(x)
#print(columns)
#print(len(columns))
#Create the CREATE table query. For now, all datatypes are text. Clarify
tableName = "table" + str(len(tables))
createQuery = 'CREATE TABLE ' + tableName + "("
for col in columns:
createQuery = createQuery + col + " text" + ","
createQuery = createQuery + "PRIMARY KEY (year, quarter, ndc))"
print(createQuery)
#Get all the entries from the json
allData = []
i = 0
entries = []
for data in dict_all:
for x in columns:
try:
allData.append(dict_all[i][x])
except:
allData.append("~")
entries.append(allData)
allData = []
i = i + 1
#print(entries)
#calculate number of questions marks. Needed as synthax of insert is c.executemany("INSERT INTO table VALUES (?,?,?,?,?...)", entries)
#Create INSERT query
questionList = []
for x in range(len(columns)):
questionList.append('?')
insertQuery = ",".join(questionList)
insertQuery = "INSERT INTO " + tableName + " VALUES (" + insertQuery + ")"
#print(insertQuery)
#if there are no tables, create the table and populate it. Name of table is "table" + number of tables
if (len(tables) == 0):
print("There are no tables")
# c.execute(createQuery)
# c.executemany(insertQuery, entries)
# conn.commit()
conn.close()
exit()
#comparing columns
latestTable = "table" + str(len(tables) - 1)
cursor = c.execute("SELECT * FROM "+latestTable)
latestColumns = list(map(lambda x: x[0], cursor.description))
#print(latestColumns)
#print(columns)
if len(columns) != len(latestColumns):
print("The number of columns have changed.")
c.execute(createQuery)
c.executemany(insertQuery, entries)
conn.commit()
conn.close()
exit()
for i in range(len(latestColumns)):
if columns[i] != latestColumns[i]:
print("The columns have changed.")
c.execute(createQuery)
c.executemany(insertQuery, entries)
conn.commit()
conn.close()
exit()
print("No Change in number/values of columns")
print("---------------------------------")
#I have to create a new table in order to do value comparison
newTable = tableName
c.execute(createQuery)
c.executemany(insertQuery, entries)
#print(latestTable)
#print(newTable)
#Outer joins to check if rows have been added or removed
rowsRemovedCount = []
leftJoinStatement = "SELECT COUNT(*) FROM "+latestTable+" LEFT OUTER JOIN "+newTable+" ON "+latestTable+".ndc = "+newTable+".ndc WHERE "+newTable+".year ISNULL"
c.execute(leftJoinStatement)
for row in c:
#print(row)
rowsRemovedCount.append(row)
rowsAddedCount = []
revLeftJoinStatement = "SELECT COUNT(*) FROM "+newTable+" LEFT OUTER JOIN "+latestTable+" ON "+latestTable+".ndc = "+newTable+".ndc WHERE "+latestTable+".year ISNULL"
c.execute(revLeftJoinStatement)
for row in c:
#print(row)
rowsAddedCount.append(row)
latestTableRowsCount = []
c.execute("SELECT COUNT(*) FROM "+latestTable)
for row in c:
#print(row)
latestTableRowsCount.append(row)
newTableRowsCount = []
c.execute("SELECT COUNT(*) FROM "+newTable)
for row in c:
#print(row)
newTableRowsCount.append(row)
matchingNDCCount = []
c.execute("SELECT COUNT(*) FROM "+latestTable+", "+newTable+" WHERE " +latestTable+".ndc = "+newTable+".ndc")
for row in c:
#print(row)
matchingNDCCount.append(row)
checkEmpty = 0
print(str(rowsRemovedCount[0][0])+ " rows has been removed from the old table which had "+str(latestTableRowsCount[0][0]) + " rows")
print(str(rowsAddedCount[0][0])+ " rows has been added to the new table which now has "+str(newTableRowsCount[0][0]) + " rows")
if int(newTableRowsCount[0][0]) == 0:
print("Shrinkage of 100%")
print("Growth of 0%")
checkEmpty = 1
if int(latestTableRowsCount[0][0]) == 0:
print("Shrinkage of 0%")
print("Growth of 100%")
checkEmpty = 1
if checkEmpty == 0:
shrinkage = str(int(rowsRemovedCount[0][0]) / int(matchingNDCCount[0][0]) * 100)
print("Shrinkage of "+shrinkage+"%")
growth = str(int(rowsAddedCount[0][0]) / int(matchingNDCCount[0][0]) * 100)
print("Growth of "+growth+"%")
#Count number of values (including null) in a column
SelectColCount1 = "SELECT COUNT(coalesce("+newTable+"." + latestColumns[0] + ",\"~\")) FROM " +newTable
ColCount1 = []
c.execute(SelectColCount1)
for row in c:
ColCount1.append(row)
# print(ColCount1[0][0])
print("---------------------------------")
#print table values for manual comparison
# c.execute("SELECT * FROM "+latestTable)
# for row in c:
# print(row)
# print("---------------------------------")
# c.execute("SELECT * FROM "+newTable)
# for row in c:
# print(row)
# print("---------------------------------")
#compare values between the two tables
hasChanged = 0
for col in latestColumns:
SelectColDifference = "SELECT COUNT(coalesce("+latestTable+"." + col + ",\"~\")) FROM "+latestTable+", "+newTable+" WHERE " +latestTable+".ndc = "+newTable+".ndc AND "+ "(SELECT coalesce("+latestTable+"." + col + ",\"~\")) <> " + "(SELECT coalesce("+newTable+"." + col + ",\"~\"))"
#print(SelectColDifference)
c.execute(SelectColDifference)
for row in c:
#print(row)
#print(row[0])
#print(ColCount1[0][0])
change = str(int(row[0]) / int(ColCount1[0][0]) * 100)
print("Change of "+change+"% in "+ col)
if change != 0:
hasChanged = 1
#delete newtable if there are no changes. Delete always for now.
if (hasChanged == 0):
c.execute("DROP TABLE " + newTable)
conn.commit()
conn.close()
exit()
if (shrinkage == 0):
c.execute("DROP TABLE " + newTable)
conn.commit()
conn.close()
exit()
if (growth == 0):
c.execute("DROP TABLE " + newTable)
conn.commit()
conn.close()
exit()
#close connection
conn.commit()
conn.close()
|
def replace_char(s , n , c):
s = s[0:n] + s[n:n+1].replace(s[n] , c) + s[n+1:]
return s
def replace_interval(a,b,s,c):
for i in range(a,b+1):
s = replace_char(s,i,c)
return s
def base_triangle(z):
a = "1"
b = "_"
# c = "_"
j = 1
n = z
li = []
for i in range(0,n - 1):
li.append(((b) * (n - i - 1) + (a) * (j) + (b ) * (n - i - 2) + b))
j+=2
li.append((a) * (j - 1) + a)
return li
# lis = []
def positions_to_draw_triangles(r,n):
s = 0
iterations = 2 ** (n-1)
rr = r / iterations
pos=[]
for i in range(0,iterations):
pos.append((i*rr) + (rr/2))
return pos
def intermediates(s):
li=[]
for i in range(0,len(s)):
if s[i] == "1":
li.append(i)
else:
li.append(0)
# print(li)
lis=[]
lis1=[]
l=[]
l1=[]
for i in range(1,len(li)):
if(li[i-1] == 0 ):
if(li[i] !=0):
lis.append(li[i])
# print(lis)
elif(li[i] == 0):
pass
if(li[i-1] != 0):
if(li[i] !=0):
pass
elif(li[i] == 0):
lis1.append(li[i-1])
# print(lis)
else:
l.append(lis)
l1.append(lis1)
l2 = []
for i in range(0,len(l[0])):
l2.append((l[0][i], l1[0][i]))
return l2
def make_t(n):
li = base_triangle()
pos1 = []
ll = len(li)
pos1 = positions_to_draw_triangles(ll,n)
pos = []
pos.append(pos1[0])
if(li[pos[0]].count('1') == 2*(pos[0])+1):
for i in range(0,(li[pos[0]].count('1') - 1)/2):
# print(i,pos[0]+i , len(li[pos[0]]) - pos[0]-i-1)
li[pos[0] + i] = replace_interval(pos[0]+i , len(li[pos[0]]) - pos[0]-i-1 , li[pos[0] + i] , '_' )
return li
# li is base_triangle() here
def make_ts(n,l):
li=l
pos1 = []
ll = len(li)
pos1 = positions_to_draw_triangles(ll,n)
pos = []
for i in range(0,len(pos1)):
pos.append(pos1[i])
for k in range(0,len(pos)):
if(li[pos[k]].count('1') == 2*(pos[k])+1):
# print(pos[k],k, li[pos[k]].count('1'), 2*(pos[k])+1)
for i in range(0,(li[pos[k]].count('1') - 1)/2):
# print(i,ll-pos[k]+i , ((ll*2)-1)-(ll-pos[k]+i)-1)
li[pos[k] + i] = replace_interval(ll-pos[k]+i , ((ll*2)-1)-(ll-pos[k]+i+1) , li[pos[k] + i] , '_' )
# print(li[pos[k] + i])
# print(".")
else:
intm = intermediates(li[pos[k]])
# offset
# print(intm , k ,pos[k], li[pos[k]])
# for x1 in range(pos[k], ((pos[k]) + ((intm[0][1]-intm[0][0])/2)) ):
for x2 in range(0,len(intm)):
for x3 in range(0,((intm[0][1]-intm[0][0])/2)):
li[pos[k]+x3] = replace_interval(intm[x2][0]+x3+1, intm[x2][1]-x3-1,li[pos[k]+x3], '_')
# print(pos[k],intm[x2][0]+x3, intm[x2][1]-x3)
return li
li=[]
def log_base2(n):
i=0
while True:
if 2**i == n:
return i
else:
i+=1
def seirpinski(base_t, a):
if a == 1:
return base_triangle(base_t)
if a <= log_base2(base_t):
return make_ts(a-1,seirpinski( base_t,a-1))
else:
return "Limit can only be reached upto " + str(log_base2(base_t)) + " for given triangle dimensions"
li = seirpinski(int(input()) , int(input()) )
for item in li:
print item
|
class EmptyPiece:
def __init__(self):
self.player = -1
def get_neighbors():
return []
# Data structure to hold information about pieces
# Useful for doing bfs
class Piece:
def __init__(self, player=-1, pos=None, neighbor1=None, neighbor2=None, neighbor3=None, neighbor4=None, neighbor5=None, neighbor6=None):
assert(player in [-1, 0, 1])
self.player = player
self.pos = pos
self.neighbor1 = None
self.neighbor2 = None
self.neighbor3 = None
self.neighbor4 = None
self.neighbor5 = None
self.neighbor6 = None
# Add neighbor to piece, and add the reverse too
def add_neighbor(self, piece, neighborNo):
if neighborNo == 1:
self.neighbor1 = piece
piece.neighbor4 = self
elif neighborNo == 2:
self.neighbor2 = piece
piece.neighbor5 = self
elif neighborNo == 3:
self.neighbor3 = piece
piece.neighbor6 = self
elif neighborNo == 4:
self.neighbor4 = piece
piece.neighbor1 = self
elif neighborNo == 5:
self.neighbor5 = piece
piece.neighbor2 = self
elif neighborNo == 6:
self.neighbor6 = piece
piece.neighbor3 = self
# Return only the neighbors of the piece that are of the same team, and that belong to a playing player's team
def get_neighbors(self):
neighbors = [self.neighbor1, self.neighbor2, self.neighbor3, self.neighbor4, self.neighbor5, self.neighbor6]
return [i for i in neighbors if i is not None and i.player == self.player and i.player != -1]
# # Board Util to deal with overflow
# class Board(list):
# def __init__(self, size=5):
# self.size = size
# self.grid = [[EmptyPiece() for i in range(self.size)] for j in range(self.size)]
# def __getitem__(self, tup):
# key1, key2 = tup
# if key1 >= self.size or key1 < 0 or key2 >= self.size or key2 < 0:
# return EmptyPiece()
# else:
# return self.grid[key1][key2]
# def __setitem__(self, tup, val):
# key1, key2 = tup
# if key1 >= self.size or key1 < 0 or key2 >= self.size or key2 < 0:
# pass
# else:
# self.grid[key1][key2] = val
# def __delitem__(self, key):
# key1, key2 = tup
# if key1 >= self.size or key1 < 0 or key2 >= self.size or key2 < 0:
# pass
# else:
# self.grid[key1][key2] = EmptyPiece() |
#! /usr/bin/env python3
# Michael Gates
# 23 October 2017
# Test suite implementations for lab07
# The parameter intList is supposed to be a list of integers.
# The function returns the product of the odd integers from intList, and leaves intList not modified.
# For instance, given [1,2,3,4], the function returns 3.
# The function performs no I/O.
def productOfOdd(intList):
# if list is empty
if(len(intList) <= 0):
return 0
last = 1
for i in intList:
if(i % 2 != 0):
last = last * i
return last
# The parameter intList is supposed to be a list of integers.
# The function returns the sum of the even integers from intList, and leaves intList not modified.
# For instance, given [1,2,3,4], the function returns 6.
# The function performs no I/O.
def sumOfEven(intList):
# if list is empty
if(len(intList) <= 0):
return 0
sumTotal = 0
for i in intList:
if(i % 2 == 0):
sumTotal = sumTotal + i
return sumTotal
#The parameter intList is supposed to be a list of integers.
# The function returns a new list containing the even integers from intList, in the same order, and
# leaves intList not modified.
# For instance, given [1,2,3,4,2,3,6], the function returns [2,4,2,6].
# The function performs no I/O.
def evenMembers(intList):
evenList = []
for i in intList:
if(i % 2 == 0):
evenList.append(i)
return evenList
# The parameter intList is supposed to be a list of integers.
# The function modifies intList:
# ● For odd integers one (1) is added and then the result is divided by 2
# ● Even integers are multiplied by 3.
# This function does not return anything. (void)
# For instance, the parameter [1,2,3,4] should become [1,6,2,12].
# The function performs no I/O.
def changeList(intList):
for index, value in enumerate(intList):
if(value % 2 == 0):
intList[index] = value*3
else:
intList[index] = round((value+1) / 2)
# The parameters intListOne and intListTwo are supposed to be lists of integers.
# The function will return true if intListTwo is the reversed version of intListOne.
# The function will return false if intListTwo is NOT the reversed version of intListOne.
# The function performs no I/O.
def isReverse(intListOne, intListTwo):
return intListTwo == intListOne[::-1]
def main():
pass
if __name__ == '__main__':
main()
|
#! /usr/bin/env python3
# Michael Gates
# 3 October 2017
# Various math functions
import testsuite
def absolute_value(x):
# return the absolute value of x
return x if x >= 0 else x * -1
def is_divisible(x, y):
# return true if x is divisible by y, false otherwise
return x % y == 0
def to_power(x, y):
# return x to the power y
return x**y
def is_greater(x, y):
# return true if x is greater than y, otherwise false
return x > y
def sub_min_max(x, y):
# return the difference between x and y as a positive integer
return absolute_value(x - y)
def mymax(x, y):
# return whichever value is the max, x or y
return x if x > y else y
# Example of a function that returns the Nth number of the fibonnaci sequence
# The testsuite checks these values as an additional example
def fibo(n):
a = 0
b = 1
for i in range(n):
c = a
a = b
b = c + b
return a
def main():
# use this to test your functions
print("Absolute value of -5 is " + str(absolute_value(-5)))
print("Is 4 divisible by 2? " + str(is_divisible(4,2)))
print("5 to the 2nd power is " + str(to_power(5,2)))
print("Is 5 greater than 15? " + str(is_greater(5,15)))
print("The (positive) difference between 30 and 4 is " + str(sub_min_max(4,30)))
print("The largest of the two numbers 5 and 50 is " + str(mymax(5,50)))
print("The 7th number in the fibonacci sequence is " + str(fibo(7)))
if __name__ == '__main__':
main()
|
from helpers import alphabet_position, rotate_character
def encrypt(text,rot):
encrypted_word = ""
for char in text:
letter = rotate_character(char,rot)
encrypted_word = encrypted_word + letter
return encrypted_word
def main():
text = input("Type a message: ")
num = int(input("Rotate by: "))
print(encrypt(text,num))
if __name__ == '__main__':
main() |
from math import radians, cos, sin, asin, sqrt
class Edge(object):
"""
Base class for Edge classes.
"""
@classmethod
def connect_edge_pairs(cls, edge_pairs):
"""
Return a new list with edges (pairs of point_a, point_b) ordered as they're connected in the graph.
Eg:
> connect_edge_pairs([[1,2], [3,1], [2,3]])
< [[1,2], [2,3], [3,1]]
"""
connected_edges = [edge_pairs[0]]
for i in range(len(edge_pairs) - 1):
current_edge = connected_edges[i]
next_edge = [edge for edge in edge_pairs if current_edge[1] == edge[0]][0]
connected_edges.append(next_edge)
return connected_edges
class Distance(Edge):
"""
Geographic edge.
"""
def __init__(self, point_a, point_b, haversine=None):
"""
Initiate Distance and calculate distance between `point_a` and `point_b`.
"""
self.point_a = point_a
self.point_b = point_b
self.haversine = haversine or self.haversine(
point_a.lon,
point_a.lat,
point_b.lon,
point_b.lat
)
@classmethod
def haversine(cls, lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth in kilometers (specified in decimal degrees)
"""
# Radius of earth in kilometers.
r = 6371
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2) ** 2
c = 2 * asin(sqrt(a))
return c * r
class DistanceTable(object):
"""
Distance table for fast lookups of distances between geographic two points.
Structured on the following format
{
"a": {
"b": distance_a_b,
"c": distance_a_c,
...
},
"b": {
"a": distance_b_a,
"c": distance_b_c
},
...
}
"""
def __init__(self):
"""
Initiate table
"""
self.table = {}
@classmethod
def generate_from_points(cls, points):
"""
Create a DistanceTable instance with distances between all points.
"""
dt = DistanceTable()
for i, point_a in enumerate(points):
dt.table.setdefault(point_a, {})
for point_b in points[i + 1:]:
dt.table.setdefault(point_b, {})
distance_a_b = Distance(point_a, point_b)
distance_b_a = Distance(point_b, point_a, distance_a_b.haversine)
dt.table[point_a][point_b] = distance_a_b
dt.table[point_b][point_a] = distance_b_a
return dt
def get_nearest_distances(self, origin_point):
"""
Get a list of Distances connected to the given Point, ordered by distance.
"""
return sorted(self.table[origin_point].values(), key=lambda d: d.haversine)
def get_nearest_distance(self, origin_point, exclude_points=None):
"""
Get the nearest Distance to a given Point. Points in `exclude_points` are excluded.
"""
exclude_points = exclude_points or []
return [d for d in self.get_nearest_distances(origin_point) if d.point_b not in exclude_points][0]
def get_nearest_point(self, origin_point, exclude_points=None):
"""
The the nearest Point to a given Point. Points in `exclude_points` are excluded.
"""
return self.get_nearest_distance(origin_point, exclude_points=exclude_points).point_b |
#####################
# Hangman.py
#
# Simulates a "Hangman" game
#
#
####################
import random
import json
import click
def build_word_map():
"""
words = {"fruit": ["apple", "banana", "grapes", "pear", "watermelon"], \
"places": ["school", "church", "library", "mall", "restaurant", "airport"],
"colors": ["red", "blue", "yellow", "cerulean", "aqua", "magenta", "green", "orange"]}
"""
with open("hangman_words.json", "r") as infile:
data = json.load(infile)
wordmap = {}
for item in data:
category = item["category"]
words = item["words"]
wordmap[category] = words
return wordmap
@click.command()
@click.option("--chances", '-c', default=5, type=click.IntRange(1, 10, clamp=True),
help="The number of wrong letters you can guess before you lose. Must be between 1 and 10.")
def main(chances):
"""Hangman game. Try to guess a random word chosen by the computer. You can guess CHANCES wrong letters before you
lose. If you guess the word, you win."""
# load the data
words = build_word_map()
num_games_played = 0
num_wins = 0
while True:
num_games_played += 1
guessed_letters = []
turns = chances
# allow user to choose a category
while True:
category = input(f"Choose a category {sorted(list(words.keys()))}: ")
if category in words.keys():
break
else:
print("Please choose a valid category.")
# once a word is selected, remove it from the list so that it cannot be used again
word = random.choice(words[category])
words[category].remove(word)
if not words[category]:
del words[category]
display = list("-" * len(word))
print(f"{' '.join(display)} ({len(word)}) \n")
while turns > 0 and '-' in display:
guess = input(f"Already guessed letters ({''.join(sorted(guessed_letters)).upper()}). Guess a letter: ")
if not (guess.isalpha() and len(guess) == 1):
print("Please enter a single letter.")
continue
guess = guess.lower()
if guess not in guessed_letters:
guessed_letters.append(guess)
else:
print("You already guessed that letter.")
print(f"{' '.join(display)} ({len(word)}) ")
continue
if guess in word:
for i, letter in enumerate(word):
if letter == guess:
display[i] = letter
print(f"{' '.join(display)} ({len(word)}) ")
else:
turns -= 1
print(f"Sorry. No {guess}'s in the hidden word. {turns} chances left.")
if "".join(display) == word:
print("\nCongratulations! You guessed the word.")
num_wins += 1
else:
print(f"\nThe word was: {word}.")
while True:
response = input("Would you like to play again (Y/N)?")
if response not in "YNyn":
print("Response not understood.")
else:
break
if response in "Nn":
print("\nThank you for playing!")
print("Here are your stats: ")
print(f"\tYou played {num_games_played} games. You won {num_wins} and lost {num_games_played-num_wins}." +
f"Your winning rate is {100*(num_wins/num_games_played):.2f}%.")
print("Good bye!")
break
if __name__ == "__main__":
main()
|
songs = ["ROCKSTAR", "Do It", "For The Night"]
print(songs[0])
print(songs[len(songs) - 1])
print(songs[1:3])
songs[0] = "Butterfly Effect"
print(songs)
songs.extend(["Neon", "Lemonade", "Dil Nadia"])
print(songs)
del songs[1]
print(songs)
animals = ["Fish", "Snake", "Turtle"]
animals.append("Bird")
print(animals[2])
del animals[0]
for animal in animals:
print(animal)
|
import json
def read_coordinates(filename='coordinates.json'):
"""
Summary line.
Parameters
----------
arg1 : int
Description of arg1
Returns
-------
int
Description of return value
"""
with open(filename, 'r') as input:
# Example plot: http://www.wolframalpha.com/input/?i=plot+%5B+%5B1,+1%5D,+%5B1,+6%5D,+%5B10,+6%5D,+%5B10,+1%5D,+%5B7,+1%5D,+%5B7,+4%5D,+%5B4,+4%5D,+%5B4,+1%5D+%5D
coordinates_json = json.loads(input.read())
# Store in dictionary
coordinates = {}
for index, coordinate in enumerate(coordinates_json):
coordinates[index + 1] = coordinate
return(coordinates)
|
# https://adventofcode.com/2020/day/8
with open("day8.input.txt", "r") as f:
input = f.read().splitlines()
exampleInput = """nop +0
acc +1
jmp +4
acc +3
jmp -3
acc -99
acc +1
jmp -4
acc +6""".splitlines()
def nop(argument, accumulator, i):
return accumulator, i + 1
def acc(argument, accumulator, i):
increment = int(argument)
return accumulator + increment, i + 1
def jmp(argument, accumulator, i):
leap = int(argument)
return accumulator, i + leap
operations = {
"nop": nop,
"acc": acc,
"jmp": jmp,
}
def loop(lines, accumulator=0, i=0, already=None):
if already is None:
already = [False for i in range(len(lines))]
elif already[i] == True:
return accumulator
if i >= len(lines):
return accumulator
operation, argument = lines[i].split(" ")
execute = operations[operation]
already[i] = True
next_accumulator, next_i = execute(argument, accumulator, i)
return loop(lines, next_accumulator, next_i, already)
def test_nop():
assert nop("+0", 0, 0) == (0, 1)
assert nop("-99", 100, 50) == (100, 51)
def test_acc():
assert acc("+0", 0, 0) == (0, 1)
assert acc("-99", 100, 50) == (1, 51)
def test_jmp():
assert jmp("+0", 0, 0) == (0, 0)
assert jmp("+2", 100, 0) == (100, 2)
assert jmp("-4", 100, 5) == (100, 1)
def test_value_before_infinite_loop():
assert loop(exampleInput) == 5
assert loop(input) == 1586
|
def is_positive(number):
if number > 0:
return True
return False
def greet(name, time):
if 7 < time < 12:
print 'Good morning %s' % name
elif time < 18:
print 'Good afternoon %s' % name
elif time < 23:
print 'Good night %s' % name
else:
print '%s, you should be sleeping!' % name |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import re
def get_input():
s = raw_input("please input:")
return s
# while True:
# print eval(get_input())
def is_exit(s):
if "q" == s.lower():
print "bye~"
exit(0)
def check(s):
# encode, decode
if "/0" in s:
print u"除数不能为0"
return False
return True
def yunsuan(s):
if "+" in s:
first_num, second_num = s.split("+")
sum_ = int(first_num) + int(second_num)
if "-" in s:
first_num, second_num = s.split("-")
sum_ = int(first_num) - int(second_num)
if "*" in s:
first_num, second_num = s.split("*")
sum_ = int(first_num) * int(second_num)
if "/" in s:
first_num, second_num = s.split("/")
sum_ = float(first_num) / float(second_num)
print sum_
if __name__ == "__main__":
while True:
rs = get_input()
is_exit(rs)
if check(rs):
yunsuan(rs)
|
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import re
s = "123*&sadf sdf13770976666Aa13770976677df12ssdf"
match_re = ".*?((13|15)\d{9}).*"
phone = re.match(match_re, s)
type(phone)
for i in phone.group:
print i
# if phone:
# phone = phone.group(1)
# print phone.group(2)
# print phone |
"""
purpose : Add the Prime Numbers that are Anagram in the Range of 0 - 1000
in a Queue using the Linked List and Print the Anagrams from the Queue
@Author : Rohini Zade
@version : 1.0
@since : 30-11-2018
"""
from com.bridgelabz.utility.Utility import Utility
from com.bridgelabz.utility.Datastructure_utility import *
if __name__ == "__main__":
utility_obj = Utility()
anagram_obj = Anagram()
stackllist = StackByLink()
print("Enter the lower limit:")
lower_limit = utility_obj.inputIntiger()
print("Enter the upper limit:")
upper_limit = utility_obj.inputIntiger()
primenumber = utility_obj.findPrimeNumber(lower_limit, upper_limit)
anagramlist = []
storeanagram = []
uniquelist = []
print("The prime number which are Anagram:")
storeanagram = anagram_obj.anagramLogic(primenumber, anagramlist)
# print(storeanagram)
uniquelist = anagram_obj.unique_list(storeanagram)
uniquelist = list(map(int, uniquelist))
sortedlist = uniquelist.sort(reverse=False)
anagram_obj.stackOperationOnAnagramlist(uniquelist)
|
"""
purpose : print the prime numbers which are anagram from given range in a 2D Array
@Author : Rohini Zade
@version : 1.0
@since : 29-11-2018
"""
from com.bridgelabz.utility.Utility import Utility
from com.bridgelabz.utility.Datastructure_utility import *
if __name__ == "__main__":
utility_obj = Utility()
print("Enter the lower limit:")
lower_limit = utility_obj.inputIntiger()
print("Enter the upper limit:")
upper_limit = utility_obj.inputIntiger()
primenumber = []
primenumber = utility_obj.findPrimeNumber(lower_limit, upper_limit)
twoDarray_obj.primenslots(primenumber)
|
file = open("mtainfo.csv", "r")
csv = file.readlines()
file.close()
print (csv[:10])
def splitCommas(list):
ctr = 0
while ctr < len(list):
list[ctr] = list[ctr].split(", ")
ctr += 1
ctr = 0
while ctr < len(list):
list[ctr] = list[ctr][0].split(",")
ctr += 1
return list
splitCommas(csv)
print ("split commas")
print(csv[:10])
def rmWhiteSp(list):
ctr = 0
while ctr < len(list):
subctr = 0
while subctr < len(list[ctr]):
list[ctr][subctr] = list[ctr][subctr].strip()
subctr += 1
ctr += 1
return list
rmWhiteSp(csv)
print("rm white space: ")
print(csv[:10])
def rmCol(num):
ctr = 0
while ctr < len(csv):
csv[ctr] = csv[ctr][0:num]+ csv[ctr][num + 1:]
ctr += 1
def makeFloat(col):
ctr = 1
while ctr < len(csv):
csv[ctr][col] = float(csv[ctr][col])
ctr += 1
rmCol(0)
rmCol(0)
rmCol(0)
rmCol(0)
rmCol(0)
rmCol(3)
print(csv[:5])
makeFloat(4)
makeFloat(3)
for i in csv:
try:
if i[2].index("6") >= 0:
print i
except:
pass
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.