text
stringlengths 37
1.41M
|
---|
# SpiralMyName.py - prints a colorful spiral of the user's name
import turtle # Set up turtle graphics
t = turtle.Pen()
turtle.bgcolor("black")
colors = ["red", "yellow", "blue", "green",]
# Ask the user's name using turtle's texttinput pop-up window
your_name = "Boo"
sides = 4
# Draw a spiral of the name on the screen, written 150 times
x = 0
while x < 100 :
t.pencolor(colors[x%4]) # Rotate through the four colors
t.penup() # Don't draw the regular spiral lines
t.forward(x*4) # Just move the turtle on the screen
t.pendown() # Write the user's name, bigger each time
t.write(your_name, font = ("Arial", int( (x + sides) / sides), "bold") )
t.right(360/sides+2) # Turn left, just as in our other spirals
x = x + 1
|
#mylist = [20,30,40,50,1,100,90]
#Approach1 : Sort the list in ascending order and print the first and last element in the list.
mylist = [20,30,40,50,1,100,90]
mylist.sort() #Sorting
print(mylist) #[1, 20, 30, 40, 50, 90, 100]
print("Smallest element is:",mylist[0])
print("Largest element is:",mylist[-1])
#Approach2 : Using min() and max() methods
mylist = [20,30,40,50,1,100,90]
print("Smallest is:",min(mylist))
print("Largest is:",max(mylist))
|
#approach1
#Input : [5,10,15,20]
#Output: 50
mylist=[5,10,15,20]
total=0
for i in range(0,len(mylist)):
total=total+mylist[i] #Index number
print("Sum of all elements in given list:", total)
#Approach2
mylist=[5,10,15,20]
total=sum(mylist)
print("Sum of all elements in given list:", total)
|
#Copy from previous lessons
class Seq:
"""A class for representing sequences"""
def __init__(self, strbases):
# this method is called every time a new object is created
self.strbases = strbases
def len(self):
return str(len(self.strbases))
def complement(self):
seq = self.strbases
seq = seq.upper()
for x, letter in enumerate(seq):
if letter == 'A':
seq = seq[:x] + seq[x:].replace('A', 'T')
if letter == 'T':
seq = seq[:x] + seq[x:].replace('T', 'A')
if letter == 'C':
seq = seq[:x] + seq[x:].replace('C', 'G')
if letter == 'G':
seq = seq[:x] + seq[x:].replace('G', 'C')
return seq
def reverse(self):
seq = self.strbases.upper()[::-1]
return seq
def count(self, base):
base=base.upper()
return str(self.strbases.upper().count(base))
def percentage(self, base):
seq = self.strbases.upper()
base=base.upper()
counter= seq.count(base)
line = len(seq)
return str(round(100.0 * counter/line, 2)) |
from collections import deque
def search(lines, pattern, history=2):
previous_lines = deque(maxlen=history)
for line in lines:
previous_lines.append(line)
if pattern in line:
yield line, previous_lines
if __name__ == '__main__':
lines = ['hello girl morining boy',
'world say hello, say hey',
'i say hello, what up',
'haha hi, new world',
'all of me love all of your world',
'hello new start'
]
for line, prelines in search(lines, 'hello'):
for l in prelines:
print(l, end=';')
print('\n')
print(line, end='.')
print('-'*20)
|
istenen = int(input("Pozitif bir tamsayı giriniz:"))
x = 2
while x <= istenen :
i = 2
while i*i <= x :
if x%i == 0:
break
i += 1
else :
print(x)
x += 1
|
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 16:07:46) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> # 연간 투자의 미래 가치를 계산하는 프로그램
>>> def main():
payment = eval(input("Enter amount to invest each year: "))
apr = eval(input("Enter the annualized interest rate: "))
years = eval(input("Enter the number of years: "))
principal = 0.0
for i in range(years):
principal = (principal + payment) * (1 + apr)
print("The amount in", years, "years is:", principal)
>>>
|
# 무조건 첫 문자 하나를 맨 뒤로 보내고 그 뒤에 'ay'를 붙이는 프로그램
a = 'happy'; b = 'pig'; c = 'python'
new_a = a[1:] + a[0] + 'ay'
new_b = b[1:] + b[0] + 'ay'
new_c = c[1:] + c[0] + 'ay'
string = '{} -> {}'
print(string.format(a, new_a))
print(string.format(b, new_b))
print(string.format(c, new_c))
|
"""A number-guessing game."""
# Put your code here
name = input("Howdy, what's is your name?")
print(name)
print(name,"I'm thinking of a number between 1 and 100.Try to guess my number.")
import random
num1 = random.randint(0,101)
ct = 0
while True:
try:
num = int(input("Your guess?"))
except ValueError:
print("That's not an int!")
continue
if num!=num1:
ct = ct + 1
if num<1 or num>100:
print("invalid. enter between 1-100")
if num in range(0,num1):
print("Your guess is too low, try again.")
elif num in range(num1+1,101):
print("Your guess is too high, try again.")
else:
print ("Well done,",name, "! You found my number in", ct, "tries!")
print("the random number was",num1)
break |
class Rectangle(object):
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
def __eq__(self, other):
return self.x == other.x and \
self.y == other.y and \
self.width == other.width and \
self.height == other.height
def __hash__(self):
return hash((self.x, self.y, self.width, self.height))
def __str__(self):
return "Rectangle(x={0},y={1},width={2},height={3})" \
.format(self.x, self.y, self.width, self.height)
def distance_to_coordinate(self, coordinate):
end_x = self.x + self.width - 1
end_y = self.y + self.height - 1
if coordinate.x < self.x:
diff_x = self.x - coordinate.x
elif coordinate.x > end_x:
diff_x = coordinate.x - end_x
else:
diff_x = 0
if coordinate.y < self.y:
diff_y = self.y - coordinate.y
elif coordinate.y > end_y:
diff_y = coordinate.y - end_y
else:
diff_y = 0
return (diff_x, diff_y)
def intersects_coordinate(self, coordinate):
return (self.x <= coordinate.x) and \
(coordinate.x < self.x + self.width) and \
(self.y <= coordinate.y) and \
(coordinate.y < self.y + self.height)
|
def number_entities(tree, start_e1, end_e1, start_e2, end_e2):
'''
returns the node number of the entities
'''
number_node_e1 = None
number_node_e2 = None
for i in range(1, len(tree.nodes)):
node = tree.nodes[i]
# it's not a bracket
if 'start' in node:
if ((start_e1 >= node["start"] and start_e1 <= node["end"] and number_node_e1 is None) or
(end_e1 >= node["start"] and end_e1 <= node["end"] and number_node_e1 is None)):
number_node_e1 = i
if ((start_e2 >= node["start"] and start_e2 <= node["end"] and number_node_e2 is None) or
(end_e2 >= node["start"] and end_e2 <= node["end"] and number_node_e2 is None)):
number_node_e2 = i
return number_node_e1, number_node_e2
def check_interaction(analysis, entities, id_e1, id_e2):
"""
Given two entities that belong to a sentence, check_interaction tries to find the type
of interaction between them if any
Parameters:
analysis: Grammar dependency tree
entities: List of all entities of the current sentence
id_e1: Entity of the sentence number 1 to compare
id_e2: Entity of the sentence number 2 to compare
Returns:
Whether there is interaction or not between two entities and its type
"""
# check they aren't multielements (that one word is used for more than one)
if len(entities[id_e1]) == 2 and len(entities[id_e2]) == 2:
start_e1 = int(entities[id_e1][0])
end_e1 = int(entities[id_e1][1])
start_e2 = int(entities[id_e2][0])
end_e2 = int(entities[id_e2][1])
# get node number of the two entities
number_node_e1, number_node_e2 = number_entities(analysis, start_e1, end_e1, start_e2, end_e2)
node_entity1 = analysis.nodes[number_node_e1]
node_entity2 = analysis.nodes[number_node_e2]
# (2) check if same parent
# check if 1under2 or 2under1 (1) has been analyzed but doesn't add anything
if node_entity1["head"] == node_entity2["head"]:
if node_entity1["rel"] == 'conj' and node_entity2["rel"] == 'conj':
return 0, 'null'
# (3) look for the verbs between the two entities
for e in range(1, len(analysis.nodes)):
node = analysis.nodes[e]
if 'start' in node:
start = node["start"]
end = node["end"]
if start >= start_e1 and end <= end_e2:
if 'V' in node["tag"]:
if (
'VB' == node["tag"] and node["lemma"] == 'increase' or
'V' in node["tag"] and node["lemma"] == 'decrease' or
'V' in node["tag"] and node["lemma"] == 'interfere' or
'V' in node["tag"] and node["lemma"] == 'inhibit' or
'V' in node["tag"] and node["lemma"] == 'alter' or
'VB' == node["tag"] and node["lemma"] == 'cause' or
'V' in node["tag"] and node["lemma"] == 'delay' or
'V' in node["tag"] and node["lemma"] == 'raise'):
return 1, 'mechanism'
elif (
'VBP' == node["tag"] and node["lemma"] == 'include' or
'V' in node["tag"] and node["lemma"] == 'potentiate' or
'VB' == node["tag"] and node["lemma"] == 'enhance' or
'VB' == node["tag"] and node["lemma"] == 'reduce' or
'VBZ' in node["tag"] and node["lemma"] == 'produce' or
'V' in node["tag"] and node["lemma"] == 'antagonize'):
return 1, 'effect'
elif (
'V' in node["tag"] and node["lemma"] == 'tell' or
'VBN' == node["tag"] and node["lemma"] == 'administer' or
'V' in node["tag"] and node["lemma"] == 'take' or
'V' in node["tag"] and node["lemma"] == 'exceed'):
return 1, 'advise'
elif (
'VBZ' == node["tag"] and node["lemma"] == 'suggest' or
'V' in node["tag"] and node["lemma"] == 'interact'):
return 1, 'int'
else:
return 0, 'null'
return 0, 'null'
|
#user/python3
for num in range(100,1000) #依次取出num的值,第一次101,最后一次999
bai = num //100
shi = num //10 % 10
ge = num % 10
if(bai**3+shi**3+ge**3 ==num):
print (num, end = ' ') #使输出的数不换行,以空格隔开同行输出
|
import collections
def part1_is_nice_string(test_string):
"""
--- Day 5: Doesn't He Have Intern-Elves For This? ---
Santa needs help figuring out which strings in his
text file are naughty or nice.
A nice string is one with all of the following properties:
It contains at least three vowels (aeiou only),
like aei, xazegov, or aeiouaeiouaeiou.
It contains at least one letter that appears twice in a row,
like xx, abcdde (dd), or aabbccdd (aa, bb, cc, or dd).
It does not contain the strings ab, cd, pq, or xy,
even if they are part of one of the other requirements.
For example:
>>> part1_is_nice_string('ugknbfddgicrmopn')
True
is nice because it has at least three vowels (u...i...o...),
a double letter (...dd...), and none of the disallowed substrings.
>>> part1_is_nice_string('aaa')
True
is nice because it has at least three vowels and a double letter,
even though the letters used by different rules overlap.
>>> part1_is_nice_string('jchzalrnumimnmhp')
False
is naughty because it has no double letter.
>>> part1_is_nice_string('haegwjzuvuyypxyu')
False
is naughty because it contains the string xy.
>>> part1_is_nice_string('dvszwmarrgswjxmb')
False
is naughty because it contains only one vowel.
How many strings are nice?
"""
def contains_three_vowels(test_string):
alpha = collections.Counter(test_string)
vowels = 0
for vowel in ['a', 'e', 'i', 'o', 'u']:
vowels += alpha.get(vowel, 0)
return vowels >= 3
def double_letter(test_string):
for x in range(len(test_string) - 1):
if test_string[x] == test_string[x + 1]:
return True
return False
def no_nasties(test_string):
for nasty in ['ab', 'cd', 'pq', 'xy']:
if nasty in test_string:
return False
return True
return (contains_three_vowels(test_string)
and double_letter(test_string)
and no_nasties(test_string))
|
#!/usr/bin/env python
import inout
def area(corners, n):
area = 0.0
for i in range(n):
j = (i + 1) % n
area += corners[i][0] * corners[j][1]
area -= corners[j][0] * corners[i][1]
area = abs(area) / 2.0
return area
print("Corners must be ordered in Clockwise or Counter-Clockwise Direction!")
n=inout.get_integer("Number of corners or '0' for 3: ", 3)
corners=[]
for corner_nr in range(0, n,1):
print ("Corner: "), corner_nr
x=inout.get_float("Enter X coordinate: ", corner_nr)
y=inout.get_float("Enter Y coordinate: ", corner_nr)
coords=(x, y)
corners.append(coords)
print("Polygon Area: "), area(corners,n)
|
import random
questions_cnt = 10
max_trials = 3
questions_list = []
for i in range(questions_cnt):
a = random.randint(1, 10)
b = random.randint(1, 10)
if (a,b) in questions_list:
continue # avoid duplicate questions
else:
questions_list.append((a,b))
for j in range(max_trials):
c = input("{} + {} = ".format(a, b))
try:
c = int(c)
except:
print("try again.")
continue
if c == a + b:
print("good job!")
break
else:
print("try again.")
print(questions_list)
|
#!/usr/bin/env python
import random
def bitonic_sort(up,x):
if len(x)<=1:
return x
else:
first = bitonic_sort(True,x[:len(x)/2])
second = bitonic_sort(False,x[len(x)/2:])
return bitonic_merge(up,first+second)
def bitonic_merge(up,x):
# assume input x is bitonic, and sorted list is returned
if len(x) == 1:
return x
else:
bitonic_compare(up,x)
first = bitonic_merge(up,x[:len(x)/2])
second = bitonic_merge(up,x[len(x)/2:])
return first + second
def bitonic_compare(up,x):
dist = len(x)/2
for i in range(dist):
if (x[i] > x[i+dist]) == up:
x[i], x[i+dist] = x[i+dist], x[i] #swap
def main():
length = 1<<6
before = list(xrange(0,length)) # list of integers from 1 to 99
random.shuffle(before)
print "before: "
print before
after = bitonic_sort(True, before)
print "after: "
print after
if __name__ == "__main__":
main()
|
def palindromePermutation(word):
dict={}
for c in word:
if (c!=" "):
if (c not in dict):
dict[c] = 1
else:
x = dict[c]
dict.update({c: x+1})
counter = 0
for x in dict:
incorrect_chars = False
if dict[x] == 1:
counter+=1
elif dict[x]%2==1:
incorect_chars = True
word = word.replace(" ", "")
if ((len(word))%2 == 1 and counter==1 and incorrect_chars == False):
return True
elif ((len(word))%2==0 and counter==0 and incorrect_chars == False):
return True
else:
return False
def main():
print(palindromePermutation("braid"))
if __name__ == "__main__":
main() |
"""
Stack class.
@author: Gautham Ganapathy
@organization: LEMS (http://neuroml.org/lems/, https://github.com/organizations/LEMS)
@contact: [email protected]
"""
from lems.base.base import LEMSBase
from lems.base.errors import StackError
class Stack(LEMSBase):
"""
Basic stack implementation.
"""
def __init__(self):
"""
Constructor.
"""
self.stack = []
""" List used to store the stack contents.
@type: list """
def push(self, val):
"""
Pushed a value onto the stack.
@param val: Value to be pushed.
@type val: *
"""
self.stack = [val] + self.stack
def pop(self):
"""
Pops a value off the top of the stack.
@return: Value popped off the stack.
@rtype: *
@raise StackError: Raised when there is a stack underflow.
"""
if self.stack:
val = self.stack[0]
self.stack = self.stack[1:]
return val
else:
raise StackError('Stack empty')
def top(self):
"""
Returns the value off the top of the stack without popping.
@return: Value on the top of the stack.
@rtype: *
@raise StackError: Raised when there is a stack underflow.
"""
if self.stack:
return self.stack[0]
else:
raise StackError('Stack empty')
def is_empty(self):
"""
Checks if the stack is empty.
@return: True if the stack is empty, otherwise False.
@rtype: Boolean
"""
return self.stack == []
def __str__(self):
"""
Returns a string representation of the stack.
@note: This assumes that the stack contents are capable of generating
string representations.
"""
if len(self.stack) == 0:
s = '[]'
else:
s = '[' + str(self.stack[0])
for i in range(1, len(self.stack)):
s += ', ' + str(self.stack[i])
s += ']'
return s
def __repr__(self):
return self.__str__() |
#!/usr/bin/env python3
from array import *
from math import *
def parse_arguments():
'''
Parse the arguments.
'''
import argparse
parser=argparse.ArgumentParser()
parser.add_argument("pqr",help="pqr file containing fpocket spheres defining pocket")
args=parser.parse_args()
return args
def parse_pqr_line(line):
'''
Take a line from a PQR file and return a tuple containing
(xcoord,ycoord,zcoord,radius) where the x, y, and z coordinates
are the coordinates of the alpha-sphere (see fpocket), and
the radius is the radius of the alpha-sphere.
'''
length=len(line)
if length < 71:
print("line too short: ",line)
return None
xcoord=float(line[31:39])
ycoord=float(line[39:47])
zcoord=float(line[47:55])
radius=float(line[67:])
return (xcoord,ycoord,zcoord,radius)
def write_sph_line(data):
'''
Take the (xcoord,ycoord,zcoord,radius) tuple and generate a sphere
line, and return that line.
'''
(xcoord,ycoord,zcoord,radius)=data
line=f" 63{xcoord:10.5f}{ycoord:10.5f}{zcoord:10.5f}{radius:8.3f} 92 0 0"
return line
def write_pdb_line(data):
'''
Take the (xcoord,ycoord,zcoord,radius) tuple and generate a sphere
line, and return that line.
'''
(xcoord,ycoord,zcoord,radius)=data
line=f"ATOM 5 C STP A 1 {xcoord:8.3f}{ycoord:8.3f}{zcoord:8.3f} 0.00 0.00 C"
return line
def distance(pnt_i,pnt_j):
'''
Calculate the Euclidian distance between two points.
'''
(xi,yi,zi,ri) = pnt_i
(xj,yj,zj,rj) = pnt_j
dx = xi-xj
dy = yi-yj
dz = zi-zj
r = sqrt(dx*dx+dy*dy+dz*dz)
return r
def prune_points(data_in,num_out):
'''
Go through the list points in the input, compute their relative
distances, and remove points that are close together until
only num_out points remain.
Return the list of remaining points.
'''
data_out = []
del_list = []
huge = 1.0e100
num_in = len(data_in)
num_del = 0
R = [ [ 0.0 for _ in range(num_in) ] for _ in range(num_in) ]
for i in range(num_in):
data_i = data_in[i]
for j in range(num_in):
data_j = data_in[j]
R[i][j] = distance(data_i,data_j)
R[i][i] = huge
num_left = num_in - num_del
while (num_left > num_out):
min_d = R[0][0]
min_i = 0
min_j = 0
for i in range(num_in):
if i in del_list:
continue
for j in range(num_in):
if j in del_list:
continue
if (R[i][j] < min_d):
min_d = R[i][j]
min_i = i
min_j = j
min_di = huge
min_dj = huge
min_ki = -1
min_kj = -1
for k in range(num_in):
if (k != min_j and R[min_i][k] < min_di):
min_di = R[min_i][k]
min_ki = k
if (k != min_i and R[min_j][k] < min_dj):
min_dj = R[min_j][k]
min_kj = k
if (min_di <= min_dj):
del_list.append(min_i)
for k in range(num_in):
R[min_i][k] = huge
R[k][min_i] = huge
else:
del_list.append(min_j)
for k in range(num_in):
R[min_j][k] = huge
R[k][min_j] = huge
num_del = len(del_list)
num_left = num_in - num_del
for i in range(num_in):
if i in del_list:
continue
data_out.append(data_in[i])
return data_out
def process_lines(list_in):
'''
Go through all lines and convert each one to the spheres format, add it to the result,
and return the list of output lines.
'''
data_in=[]
list_out=[]
length=len(list_in)
list_out.append(f"DOCK spheres within 10.0 ang of ligands")
list_out.append(f"cluster 1 number of spheres in cluster {length:4d}")
for line_in in list_in:
keyw=line_in[0:6]
if keyw == b"ATOM " or keyw == b"HETATM":
data=parse_pqr_line(line_in)
data_in.append(data)
data_out = prune_points(data_in,100)
for data in data_out:
#line_out=write_pdb_line(data)
line_out=write_sph_line(data)
list_out.append(line_out)
return list_out
if __name__ == "__main__":
args=parse_arguments()
fobj=open(args.pqr,"rb")
pqr_in=fobj.readlines()
fobj.close()
sph_out=process_lines(pqr_in)
for line_out in sph_out:
print(line_out)
|
from config import term_regex, num_regex
import re
def search_terms(prepare_line):
return [(term[1], term[-1]) for term in term_regex.findall(prepare_line)[:-1]]
def parse_term(term: str):
coef = re.fullmatch(num_regex, term)
if coef:
return {'coef': float(coef.group())}
degree = num_regex.search(term)
if not degree:
return {'degree': 1}
return {'degree': int(degree.group())}
def combine_similar_terms(terms: list):
combine_terms = {}
for term in terms:
degree = term['degree']
combine_terms[degree] = combine_terms.get(degree, {})
combine_terms[degree]['coef'] = combine_terms[degree].get('coef', 0) + term['coef']
return {degree: coef['coef'] for degree, coef in combine_terms.items() if coef['coef']} or {0: 0.0}
def parse_polynomial(prepare_line, debug_mode=False):
all_terms = []
for i, part in enumerate(prepare_line.split('=')):
curr_operation = ''
coef = 1
degree = 0
for term, next_operation in search_terms(part):
# print(term, f"'{next_operation}'")
new_term = parse_term(term)
# print('new_term', new_term)
if curr_operation == '/':
num = new_term.get('coef', 1) * (-1 if curr_operation == '-' else 1)
if num == 0:
print('You have no right to divide by zero')
exit()
coef /= num
degree -= new_term.get('degree', 0)
else:
coef *= new_term.get('coef', 1) * (-1 if curr_operation == '-' else 1)
degree += new_term.get('degree', 0)
if debug_mode:
print(f'term={term}\tnext_operation={next_operation}', '-->', f'coef={coef},degree={degree}')
if not next_operation or next_operation == '+' or next_operation == '-':
all_terms.append({'degree': degree, 'coef': coef * (1 if i == 0 else -1)})
degree = 0
coef = 1
curr_operation = next_operation
return combine_similar_terms(all_terms)
def look_major_degree(polynomial_struct):
return max(polynomial_struct)
def is_valid_degrees(polynomial_struct):
return not set(polynomial_struct) - {0, 1, 2}
def get_invalid_degree(polynomial_struct):
if max(polynomial_struct) > 2:
return max(polynomial_struct)
return min(polynomial_struct)
|
# Utilizando Módulos
# Módulo matemático
'''
import math # Importação que abrange TODO o módulo
num = int(input('Digite um número: '))
raiz = math.sqrt(num)
quadrado = math.pow(num,2)
print('As operações realizadas com o número {} foram:'.format(num))
print('Raiz quadrada: {}'.format(raiz))
print('Raiz quadrada aproximada pra cima: {}'.format(math.ceil(raiz)))
print('Raiz quadrada aproximada pra baixo: {}'.format(math.floor(raiz)))
print('Potenciação ao quadrado: {}'.format(quadrado))
from math import sqrt, floor, ceil, pow #Importação específica do módulo
raiz = sqrt(num)
quadrado = pow(num,2)
print('Utilizando importação específica:')
print('As operações realizadas com o número {} foram:'.format(num))
print('Raiz quadrada: {}'.format(raiz))
print('Raiz quadrada aproximada pra cima: {}'.format(ceil(raiz)))
print('Raiz quadrada aproximada pra baixo: {}'.format(floor(raiz)))
print('Potenciação ao quadrado: {}'.format(quadrado))
'''
import random
num = random.random()
numInt = random.randint(1,10)
print('Float randômico: {}'.format(num))
print('Int randômico: {}'.format(numInt))
'''
Algumas bibliografias:
Pacotes built-in: https://docs.python.org/3.7/library/index.html
Índice de Pacotes Extras: https://pypi.org/
'''
import emoji
print(emoji.emojize('Olá, mundo!! :sunglasses:', use_aliases=True))
print(emoji.emojize('Olá, mundo!! :earth_americas:', use_aliases=True)) |
# Leia 3 numeros e informe o maior e o menor
n1 = int(input('Informe um número: '))
n2 = int(input('Informe outro número: '))
n3 = int(input('Informe o último número: '))
nums = [n1, n2, n3]
nums.sort()
print('O maior número foi: {} e o menor: {}'.format(nums[-1], nums[0]))
|
# Leia um número informado e diga se é um ano bisexto
ano = int(input('Informe um ano: '))
if ano % 4 == 0:
print('{} é um ano bissexto'.format(ano))
else:
print('{} não é um ano bissexto'.format(ano))
|
#! List of acceptable profanities which is mutable to make changes anytime
dict_of_profanities={
'low':('abc','pqr','xyz'),
'medium':('defg','hijk'),
'high':('qwerty','zxcvbn','asdfgh')
}
#! An Abstract Data Type to store the user comment during degree_check
class Comment():
"""
Comment is an ADT to store the current comment details and keep them secure until the end of execution of profanity check.
arguments:
1. user_id: here we have considered the name of a user, which will be the user_ID in a practical situation.
2. comment: The actual comment (string) which will be checked for degree of profanity.
functions:
1. comment_details: This function will return a tuple (immutable) of required information. (further used by function-degree_check)
"""
def __init__ (self,user_id,comment):
self.user=user_id
self.comment=comment
def comment_details(self):
#! RETURN A TUPLE TO AVOID MUTATION TO THE DATA DURING RUNTIME
return (self.user,self.comment)
def profanity_check(comment_details):
degrees=('high','medium','low') #to iterate through the dict
#reversed order of degrees because if we find HIGH then we need not check lower order profanities
for degree in degrees:
for prof in dict_of_profanities[degree]:
if prof in comment_details:
return degree
def degree_check(comment_dict):
for user in comment_dict:
com=Comment(user,comment_dict[user]) #! com is the instance of our Comment class which is an ADT to store our comment details
user_comment_details=com.comment_details()
degree=profanity_check(user_comment_details[1].lower())
#! using print here to output all the details. Should Ideally return an output to take an action.
print(f'The degree of profanity is {degree} for {user}')
|
#!/usr/bin/env python3
VALID_2ND_POSITION_TOKENS = ('NAME', 'SEX', 'BIRT', 'DEAT', 'FAMC', 'FAMS',
'MARR', 'HUSB', 'WIFE', 'CHIL', 'DIV', 'DATE', 'HEAD', 'TRLR', 'NOTE')
VALID_3RD_POSITION_TOKENS = ('INDI', 'FAM')
def detect_tokens(line):
# determines tokens in a GEDCOM file line
tokens = {}
tokens["string"] = line
split_line = line.split(" ", 2)
tokens["level"] = split_line[0]
if split_line[1] in VALID_2ND_POSITION_TOKENS:
tokens["tag"] = split_line[1]
tokens['args'] = split_line[2] if len(split_line) == 3 else ""
tokens['valid'] = 'Y'
elif split_line[2] in VALID_3RD_POSITION_TOKENS:
tokens['args'] = split_line[1]
tokens["tag"] = split_line[2]
tokens['valid'] = 'Y'
else:
tokens["tag"] = split_line[1]
tokens['args'] = split_line[2]
tokens['valid'] = 'N'
return tokens
def parse(dir):
# opens a GEDCOM file and splits it by line
parsed_file = []
with open(dir, "r") as reader:
content = reader.read().splitlines()
for line in content:
parsed_file.append(detect_tokens(line))
return parsed_file
def project02(path):
# satisfies the requirements for project02
parsed_file = parse(path)
for tokens in parsed_file:
print(f"--> {tokens['string']}\n"
f"<-- {tokens['level']}|{tokens['tag']}|{tokens['valid']}|{tokens['args']}")
def main():
# run main code here
project02("test.ged")
if __name__ == "__main__":
main()
|
import sys
import os
import math
import time
# helper function to calculate the distance between city1 & city2
def getDistance(city1, city2):
# tried this initially with pow - it works, but it's slower
dist1 = (city1[0]-city2[0])**2
dist2 = (city1[1]-city2[1])**2
# dont use decimals
return int(round(math.sqrt(dist1 + dist2),0))
def getCycle(start, cities):
unvisitedCities = [city for city in cities]
cycle = []
totalDistance = 0
unvisitedCities.remove(start)
cycle.append(start)
currentCity = start
while len(unvisitedCities) > 0:
# assumes no cities are farther than this big number
closestCity = (0, 9999999999)
for city in unvisitedCities:
distance = getDistance(cities[currentCity], cities[city])
if distance < closestCity[1]:
closestCity = (city, distance)
cycle.append(closestCity[0])
unvisitedCities.remove(closestCity[0])
currentCity = closestCity[0]
totalDistance += closestCity[1]
# go back to start
totalDistance += getDistance(cities[start], cities[closestCity[0]])
return (cycle, totalDistance)
def getBestCycleTuple(cities, tFlag, timeoutTime):
timeStart = time.clock()
cycle = []
timeout = 0
for i in range(0, len(cities)):
if tFlag:
timeIteration = time.clock()
cycle.append(getCycle(i, cities))
if tFlag:
timeIteration = time.clock() - timeIteration
if time.clock() - timeStart > timeoutTime:
print "TIMEOUT! REMOVING LAST ITERATION (WENT OVER TIME)"
cycle.pop()
timeout = 1
break
if time.clock() + timeIteration > timeStart + timeoutTime:
print "PREDICTED TIMEOUT!"
timeout = 1
break
cycle.sort(key=lambda tup: tup[1])
bestCycle = cycle[0]
timeTotal = time.clock() - timeStart
if timeout:
if timeTotal > timeoutTime:
timeTotal = timeoutTime
return (timeTotal, bestCycle)
if __name__ == "__main__":
inFile = sys.argv[1]
try:
timeoutTime = int(sys.argv[2])
tFlag = 1
print "Running with timeout of: " + str(timeoutTime) + " seconds"
except:
timeoutTime = 0
tFlag = 0
print "Running with no timeout"
f = open(inFile, "r")
cities = {}
while 1:
line = f.readline()
if line:
data = line.strip("\n\r").split()
# adds each city's coordinates to a dictionary as {(x, y)}
# the index of the dictionary correlates to the key of the city
# that is the first number column in the text doc which is not added
cities[int(data[0])] = (int(data[1]), int(data[2]))
else:
break
f.close()
result = getBestCycleTuple(cities, tFlag, timeoutTime);
timeTotal = result[0]
bestCycle = result[1]
# need to comment these 2 print lines out when turning in
print "Total time: " + str(timeTotal) + " seconds"
print "Best path distance: " + str(bestCycle[1]) + "\n"
outFile = open(inFile + ".tour", "w")
outFile.write(str(bestCycle[1]) + "\n")
for j in bestCycle[0]:
outFile.write(str(j) + "\n")
outFile.close()
|
from numpy import *
def sigmoid(x):
"""
The formula of sigmoid function
:param x: The value of x to map to the sigmoid function
:return: The value of f(x) on the sigmoid curve
"""
return 1 / (1 + exp(-x))
def sigmoid_derivative(x):
"""
The formula of the sigmoid gradient function
:param x: The value of x to map to the function
:return: The value of f'(x) on the sigmoid curve derivative
"""
fx = sigmoid(x)
return fx * (1 - fx)
def mse_loss(desireOutput, predictOutput):
"""
Computes the Mean Squared Loss (MSE) given a prediction and a desired outcome
:param desireOutput: The desired value of output
:param predictOutput: The predicted value of output
:return: The Mean Squared Loss MSE
"""
return ((desireOutput - predictOutput)**2).mean()
class NeuralNet(object):
"""
This class trains a two-input neuron network, x1 and x2.
Both of these two inputs would be passed onto the two neurons h1 and h2.
The outputs of the neurons will be the input of the final neuron o1,
which produces the final output.
"""
def __init__(self):
"""
Constructor
"""
# Generate random numbers
random.seed(1)
# Assign random weights of each neuron to an array
self.h1_weights = array([random.random(), random.random()])
self.h2_weights = array([random.random(), random.random()])
self.o1_weights = array([random.random(), random.random()])
def train(self, inputs, outputs, training_iterations):
"""
supervised training of the neuron network given a training sample sets
:param inputs [x1, x2]: inputs for neurons h1 and h2 of the training set
:param outputs o1: output from neuron o1 of the training set
:param training_iterations: The number of iterations that the training undergoes
"""
# The learning rate constant.
eta = 0.01
for iteration in range(training_iterations):
k = 0
# Adjust weight with refinement from each pair of input in the training set
while k < len(inputs):
# The input and output of the current training set
x = inputs[k]
y_true = outputs[k]
# Expected output of each neuron with the current weights
predict_output = self.learn(x)
h1 = predict_output[0]
h2 = predict_output[1]
o1 = predict_output[2]
y_pred = o1
# dot product of each neuron given inputs from training set
sum_h1 = dot(x, self.h1_weights)
sum_h2 = dot(x, self.h2_weights)
sum_o1 = dot(x, self.o1_weights)
# ---------Calculate the derivatives------------#
dL_dy = -2*(y_true - y_pred)
dy_dh1 = (self.o1_weights[0] * sigmoid_derivative(sum_o1))
dy_dh2 = (self.o1_weights[1] * sigmoid_derivative(sum_o1))
# Neuron h1
dh1_dw = x * sigmoid_derivative(sum_h1)
# Neuron h2
dh2_dw = x * sigmoid_derivative(sum_h2)
# Neuron o1
h_array = array([h1, h2])
dy_dw = h_array * sigmoid_derivative(sum_o1)
# --------------- Update the weight -------------#
# Neuron h1
dL_dw = eta * dL_dy * dy_dh1 * dh1_dw
self.h1_weights = subtract(self.h1_weights, dL_dw)
# Neuron h2
self.h2_weights = subtract(self.h2_weights, eta * dL_dy * dy_dh2 * dh2_dw)
# Neuron o1
self.o1_weights = subtract(self.o1_weights, eta * dL_dy * dy_dw)
k += 1
def learn(self, inputs):
"""
Predict the outputs from each neuron with current weights
:param inputs: inputs from x1 and x2
:return: output of neurons in a list
"""
h1 = sigmoid(dot(inputs, self.h1_weights))
h2 = sigmoid(dot(inputs, self.h2_weights))
o1_inputs = array([h1, h2]).T
o1 = sigmoid(dot(o1_inputs, self.o1_weights))
return [h1, h2, o1]
if __name__ == "__main__":
# Initialize
neural_network = NeuralNet()
# The training set.
inputs = array([[-2, -1], [25, 6], [17, 4], [-15, -6]])
outputs = array([1, 0, 0, 1], dtype=float64).T
# Train the neural network
neural_network.train(inputs, outputs, 10000)
# Test the neural network with a test example.
print(int(round(neural_network.learn(array([-10, -10]))[2])))
|
# Node object
class Node(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
# Tree object
class BST(object):
def __init__(self, root):
self.root = Node(root)
def insert(self, new_val):
self.insert_helper(self.root, new_val)
def search(self, find_val):
return self.search_helper(self.root, find_val)
def insert_helper(self, current, new_val):
if current.value < new_val:
if current.right:
# print "Right available for: %s" % current.right.value
self.insert_helper(current.right, new_val)
else:
# print "No right inserting node"
current.right = Node(new_val)
else:
# print "current>new_val"
if current.left:
# print "Left available for: %s" % current.left.value
self.insert_helper(current.left, new_val)
else:
# print "No left inserting node"
current.left = Node(new_val)
def search_helper(self, current, find_val):
# print "current.value: %s" % current.value
if current:
if current.value == find_val:
# print "current==find_val"
return True
elif current.value < find_val:
# print "current.value<find_val"
# print current.right.value
print find_val
self.search_helper(current.right, find_val)
else:
# print "current.value>find_val"
# print current.left.value
self.search_helper(current.left, find_val)
else:
return False
def lca(root, n1, n2):
while root is not None:
if root is None:
return None
elif n1 < root.value and n2 < root.value:
root = root.left
elif n1 > root.value and n2 > root.value:
root = root.right
else:
break
return root.value
root = Node(20)
root.left = Node(8)
root.right = Node(22)
root.left.left = Node(4)
root.left.right = Node(12)
root.right.left = Node(10)
root.right.right = Node(14)
# t = lca(root, 10, 14)
# print "Least common ancestor is: %s" % t
# Set up tree
tree = BST(4)
# Insert elements
tree.insert(2)
tree.insert(1)
tree.insert(3)
tree.insert(5)
# Check search
# Should be True
tree.search(6)
# Should be False
tree.search(1)
T = [[0, 1, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[1, 0, 0, 0, 1],
[0, 0, 0, 0, 0]]
T1 = [[0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0],
[0, 1, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 1],
[0, 0, 0, 0, 0, 0]]
def lca_ad(T, r, n1, n2):
print n1, n2
if T is None:
return "Error: Please enter a valid adjacency matrix"
if n1 is None or n2 is None:
return "Error: Please enter valid nodes"
if r is None:
return "Error: Please enter a valid root node"
while r is not None:
left = None
right = None
for i in range(len(T[r])):
if T[r][i] == 1 and i < r:
left = i
else:
right = i
print "Left: %s" % left
print "Right: %s" % right
print "r: %s" % r
if n1 < r and n2 < r:
r = left
print "r in left: %s" % r
elif n1 > r and n2 > r:
r = right
print "r in right: %s" % r
elif r is None:
return None
else:
break
return r
# print "Lca: %s" % lca_ad(T, 3, 0, 4)
print "Lca: %s" % lca_ad(T1, 4, 2, 5) |
# f(x) = 2x + 1
def f(x):
return 2 * x + 1
print(f(10))
# p(x) = x^2 + 2x + 1
def p(y):
return y ** 2 + 2 * y + 1 # 다른 표현 : y * y + 2 * y + 1
print(p(10))
# 실행결과
# 3150
def mul(*values):
output = 1
for value in values:
output *= value
return output
print(mul(5, 7, 9, 10))
# 틀린 오답
#for i in range(): → output처럼 숫자로 범위 지정
# for value in values:
# print(value) → output을 통해 value의 계산식 설정
# print() → return output을 통해 가변 매개변수 설정
# 정상 호출
def function(valueA=10, valueB=20, *values):
pass
function(1, 2, 3, 4, 5)
# 정상 호출
def function(valueA, valueB, *values):
pass
function(1, 2, 3, 4, 5)
# 정상 호출
def function(*values, valueA=10, valueB=20):
pass
function(1, 2, 3, 4, 5)
# 문제 발생
def function(*values, valueA, valueB): # 순서가 바뀔 경우 valueA, B에 값 지정 필요
pass
function(1, 2, 3, 4, 5) |
# 실행결과
# 태어난 월을 입력해주세요 > 1
# 물병자리 입니다
str_input = input("태어난 월을 입력해 주세요>")
birth_start_month = int(str_input) % 12
if birth_start_month == 3:
print("양자리입니다")
elif birth_start_month == 4:
print("황소자리입니다")
elif birth_start_month == 5:
print("쌍둥이자리입니다")
elif birth_start_month == 6:
print("게자리입니다")
elif birth_start_month == 7:
print("사자자리입니다")
elif birth_start_month == 8:
print("처녀자리입니다")
elif birth_start_month == 9:
print("천칭자리입니다")
elif birth_start_month == 10:
print("전갈자리입니다")
elif birth_start_month ==11:
print("궁수자리입니다")
elif birth_start_month == 12:
print("염소자리입니다")
elif birth_start_month == 1:
print("물병자리입니다")
elif birth_start_month == 2:
print("물고기자리입니다") |
def even_nums(n):
even = []
for x in n:
if x % 2 == 0:
even.append(x)
return even
print(even_nums([1, 2, 3, 4, 5, 6, 7, 8, 9])) |
# "Stopwatch: The Game"
import simplegui
# define helper function format that converts time
# in tenths of seconds into formatted string A:BC.D
def init():
global stop_watch,counter_hits,counter_success,stop_watch_state
stop_watch=0
counter_hits=0
counter_success=0
stop_watch_state=False
def increase_counter_hits():
global counter_hits,stop_watch_state
if stop_watch_state:
counter_hits +=1
def check_success():
global stop_watch,counter_success,stop_watch_state
if stop_watch_state:
if stop_watch%10==0:
counter_success +=1
def set_stop_watch_state(state):
global stop_watch_state
stop_watch_state=state
def format_stop_watch(t):
min=t/600
min_to_str=str(min)
seconds=(t-min*600)/10
if seconds<10:
seconds_to_str="0"+str(seconds)
else:
seconds_to_str=str(seconds)
milseconds=t%10
milseconds_to_str=str(milseconds)
return min_to_str+":"+seconds_to_str+"."+milseconds_to_str
def format_counters():
global counter_hits,counter_success
return str(counter_success)+"/"+str(counter_hits)
# define event handlers for buttons; "Start", "Stop", "Reset"
def start():
timer.start()
set_stop_watch_state(True)
def stop():
timer.stop()
increase_counter_hits()
check_success()
set_stop_watch_state(False)
def reset():
timer.stop()
init()
# define event handler for timer with 0.1 sec interval
def tick():
global stop_watch
stop_watch +=1
# define draw handler
def draw(canvas):
canvas.draw_text(format_counters(),[162,20],20,"Green")
canvas.draw_text(format_stop_watch(stop_watch),[70,60],24,"Red")
# create frame
frame=simplegui.create_frame("Stop watch game",200,110)
button_start=frame.add_button("Start",start,100)
button_stop=frame.add_button("Stop",stop,100)
button_reset=frame.add_button("Reset",reset,100)
timer=simplegui.create_timer(100,tick)
# register event handlers
frame.set_draw_handler(draw)
# start frame
init()
frame.start()
# Please remember to review the grading rubric
|
#Write a short Python function, minmax(data),that takes a sequence of
#one or more numbers, and returns the smallest and largest numbers,
#in the form of a tuple of length two, Do no use the built-in functions
#min or max in implementing your solution.
def minMax(data):
print(data)
Mi = data[0]
Ma = data[0]
for i in range(len(data)):
if Mi>data[i]:
Mi=data[i]
if Ma<data[i]:
Ma=data[i]
# mMi = ()
# mMa= ()
# mM = ()
# mMi = mM+(Mi,)
# mMa = mM +(Ma,)
# mM = mMi + mMa
# print(mM)
# return mM
return Mi,Ma
d = (299,28,-1,-345,45,19,35,67,128,-26,9,0,1000,-18,199,200,-281,231,2,4,5,32,-299)
print(minMax(d))
|
'''
Implement the __mul__ method for the Vector class of Section 2.3.3, so
that the expression v*3 returns a new vector with coordinates that are 3
times the respective coordinates of v.
'''
def __mul__(self,n):
result = Vector(len(self))
for i in range(len(self)):
result[i] = self.[i]*n
return result |
#Give an example of a Python code fragment that attempts to write
#an element to a list based on an index that may be out of bounds.
#If that index is out of bounds,the program should catch the
#exception that results, and print the following erros message:
#"Don't try buffer overflow attacks in Pyton!"
a = [1,2,3,4,5]
try:
a[5] = 6
except IndexError:
print("Don't try buffer overflow attacks in Pyton!")
|
#In our implementation of the scale function(page 25),the body of the loop
#executes the command data[j] *= factor. We have discussed that numeric
#types are immutable, and that use of the *= operator in this context causes
#the creation of a new instance (not the mutation of an existion instance).
#how is it still possible, then, that our implementation of scale changes the
#actual parameter sent by the caller?
#data and data1 are alias
data = [1,2,3,4,5,6]
data1 = data
def scale(data,factor):
for j in range(len(data)):
data[j] *= factor
scale(data,0.5)
print(data)
print(data1)
data1 += [10]
print(data)
print(data1)
#data and data1 alias break
data1 = data1 + [7]
print(data)
print(data1)
|
#Write a short Python function that takes a string s, representing a
#sentence, and return a copy of the string with all punctuation removed.
s = input("please, input .a sentence ?")
def removePun(s):
for char in (",.?'/;:"):
s = s.replace(char,"")
return s
print(removePun(s))
|
def is_multiple(n,m):
x,y = divmod(n,m)
if x >=1 and y ==0:
print('n is %d time of m'%x)
else:
print('n is not multiple of m')
n = int(input('please input first number'))
m = int(input('please input second number'))
is_multiple(n,m)
|
'''
If the parameter to the make payment method of the CreditCard class
were a negative number, that would have the effect of raising the balance
on the account. Revise the implementation so that it raises a ValueError if
a negative value is sent.
'''
def make_payment(self,amount):
if amount < 0:
raise ValueError("Payment amount can not be negative")
else:
try:
self._balance -= amount
msg = '$' + str(amount) +' Payment received' + 'New balance is '+'$'+str(self._balance)
return msg
except (ValueError,NameError,SyntaxError) as e:
print('Please input correct number')
print(e) |
import sqlite3
# Database: stationDB.sqlite
# Table: stations
# Columns: stn_number, letters_left
NUM_STATIONS = 10
DEFAULT_REDEMPTIONS = 3
class StationDBHelper:
def __init__(self, dbname="stationDB.sqlite"):
self.dbname = dbname
self.conn = sqlite3.connect(dbname, check_same_thread=False)
self.cur = self.conn.cursor()
def setup(self):
self.conn.execute("DROP TABLE IF EXISTS stations") #(for testing purposes)
print("creating stations table (if it does not exist)")
stmt = "CREATE TABLE IF NOT EXISTS stations (stn_number integer, letters_left integer)"
self.conn.execute(stmt)
self.conn.commit()
for stn in range(1, NUM_STATIONS + 1):
stmt = "INSERT INTO stations VALUES (?, ?)"
args = (stn, DEFAULT_REDEMPTIONS,)
self.conn.execute(stmt, args)
self.conn.commit()
def decrease_letter_count(self, station):
letter_count = self.get_letters_left(station) - 1
stmt = "UPDATE stations SET letters_left=(?) WHERE stn_number=(?)"
args = (letter_count, station, )
self.conn.execute(stmt, args)
self.conn.commit()
def get_letters_left(self, station):
stmt = "SELECT letters_left FROM stations WHERE stn_number = (?)"
args = (station,)
self.cur.execute(stmt, args)
entry = self.cur.fetchone()
return entry[0]
|
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 29 22:56:34 2020
@author: Marty
"""
from numpy import diff
from collections import Counter
data = open("Problem 10 Data.txt", "r").read()
data = data[:-1].split('\n')
numbers = [int(x) for x in data]
# PART 1
numbers.sort()
numbers.insert(0, 0) # the starting 0 jolts from the charging outlet
numbers.append(numbers[len(numbers) - 1] + 3) # the build-in adapter
differences = list(diff(numbers))
distribution = Counter(differences)
print("PART 1:", distribution[1] * distribution[3])
# PART 2
# Don't use graph traversal (especially with memoization).
# INFORMED SOLUTION:
# We have only two possible differences - 1 and 3.
# - when the difference is 3, there is only one way to reach the larger number,
# and that is through the number which is 3 less than it.
# - when the difference is 1 is when we get different ways to arrange the adaptors.
# The smallest and the largest numbers in a sequence of consequtive numbers are
# anchored. If we consider the visited numbers as 1s and the unvisited ones as
# 0s, we can turn this into a binary number construction, where the number of
# valid possibilities are: all numbers but the ones containing 3 or more consequtive
# 0s. Formula to find the number of possibilities: https://math.stackexchange.com/a/2023263
def x(num):
if num == 1 or num == 2:
return 1
if num == 3:
return 2
return x(num - 3) + x(num - 2) + x(num - 1)
# Count subarrays of consequtive numbers: https://www.geeksforgeeks.org/count-subarrays-with-consecutive-elements-differing-by-1/
def countDiffArrangements(arr):
result = 1
# Take two pointers for maintaining a window of consecutive elements
fast, slow = 0, 0
for i in range(1, len(arr)):
# If elements differ by 1, increment only the fast pointer
if (arr[i] - arr[i - 1] == 1):
fast += 1
else:
# Calculate length of subarray
length = fast - slow + 1
# The possible arrangements - a function of the number of consequtive numbers
result *= x(length)
fast = i
slow = i
# For last iteration. That is if array is traversed and fast > slow
if (fast > slow):
length = fast - slow + 1
result *= x(length)
return result
print("PART 2:", countDiffArrangements(numbers))
"""
--- Day 10: Adapter Array ---
Patched into the aircraft's data port, you discover weather forecasts of a massive tropical storm. Before you can figure out whether it will impact your vacation plans, however, your device suddenly turns off!
Its battery is dead.
You'll need to plug it in. There's only one problem: the charging outlet near your seat produces the wrong number of jolts. Always prepared, you make a list of all of the joltage adapters in your bag.
Each of your joltage adapters is rated for a specific output joltage (your puzzle input). Any given adapter can take an input 1, 2, or 3 jolts lower than its rating and still produce its rated output joltage.
In addition, your device has a built-in joltage adapter rated for 3 jolts higher than the highest-rated adapter in your bag. (If your adapter list were 3, 9, and 6, your device's built-in adapter would be rated for 12 jolts.)
Treat the charging outlet near your seat as having an effective joltage rating of 0.
Since you have some time to kill, you might as well test all of your adapters. Wouldn't want to get to your resort and realize you can't even charge your device!
If you use every adapter in your bag at once, what is the distribution of joltage differences between the charging outlet, the adapters, and your device?
For example, suppose that in your bag, you have adapters with the following joltage ratings:
16
10
15
5
1
11
7
19
6
12
4
With these adapters, your device's built-in joltage adapter would be rated for 19 + 3 = 22 jolts, 3 higher than the highest-rated adapter.
Because adapters can only connect to a source 1-3 jolts lower than its rating, in order to use every adapter, you'd need to choose them like this:
The charging outlet has an effective rating of 0 jolts, so the only adapters that could connect to it directly would need to have a joltage rating of 1, 2, or 3 jolts. Of these, only one you have is an adapter rated 1 jolt (difference of 1).
From your 1-jolt rated adapter, the only choice is your 4-jolt rated adapter (difference of 3).
From the 4-jolt rated adapter, the adapters rated 5, 6, or 7 are valid choices. However, in order to not skip any adapters, you have to pick the adapter rated 5 jolts (difference of 1).
Similarly, the next choices would need to be the adapter rated 6 and then the adapter rated 7 (with difference of 1 and 1).
The only adapter that works with the 7-jolt rated adapter is the one rated 10 jolts (difference of 3).
From 10, the choices are 11 or 12; choose 11 (difference of 1) and then 12 (difference of 1).
After 12, only valid adapter has a rating of 15 (difference of 3), then 16 (difference of 1), then 19 (difference of 3).
Finally, your device's built-in adapter is always 3 higher than the highest adapter, so its rating is 22 jolts (always a difference of 3).
In this example, when using every adapter, there are 7 differences of 1 jolt and 5 differences of 3 jolts.
Here is a larger example:
28
33
18
42
31
14
46
20
48
47
24
23
49
45
19
38
39
11
1
32
25
35
8
17
7
9
4
2
34
10
3
In this larger example, in a chain that uses all of the adapters, there are 22 differences of 1 jolt and 10 differences of 3 jolts.
Find a chain that uses all of your adapters to connect the charging outlet to your device's built-in adapter and count the joltage differences between the charging outlet, the adapters, and your device. What is the number of 1-jolt differences multiplied by the number of 3-jolt differences?
Your puzzle answer was 1820.
--- Part Two ---
To completely determine whether you have enough adapters, you'll need to figure out how many different ways they can be arranged. Every arrangement needs to connect the charging outlet to your device. The previous rules about when adapters can successfully connect still apply.
The first example above (the one that starts with 16, 10, 15) supports the following arrangements:
(0), 1, 4, 5, 6, 7, 10, 11, 12, 15, 16, 19, (22)
(0), 1, 4, 5, 6, 7, 10, 12, 15, 16, 19, (22)
(0), 1, 4, 5, 7, 10, 11, 12, 15, 16, 19, (22)
(0), 1, 4, 5, 7, 10, 12, 15, 16, 19, (22)
(0), 1, 4, 6, 7, 10, 11, 12, 15, 16, 19, (22)
(0), 1, 4, 6, 7, 10, 12, 15, 16, 19, (22)
(0), 1, 4, 7, 10, 11, 12, 15, 16, 19, (22)
(0), 1, 4, 7, 10, 12, 15, 16, 19, (22)
(The charging outlet and your device's built-in adapter are shown in parentheses.) Given the adapters from the first example, the total number of arrangements that connect the charging outlet to your device is 8.
The second example above (the one that starts with 28, 33, 18) has many arrangements. Here are a few:
(0), 1, 2, 3, 4, 7, 8, 9, 10, 11, 14, 17, 18, 19, 20, 23, 24, 25, 28, 31,
32, 33, 34, 35, 38, 39, 42, 45, 46, 47, 48, 49, (52)
(0), 1, 2, 3, 4, 7, 8, 9, 10, 11, 14, 17, 18, 19, 20, 23, 24, 25, 28, 31,
32, 33, 34, 35, 38, 39, 42, 45, 46, 47, 49, (52)
(0), 1, 2, 3, 4, 7, 8, 9, 10, 11, 14, 17, 18, 19, 20, 23, 24, 25, 28, 31,
32, 33, 34, 35, 38, 39, 42, 45, 46, 48, 49, (52)
(0), 1, 2, 3, 4, 7, 8, 9, 10, 11, 14, 17, 18, 19, 20, 23, 24, 25, 28, 31,
32, 33, 34, 35, 38, 39, 42, 45, 46, 49, (52)
(0), 1, 2, 3, 4, 7, 8, 9, 10, 11, 14, 17, 18, 19, 20, 23, 24, 25, 28, 31,
32, 33, 34, 35, 38, 39, 42, 45, 47, 48, 49, (52)
(0), 3, 4, 7, 10, 11, 14, 17, 20, 23, 25, 28, 31, 34, 35, 38, 39, 42, 45,
46, 48, 49, (52)
(0), 3, 4, 7, 10, 11, 14, 17, 20, 23, 25, 28, 31, 34, 35, 38, 39, 42, 45,
46, 49, (52)
(0), 3, 4, 7, 10, 11, 14, 17, 20, 23, 25, 28, 31, 34, 35, 38, 39, 42, 45,
47, 48, 49, (52)
(0), 3, 4, 7, 10, 11, 14, 17, 20, 23, 25, 28, 31, 34, 35, 38, 39, 42, 45,
47, 49, (52)
(0), 3, 4, 7, 10, 11, 14, 17, 20, 23, 25, 28, 31, 34, 35, 38, 39, 42, 45,
48, 49, (52)
In total, this set of adapters can connect the charging outlet to your device in 19208 distinct arrangements.
You glance back down at your bag and try to remember why you brought so many adapters; there must be more than a trillion valid ways to arrange them! Surely, there must be an efficient way to count the arrangements.
What is the total number of distinct ways you can arrange the adapters to connect the charging outlet to your device?
Your puzzle answer was 3454189699072.
Both parts of this puzzle are complete! They provide two gold stars: **
""" |
"""
Given two arrays A1[] and A2[] of size N and M respectively. The task is to sort A1 in such a way that the relative order among the elements will be same as those in A2. For the elements not present in A2, append them at last in sorted order. It is also given that the number of elements in A2[] are smaller than or equal to number of elements in A1[] and A2[] has all distinct elements.
Note: Expected time complexity is O(N log(N)).
Input:
First line of input contains number of testcases. For each testcase, first line of input contains length of arrays N and M and next two line contains N and M elements respectively.
Output:
Print the relatively sorted array.
Constraints:
1 ≤ T ≤ 100
1 ≤ N,M ≤ 106
1 ≤ A1[], A2[] <= 106
Example:
Input:
2
11 4
2 1 2 5 7 1 9 3 6 8 8
2 1 8 3
8 4
2 6 7 5 2 6 8 4
2 6 4 5
Output:
2 2 1 1 8 8 3 5 6 7 9
2 2 6 6 4 5 7 8
Explanation:
Testcase 1: After sorting the resulted output is 2 2 1 1 8 8 3 5 6 7 9.
Testcase 2: After sorting the resulted output is 2 2 6 6 4 5 7 8.
"""
t= int(input())
i = 0
while t>0:
n1, n2 = map(int, input().split())
l1 = list(map(int, input().split()))
l2 = list(map(int, input().split()))
d1 = {}
for i in l1:
d1[i] = 0
for i in l1:
d1[i] = d1[i] + 1
x = []
o=[]
j = 0
leftElements=[]
for i in range(0, n2):
if l2[i] in l1 :
if l2[i] not in o:
x+=[l2[i]]*d1[l2[i]]
o.append(l2[i])
j=j+1
sortedList=[]
for i in l1:
if i not in x:
sortedList.append(i)
sortedList.sort()
for i in sortedList:
x.append(i)
s=""
for i in x:
s=s+str(i)+" "
print(s)
t=t-1
|
from factorial import factorial
def combination(n, r):
return int(factorial(n)/(factorial(r)*factorial(n-r)))
def permutation(n, r):
return int(factorial(n)/factorial(n-r))
def main():
nums= input("Enter n,r: ")
n, r=int(nums.split(",")[0]),int(nums.split(",")[1])
print("Combination: ", str(combination(n,r)))
print("Permutation: ", str(permutation(n,r)))
if __name__ == "__main__":
main() |
"""
Programmer-friendly interface to the neural network.
"""
import json
import numpy as np
from decisiontree import DecisionTree
from card import format_input
class Bot(object):
"""
Object that wraps around the neural net, handling concepts
such as "hand" and the list of previous plays.
"""
def __init__(self, hand, actions=[]):
"""
Creates a bot with an initial hand, and a list of actions
that it can perform.
"""
self.hand = hand
self.valid_samples = []
self.actions = actions
# Create one list per action
self.action_samples = [[]] * len(self.actions)
def add_sample(self, card, prev_card, is_valid, actions=[]):
"""
Adds a new sample for the bot to train on. actions is
not needed if the move is invalid, and must always be a list,
even if there is only one action.
"""
sample = format_input(card, prev_card)
self.valid_samples.append([is_valid, *sample])
if is_valid:
for i in range(len(actions)):
self.action_samples[i].append([actions[i], *sample])
def add_card(self, card):
"""
Adds a card to the bot's hand. The card should be a pair of ints.
"""
self.hand.append(card)
def play(self, prev_card):
"""
Bot plays the best card from its hand, or passes by returning
False. If bot plays a card, it also returns a list of actions.
"""
if not self.hand:
raise Exception("Empty Hand")
cards = [format_input(card, prev_card) for card in self.hand]
output = []
schema = [2, 13, 4, 13, 4, 3, 2]
if not self.valid_samples:
return False
tree = DecisionTree(self.valid_samples, schema)
for card in cards:
output.append(tree(card))
card = False
for i in range(len(cards)):
if output[i]:
card = self.hand.pop(i)
break
if not card:
return False
actions = []
for i in range(len(self.actions)):
max_class = max(
[sample[0] for sample in self.action_samples[i]])
schema[0] = max_class
action_tree = DecisionTree(self.action_samples[i], schema)
actions.append(action_tree(card))
return card, actions
def add_action(self, action):
self.actions.append(action)
self.action_samples.append([])
for sample in self.valid_samples:
if sample[0] == True:
self.action_samples[len(self.actions)-1].append([0, *sample])
def save(self, filename):
"""
Save the bot's data to the given file, so it can be reloaded later.
"""
f = open(filename, "w")
obj = (self.hand,
self.valid_samples,
self.action_samples,
self.actions)
f.write(json.dumps(obj))
@classmethod
def load(cls, filename):
"""Create a new Bot from the file given."""
f = open(filename, "r")
bot = object.__new__(cls)
bot.hand, \
bot.valid_samples, \
bot.action_samples, \
bot.actions = json.loads(f.read())
return bot
|
"""Miscellaneous functions for dealing with cards."""
from random import randrange
def format_input(card, prev_card):
"""
Format two cards in a manner that the decision tree can understand them.
"""
if prev_card[0] < card[0]:
rank = 0
elif prev_card[0] == card[0]:
rank = 1
else:
rank = 2
suite = prev_card[1] == card[1]
return card + prev_card + (rank, suite)
def deal(num_cards):
"""
Deal a hand with the given number of cards. Cards are randomly generated,
and therefore not guaranteed to be unique.
"""
return [(randrange(13), randrange(4)) for i in range(num_cards)]
def tuple_from_s(s):
"""
Create a tuple representing a card, based on its string
representation.
"""
if s == "":
return False
rank = s[:len(s)-1]
suit = s[len(s)-1]
if suit.lower() == 'c':
suit = 0
elif suit.lower() == 'd':
suit = 1
elif suit.lower() == 'h':
suit = 2
elif suit.lower() == 's':
suit = 3
else:
return False
if rank.isdigit() and int(rank) > 1 and int(rank) < 11:
rank = int(rank) - 2
elif rank.lower() == 'j':
rank = 9
elif rank.lower() == 'q':
rank = 10
elif rank.lower() == 'k':
rank = 11
elif rank.lower() == 'a':
rank = 12
else:
return False
return (rank, suit)
def s_from_tuple(t):
"""Convert a card tuple into its corresponding name."""
rank, suit = t
if rank == 12:
s = "Ace"
elif rank == 11:
s = "King"
elif rank == 10:
s = "Queen"
elif rank == 9:
s = "Jack"
else:
s = str(rank + 2)
if suit == 0:
s += " of Clubs"
elif suit == 1:
s += " of Diamonds"
elif suit == 2:
s += " of Hearts"
elif suit == 3:
s += " of Spades"
return s
|
def mod(n1,n2):
return n1*n2
def mod2(n1,n2,n3):
return n1*n2*n3
print(mod2(10,11,12))
|
import sys
import os
from PIL import Image
'''
taking two commandline arguments as source and target folder
converting all jpg files in the source folder to png and save in the target folder
'''
src_folder = sys.argv[1]
tar_folder = sys.argv[2]
# if target folder does not exist, create one
if not os.path.isdir(tar_folder):
os.mkdir(tar_folder)
file_names = os.listdir(src_folder)
# loop through all files in source folder and save them as png in target folder
for file_name in file_names:
file = Image.open(src_folder + file_name)
file.save(tar_folder+file_name.replace('jpg', 'png'), 'png')
|
#!/usr/bin/env python3
'''
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
'''
from sys import argv
class Factors:
def __init__(self, num):
self.set = set()
self.counts = dict()
self.update(num)
def product(self):
p = 1
for i in self.set:
p *= i ** self.counts[i]
return p
def update(self, num):
for i in range(2, num + 1):
if num % i == 0:
if i not in self.set:
self.set.add(i)
self.counts[i] = 0
count = 0
while num % i == 0:
count += 1
num //= i
if count > self.counts[i]:
self.counts[i] = count
def __or__(self, other):
n = Factors(1)
n.set = self.set | other.set
for i in n.set:
n.count[i] = max(self.count[i], self.other[i])
return n
def min_mul(num):
factors = Factors(num)
for i in range(num - 1, 1, -1):
if ( num % i ) != 0:
factors.update(i)
return factors.product()
def check(num, x):
for i in range(2, x + 1):
if ( num % i ) != 0:
return False
return True
def main():
if len(argv) == 3:
num, x = int(argv[1]), int(argv[2])
fmt = '{} {} divisible by every natural number up to {}'
print(fmt.format(num, "is" if check(num, x) else "is not", x))
elif len(argv) == 2:
x = int(argv[1])
print(f'{min_mul(x)} is divisible by every natural number up to {x}')
else:
print('Give one or two integers.')
if __name__ == '__main__':
main()
|
#!/usr/bin/env python3
# Find the sum of all the multiples of 3 or 5 below 1000.
def do():
sum = 0
for i in range(1000):
if (i % 3 == 0) or (i % 5 == 0):
sum += i
return sum
if __name__ == '__main__':
print(do())
|
#!/bin/python3
import os
import sys
#
# Complete the runningMedian function below.
#
class LinkedList(object):
def __init__(self, value, next_node = None):
self.value = value
self.next_node = next_node
def add_node_to_linkedlist(node, value):
head = node
new_node = None
if node.value > value:
new_node = LinkedList(value, head)
return new_node
while node.next_node is not None:
if node.next_node.value >= value:
new_node = LinkedList(value, node.next_node)
node.next_node = new_node
return head
else:
node = node.next_node
node.next_node = LinkedList(value)
return head
def runningMedian(a):
length = len(a)
medians = []
head = LinkedList(a[0])
new_head = head
medians.append(float(head.value))
for i in range(1, length):
new_head = add_node_to_linkedlist(head, a[i])
head = new_head
# while new_head is not None:
# print (new_head.value)
# new_head = new_head.next_node
# print ()
node = head
total = i+1
if total%2 == 0:
right = total/2
left = right-1
while left >= 0:
if left == 0:
median = (node.value + node.next_node.value) / 2.0
medians.append(median)
else:
node = node.next_node
left = left - 1
else:
left = int(total/2)
while left >= 0:
if left == 0:
median = float(node.value)
medians.append(median)
else:
node = node.next_node
left -= 1
return medians
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
a_count = int(input())
a = []
for _ in range(a_count):
a_item = int(input())
a.append(a_item)
result = runningMedian(a)
fptr.write('\n'.join(map(str, result)))
fptr.write('\n')
fptr.close()
|
'''
Longest Substring Without Repeating Characters
Given a string s, find the length of the longest substring without repeating characters.
Example 1:
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
Example 4:
Input: s = ""
Output: 0
Constraints:
0 <= s.length <= 5 * 104
s consists of English letters, digits, symbols and spaces.
'''
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
if len(s) < 2:
return len(s)
i = 0
l = 1
size = len(s)
window = set()
window.add(s[i])
count = 1
for j in range(1, size):
count += 1
if s[j] in window:
while i < j:
if s[i] in window:
window.remove(s[i])
i += 1
count -= 1
if s[i-1] == s[j]:
break
window.add(s[j])
l = max(count, l)
return l
|
def insert(r,val):
if r == None:
root = Node(val)
return root
else:
rec(r, val)
return r
#Enter you code here.
def rec(r, val):
if val < r.data:
if r.left == None:
node = Node(val)
r.left = node
else:
rec(r.left, val)
elif val > r.data:
if r.right == None:
node = Node(val)
r.right = node
else:
rec(r.right, val) |
prime_numbers = []
is_prime = True
for num in range(2, 2001):
check_till = int(num/2)
is_prime = True
for x in range(2, check_till+1):
if num%x == 0:
is_prime = False
if is_prime == True:
prime_numbers.append(num)
print ('Prime number between 1 to 2000 (including) are')
print (prime_numbers)
print ('Total there are ' +str((len(prime_numbers))) + ' prime numbers')
|
"""
Node is defined as
self.left (the left child of the node)
self.right (the right child of the node)
self.data (the value of the node)"""
def insert(r,val):
if r == None:
return Node(val)
p = r
while p != None:
if p.data < val:
if p.right == None:
p.right = Node(val)
break
else:
p = p.right
else:
if p.left == None:
p.left = Node(val)
break
else:
p = p.left
return r
#Enter you code here. |
def runProgram(fileList):
printFiles(fileList)
fileName = takeInput(fileList)
dic = getDicFromFile(fileName)
count = askNumber(len(dic))
worngWordDic = quizzed(dic, count)
print('''
Do you want to export wrong word to txt file?
1. yes
2. no
''')
question = int(input())
if(question == 1):
name = input("please enter file name: ")
exportFile(name, worngWordDic)
else:
print "bye. See you soon"
#Export file
def exportFile(name, worngWordDic):
name = name + ".txt"
f = open(name,"w")
for x in worngWordDic:
f.write(x + ":" + worngWordDic[x] + "\n")
f.close()
print (name + " is created. \nThank you, Bye")
import random
#Quizzed function to start quiz
def quizzed(dic, count):
wrong = {}
k = dic.keys()
random.shuffle(k)
for i in range(count):
ans = input(k[i] + " = ")
l = dic[k[i]].split(',')
l[-1] = l[-1].strip()
if(ans not in l):
wrong[k[i]] = ans
print "Wrong"
else:
print "correct"
return wrong
#ask number to user and validate the user input
def askNumber(count):
userCount = input("Please enter number of words you would like to be quizzed on: ")
while(userCount < 1 or userCount > count):
print ("\nnumber should be between one and the number of English words in the dictionary")
userCount = input("Please enter number of words you would like to be quizzed on: ")
return userCount
#create dictionary using files.
def getDicFromFile(fileName):
#f = open(fileName, "r")
#print f.read()
dic = {}
with open(fileName) as f:
for line in f:
(key, val) = line.split(':')
dic[key] = val
print ("\nThere is total " + str(len(dic)) + " words.\n")
return dic
#take input from user on which files we want to attend quiz
def takeInput(fileList):
fileName = input("which vocabulary file you would like to use: ")
while(fileName not in fileList):
print ("\n" +fileName + " is not exist, Please try again\n")
fileName = input("which vocabulary file you would like to use:")
return fileName
#print function
def printFiles(fileList):
print ("Files are "),
print fileList
#Stop function and say bye
def quitProgram():
print "I am not able to find file in directory. Sorry :("
#starting of the program
import glob
fileList = glob.glob('*.txt')
if(len(fileList) > 0):
runProgram(fileList)
else:
quitProgram()
|
def intToRoman(s):
roman = ['I', 'IV', 'V', 'IX', 'X', 'XL', 'L', 'XC', 'C', 'CD', 'D', 'CM', 'M']
no_list = [1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000]
no_list.reverse()
roman.reverse()
number = ''
i = 0;
while s > 0:
while s >= no_list[i]:
s -= no_list[i]
number += roman[i]
i += 1
return number
print romanToInt(49) |
## The sum of the squares of the first ten natural numbers is,
# 1^2 + 2^2 + ... + 10^2 = 385
#
# The square of the sum of the first ten natural numbers is,
# (1 + 2 + ... + 10)^2 = 55^2 = 3025
#
# Hence the difference between the sum of the squares of the first ten natural
# numbers and the square of the sum is 3025 − 385 = 2640.
#
# Find the difference between the sum of the squares of the first one hundred
## natural numbers and the square of the sum.
def summ(max):
sum = 0
for i in range(0, max + 1):
add = i * i
sum += add
return sum
def square(max):
sum = 0
for i in range(0, max + 1):
sum += i
output = (sum * sum)
return output
def dif(max):
dif = square(max) - summ(max)
return dif
print(dif(100))
#returns 25164150
|
#Prints out odd or even numbers
x = str(input("odd/even = "))
if x == 'even':
for i in range(2,11,2):
print(i)
elif x == "odd":
for i in range(1,11,2):
print(i) |
parrot = "Norwegian Blue"
print(parrot)
print(parrot[3])
print(parrot[4])
print(parrot[9])
print(parrot[3])
print(parrot[6])
print(parrot[8])
print()
print(parrot[-1])
print(parrot[-14])
print()
print(parrot[3 - 14])
print(parrot[4 - 14])
print(parrot[9 - 14])
print(parrot[3 - 14])
print(parrot[6 - 14])
print(parrot[0:6])
print(parrot[3:5])
print(parrot[0:9])
print(parrot[:9])
print(parrot[10:14])
print(parrot[10:])
print(parrot[:6])
print(parrot[6:])
print(parrot[:6] + parrot[6:])
print(parrot[:])
print(parrot[0:6:2])
print(parrot[0:6:3])
number = "9,223;372:036 854,775;807"
seperators = number[1::4]
print(seperators)
"""
I run over number by 'for char in number'; Then, I wanna filter the characters - so, I do it by
'char if char not in seperators else ""', which mean - take the current char on condition that
it doesn't exist in the the string called seperators;
All of the above can can be written only in join function, so - we do it bu concatenating empty
string to desired string represented in join function.
"""
values = "".join(char if char not in seperators else "" for char in number).split()
print([int(val) for val in values]) |
"""
The alignment is to right; For the first item it'll take 2 places, for the second item it'll take 3 places
and for the third - last one, it'll tale four places.
"""
for i in range(1, 13):
print("No. {0:2} squared is {1:3} and cubed is {2:4}".format(i, i ** 2, i ** 3))
print()
"""
Due to '<' sign, the alignment will be to left side.
As, if the number of the char are smaller than the mentioned number, so the alignment go to left side.
"""
for i in range(1, 13):
print("No. {0:2} squared is {1:<3} and cubed is {2:<4}".format(i, i ** 2, i ** 3))
print("Pi is approximately {0:12}".format(22 / 7))
print("Pi is approximately {0:12f}".format(22 / 7))
print("Pi is approximately {0:12.50f}".format(22 / 7))
print("Pi is approximately {0:52.50f}".format(22 / 7))
print("Pi is approximately {0:62.50f}".format(22 / 7))
print("Pi is approximately {0:<72.50f}".format(22 / 7))
print("Pi is approximately {0:<72.54f}".format(22 / 7))
"""
If the items needed to be print are according to the order they'rementioned, so - there's no need to
mention them; the second parameter is for the alignment.
"""
for i in range(1, 13):
print("No. {:2} squared is {:3} and cubed is {:4}".format(i, i ** 2, i ** 3))
# The end of No.8 meeting; the first one of Python module.
|
def transfer2string(list):
str_list = ""
for i in range(len(list)):
if list[i] == list[-1]:
str_list += "and " + list[i]
else:
str_list += list[i] + ", "
return str_list
spam = ['apples', 'bananas', 'tofu', 'cats']
str_spam = transfer2string(spam)
print(str_spam)
|
stanje = 0
while stanje > (-100):
sprememba = int(input("Sprememba "))
stanje += sprememba
print("Stanje ", stanje)
print("Bankrot") |
"""
from random import *
from math import *
r = 1
i = 1
n = 0
st_koordinatov = 1000
while i <= st_koordinatov:
x = 2 * random() - 1
y = 2 * random() - 1
if sqrt(x**2 + y**2) < r:
n += 1
i += 1
pi_rac = 4 * n / st_koordinatov
print("PI:", pi_rac)
"""
from random import *
from math import *
r = 1
i = 1
n = 0
pi_prejsni = 0
pi_nov = 100
st_koordinatov = 1000
while abs(pi_prejsni - pi_nov) > 0.000001:
x = 2 * random() - 1
y = 2 * random() - 1
if sqrt(x**2 + y**2) < r:
n += 1
if i % 1000 == 0:
pi_prejsni = pi_nov
pi_nov = 4 * n / i
i += 1
print("Zadnji PI:", pi_nov)
print("Prejšni PI:", pi_prejsni)
print("Stevilo točk:", n)
|
from math import *
a = float(input("Kateta?"))
b = float(input("Kateta?"))
c = sqrt((a**2) + (b**2))
print("Hipotenuza: ",c)
|
vsota = 0
i = 1
while i <= 5:
cena = int(input("Cena artikla: "))
vsota += cena
i += 1
print("Vsota: ",vsota) |
# Determinar si un número entero proporcionado por el usuario es primo.
m= int(2);
band = "V";
numero = int(input("Ingrese el numero: "));
while((band == "V") and (m < numero)):
if((numero % m) == 0):
band = "F";
else:
m = m + 1;
if(band == "V"):
print("El numero leido es primo");
else:
print("El numero leido no es primo"); |
# Diseñar un algoritmo tal que dados como datos dos variables de tipo entero, obtenga el resultado de la siguiente función:
num= int(input("Ingrese numero: "))
V= int(input("Ingrese valor: "))
if num == 1:
resp=100*V
elif num == 2:
resp=100**V
elif num == 3:
resp=100/V
else:
resp=0
print("La respuesta es: ",resp)
|
class CircularPrime(object):
def __init__(self):
super(CircularPrime, self).__init__()
def is_prime(self, number):
if number == 2:
return True
if (number < 2) or not (number % 2):
return False
for i in range(3, int(number**0.5) + 1, 2):
if (number % i) == 0:
return False
return True
def number_circle(self, number):
numL = list(str(number))
firstN = numL.pop(0)
numL.append(firstN)
return ''.join(numL)
def circular_prime_calc(self, number):
num_circle = number
for i in range(0, len(str(number))):
if self.is_prime(int(num_circle)) == False:
return False
num_circle = self.number_circle(num_circle)
return True
def how_many_circular_prime(self, number):
circular_prime_count = 0
for i in range(2, int(number)):
c_prime_calc = self.circular_prime_calc(i)
if c_prime_calc == True:
circular_prime_count += 1
return circular_prime_count
|
"""Defines the encryption protocol."""
import random
import string
import numpy as np
from typing import List
from collections import deque
from content.helper.constant import Key
from content.encrypt_item.cube import Cube
class Encryption:
"""Perform encryption and decryption of the input."""
def __init__(self, message: str, cube_side_length: int):
"""Put the message into a cube and create a queue to hold keys.
:param message: The message to encrypt.
:param cube_side_length: The desired length of cube side.
"""
# Remove blanks and punctuations.
message = self.process_string(message=message)
# Store the important information for other method to access.
chunk_size = cube_side_length ** 2 * 6
self.pad_size = chunk_size - len(message) % chunk_size
# Make sure that the message is all lowercase and pad it.
message += "".join(
random.choice(string.ascii_lowercase) for _ in range(self.pad_size)
)
# Split the message into chunks that fits in the cube.
messages = np.array_split(
ary=list(message),
indices_or_sections=int(len(message) / chunk_size)
)
# Get the cubes.
self._cubes = [
Cube(cube_input=message, cube_side_length=cube_side_length)
for message in messages
]
# Set up the holder for the key.
self._key = deque()
@staticmethod
def process_string(message: str) -> str:
"""Remove blanks and punctuations in input and make it lowercase."""
return "".join([
char if char in string.ascii_letters else "" for char in message
]).lower()
def get_current_content(self) -> str:
"""Get the input string at the current state."""
# Note: This implementation assumes that input was a string.
return "".join(["".join(cube.content) for cube in self._cubes])
def encrypt(self, key: List[Key]):
"""Encrypt the message based on a given key.
:param key: A list of keys used for encryption.
"""
# Loop through all the keys.
for each_key in key:
# Shift all the cubes.
for cube in self._cubes:
# Shift content.
cube.shift_content()
# Perform cube move.
cube.shift(key=each_key)
# Append the used key to key list.
self._key.append(each_key)
def decrypt(self):
"""Decrypt the message to plain text."""
# While there are still keys, keep running.
while self._key:
# Pop the key from saved keys.
each_key = self._key.pop()
for cube in self._cubes:
# Reverse the cube shift move.
cube.shift(
key=Key(
move=each_key.move,
angle=360 - each_key.angle,
index=each_key.index
)
)
# Shift content backward.
cube.shift_content_back()
def get_decrypted_str(self) -> str:
"""Decrypt the message and return the original input.
:return: The original message that was encrypted as a string.
"""
# First make sure that all cubes are decrypted.
self.decrypt()
# Return the decrypted string.
return self.get_current_content()[:-self.pad_size]
|
import binascii
from Cryptodome.Cipher import AES
KEY = 'This is a key123'
IV = 'This is an IV456'
MODE = AES.MODE_CFB
BLOCK_SIZE = 16
SEGMENT_SIZE = 128
def encrypt(key, iv, plaintext):
aes = AES.new(key, MODE, iv)#, segment_size=SEGMENT_SIZE)
plaintext = _pad_string(plaintext)
encrypted_text = aes.encrypt(plaintext)
return binascii.b2a_hex(encrypted_text).rstrip()
def decrypt(key, iv, encrypted_text):
aes = AES.new(key, MODE, iv)#, segment_size=SEGMENT_SIZE)
encrypted_text_bytes = binascii.a2b_hex(encrypted_text)
decrypted_text = aes.decrypt(encrypted_text_bytes)
decrypted_text = _unpad_string(decrypted_text)
return decrypted_text
def _pad_string(value):
length = len(value)
pad_size = BLOCK_SIZE - (length % BLOCK_SIZE)
return value.ljust(length + pad_size, '\x00')
def _unpad_string(value):
while value[-1] == '\x00':
value = value[:-1]
return value
if __name__ == '__main__':
input_plaintext = 'The answer is no'
print(input_plaintext)
encrypted_text = encrypt(KEY, IV, input_plaintext)
print(encrypted_text)
decrypted_text = decrypt(KEY, IV, encrypted_text)
print(decrypted_text)
assert decrypted_text == input_plaintext |
import math
def gap(g, m, n):
prime = 2
for i in range(m, n+1):
is_prime = True
for j in range(2,int(math.sqrt(n))+1):
if i % j == 0:
is_prime = False
break
if is_prime:
if i - prime == g:
return [prime, i]
else:
prime = i
|
# def compress(string):
# finalString = ""
# if string == "":
# return "\"\""
# if len(string) == 1:
# return finalString + 1
# count = 1
# i = 1
# for letter in string:
# if letter == string[i - 1]:
# # finalString = finalString + letter + str(count + 1)
# i += 1
# count += 1
# else:
# finalString += finalString + letter + str(count)
# count = 1
# i += 1
# return finalString
# print(compress('AAAAABBBBCCCC'))
# The script below will let me understand negative indexes
# the for loop will terminate if the next character is DIFFERENT
# count = 0
# index = 0
# for i in string:
# if string[index - 1] == string[index - 2]:
# print(string[index - 1])
# index -= 1
# else:
# print("A different letter is encountered")
# print("The letter is " + string[index - 2])
# break
string = 'AAAAABBBBCCCC'
index = 1
for letter in string:
def inner(index):
count = 0
finalString = ""
print(count)
print(index)
if letter == string[index]:
print(letter)
# if IndexError:
# break
# # finalString = finalString + letter + str(count + 1)
# else:
# continue
count += 1
index += 1
return
else:
finalString = finalString + letter + str(count)
count = 1
index += 1
return
inner(index)
|
# Declaring a Node class and forming a singly linked list
class Node(object):
def __init__(self, value):
self.value = value
self.next = None
def cycle_checker(self):
next = self.next
while next is not None:
if self.value == next.value:
return True
else:
next = next.next
return False
###### Test Case # 1 ######
print("###### Test Case # 1 ######")
print('\n')
print("###### True ######")
a = Node(1)
b = Node(2)
c = Node(3)
a.next = b
b.next = c
# this points back to the head of the singly linked list
c.next = a
print('\n')
print("Cyclic Check for a: " + str(a.cycle_checker()))
print('\n')
###### Test Case # 1 ######
print("###### Test Case # 2 ######")
print('\n')
print("###### False ######")
# CREATE NON CYCLE LIST
x = Node(1)
y = Node(2)
z = Node(3)
x.next = y
y.next = z
print('\n')
print("Cyclic Check for a: " + str(x.cycle_checker())) |
class Stack(object):
"""
Implementing my own stack
reference:
https://digitalu.udemy.com/course/python-for-data-structures-algorithms-and-interviews/learn/lecture/3179606#overview
"""
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
# takes a look at the top item
def peek(self):
return self.items[len(self.items) - 1]
def size(self):
return len(self.items)
s = Stack()
print (s.isEmpty())
print(s.push("Pcap"))
print (s.isEmpty())
print(s.push("is"))
print(s.push("Awesome"))
print("###### Understanding memory locations")
print(s.peek)
print(s.peek())
# <bound method Stack.peek of <__main__.Stack object at 0x0000021488894CA0>>
print(s.pop)
print(s.pop())
# <bound method Stack.pop of <__main__.Stack object at 0x0000019884B44CA0>>
print(s.peek)
print(s.peek())
# <bound method Stack.peek of <__main__.Stack object at 0x000002A8DEF44CA0>>
# After the pop, the current top of the stack takes the same memory location
# as the one that was previously popped
|
''' TAREA3
Examina cómo las diferencias en los tiempos de ejecución de los
diferentes ordenamientos cambian cuando se varía el número de núcleos
asignados al cluster, utilizando como datos de entrada un vector que
contiene primos grandes, descargados de
https://primes.utm.edu/lists/small/millions/ y no-primos con por lo
menos ocho dígitos. Investiga también el efecto de la proporción de
primos y no-primos en el vector igual como, opcionalmente, la magnitud
de los números incluidos en el vector con pruebas estadísticas
adecuadas.
'''
#---------------- Var Datos_faciles -----------------
o = 0
datos_faciles = []
#---------------- Var Datos_faciles -----------------
from math import ceil, sqrt
def primo(n):
if n < 4:
return True
if n % 2 == 0:
return False
for i in range(3, int(ceil(sqrt(n))), 2):
if n % i == 0:
return False
return True
from scipy.stats import describe
from random import shuffle
from time import time
import matplotlib.pyplot as plt
import multiprocessing
import numpy as np
import psutil
core = psutil.cpu_count()
v_core = psutil.cpu_count(logical = False)
if __name__ == "__main__":
print()
print("Este programa corre en una pc con", core, "nucleos, de los cuales", v_core, "son nucleos virtuales.")
print()
#---------------------- Importar Datos -----------------------
with open('Datos.txt', 'r') as input:
linea = input.readline()
datos = [int(valor) for valor in linea.split(',')]
num_datos = len(datos)
print("Para este programa se han importado", num_datos, " numeros primos, desde", min(datos), "hasta", max(datos)," lo que conforma la variable datos. De esta variable se han obtenido los intervalos de numeros no-primos para generar la variable datos_faciles." )
print("")
#---------------------- Importar Datos -----------------------
#---------------- De Datos genera Datos_faciles -----------------
for exp in range(int((num_datos + 1)/2)):
if exp == 0:
imp = datos[exp]
imp2 = datos[exp + 1]
o = exp + 1
elif exp > 0:
imp = datos[o + 1]
imp2 = datos[o + 2]
o = o + 2
#print(imp, imp2, exp)
for cand in range(imp, imp2+1):
datos_faciles.append(cand)
num_datos_faciles = len(datos_faciles)
total_datos = num_datos + num_datos_faciles
porcentaje_num_faciles = int((num_datos_faciles/total_datos) * 100)
porcentaje_num_dificiles = int((num_datos/total_datos) * 100)
print("Dado que para este programa se tienen", num_datos, "numeros primos, y", num_datos_faciles, "numeros no-primos. Por lo tanto, se tiene ", porcentaje_num_dificiles,"% de numeros primos, y un", porcentaje_num_faciles, "% de numeros no-primos." )
print("")
#---------------- De Datos genera Datos_faciles -----------------
#--------------- Genera combinaciones de Datos ----------------
D_F = datos
D_F.extend(datos_faciles)
F_D = D_F[::-1]
Aleatorio = D_F.copy()
shuffle(Aleatorio)
#--------------- Genera combinaciones de Datos ----------------
pg1 = []
pg2 = []
pg3 = []
grafica1 = []
grafica2 = []
grafica3 = []
grafica4 = []
replicas = 10
REPLICAS = replicas - 1
NUCLEOS = range(1, core + 1) # Hasta 4 nucleos
tiempos = {"ot": [], "it": [], "at": []}
for core in NUCLEOS:
print("-----------------------", core, "-----------------------")
with multiprocessing.Pool(core) as pool:
for r in range(replicas):
t = time()
pool.map(primo, D_F)
tiempos["ot"].append(time() - t)
t = time()
pool.map(primo, F_D)
tiempos["it"].append(time() - t)
t = time()
pool.map(primo, Aleatorio)
tiempos["at"].append(time() - t)
for tipo in tiempos:
print("")
print(describe(tiempos[tipo]))
print("")
if core == 1:
grafica1.append(tiempos[tipo])
elif core == 2:
grafica2.append(tiempos[tipo])
elif core == 3:
grafica3.append(tiempos[tipo])
elif core == 4:
grafica4.append(tiempos[tipo])
pg1.append(np.mean(tiempos["ot"]))
pg2.append(np.mean(tiempos["it"]))
pg3.append(np.mean(tiempos["at"]))
tiempos = {"ot": [], "it": [], "at": []}
print("-----------------------", core, "-----------------------")
print("--------------------", "Global", "---------------------")
print("")
print(pg1)
print("")
print("")
print(pg2)
print("")
print("")
print(pg3)
print("")
print("--------------------", "Global", "---------------------")
plt.subplot(221)
plt.boxplot(grafica1)
plt.xticks([1, 2, 3], ['D_F', 'F_D', 'Aleatorio'])
plt.ylabel('Tiempo (seg)')
plt.title('1 Núcleo')
plt.subplot(222)
plt.boxplot(grafica2)
plt.xticks([1, 2, 3], ['D_F', 'F_D', 'Aleatorio'])
plt.ylabel('Tiempo (seg)')
plt.title('2 Núcleos')
plt.subplot(223)
plt.boxplot(grafica3)
plt.xticks([1, 2, 3], ['D_F', 'F_D', 'Aleatorio'])
plt.ylabel('Tiempo (seg)')
plt.title('3 Núcleos')
plt.subplot(224)
plt.boxplot(grafica4)
plt.xticks([1, 2, 3], ['D_F', 'F_D', 'Aleatorio'])
plt.ylabel('Tiempo (seg)')
plt.title('4 Núcleos')
plt.subplots_adjust(top=0.95, bottom=0.08, left=0.05, right=0.95, hspace=0.35,
wspace=0.2)
plt.show()
plt.close()
plt.plot(pg1, label="D_F")
plt.xticks([0, 1, 2, 3], ['1', '2', '3', '4'])
plt.plot(pg2, label="F_D")
plt.xticks([0, 1, 2, 3], ['1', '2', '3', '4'])
plt.plot(pg3, label="Aleatorio")
plt.xticks([0, 1, 2, 3], ['1', '2', '3', '4'])
plt.xlabel('Núcleos')
plt.ylabel('Tiempo (seg)')
plt.legend()
plt.show()
plt.close()
|
def check_matches(fn ="test.csv"):
import pandas as pd
vsc = {}
df = pd.read_csv(fn)
for row in df.iterrows():
r = row[1]
for row1 in df.iterrows():
r1 = row1[1]
if r.Week == r1.Week and (r.Match1 == r1.Match1 or r.Match2 == r1.Match2 or r.Match3 == r1.Match3):
if r['Team#'] != r1['Team#']:
# print(f"WK{r.Week} A{r['Team#']} B{r1['Team#']}")
if r['Team#'] in vsc:
vsc[r['Team#']].append(r1['Team#'])
else:
vsc[r['Team#']] = [r1['Team#']]
for v in vsc:
print(v, len(set(vsc[v])), vsc[v])
print()
dc = []
for row in df.iterrows():
r = row[1]
i = row[0]
if r.Match1 == r.Match2 or r.Match2 == r.Match3 or r.Match1 == r.Match3:
dc.append(r)
else:
# print(f"{i} pass")
pass
print(len(dc))
for d in dc:
print(d)
print()
if __name__ == "__main__":
check_matches() |
import collections
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
class Solution(object):
def height(self, root, cached):
max_height = 1
if len(root.children) > 0:
for child in root.children:
if child.val not in cached:
max_height = max(max_height, self.height(child, cached))
else:
max_height = max(max_height, cached[child.val])
max_height += 1
cached[root.val] = max(cached[root.val], max_height)
return max_height
def build_tree(self, root, matrix, row1, col1, row2, col2, node_map, root_nodes):
p = 0 <= row2 < len(matrix)
q = 0 <= col2 < len(matrix[0])
if p and q and matrix[row2][col2] > matrix[row1][col1]:
if (row2, col2) in node_map:
new_node = node_map[(row2, col2)]
if (row2, col2) in root_nodes:
root_nodes.remove((row2, col2))
else:
new_node = Node((row2, col2), [])
node_map[(row2, col2)] = new_node
root.children.append(new_node)
def longestIncreasingPath(self, matrix):
if len(matrix) == 0 or len(matrix[0]) == 0:
return 0
node_map = collections.defaultdict(Node)
root_nodes = set()
for row in range(len(matrix)):
for col in range(len(matrix[0])):
if (row, col) in node_map:
node = node_map[(row, col)]
else:
node = Node((row, col), [])
node_map[(row, col)] = node
root_nodes.add((row, col))
self.build_tree(node, matrix, row, col, row - 1, col, node_map, root_nodes)
self.build_tree(node, matrix, row, col, row, col - 1, node_map, root_nodes)
self.build_tree(node, matrix, row, col, row + 1, col, node_map, root_nodes)
self.build_tree(node, matrix, row, col, row, col + 1, node_map, root_nodes)
max_len = 1
for key in root_nodes:
node = node_map[key]
cached = collections.defaultdict(int)
max_len = max(max_len, self.height(node, cached))
return max_len
sol = Solution()
print sol.longestIncreasingPath([
[9,9,4],
[6,6,8],
[2,1,1]
]) |
def find_pivot(arr):
i, j, pivot_idx = -1, 0, len(arr)-1
while j < len(arr)-1:
if i >= 0 and arr[j] <= arr[pivot_idx]:
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
i += 1
else:
if i == -1 and arr[j] > arr[pivot_idx]:
i = j
j += 1
temp = arr[pivot_idx]
arr[pivot_idx] = arr[i]
arr[i] = temp
return arr, (i+len(arr))%len(arr)
def quicksort(arr):
if len(arr) == 1:
return [arr[0]]
if len(arr) == 0:
return []
arr, pivot = find_pivot(arr)
a = quicksort(arr[:pivot])
b = quicksort(arr[pivot+1:])
return a + [arr[pivot]] + b
|
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def largestValues(self, root):
queue, largest = [(root, 0)], []
last_depth = 0
running = []
while len(queue) > 0:
node, depth = queue.pop()
if depth > last_depth:
max_val = -float("Inf")
for idx in range(len(running)):
if running[idx] > max_val:
max_val = running[idx]
largest.append(max_val)
running = [node.val]
else:
running.append(node.val)
last_depth = depth
if node.left is not None:
queue.insert(0, (node.left, depth + 1))
if node.right is not None:
queue.insert(0, (node.right, depth + 1))
max_val = -float("Inf")
for idx in range(len(running)):
if running[idx] > max_val:
max_val = running[idx]
largest.append(max_val)
return largest |
import heapq
class Solution(object):
def merge(self, enc, u):
i = 0
while 0 <= i < len(enc):
x, y = enc[i]
if y >= 3:
u -= y
if i-1 >= 0 and i+1 < len(enc) and enc[i-1][0] == enc[i+1][0]:
enc = enc[:i-1] + [(enc[i-1][0], enc[i-1][1]+enc[i+1][1])] + enc[i+2:]
i -= 1
else:
enc = enc[:i] + enc[i+1:]
else:
i += 1
return enc, u
def findMinStep(self, board, hand):
encoded, cnt = [], 1
for i in range(1, len(board)):
if board[i] != board[i-1]:
encoded.append((board[i-1], cnt))
cnt = 1
else:
cnt += 1
encoded.append((board[-1], cnt))
heap = [(len(board), encoded, 0, hand)]
min_balls = float("Inf")
while len(heap) > 0:
u, enc, num_balls, hnd = heapq.heappop(heap)
# print u, enc, num_balls, hnd
enc, u = self.merge(enc, u)
if u <= 0:
min_balls = min(min_balls, num_balls)
for j in range(len(hnd)):
h = hnd[j]
flag = False
for i in range(len(enc)):
x, y = enc[i]
if x == h:
flag = True
if y == 2:
if i-1 >= 0 and i+1 < len(enc) and enc[i-1][0] == enc[i+1][0]:
enc1 = enc[:i-1] + [(enc[i-1][0], enc[i-1][1]+enc[i+1][1])] + enc[i+2:]
else:
enc1 = enc[:i] + enc[i+1:]
heapq.heappush(heap, (u-y, enc1, num_balls+1, hnd[:j] + hnd[j+1:]))
else:
heapq.heappush(heap, (u+1, enc[:i] + [(x, y+1)] + enc[i+1:], num_balls+1, hnd[:j] + hnd[j+1:]))
if flag is False:
heapq.heappush(heap, (u+1, enc + [(h, 1)], num_balls+1, hnd[:j] + hnd[j+1:]))
return min_balls if min_balls != float("Inf") else -1
|
class Solution:
def custom_merge(self, nums1, nums2):
i, j = 0, 0
out = []
while i < len(nums1) and j < len(nums2):
if int(str(nums1[i]) + str(nums2[j])) > int(str(nums2[j]) + str(nums1[i])):
out.append(nums1[i])
i += 1
else:
out.append(nums2[j])
j += 1
if i < len(nums1):
for k in range(i, len(nums1)):
out.append(nums1[k])
if j < len(nums2):
for k in range(j, len(nums2)):
out.append(nums2[k])
return out
def custom_merge_sort(self, nums, left, right):
if left >= right:
return [nums[left]]
else:
mid = (left + right) / 2
a = self.custom_merge_sort(nums, left, mid)
b = self.custom_merge_sort(nums, mid + 1, right)
return self.custom_merge(a, b)
def largestNumber(self, nums):
sorted_nums = self.custom_merge_sort(nums, 0, len(nums) - 1)
if sorted_nums[0] == 0:
return "0"
out = ""
for num in sorted_nums:
out += str(num)
return out
sol = Solution()
print sol.largestNumber([0,0]) |
numeros = [0,1,2,3,4,5,6,7,8,9]
soma = 0
for i in numeros:
soma = soma + numeros[i]
print(soma) |
# Descripcion: Programa que permite a un usuario jugar a Piedra, papel o tijera con un jugador virtual PC
# Entrada: Seleccion entre piedra, papel o tijera hecha por el usuario
# Salida: Felicitaciones al usuario ganador
# Autor: EALCALA
# Fecha: 03.05.2017
# Version: 1.0
#Plataforma: Python v2.7
import sys
w = int(input("Escribe 3 si deseas jugar piedra, papel o tijera, o 4 si no deseas jugar: "))
if w == 4:
sys.exit("Adios")
while w == 3:
import random
a = random.randrange(0, 3)
Pc = ""
print("Escoge 0)Piedra")
print("1)Papel")
print("2)Tijera")
j1 = int(input("Escoge una opcion: "))
if j1 == 0:
Usuario = "piedra"
elif j1 == 1:
Usuario = "papel"
elif j1 == 2:
Usuario = "tijera"
if a == 0:
Pc = "piedra"
elif a == 1:
Pc = "papel"
elif a == 2:
Pc = "tijera"
print("...")
if Pc == "piedra" and Usuario == "papel":
print("Ganaste!!, papel gana a piedra")
elif Pc == "papel" and Usuario == "tijera":
print("Ganaste!!, Tijera gana a papel")
elif Pc == "tijera" and Usuario == "piedra":
print("Ganaste!!, Piedra gana a tijera")
elif Pc == "papel" and Usuario == "piedra":
print("Perdiste!!, papel gana a piedra")
elif Pc == "tijera" and Usuario == "papel":
print("perdiste!!, Tijera gana a papel")
elif Pc == "piedra" and Usuario == "tijera":
print("perdiste!!, Piedra gana a tijera")
elif Pc == Usuario:
print("Hay un empate")
break
sys.exit()
|
# Descripcion: Programa que genera una contrasena fuerte o debil segun desea el usuario
# Entrada: Solicitud de contrasena fuerte o debil
# Salida: Contrasena aleatoriamente generada
# Autor: EALCALA
# Fecha: 17.05.2017
# Version: 3.0
#Plataforma: Python v2.7
def nivel():
return raw_input("Introduzca un nivel de seguridad de contrasena:['debil' || 'fuerte'] :")
def clave_deb(len=5):
import random
items = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
lista_items = list(items)
return ''.join(random.sample(lista_items,len))
return lista_items
def clave_fuer(len=10):
import random
items = "1234567890!@#$%*()abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
lista_items = list(items)
return ''.join(random.sample(lista_items,len))
return lista_items
def clave():
n = nivel()
if (n.lower() == 'debil'):
print "Contrasena : " ,clave_deb()
elif (n.lower() == 'fuerte'):
print "Contrasena : ", clave_fuer()
else:
print "Usted no introdujo una opcion, valida"
clave()
|
# Descripcion: Programa que juega con un usuario vacas y toros
# Entrada: Eleccion para adivinar de un numero de 4 digitos
# Salida: Numero de Vacas y Toros hasta acertar
# Autor: EALCALA
# Fecha: 19.05.2017
# Version: 1.0
#Plataforma: Python v2.7
def vacas_toros():
from random import randint
vacas = 0
toros = 0
uno = randint(1,9)
dos = randint(1,9)
tres = randint(1,9)
cuatro = randint(1,9)
num = str(uno) + str(dos) + str(tres) + str(cuatro)
while True:
vacas = toros = 0
adiv = input('Bienvenido al juego de vacas y toros, adivine un numero de cuatro digitos: ')
for i in adiv:
if i in num:
vacas += 1
else:
toros += 1
if toros == 0:
print('Usted ha adivinado el numero')
break
else:
print('Llevas ' + str(cows) + ' vacas, y ' + str(bulls) + ' toros!')
continue
if __name__=="__main__":
vacas_toros()
|
#!/usr/bin/env python3
import sys
import csv
import os
def process_csv(csv_file):
"""Turn the contents of the CSV file into a list of lists"""
print("Processing {}".format(csv_file))
with open(csv_file,"r") as datafile:
data = list(csv.reader(datafile))
return data
def data_to_html(title, data):
"""Turns a list of lists into an HTML table"""
# HTML Headers
html_content = """
<html>
<head>
<style>
table {
width: 25%;
font-family: arial, sans-serif;
border-collapse: collapse;
}
tr:nth-child(odd) {
background-color: #dddddd;
}
|
# creating a file 'GoldenThoughts.txt' in the same location like *.py file is //'w'
FileWithParagraphs=open('GoldenThoughts.txt','w')
# I save both paragraphs of the text into the created file
FileWithParagraphs.write('What if I said that randomness, coincidence, chance, karma, miracle—all such notions do not exist? That from the moment a being is born, their future is already carved into stone? \nIf so, a being’s actions do not truly stem from his own choices, but are manipulated to suit the performance of a “conductor”. In that sense—prayer, perfection and imperfection, reality and dream, hope and despair, righteousness and wickedness, love and hatred and even life and death are but illusionary oncepts—equally and utterly devoid of meaning.')
# I'm opening the file for reading purpouse //'r'
FileWithParagraphs=open('GoldenThoughts.txt','r')
#the writer can choose 1st or 2nd paragraph\\ loop: another answer will repeat the question
paragraph_number=input("Which paragraph number you want to display, 1st or 2nd? : ")
while paragraph_number!='1' and paragraph_number!='2':
print("\nSorry, but you can choose only 1 or 2. \nYou can try again :)")
paragraph_number=input(" Which paragraph number you want to display, 1st or 2nd?: ")
print("You choose ",paragraph_number," paragraph.")
print("\n\n******************************************************************")
# defining the response as an integer
paragraph_number=int(paragraph_number)
# defining a class for paragraph, name, aurhor rights
class Paragraphs:
def __init__(self, paragraph, name, aurhorRights):
self.paragraph = paragraph
self.name = name
self.aurhorRights = aurhorRights
# displaying an paragraph depending on the writer's choice
if paragraph_number==1:
text1 = Paragraphs(str(FileWithParagraphs.readlines()[0]), '\nAuthor name: Todoki', '\n© Copyright 2021 Todoki. All Rights Reserved. ')
print (text1.paragraph)
print (text1.name)
print (text1.aurhorRights)
elif paragraph_number==2:
text2 = Paragraphs(str(FileWithParagraphs.readlines()[1]), '\nAuthor name: Todoki','\n© Copyright 2021 Todoki. All Rights Reserved. ')
print (text2.paragraph)
print (text2.name)
print (text2.aurhorRights)
# I close the previously opened file for reading
FileWithParagraphs.close()
# it is an Coding Exercise 4 Piotr Fraczek |
from cs50 import *
import sys
def main():
if len(sys.argv) != 2:
print("You must use exactly 1 command argument!\n")
return
key = int(sys.argv[1])
plain_text = get_string()
for char in plain_text:
if char.isalpha():
if char.isupper():
print(chr(((ord(char) + key - 65) % 26) + 65), end="")
if char.islower():
print(chr(((ord(char) + key - 97) % 26) + 97), end="")
else:
print(char, end="")
print("\n")
if __name__ == "__main__":
main() |
def triangle(n):
k = 2*n-2
for i in range(0,n):
for j in range(0,k):
k = k-1
for j in range(0,i+1):
print("*",end="")
print("\n")
n = 5
|
n=10
for i in range(n):
print(" "*(n-i-1)+'* '*(i+1))
for j in range(n-1,0,-1):
print(' '*(n-j)+'* '*(j))
|
def my_fun():
global a
a = 10
print(a)
a = 20
my_fun()
print(a)
def my_fun(argv): # argv = k
argv.append(2)
k = [7,8]
my_fun(k)
print(k)
def my_fun():
def inner():
k = 78
def inner_non():
nonlocal k
k = 60
def inner_global():
global k
k = 90
k = 0
inner()
print(k)
inner_non()
print(k)
inner_global()
print(k)
k = 1
my_fun()
print(k)
|
str = input()
sub = input()
c = 0
for i in range(0,len(str)-len(sub)+1):
if sub == str[0:3]:
c = c+1
print(c)
|
class User:
def __init__(self, first_name, last_name, age, height, weight, login_attempts=0):
self.first_name = first_name
self.last_name = last_name
self.age = age
self.height = height
self.weight = weight
self.login_attempts = login_attempts
def increment_login_attempts(self):
self.login_attempts += 1
def reset_login_attempts(self):
self.login_attempts = 0
def show_login_attempts(self):
print(f"Number of login attempts = {self.login_attempts}")
def describe_user(self):
print(f"User's name is {self.first_name} {self.last_name}.")
print(f"User's age is {self.age}.")
print(f"User's height is {self.height}.")
print(f"User's weight is {self.weight}.")
def greet_user(self):
print(f"Hello {self.first_name} {self.last_name}")
class Admin(User):
def __init__(self, first_name, last_name, age, height, weight):
self.privileges = Privileges()
super().__init__(first_name, last_name, age, height, weight, login_attempts=0)
class Privileges:
def __init__(self):
self.privileges = ["allowed to add messages",
"allowed to delete users",
"allowed to ban users"]
def show_privileges(self):
print("\nPrivileges:")
if self.privileges:
for privilege in self.privileges:
print("- " + privilege)
albert = Admin('albert', 'einstein', 80, 165, 55)
albert.privileges.show_privileges()
|
import math
from ZeroTwoPi import ZeroTwoPi as ZeroTwoPi
def CartToSph(cn,ce,cd):
'''
CartToSph converts from Cartesian to spherical coordinates
CartToSph(cn,ce,cd) returns the trend (trd)
and plunge (plg) of a line for input north (cn),
east (ce), and down (cd) direction cosines
NOTE: Trend and plunge are returned in radians
CartToSph uses function ZeroTwoPi
Python function translated from the Matlab function
CartToSph in Allmendinger et al. (2012)
'''
pi = math.pi
# Plunge
plg = math.asin(cd) # Eq. 4.13a
# Trend: If north direction cosine is zero, trend
# is east or west. Choose which one by the sign of
# the east direction cosine
if cn == 0.0:
if ce < 0.0:
trd = 3.0/2.0*pi # Eq. 4.14d, trend is west
else:
trd = pi/2.0 # Eq. 4.14c, trend is east
# Else
else:
trd = math.atan(ce/cn) # Eq. 4.14a
if cn < 0.0:
# Add pi
trd = trd+pi # Eq. 4.14b
# Make sure trend is between 0 and 2*pi
trd = ZeroTwoPi(trd)
return trd, plg |
import math
def SphToCart(trd,plg,k):
'''
SphToCart converts from spherical to Cartesian coordinates
SphToCart(trd,plg,k) returns the north (cn),
east (ce), and down (cd) direction cosines of a line.
k: integer to tell whether the trend and plunge of a line
(k = 0) or strike and dip of a plane in right hand rule
(k = 1) are being sent in the trd and plg slots. In this
last case, the direction cosines of the pole to the plane
are returned
NOTE: Angles should be entered in radians
Python function translated from the Matlab function
SphToCart in Allmendinger et al. (2012)
'''
# If line (see Table 4.1)
if k == 0:
cn = math.cos(trd) * math.cos(plg)
ce = math.sin(trd) * math.cos(plg)
cd = math.sin(plg)
# Else pole to plane (see Table 4.1)
elif k == 1:
cn = math.sin(trd) * math.sin(plg)
ce = -math.cos(trd) * math.sin(plg)
cd = math.cos(plg)
return cn, ce, cd |
import numpy as np
def OutcropTrace(strike,dip,p1,XG,YG,ZG):
'''
OutcropTrace estimates the outcrop trace of a plane,
given the strike (strike) and dip (dip) of the plane,
the ENU coordinates of a point (p1) where the plane
outcrops, and a DEM of the terrain as a regular grid
of points with E (XG), N (YG) and U (ZG) coordinates.
After using this function, to draw the outcrop trace
of the plane, you just need to draw the contour 0 on
the grid XG,YG,DG
NOTE: strike and dip should be input in radians
p1 must be an array
XG and YG arrays should be constructed using
the Numpy function meshgrid
'''
# make the transformation matrix from ENU coordinates to
# SDP coordinates. We just need the third row of this
# matrix
a = np.zeros((3,3))
a[2,0] = -np.cos(strike)*np.sin(dip)
a[2,1] = np.sin(strike)*np.sin(dip)
a[2,2] = -np.cos(dip);
# Initialize DG
n, m = XG.shape
DG = np.zeros((n,m))
# Estimate the P coordinate of the outcrop point p1
P1 = a[2,0]*p1[0] + a[2,1]*p1[1] + a[2,2]*p1[2]
# Estimate the P coordinate at each point of the DEM
# grid and subtract P1. Eq. 5.13
for i in range(n):
for j in range(m):
DG[i,j] = P1 - (a[2,0]*XG[i,j] + a[2,1]*YG[i,j] + a[2,2]*ZG[i,j])
return DG |
from constants import BASIC_TAX_EXEMPT
from sales_tax import CalculateTax
# Added items in cart represented in list format
order_one = [
'1 book at 12.49',
'1 music CD at 14.99',
'1 chocolate bar at 0.85'
]
order_two = [
'1 imported box of chocolates at 10.00',
'1 imported bottle of perfume at 47.50'
]
order_three = [
'1 imported bottle of perfume at 27.99',
'1 bottle of perfume at 18.99',
'1 packet of headache pills at 9.75',
'1 box of imported chocolates at 11.25',
]
class ShoppingCart:
def __init__(self, item_list):
self.item_list = item_list
def finalize_cart(self):
"""
Based on the item details passed it loops through all the items and extract necessary item details for
calculating tax and displaying item details and returns array of objects.
"""
cart_details = []
for item in self.item_list:
item_detail_object = {}
item_detail = item.split(' ')
last_index_of_list = len(item_detail) - 1
item_name = self.__get_item_name(item_detail, last_index_of_list)
item_quantity = item_detail[0]
item_price = item_detail[last_index_of_list]
item_detail_object['item_name'] = item_name
item_detail_object['item_quantity'] = item_quantity
item_detail_object['item_price'] = item_price
final_object = self.__check_tax_constraints(item_detail_object, item_detail)
cart_details.append(final_object)
return cart_details
@staticmethod
def __get_item_name(item_list, last_index_of_list):
"""
Gets item name from item list by deleting all the un-wanted details and joins the list.
"""
new_item_list = item_list.copy()
index_of_at = new_item_list.index('at')
new_item_list.pop(last_index_of_list)
new_item_list.pop(index_of_at)
new_item_list.pop(0)
item_name = ' '.join(new_item_list)
return item_name
@staticmethod
def __check_tax_constraints(item_detail_object, item_detail):
"""
Based on the item it modifies flag for calculating taxes if item name exists in tax exempt list then
is_basic_tax is False and if the item contains imported then imported flag will be enabled.
"""
is_basic_tax = True
is_imported = False
item_name = item_detail_object['item_name']
if item_name in BASIC_TAX_EXEMPT:
is_basic_tax = False
if 'imported' in item_detail:
is_imported = True
item_detail_object['is_imported'] = is_imported
item_detail_object['is_basic_tax'] = is_basic_tax
return item_detail_object
# Prints order receipt based on items in the cart
def print_receipt(order_list):
"""
:param order_list: Input param must be list
:return:
"""
if len(order_list) == 0:
print("No items in cart")
else:
shopping_cart = ShoppingCart(order_list)
cart_details = shopping_cart.finalize_cart()
cart_after_tax = CalculateTax().calculate_total_tax(cart_details)
total_sales_tax = []
total_price = []
print('-------------- AISLE ---------------')
for item in cart_after_tax:
total_sales_tax.append(item['total_tax'])
total_price.append(item['item_price'])
print(f"{item['item_quantity']} {item['item_name']}: {'{:.2f}'.format(item['item_price'])}")
print(f'Sales Taxes: {"{:.2f}".format(sum(total_sales_tax))}')
print(f'Total: {sum(total_price)}')
print('------------ Thank You! ------------')
print_receipt(order_one)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# função que verifica se o programa está infectado
def infected(path, pathInfected):
# score conta as chamadas diferentes
# total conta o número de chamadas do arquivo
score, total = 0, 0
# abre o arquivo sadio para leitura
file = open(path, "r")
# abre o arquivo infectado para leitura
fileInfected = open(pathInfected, "r")
# percorerá todo o arquivo infectado, após o arquivo sadio ser percorrido
for lineInfe in fileInfected:
# essa flag será utilizada quando for encontrado linhas iguais
flag = False
# percorerá todo o arquivo sadio
for line in file:
# compara a linha do infectado com a linha do sadio
if line == lineInfe:
# se as linhas forem iguais a flag passa a ser verdadeira
flag = True
break
# se a flag estiver falsa incrementa o score, já que não foi encontrada a linha no sadio
if flag == False:
score += 1
# conta o total de chamadas
total += 1
# converte o total em ponto flutuante para que se possa ter o resultado da divisão um número não inteiro
total = total / 1.0
# probabilidade do programa estar infectado
print(score / total) * 100, "%"
# função que gera as janelas
def sliding_window(path, name):
# começo da janela
begin = 0
# final da janela
end = 10
# conta o numero de system calls no arquivos
num_lines_file = sum(1 for line in open(path))
# numero de conjuntos de 10
number_of_windows = num_lines_file - 10 + 1
i = 1
# loop ate vc atingir o numero de conjuntos de 10 que vc quer
while i <= number_of_windows:
# abre o arquivo para leitura
input_file = open(path, "r")
# abri o arquivo para add (desse jeito vc sempre poe no final a nova entrada)
output_file = open("window-" + name + ".txt", "a")
# cria um array vazio
result = []
# for para ler cada linha do arquivo e uma variavel j que vai receber o valor da linha do arquivo
for j, line in enumerate(input_file):
# se a linha tiver entre a sua janela
if begin <= j < end:
# add ela ao array (removendo o \n da linha)
result.append(line.rstrip())
# junta todas as entradas do array em uma string separada por espaco
result = " ".join(result)
# escreve a string para seu arquivo
output_file.write(result + "\n")
# fecha o arquivo
input_file.close()
# fecha o arquivo
output_file.close()
# incrementa o i e a janela
i += 1
begin += 1
end += 1
# abre o arquivo ls para escrita
output = open("mv.txt", "w")
# abre o arquivo ls sem os id para escrita
outputWithoutID = open("mv-without-id.txt", "w")
# abre o arquivo grep para escrita
outputGrep = open("cp.txt", "w")
# abre o arquivo grep semos id para escrita
outputGrepWithoutID = open("cp-without-id.txt", "w")
# abre o primeiro arquivo ls gerado
with open("log_cp.txt") as file:
# percore cada linha do arquivo
for line in file:
# escreve apenas o id e a system call do arquivo ls em outro arquivo
output.write(str(line.split("(")[0]) + "\n")
# escreve apenas as system call de ls em outro arquivo
outputWithoutID.write(line[:line.find("(")].split(" ")[1] + '\n')
# fecha o arquivo
file.close()
# fecha o arquivo
output.close()
with open("log_mv.txt") as file:
# abre o primeiro arquivo grep gerado
for line in file:
# escreve apenas o id e a system call do arquivo grep em outro arquivo
outputGrep.write(line.split("(")[0] + "\n")
# escreve apenas as system call de ls em outro arquivo
outputGrepWithoutID.write(line[:line.find("(")].split(" ")[1] + '\n')
# fecha o arquivo
file.close()
# fecha o arquivo
outputGrep.close()
# fecha o arquivo
outputWithoutID.close()
# fecha o arquivo
outputGrep.close()
# fecha o arquivo
outputGrepWithoutID.close()
# chama a função que gera as janelas de ls
sliding_window("mv-without-id.txt", "mv")
# chama a função que gera as janelas de grep
sliding_window("cp-without-id.txt", "cp")
# chama a função que detecta se o programa está infectado
infected("window-cp.txt", "window-mv.txt")
|
#finding the fibonacci series using recursive method.
#defining the function.
def fibonacci(n):
#if the given input is less than or equal to 1 then return the following.
if n <= 1:
return n
#if the given input is greater than 1 then return the following.
else:
return (fibonacci(n-1) + fibonacci(n-2))
#storing the input as integer datatype given by user in a variable.
n= int(input("Enter you number = "))
#printing the result.
print("fibonacci series is -")
for i in range(n):
print(fibonacci(i))
#end of code.
|
class Clock(object):
def __init__(self, hour, minute):
extra_hours, minute = self.__calculate_minute(minute)
hour = self.__calculate_hour(extra_hours, hour)
self.hour = hour
self.minute = minute
def __calculate_minute(self, minute):
result = (0, 0)
if minute >= 0:
final_minute = minute % 60
extra_hours = self.__extra_hours(minute)
result = (extra_hours, final_minute)
else:
hours_for_decrement, minute = self.__normalize_minute(minute)
result = (hours_for_decrement, minute)
return result
def __calculate_hour(self, extra_hours, hour):
hour += extra_hours
hour = self.__normalize_hour(hour)
return hour % 24
def __normalize_minute(self, minute):
hours_for_decrement = 0
while (minute < 0):
minute += 60
hours_for_decrement -= 1
return (hours_for_decrement, minute)
def __normalize_hour(self, hour):
while (hour < 0):
hour += 24
return hour
def __extra_hours(self, minutes):
extra_hours = 0
while(minutes > 59):
minutes -= 60
extra_hours += 1
return extra_hours
def __repr__(self):
hour_representation = self.__hour_representation(self.hour)
minute_representation = self.__minute_representation(self.minute)
return "{0}:{1}".format(hour_representation, minute_representation)
def __hour_representation(self, hour):
if hour >= 0 and hour < 10:
return '0' + str(hour)
elif hour >= 10 and hour < 24:
return str(hour)
def __minute_representation(self, minute):
if minute >= 0 and minute < 10:
return '0' + str(minute)
elif minute > 9 and minute < 60:
return str(minute)
def __eq__(self, other):
return self.hour == other.hour and self.minute == other.minute
def __add__(self, minutes):
return Clock(self.hour, self.minute + minutes)
def __sub__(self, minutes):
return Clock(self.hour, self.minute - minutes)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.