text stringlengths 37 1.41M |
|---|
import random
def Name():
a = random.randint(0, 5)
Names = ["Bob", "Robert", "Roberto", "Roberta", "Robin", "Rose"]
print(Names[a])
def Menu():
s = random.randint(0, 2)
m = random.randint(0, 3)
d = random.randint(0, 1)
sides = ["salad", "soup", "bread"]
mainCourse = ["salmon", "pizza", "pasta", "rice"]
dessert = ["ice cream", "a sorbet"]
print("Your menu is " + sides[s] + ", " + mainCourse[m] + ", and " + dessert[d] + ".")
def Haiku():
a = random.randint(0, 1)
b = random.randint(0, 3)
c = random.randint(0, 1)
d = random.randint(0, 2)
e = random.randint(0, 0)
fiveArticle = ["The", "A"]
fiveNoun = ["crow", "horse", "dog", "tree"]
fiveAdverb = ["sad.", "lonely."]
print(fiveArticle[a] + " " + fiveNoun[b] + " is " + fiveAdverb[c])
sevenVerb = ["jumps", "sings", "dies"]
sevenAdverb = ["quietly, alone."]
print("It " + sevenVerb[d] + " " + sevenAdverb[e])
print("It's snowing on Mt. Fuji.")
Haiku()
|
def factor(num1, num2):
if num2 % num1 == 0:
return True
else:
return False
def FizzBuzz(num):
if num == 0:
print("Bad number")
elif factor(15, num):
print("FizzBuzz")
elif factor(5, num):
print("Buzz")
elif factor(3, num):
print("Fizz")
else:
print("Bad number")
repeat = True
while repeat:
number = input("Input a number: ")
if number == "exit":
repeat = False
else:
if number.isnumeric():
num = int(number)
FizzBuzz(num)
else:
print("Not a number")
|
import random
#reads file
def readFile(fileName):
f = open(fileName, "r")
content = f.readline()
return content
#writes file
def writeFile(fileName, content):
f = open(fileName, "w")
f.write(content)
f.close()
#interprets the file so that the file is put into a dictionary format, and returns a dictionary
def readScoreboard():
scoreboard = readFile("scoreboard.txt")
scoreTable = {}
word = ""
isPerson = True
for letter in scoreboard:
if letter != " ":
word = word + letter
else:
if isPerson:
scoreTable[word] = 0
person = word
isPerson = False
else:
scoreTable[person] = int(word)
isPerson = True
word = ""
return scoreTable
#writes the scoreboard so that it can be read by the readScoreboard function
def writeScoreboard(scoreboard):
content = ""
for name, number in scoreboard.items():
content = content + name + " " + str(number) + " "
writeFile("scoreboard.txt", content)
#prints the scoreboard ingame after the user loses
def printScoreboard(scoreboard):
for name, number in scoreboard.items():
print("User: " + name + "\tScore: " + str(number))
#reads the scoreboard, asks the user for their name, and sets their score to zero
scoreboard = readScoreboard()
missed = False
user = input("Enter a name: ")
score = 0
while not missed:
#user guesses heads or tails
guess = input("\nHeads or tails? ")
#computer generates heads or tails
randomNum = random.randrange(1, 3)
if randomNum == 1:
randomNum = "heads"
else:
randomNum = "tails"
#if the user guesses correctly, their score increases; else, the game ends
if guess.lower() == randomNum:
score += 1
print("Good job")
else:
print("Game over")
missed = True
#replace the scoreboard's score if the user's score is higher
if user in scoreboard:
if score > scoreboard[user]:
scoreboard[user] = score
else:
scoreboard[user] = score
#prints the highscore table
print("\nHighscores")
printScoreboard(scoreboard)
#writes the table to the file
writeScoreboard(scoreboard)
|
roman_numerals = {"M":1000,"CM":900,"D":500,"CD":400,"C":100,"XC":90,"L":50,"XL":40,"X":10,"V":5,"IV":4,"I":1}
def roman_int(user_choice):
if user_choice == "1":
user_roman = input("What numeral would you like to convert?\n").upper()
resultI = 0
for k,v in roman_numerals.items():
if user_roman == k:
resultI += roman_numerals.get(user_roman)
else:
for i in user_roman:
if i in roman_numerals.keys():
if i == k:
resultI += v
print(resultI)
|
p = int(raw_input())
factorial = 1
for i in range(1,p+ 1):
factorial = factorial*i
print(factorial)
|
class stack_min:
num_of_stacks = 0
def __init__(self):
self.top = None
self.min_stack = []
stack_min.num_of_stacks+=1
class stack_node:
def __init__(self,data= None):
self.data = data
self.next = None
def push(self,data):
if self == None:
return None
if self.top == None:
self.min_stack.append(data)
n = stack_min.stack_node(data)
n.next = self.top
self.top = n
if n.data < self.min_stack[len(self.min_stack) -1]:
self.min_stack.append(self.top.data)
def pop(self):
if self.isEmpty:
return None
tmp = self.top
if tmp.data == self.min_stack[len(self.min_stack)-1]:
self.min_stack.pop()
self.top = self.tmp.next
return tmp
def minn(self):
if len(self.min_stack) == 0:
return None
else:
return self.min_stack[len(self.min_stack)-1]
def peek(self):
return self.top.data
def isEmpty(self):
if self.top == None:
return True
else:
return False
stack = stack_min()
for i in range(1,20):
stack.push(i)
stack.push(-1)
print(stack.minn())
|
from LinkedList import *
from math import *
#Stack approach.
def palindrome(LL):
sta = stack()
tmp = LL.head
while tmp!=None:
sta.push(tmp)
tmp = tmp.next
tmp = LL.head
while tmp != None and tmp == sta.peek():
tmp = tmp.next
sta.pop()
if sta.peek() == None and tmp == None:
return True
else:
return False
#Reverse LL approach.
def palindrome1(LL):
rev = LL
rev.reverse()
rev = rev.head
tmp = LL.head
while tmp != None and rev == tmp:
rev = rev.next
tmp = tmp.next
if rev == None and tmp == None:
return True
else:
return False
#Length based approach. Assuming no size() or len() as that would be most complex case.
def palindrome2(LL):
length = 0
far = LL.head
while far != None:
far = far.next
length += 1
length = ceil(length/2)
far = LL.head
for i in range(length):
far = far.next
near = LL.head
while far != None and near == far:
near = near.next
far = far.next
if far == None:
return True
else:
return False
LL = LinkedList()
LL.append(Node('a'))
LL.append(Node('b'))
LL.append(Node('a'))
print(palindrome1(LL))
|
#Array ascii method no bit vector (original way I coded it).
def isUnique1(st):
if len(st) > 128:
return False
list = [0] * 128
for c in st:
list[ord(c)]+=1
if list[ord(c)] > 1:
return False
return True
#Sort method
def isUnique2(st):
st = sorted(st)
for i in range(1, len(st)):
if st[i] == st[i-1]:
return False
return True
from bitarray import bitarray
#Bitvector ascii method.
def isUnique3(st):
if len(st) > 128:
return False
bitarr = bitarray(128)
for c in st:
if bitarr[ord(c)] == True:
return False
else:
bitarr[ord(c)] = True
return True
print(isUnique3("hh"))
|
class Person:
def __init__(self, name):
self.name = name
class Employee(Person):
def __init__(self,name, position):
super(Employee, self).__init__(name) #this is better than the hard coding way of initialization, because the sub class may be inherited from more than one parent class
self.position = position
thomas = Employee('Thomas','Manager')
thomas.name = "David"
print(thomas.name)
print(thomas.position) |
import tensorflow as tf
import numpy as np
import collections
#logistic = lambda x: 1.0/(1+np.exp(-x))
#print(logistic(3))
# Example 1:
#j = tf.constant(0)
#c = lambda i: tf.less(i, 9) # loop termination condition
#b = lambda i: tf.add(i, 1) # loop body: loop body that is executed in each loop
#r = tf.while_loop(c, b, [j]) # [] includes the initial condition of loop
#with tf.Session() as sess:
# print(sess.run(r))
# How to understand this: in each loop, the value of j will be passed to c and b.
# this loop function can be unfolded by:
# j
# while (c(j)):
# j=b(j)
# question: what is the body is very complicated?
# see here: https://stackoverflow.com/questions/47955437/tensorflow-stacking-tensors-in-while-loop
# the loop body can be defined as a function
# the resulted code is shown in example 3.
# Example 2:
#Pair = collections.namedtuple('Pair', 'j, k')
#ijk_0 = (tf.constant(0), Pair(tf.constant(1), tf.constant(2)))
#c = lambda i, p: i < 10
#b = lambda i, p: (i + 1, Pair((p.j + p.k), (p.j - p.k)))
#ijk_final = tf.while_loop(c, b, ijk_0)
#with tf.Session() as sess:
# print(sess.run(ijk_final))
# How to understand the code:
# the loop body is a tuple made by all relevant variables.
# Example 3:
def body(i,p):
return (i + 1, Pair((p.j + p.k), (p.j - p.k)))
Pair = collections.namedtuple('Pair', 'j, k')
ijk_0 = (tf.constant(0), Pair(tf.constant(1), tf.constant(2)))
c = lambda i, p: i < 10
b = lambda i, p: body(i,p)
ijk_final = tf.while_loop(c, b, ijk_0)
with tf.Session() as sess:
print(sess.run(ijk_final))
|
"""
a class of stars is written in this module
"""
import const_and_inp
class Star:
def __init__(self, star_id, ra, dec, mag):
"""
the star object characterizes 5 attributes, id, ra, dec, mag and distance,
the distance we count as having ra and dec
"""
self.id = star_id
self.ra = ra
self.dec = dec
self.mag = mag
self.distance = ((self.ra-const_and_inp.fov_v)**2 +
(self.dec-const_and_inp.fov_h)**2)**0.5
def __repr__(self):
return f'{self.id}, {self.ra}, {self.dec}, {self.mag}, {self.distance}'
|
import itertools
import copy
# Takes a list of integers shipments and an int capacity and returns a list of shipments that best fit the given capacity.
def get_optimal_load(capacity, shipments):
# Get all unique combinations of shipments that are less than or equal to the truck's capacity.
combinations = [el for i in range(len(shipments), 0, -1) for el in itertools.combinations(shipments, i) if sum(el) <= capacity]
maximum, index, result = 0, 0 , 0
# Test each combination.
for combination in combinations:
total = sum(combination)
if total > maximum:
maximum = total
result = index
index += 1
return [] if combinations == [] else list(combinations[result])
def remove_loaded(loaded, shipments):
for load in loaded: shipments.remove(load) if load in shipments else None
return shipments
def distribute_shipments(trucks, shipments):
if trucks == [] or shipments == []:
return [[]]
shipments_cp = copy.copy(shipments)
if len(trucks) == 1:
return [get_optimal_load(trucks[0], shipments_cp)]
optimal_shipment = []
trucks_cp = copy.copy(trucks)
truck_arrangements = list(itertools.permutations(trucks, len(trucks))) # Get all possible arrangements of the trucks.
current_shipment = []
index, maximum, capacity_filled = 0, 0, 0
for arrangement in truck_arrangements:
current_shipment.append([])
capacity_filled = 0
for truck in arrangement:
loaded = get_optimal_load(truck, shipments_cp)
current_shipment[index].append((truck, loaded) )
shipments_cp = remove_loaded(loaded, shipments_cp)
capacity_filled += sum(loaded)
if capacity_filled > maximum:
maximum = capacity_filled
optimal_shipment = current_shipment[index]
index += 1
shipments_cp = copy.copy(shipments)
result = []
# Sort the optimal_shipment to match the order of the original trucks list and return it.
for i in range(len(trucks)):
for truck in optimal_shipment:
if truck[0] == trucks[i]:
result.append(truck[1])
return result |
name_file = open("name.txt", "w")
user_name = input("Please enter your name:")
print(user_name, file=name_file)
name_file.close()
name_file = open("name.txt", "r")
name = name_file.read().strip()
name_file.close()
print(name)
|
# conditional
a = 10
if 0 < a < 11:
print('cool')
b = int(input('input number : '))
if (b > 10):
pass
elif (b < 10):
print(f'input number is {b}')
else:
print('input number is 10')
# loop
print('loop in list')
l = [1,2,3,4,5]
for i in l:
print(i)
print('loop in tuple')
t = (1,2,3,4,5)
for i in t:
print(i)
print('loop in dict')
d = {1: 'one', 2: 'two', 3: 'three'}
for i in d:
print(f'{i} : {d[i]}') |
print ("put the measurements of you fish tankin cm centimeters" )
print ("hegiht")
heigth =eval(input())
h = heigth
print ("deep")
deep=eval(input())
d = deep
print ("large")
large= eval(input())
l = large
mileliters = d*l*h
liters = mileliters /1000
print ("liters of fish tank have ")
print(liters)
if d == h ==l:
print ("you fish tank are cube ")
else :
print ("you acurium are a rectangle ")
print ("and have in galons :")
galons = liters /3.73
print (galons)
|
"""Reactor with socket.select
First, instantiate a reactor.
Next, register a file descriptor integer and corresponding
object with the reactor.
Then, register read or write on the integer (and therefore object)
in order to have that object called on that read or write event
Implement the read_event / write_event interface in that object
Unregister read or write if you don't want the notification to happen again
A read_event or write_event should never cause a readerwriter to dissappear,
because there could be another event in the queue for it, retrieved in the
same batch of messages. In this case a reference to that object would
still be hanging around.
Timers: start_timer(seconds, object-which-implements-timer_event())
cancel_timers(objects-which-you-started-one-or-more-timers-for-earlier)
Timer objects, on the other hand, may cause things to dissapear.
Only one timer event is ever retrieved at a time, so there's still
time to cancel an object's timers, and therefore possible to destroy it.
"""
import select
import time
DEFAULT_TIMEOUT = .03 # how long after a timer comes up it may be delayed
DEFAULT_TIMER_SLEEP = .01
class Reactor(object):
def __init__(self):
self.fd_map = {}
self.wait_for_read = set()
self.wait_for_write = set()
self.timers = []
def reg_read(self, fd):
if not isinstance(fd, int): fd = fd.fileno()
self.wait_for_read.add(fd)
def reg_write(self, fd):
if not isinstance(fd, int): fd = fd.fileno()
self.wait_for_write.add(fd)
def unreg_read(self, fd):
if not isinstance(fd, int): fd = fd.fileno()
try: self.wait_for_read.remove(fd)
except KeyError: pass
def unreg_write(self, fd):
if not isinstance(fd, int): fd = fd.fileno()
try: self.wait_for_write.remove(fd)
except KeyError: pass
def start_timer(self, delay, dinger):
self.timers.append((time.time() + delay, dinger))
def cancel_timers(self, dinger):
"""Takes an object which impements .timer_event()"""
self.timers = filter(lambda (t, x): x != dinger, self.timers)
def add_readerwriter(self, fd, readerwriter):
self.fd_map[fd] = readerwriter
def poll(self, timeout=DEFAULT_TIMEOUT, timer_sleep=DEFAULT_TIMER_SLEEP):
"""Triggers every timer, and the first read or write event that is up
Returns False if no events were hit
Returns None if no events are registered
timeout is the timeout passed to select in seconds
timer_sleep is the time slept if no select is necessary because we're just
using timers, (no io registered) to prevent thrashing the cpu
"""
if not any([self.wait_for_read, self.wait_for_write, self.timers]):
return None
if not any([self.wait_for_read, self.wait_for_write]):
time.sleep(timer_sleep)
return False
now = time.time()
while True:
self.timers.sort(key=lambda x: x[0])
timerlist = self.timers[:]
for t, dinger in timerlist:
if t < now:
self.timers.remove((t, dinger))
dinger.timer_event()
break
else:
break
read_fds, write_fds, err_fds = select.select(self.wait_for_read, self.wait_for_write, [], timeout)
if not any([read_fds, write_fds, err_fds]):
return False
for fd in read_fds:
self.fd_map[fd].read_event()
return self.fd_map[fd]
for fd in write_fds:
self.fd_map[fd].write_event()
return self.fd_map[fd]
return False
|
'''
Given an array arr of N integers. Find the contiguous sub-array with maximum sum.
Input:
The first line of input contains an integer T denoting the number of test cases. The description of T test cases follows. The first line of each test case contains a single integer N denoting the size of array. The second line contains N space-separated integers A1, A2, ..., AN denoting the elements of the array.
Output:
Print the maximum sum of the contiguous sub-array in a separate line for each test case.
Constraints:
1 ≤ T ≤ 110
1 ≤ N ≤ 106
-107 ≤ A[i] <= 107
Example:
Input
2
5
1 2 3 -2 5
4
-1 -2 -3 -4
Output
9
-1
'''
#DCP7
def maxSubArraySum(a,size):
max_so_far =a[0]
curr_max = a[0]
for i in range(1,size):
curr_max = max(a[i], curr_max + a[i])
max_so_far = max(max_so_far,curr_max)
return max_so_far
if __name__ == "__main__":
ans = 0
ans_list = []
test_cases = int(input())
for i in range(test_cases):
n = int(input())
a = list(map(int,input().split()))
ans = maxSubArraySum(a,n)
ans_list.append(ans)
for i in range(len(ans_list)):
print(ans_list[i])
|
'''
Given two arrays X and Y of positive integers, find number of pairs such that xy > yx (raised to power of) where x is an element from X and y is an element from Y.
Input:
The first line of input contains an integer T, denoting the number of test cases. Then T test cases follow. Each test consists of three lines. The first line of each test case consists of two space separated M and N denoting size of arrays X and Y respectively. The second line of each test case contains M space separated integers denoting the elements of array X. The third line of each test case contains N space separated integers denoting elements of array Y.
Output:
Corresponding to each test case, print in a new line, the number of pairs such that xy > yx.
Constraints:
1 ≤ T ≤ 100
1 ≤ M, N ≤ 105
1 ≤ X[i], Y[i] ≤ 103
Example:
Input
1
3 2
2 1 6
1 5
Output
3
'''
#DCP11
def comopare_power(a,b,m,n):
count = 0
for i in range(len(a)):
for j in range(len(b)):
if pow(a[i],b[j])>pow(b[j],a[i]):
count += 1
return count
if __name__ == "__main__":
ans = 0
ans_list = []
test_cases = int(input())
for i in range(test_cases):
n , m = map(int,input().split())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
ans = comopare_power(a,b,m,n)
ans_list.append(ans)
for i in range(test_cases):
print(ans_list[i], end = " ")
|
"""Weekdays in December"""
import sys
import datetime
def get_weekday(number):
return datetime.date(2017, 12, number).weekday()
for input in sys.stdin.readlines():
values = input.split(' ')
for i, value in enumerate(values):
if value == "end":
sys.exit(0)
elif value == "December":
if value[i+1] != "end":
if int(values[i+1]) <= 31 and int(values[i+1]) >= 1:
weekdays = ["Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday"]
sys.stdout.write(weekdays[get_weekday(int(values[i+1]))]+"\n")
|
import turtle
wn=turtle.Screen()
t1=turtle.Turtle()
def drawSquareAt(x,y,size):
t1.penup()
t1.goto(x,y)
t1.pendown()
for a in range(0,4):
t1.fd(size)
t1.rt(90)
def drawTriangleAt(x,y,size):
t1.penup()
t1.goto(x,y)
t1.pendown()
for a in range(0,3):
t1.fd(size)
t1.lt(120)
def drawStarAt(x,y,size):
t1.penup()
t1.goto(x,y)
t1.pendown()
for a in range(0,5):
t1.fd(size)
t1.rt(144)
drawSquareAt(-470,0,100)
drawTriangleAt(-100,0,100)
drawStarAt(370,0,100) |
# https://www.hackerrank.com/challenges/validating-credit-card-number/problem
# Those two lines make the code 1:1 compatiple with hackerrank
f = open('./input/test_case_5.txt')
input=f.readline
import re
def validate(cnum):
if re.match('\d{5}-', cnum)!=None:
return False
if re.match('-\d{5}', cnum)!=None:
return False
if len(re.findall('--', cnum)) != 0:
return False
cnum=cnum.replace('-','')
if cnum[0] not in ['4', '5', '6']:
return False
if len(cnum)!=16:
return False
for i in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:
if i*4 in cnum:
return False
if re.match('^\d+$', cnum)==None:
return False
return True
N = int(input())
for _ in range(N):
cnum=input().rstrip()
if validate(cnum):
print("Valid")
else:
print("Invalid") |
def iterativeFactorial(x):
if(x==0): return 1
factorial = 1
for i in range(1,x+1):
factorial*=i
return factorial
def recursiveFactorial(x):
if(x==0): return 1
return x * recursiveFactorial(x-1)
print(iterativeFactorial(5))
print(recursiveFactorial(5))
|
"""
Inheritance tools.
------------------
This sets up inheritance of the docstrings for use when we inherit
classes. This makes it simple to add further details to or replace the
docstring present on the base class.
"""
def update_docstring(method_name, content, append=True):
r"""
Update docstring of (an inherited) class method.
For subclasses that use hooks to change behavior of superclass methods.
:param append: If true, append to the docstring, else overwrite it entirely.
Example::
class Base(object):
def method(self, **kwargs):
'''Print the base_arg kwarg.'''
print kwargs.pop('base_arg')
self.process_additional(**kwargs)
def process_additional(self, **kwargs):
pass
@update_docstring('method', '\n\nAlso print the sub_arg kwarg.', append=True)
class Subclass(Base):
def process_additional(self, **kwargs):
print kwargs['sub_arg']
@update_docstring('method', 'Print all kwargs.', append=False)
class Allprinter(Base):
def process_additional(self, **kwargs):
for _, value in kwargs.items():
print value
"""
def wrapper(cls):
"""Update the method docstring and return the class."""
if append:
getattr(cls, method_name).__func__.__doc__ = ''
else:
getattr(cls, method_name).__func__.__doc__ = content
return cls
return wrapper
|
size = 8
a = [2 * n for n in range(size * size)]
Sums = [0 for i in range(3)]
def t():
for k in range(3):
Sum = 0
for i in range(size):
for j in range(size):
tmp = a[i * size + j]
Sum += tmp
Sums[0] += Sum
t()
print(Sums)
|
def t():
for j in range(len(a)):
for i in range(len(b)):
c[j] = b[i] + a[j]*2
a = [1., 2., 3.]
b = [4., 5., 6.]
c = [0., 0., 0.]
t()
print(c)
d = [10., 20., 30.]
for i in range(len(a)):
a[i] = d[i]
t()
print(c)
|
size = 8
a = [2 * n for n in range(size)]
Sums = [0]
def t():
for k in range(3):
Sum = 0
x = 0
for i in range(size):
x = i
Sum += a[i]
Sums[0] += Sum + x
t()
print(Sums)
|
#Object to be clustered
class DataObject:
def __init__(self, name, values):
self.name = name
self.values = values
def __str__(self):
return self.name
def __repr__(self):
return self.name
#Two clusters (from and to) and the distance between the two clusters
class DistanceMeasurement:
def __init__(self, fm, to, distance):
self.fm = fm
self.to = to
self.distance = distance
def display(self):
print "From: " + str(self.fm) + " To: " + str(self.to) + " Distance: " + str(self.distance)
def displayTo(self):
print str(self.to)
def displayFm(self):
print (self.fm)
def __str__(self):
return "fm:" + str(self.fm) + " to:" + str(self.to) + " " + str(self.distance)
class Node:
def __init__(self, left, right, distance, cluster):
self.left = left
self.right = right
self.distance = distance
self.cluster = cluster
def __str__(self):
return str(self.cluster)
def __repr__(self):
return str(self.cluster)
def displayNode(self):
print 'L: ' + str(self.left) + ' R: ' + str(self.right) + ' D: ' + str(self.distance) + ' C: ' + str(self.cluster)
|
# По длинам трех отрезков, введенных пользователем, определить возможность существования треугольника,
# составленного из этих отрезков. Если такой треугольник существует, то определить, является ли
# он разносторонним, равнобедренным или равносторонним.
side_a = int(input('Введите первую сторону треугольника: '))
side_b = int(input('Введите вторую сторону треугольника: '))
side_c = int(input('Введите третью сторону треугольника: '))
#проверка на существования треугольника
if not (side_a <= side_b + side_c) :
print('Треугольника не существует')
elif not (side_b <= side_a + side_c):
print('Треугольника не существует')
elif not (side_c <= side_a + side_b):
print('Треугольника не существует')
else:
#проверка на тип треугольника
if (side_a == side_b or side_a == side_c or side_b == side_c):
if (side_a == side_b and side_a == side_c):
print('Треугольник равносторонний')
else:
print('Треугольник равнобедренный')
else:
print('Треугольник разносторонним') |
#Задание 2
#По введенным пользователем координатам двух точек
#вывести уравнение прямой вида y = kx + b, проходящей через эти точки.
# Уравнение прямой имеет вид (y-y1) / (y2-y1) = (x - x1) / (x2 - x1)
# => k = (y1 - y2)/-c b = (x1*y2 - x2*y1) / -c c = (x2-x1)
#Точка 1
x1 = int(input('x1 = '))
y1 = int(input('y1 = '))
#Точка 2
x2 = int(input('x2 = '))
y2 = int(input('y2 = '))
if (x1 == x2 and y1 == y2): #если совпали точки
print('Точки должны быть различны')
elif (x1 == x2): #Если прямая параллельна оси x
print(f'y={x1}')
elif (y1 == y2): #Если прямая параллельна оси y
print(f'x={y1}')
else:
c = (x2-x1)
k = (y1 - y2) / -c
b = (x1*y2 - x2*y1) / -c
print(f'y={k}x + ({b})')
|
def func(a, b) -> str:
if (a==b):
return f'{a}'
elif (a > b): #по возрастанию
return f'{a}, {func(a-1, b)}'
elif (a < b): #по убыванию
return f'{a}, {func(a+1, b)}' #f строки
print(func(8, 10000)) #глубина рекурсии 1000
|
class Point:
"""Point Model"""
def __init__(self, position):
self.__charge = -1
self.__position = position
self.__distance = []
def __str__(self):
return "Point: " + self.__position
@property
def charge(self):
return self.__charge
@charge.setter
def charge(self, charge):
self.__charge = charge
@property
def position(self):
return self.__position
@position.setter
def position(self, position):
self.__position = position
@property
def distance(self):
return self.__distance
@distance.setter
def distance(self, distance):
self.__distance = distance
|
graph = {
1:[2,3,4],
2:[],
3:[5],
4:[6],
5:[],
6:[]
}
visited = []
queue = []
def bfs( node):
visited.append(node)
queue.append(node)
while queue:
s = queue.pop(0)
print (s, end = " ")
for neighbour in graph:
if neighbour not in visited:#neighbour group ar modde ase kina
visited.append(neighbour)
queue.append(neighbour)
bfs(1)
|
weather_tbl=[] #for weather
play_tbl=[] #for play
n=int(input("Enter number of dataset:"))
for i in range(n):
weather=input("Enter weather name:")
weather_tbl.append(weather.lower())
play=input("Enter paly or not:")
play_tbl.append(play.lower())
t_rainy_y=t_rainy_n=0
t_y=t_n=0
t_rainy=0
for i in range(n):
if play_tbl[i]=="yes":
t_y +=1
else:
t_n +=1
if weather_tbl[i]=="rainy":
t_rainy +=1
if play_tbl[i]=="yes":
t_rainy_y +=1
else:
t_rainy_n +=1
p_rainy_y=(t_rainy_y/t_y)
p_y=(t_y/n)
p_rainy=(t_rainy/n)
p_rainy_n=(t_rainy_n/t_n)
p_n=(t_n/n)
p_y_rainy=(p_rainy_y*p_y)/p_rainy
p_n_rainy=(p_rainy_n*p_n)/p_rainy
if p_n_rainy>p_y_rainy:
print("Player will play,if it not rainy")
else:
print("player will not play if it rainy")
|
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
openParen = '([{'
closeParen = ')]}'
parenStack = []
for p in s:
if p in openParen:
parenStack.append(p)
elif p in closeParen:
if len(parenStack) == 0:
return False
last = parenStack.pop()
if p == ')' and last == '(':
pass
elif p == ']' and last == '[':
pass
elif p == '}' and last == '{':
pass
else:
return False
if len(parenStack) > 0:
return False
else:
return True
if __name__ == '__main__':
s= Solution()
print(s.isValid('()'))
print(s.isValid('()[]{}'))
print(s.isValid('{[]}'))
print(s.isValid('([)]'))
print(s.isValid('(]'))
print(s.isValid('('))
print(s.isValid(''))
|
import random
class Stack:
def __init__(self):
self.container = []
def isEmpty(self):
return self.container == []
def push(self, item):
self.container.append(item)
def pop(self):
return self.container.pop()
def peek(self):
return self.container[len(self.container) - 1]
def size(self):
return len(self.container)
def pushMethod(self, n, m):
for i in range(0, n, m):
self.push(random.randint(1,10))
print(self.size())
# return stack1
def popMethod(self, n, m):
for i in range(0, n, m):
self.pop()
print(self.size())
def peekMethod(self):
print(self.peek())
def checkIfEmpty(self):
if self.isEmpty():
print("Stack is empty.")
else:
print("Stack is not empty - Size: " + str(self.size()))
'''
Because push and pop both work with the same end of the stack, the front, the complexity will be constant, O(n).
This also means that isempty and size will also be constant time complexities.
'''
'''
experimented with different parameter sizes
'''
stack1 = Stack()
stack1.pushMethod(10000000,10)
stack1.popMethod(1000000, 10)
stack1.peekMethod()
stack1.checkIfEmpty()
|
# Given a non negative integer number num.
# For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in
# their binary representation and return them as an array.
class Solution:
def countBits(self, num: int):
return [self.hammingWeight(n) for n in range(num + 1)]
def hammingWeight(x):
x -= (x >> 1) & 0x5555555555555555
x = (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333)
x = (x + (x >> 4)) & 0x0f0f0f0f0f0f0f0f
return ((x * 0x0101010101010101) & 0xffffffffffffffff) >> 56
|
for x in range(3):
user=input("Ingresa el usuario");
pas=input("ingresa paswors");
if(user=="alex" and pas=="3ct"):
print("Bienvenido" + user);
break;
else:
print("verificar datos");
|
numero = int(input("dame el numero de la taba "));
x=1;
while x<=10:
# print("el resultado de "+ str(numero) +" * "+str(x)+" es " +str(x*numero));
print(f'{x * numero}');# Epesiones
x+=1;
|
print('----------------------------------')
year=int(input("请输入年份:"))
month=int(input("请输入月份:"))
day=int(input("请输入日期:"))
monthlist=[31,28,31,30,31,30,31,31,30,31,30,31]
sum=day
if year % 4==0 and year % 100 !=0 or year % 400==0:# or 表示只要满足两方一个条件即可,即为闰年。
monthlist[1]=29
for i in range(month-1):# range(0)=[] range(1)=[0] range(2)=[0,1] 把列表里所有的值取出来,print一次,去一次。
sum=sum+monthlist[i]
#sum=sum+day
else :
for i in range(month-1):
sum=sum+monthlist[i]
#sum=sum+day
print('今天是今年的第',sum,'天')
|
sum=0
for i in range(100):
if i %2 !=0:
sum=sum+i
print(sum)#在这里打印就是每循环一次就打印一次
else:
continue
#倘若在这里打印,那么直接将所有循环后相加的和打印出来
|
'''x={'陈':1,'思':2,'未':3,'帅':4}
for i in x:
print(x[i])'''
x=[59,70,58,60,61]
a=[]
b=[]
for i in x :
if i>=60:
a.append(i)
else:
b.append(i)
print('不小于60的数组:',a)
print('小于60的数组:',b)
#print(a,end='@')
#print(b,end='@')
|
"""
Functions for ActivityLogger
Luke Fitzpatrick 2014
"""
import os.path
from datetime import *
ACTIVITYFILENAME = "activities.txt"
def loadActivities():
"""
Loads and returns a list of all activities in the activities.txt file.
"""
try:
f = open(ACTIVITYFILENAME, 'r')
lines = []
for line in f:
lines.append(line.strip(' \t\n\r'))
return lines
except:
print "Couldn't open " + ACTIVITYFILENAME + "."
def validateActivityName(name):
"""
Takes an activity name and verifies that it exists in the activities file.
Returns true/false.
"""
#all of the names in the file are lowercase, the names are not case sensitive.
if name.lower() in loadActivities():
return True
elif name.lower() == "add":
return True
else:
return False
def validateNewActivityName(name):
return True
def validateTimestamp(timeStamp):
"""
Takes a user provided timeStamp and verifies that it follows the correct format.
Returns true/false.
Valid timestamp formatting:
[TIME1] to [TIME2]
TIME: integer number of hours before current time.
[TIME2] <= [TIME1]
"""
words = timeStamp.split()
try:
if(words[0].isdigit() and words[1] == "to" and words[2].isdigit()):
if(int(words[2]) <= int(words[0])):
return True
except:
pass
return False
def validateComment(comment):
"""
Takes a user provided comment and verifies it is valid.
Returns true/false.
"""
if "\n" in comment or "," in comment:
return False
return True
def convertInputToData(timeStamp, comment):
"""
Takes a correct user timeStamp and comment and converts it to the data folder format.
Returns string with the correct data folder formatted data.
"""
words = timeStamp.split()
timestamp1 = datetime.now() - timedelta(minutes = int(words[0]))
timestamp2 = datetime.now() - timedelta(minutes = int(words[2]))
data = str(timestamp1) + "," + str(timestamp2) + "," + comment
return data
def writeDataToFile(activityName, data):
"""
Writes the provided data to the file of the activityName.
"""
fileName = "data/" + activityName + ".txt"
with open(fileName, 'a') as file:
file.write(data)
file.write("\n")
def getValidatedInput(message, validationFunction):
"""
Prints message, gets input and continues to do this until
validationFunction returns true.
"""
valid = False
while (not valid):
value = raw_input(message)
valid = validationFunction(value)
return value
def addActivity(name):
writeDataToFile(name, "")
with open("activities.txt", 'a') as file:
file.write("\n")
file.write(name)
file.write("\n")
|
#!/usr/bin/python
import sys
import lxml
from lxml import html
import urllib
import urllib2
# read page html
def get_page(url):
request = urllib2.Request(url)
request.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)')
response = urllib2.urlopen(request)
html = response.read()
response.close()
return html
# parse and print image url
def getImgURL(html):
# find html item
alst = html.xpath('//img[@class="browseListImageXL"]')
imgAddressList = []
for aitem in alst:
text = aitem.get('src')
idx = text.rfind('_')
# print the file name so we can use "wget"
print text[0:idx+1]+'9'+text[idx+2:]
category=sys.argv[1]
i=sys.argv[2]
# open and read html
html_txt = get_page('http://www.houzz.com/photos/'+category+'/p/'+i);
# pares html text into html structure
html = lxml.html.fromstring(html_txt);
# print image file urls
getImgURL(html);
|
from contact_book.src.contacts_trie import Trie, insert_data, search_data
def deligator(choice):
deligator_map = {
1: insert_data,
2: search_data,
}
return deligator_map.get(choice)
class ContactBook:
def __init__(self):
self.name = Trie('')
self.surname = Trie('')
def run(self):
while True:
choice = input('1) Add contact 2) Search 3) Exit\n')
func = deligator(choice)
if func:
data = raw_input('Enter name: ')
func(self.name, self.surname, data)
else:
print "Happy Searching"
break
if __name__ == '__main__':
c = ContactBook()
c.run()
|
lst=[1,2,3,4]
sq=[(i*i) for i in lst]
print(sq)
pairs=[(i,j) for i in lst for j in lst if i!=j]
print(pairs)
odd=[i for i in lst if i%2!=0]
print(odd) |
class Employee:
def __init__(self,eid,name,des,salary):
self.eid=eid
self.name=name
self.des=des
self.salary=int(salary)
def printValues(self):
print(self.eid,self.name,self.salary)
def __str__(self):
return self.name
f=open("edetails","r")
emplst=[]
for data in f:
values=data.rstrip("\n").split(",")
id=values[0]
name=values[1]
desg=values[2]
sal=values[3]
obj=Employee(id,name,desg,sal)
#print(obj)
#obj.printValues()
emplst.append(obj)
# for emp in emplst:
# print(emp.salary)
out=list(map(lambda obj:obj.name.upper(),emplst))
print(out)
out2=list(filter(lambda obj:obj.salary>10000,emplst))
for i in out2:
print(i)
out3=list(map(lambda obj:obj.salary+5000,emplst))
#print(out3)
for i in out3:
print(i) |
from re import *
pattern="a{2}" #two noes of a
pattern="a{2,3}" #min 2 noes max 3 noes of a
matcher=finditer(pattern,"abaaabaaaaa 05@x")
for match in matcher:
print(match.start())
print(match.group()) |
lst=['x','y','z','x']
for i in range(len(lst)-1):
for j in range(i+1,len(lst)):
if(lst[i]!=lst[j]):
print(lst[i], lst[j])
|
lst=[]
newlst=[]
n=int(input("enter the size of list"))
print("enter elements:")
for i in range(0,n):
ele=int(input())
lst.append(ele)
for i in lst:
if i not in newlst:
newlst.append(i)
print(newlst)
|
from re import *
pattern="\s" #spaces
matcher=finditer(pattern,"abab 05@x")
for match in matcher:
print(match.start())
print(match.group())
pattern="\d" #[0-9]
matcher=finditer(pattern,"abab 05@x")
for match in matcher:
print(match.start())
print(match.group())
pattern="\D" #[^0-9]
matcher=finditer(pattern,"abab 05@x")
for match in matcher:
print(match.start())
print(match.group())
pattern="\w" #[a-zA-Z0-9] all words except special characters
matcher=finditer(pattern,"abab 05@x")
for match in matcher:
print(match.start())
print(match.group())
pattern="\W" #special characters
matcher=finditer(pattern,"abab 05@x")
for match in matcher:
print(match.start())
print(match.group()) |
#program to print star triangle
n=int(input("enter the number of rows"))
sp=2*n-2 #calculating the space needed
for i in range(1,n+1):
for j in range(0,sp):
print(end=" ")
sp=sp-1
for k in range(0,i):
print("*",end=" ")
print(" ")
|
#program to check whether a given sequence is palindrome or not
num=int(input("enter a number"))
temp=num
rev=0
while(num>0):
rem=num%10
rev=rev*10+rem
num=num//10
#print(rev)
if(temp==rev):
print("palindrome")
else:
print("not palindrome")
|
# APPROACH 1: BRUTE FORCE (MY APPROACH)
# Time Complexity : O(n^3) - n is the length of nums
# Space Complexity : O(1)
# Did this code successfully run on Leetcode : No (TIME LIMIT EXCEEDED)
# Any problem you faced while coding this : None
#
#
# Your code here along with comments explaining your approach
# 1. Consider different subarrays by varying start and end positions
# 2. For each subarray, count the number of 0 and 1
# 3. If count of 0 and count of 1 is same then check if the current length is greater than the max length found so far. Update accordingly.
class Solution:
def findMaxLength(self, nums: List[int]) -> int:
if not nums:
return 0
max_len, count_0, count_1 = 0, 0, 0
for start in range(0, len(nums)):
for end in range(start + 1, len(nums)):
for ind in range(start, end + 1):
if nums[ind] == 0:
count_0 += 1
elif nums[ind] == 1:
count_1 += 1
if count_0 == count_1:
curr_len = end - start + 1
max_len = max(max_len, curr_len)
count_0, count_1 = 0, 0
return max_len
# APPROACH 2: BRUTE FORCE SOLUTION (From class)
# Time Complexity : O(n^2) - n is the length of nums
# Space Complexity : O(1)
# Did this code successfully run on Leetcode : NO (Time Limit Exceeded)
# Any problem you faced while coding this : None
#
#
# Your code here along with comments explaining your approach
# 1. Vary the start index from 0 till end of list
# 2. For each start pos compute the sum in this way -> for 0: add 1 and for 1: add -1, till end of list
# 3. Each time the sum is computed, check if it's equal to 0 -> then update the max length found so far
class Solution:
def findMaxLength(self, nums: List[int]) -> int:
if not nums:
return 0
max_len = 0
for start in range(len(nums)):
curr_sum = 0
for ind in range(start, len(nums)):
if nums[ind] == 0:
curr_sum += 1
elif nums[ind] == 1:
curr_sum -= 1
if curr_sum == 0:
max_len = max(max_len, ind - start + 1)
return max_len
# APPROACH 3: OPTIMAL SOLUTION
# Time Complexity : O(n) - n is the length of nums
# Space Complexity : O(n) - size of hashmap
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : None
#
#
# Your code here along with comments explaining your approach
# 1. Store hashmap where key is the sum and value is the lowest index at which this sum was obtained
# 2. for each element of the list, compute the sum in this way -> for 0: add 1 and for 1: add -1
# 3. Check if the sum exist in hashmap (x - k, but k is 0 here), if so, update the max length found so far.
# Else, store the sum in hashmap and the index. (don't update when we find the same sum again as we need to
# find the longest length here, so we need lowest index possible)
class Solution:
def findMaxLength(self, nums: List[int]) -> int:
if not nums:
return 0
hashmap, curr_sum, max_len = {0: -1}, 0, 0
for ind in range(len(nums)):
if nums[ind] == 0:
curr_sum += 1
elif nums[ind] == 1:
curr_sum -= 1
# DOMINIC'S WAY
# if curr_sum == 0:
# max_len = ind + 1
# if curr_sum not in hashmap:
# hashmap[curr_sum] = ind
# else:
# max_len = max(max_len, ind - hashmap[curr_sum])
if curr_sum in hashmap:
max_len = max(max_len, ind - hashmap[curr_sum])
if curr_sum not in hashmap:
hashmap[curr_sum] = ind
return max_len
|
import random
class Card(object):
#constructor
def __init__(self,suite,face):
self._suite = suite
self._face = face
self._showCase = ''
#self._faceShowing = ''
#getter and setter
@property
def suite(self):
return self._suite
@property
def face(self):
return self._face
@suite.setter
def suite(self, suite):
self._suite = suite
@face.setter
def face(self, face):
self._face = face
def makeShowCase(self):
if(self.face == 1):
self._showCase = 'A'
elif(self.face == 11):
self._showCase = 'J'
elif(self.face == 12):
self._showCase = 'Q'
elif(self.face == 13):
self._showCase = 'K'
else:
self._showCase = self.face
def showCard(self):
return print(self._suite+str(self._showCase))
'''overloading operator: < '''
def __lt__(self, other):
if(self._face < other._face):
return True
else:
return False
#TODO: All class function go here
|
'''OOP NOTES'''
class Student(object):
#slots : restrict constructor: what attribute can user setup.
__slots__ = ("_name","_age","_email")
# constructor
def __init__(self, name, age, email):
self._name = name
self._age = age
self._email = email
#getter
@property
def getName(self):
return self._name
@property
def getEmail(self):
return self._email
#setter
@age.setter
def age(self, num):
self.age = num
def display(self):
print(f"student name: {self.name}, age is {self.age}")
student1 = Student("ggg",18, "sdf@gmail.com")
student1.display() |
# Menu
from ram import ram
import Creacion_archivo
ram = ram()
def subir_archivo():
nombre_archivo = raw_input("introduzca el nombre del archivo a subir ")
espacio_suficiente, cant_bloques = Creacion_archivo.restriccion_archivo(nombre_archivo)
if espacio_suficiente:
ram.agregar_archivo(cant_bloques, nombre_archivo)
def main():
while(True):
opcion = input("Presione:\n 1 para subir archivo \n 2 para agregar contacto al disco \n 3 para leer archivo \n 4 para imprimir archivos en ram \n 0 para salir \n")
if opcion == 1:
subir_archivo()
# OPCION 2 NO IMPLEMENTADA AUN
elif opcion == 3:
nombre_archivo = raw_input("introduzca el nombre del archivo a leer ")
ram.leer_archivo(nombre_archivo)
elif opcion == 4:
ram.imprime_archivos()
else:
break
if __name__ == "__main__":
main()
|
import json
import datetime
class MyEncoder(json.JSONEncoder):
'''
Usage, when you call a json.dumps(), call like
json.dumps(obj, cls = MyEncoder), to convert json
objects to str object
'''
def default(self, obj):
if isinstance(obj, datetime.datetime):
return obj.strftime("%s")
return json.JSONEncoder.default(self, obj) |
class ASTVisitor():
'''
Wrapper class to walk througha tree and visit each Node.
'''
def visit(self, astnode):
'A read-only function which looks at a single AST node.'
pass
def return_value(self):
return None
class ASTModVisitor(ASTVisitor):
'''
A visitor class that can also construct a new, modified AST.
Two methods are offered: the normal visit() method, which focuses on
analyzing and/or modifying a single node; and the post_visit() method,
which allows you to modify the child list of a node.
The default implementation does nothing; it simply builds up itself,
unmodified.'''
def visit(self, astnode):
# note: this overrides the super's implementation, because we need a
# non-None return value.
return astnode
def post_visit(self, visit_value, child_values):
'''
A function which constructs a return value out of its children.
This can be used to modify an AST by returning a different or modified
ASTNode than the original. The top-level return value will then be the
new AST.
'''
return visit_value
class ASTNode(object):
'''
Node of the AST tree.
'''
def __init__(self):
self.parent = None
self._children = []
@property
def children(self):
return self._children
@children.setter
def children(self, children):
self._children = children
if children is not None:
for child in children:
child.parent = self
def pprint(self, indent=''):
'''
Recursively prints a formatted string representation of the AST.
Format of the print:
parent
child1
child11 child12
child2
child21 child22
'''
print(indent + str(self))
if self.children is not None:
for child in self.children:
child.pprint(indent=indent+'\t')
def walk(self, visitor):
'''
Traverses an AST, calling node.visit(visitor) on every node.
This is a depth-first, pre-order traversal. Parents will be visited
before any children, children will be visited in order, and (by
extension) a node's children will all be visited before its siblings.
The visitor may modify attributes, but may not add or delete nodes.
'''
# visit self first
visitor.visit(self)
# then visit all children (if any)
if self.children is not None:
for child in self.children:
child.walk(visitor)
return visitor.return_value()
def mod_walk(self, mod_visitor):
'''
Traverses an AST, building up a return value from visitor methods.
Similar to walk(), but constructs a return value from the result of
postvisit() calls. This can be used to modify an AST by building up the
desired new AST with return values.
'''
selfval = mod_visitor.visit(self)
child_values = [child.mod_walk(mod_visitor) for child in self.children]
retval = mod_visitor.post_visit(self, selfval, child_values)
return retval
class ASTProgram(ASTNode):
'''
Node storing a programm in the AST.
'''
def __init__(self, statements):
super().__init__()
self.children = statements
class ASTImport(ASTNode):
'''
Node storing an import statement in the AST.
'''
def __init__(self, module):
super().__init__()
self.module = module
class ASTComponent(ASTNode):
'''
Node storing a component in the AST, ie a group of instructions between
brackets.
'''
def __init__(self, children):
super().__init__()
self.children = children
@property
def name(self):
return self.children[0]
@property
def expressions(self):
return self.children[1:]
class ASTInputExpr(ASTNode):
'''
Node storing an input expression in the AST.
'''
def __init__(self, children=None):
super().__init__()
self.children = children
class ASTOutputExpr(ASTNode):
'''
Node storing an output expression in the AST.
'''
def __init__(self, children=None):
super().__init__()
self.children = children
class ASTAssignmentExpr(ASTNode):
'''
Node storing an assignement expression in the AST.
'''
def __init__(self, children):
super().__init__()
self.children = children
@property
def binding(self):
return self.children[0]
@property
def value(self):
return self.children[1]
class ASTEvalExpr(ASTNode):
'''
Node storing an evaluation expression in the AST.
'''
def __init__(self, children):
super().__init__()
self.children = children
@property
def op(self):
return self.children[0]
@property
def args(self):
return self.children[1:]
class ASTID(ASTNode):
'''
Node storing an ID in the AST.
'''
def __init__(self, name, typedecl=None):
super().__init__()
self.name = name
self.type = typedecl
class ASTLiteral(ASTNode):
'''
Node storing a Literal variable in the AST.
'''
def __init__(self, value):
super().__init__()
self.value = value
self.type = 'Scalar'
|
import re
import phonenumbers
### Checks if a variable is empty or not ###
def is_empty(variable):
if variable:
return variable
else:
return None
# # An array of fields to be validated
# validation_list = [
# # Each element is made up of the field that is being validated
# # and the alias of the field that is to be displayed, should there be an error
# # Sample dict:
# # {"name": "", e.g "first_name"
# # "alias[optional]": "", eg "First Name" If left out, title case of field name is used
# # "var_type[optional]": "", eg [str, bool, int]
# # "length[optional]": "[min, max(optional)]", eg [2, 10]
# # "sub_array[optional]": "",
# # "sub_array_validate[optional]": "", boolean either True or False
# # "special_rules": ""} eg ["email"] Only email is supported for now
# # Coming soon: More special rules eg phone numbers
# {"name": "type", "alias": "Booking type"}
# {"name": "check_in", "alias": "Check-in date"},
# {"name": "check_out", "alias": "Check-out date"},
# {"name": "currency"}
# ]
### Field validation takes place ###
# The arguments:
# 1. requestData - The request data e.g the data found in request.json
# 2. fieldList - An array of fields to be validated against which requestData is compared
# Returns an array of missing or empty fields (if any)
def field_validation(requestData, fieldList):
messages = []
for field in fieldList:
# field['field'] is the name of the key being searched for in requestData
# field['alias'] is the key alias that you wish to have displayed as part of the error message
# Alternatively: field_name = field["field"]
field_name = field.get("field")
field_alias = field.get("alias", field.get("field").title())
## Optional keys
field_var_type = field.get("var_type", None)
field_length = field.get("length", None)
field_sub_array = field.get("sub_array", None)
field_sub_array_validate = field.get("sub_array_validate", None)
field_special_rules = field.get("special_rules", None)
if field_sub_array_validate:
if field_sub_array_validate == True:
pass
elif field_sub_array_validate == False:
pass
else:
pass
if field_name in requestData:
if not requestData[field_name]:
messages.append(field_alias + " is empty.")
else:
## Handling the variable type check
data_type_helper(messages, field_name, field_alias, requestData, field_var_type)
## Handling the length check
data_length_helper(messages, field_name, field_alias, requestData, field_length)
## Handling the sub-array check
sub_array_helper(messages, field_name, field_alias, requestData, field_sub_array)
## Handling the special rules
special_rules_helper(messages, field_name, field_alias, requestData, field_special_rules)
else:
messages.append(field_alias + " is missing.")
return messages
# Helpers #
def data_type_helper(returnList, fieldName, fieldAlias, requestData, dataTypeList):
if dataTypeList == None:
pass
elif dataTypeList != None:
if type(requestData[fieldName]) in dataTypeList:
pass
else:
returnList.append(fieldAlias + " data type is not of the expected data type.")
def data_length_helper(returnList, fieldName, fieldAlias, requestData, dataLength):
if dataLength == None:
pass
elif dataLength != None:
try:
start = dataLength[0]
except IndexError:
start = None
try:
end = dataLength[1]
except IndexError:
end = None
if end:
if end < start:
returnList.append("The maximum length cannot be shorter than the minimum length.")
if start == None:
returnList.append(fieldAlias + " minimum length is not defined.")
elif start != None:
if len(requestData[fieldName]) >= start:
pass
else:
returnList.append(fieldAlias + " length is less than the minimum required length.")
if end == None:
pass
elif end != None:
if len(requestData[fieldName]) > end:
returnList.append(fieldAlias + " length is greater than the maximum required length.")
elif len(requestData[fieldName]) >= end & len(requestData[fieldName]) <= end:
pass
def sub_array_helper(returnList, fieldName, fieldAlias, requestData, dataSubArray):
if dataSubArray == None:
pass
else:
position = 1
for single_element in requestData[fieldName]:
if dataSubArray in single_element:
if not single_element[dataSubArray]:
returnList.append(fieldAlias + " " + dataSubArray + " is empty at position " + str(position) + ".")
else:
pass
else:
returnList.append(fieldAlias + " " + dataSubArray + " is missing at position " + str(position) + ".")
position += 1
def special_rules_helper(returnList, fieldName, fieldAlias, requestData, dataSpecialRules):
if dataSpecialRules == None:
pass
else:
# Email addresses
if "email" in dataSpecialRules:
valid = validate_email(is_empty(requestData[fieldName]))
if valid == True:
pass
else:
returnList.append(fieldAlias + " is not a valid email address.")
else:
pass
### Simple email validation rule ###
# emailAddress is the email address to be validated
# Function is regex-based
def validate_email(emailAddress):
if emailAddress == None:
valid = False
else:
address_to_verify = emailAddress
match = re.match('^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$', address_to_verify)
if match == None:
valid = False
else:
valid = True
return valid
### Phone number validation rule ##
# phoneNumber is the phone number to be validated
# Function requires import of phonenumbers
def validate_phone_number(phoneNumber):
valid = []
if phoneNumber == None:
valid.append(False)
valid.append("The phone number is empty.")
else:
phoneNumber = str(phoneNumber).strip("+")
phoneNumber = "+" + str(phoneNumber)
try:
parse = phonenumbers.parse(phoneNumber, None)
valid_number = phonenumbers.is_valid_number(parse)
if valid_number:
str_parse = str(parse).split(" ")
country_code = str_parse[2]
number = str_parse[5]
valid.append(True)
valid.append("+" + country_code + "-" + number)
else:
valid.append(False)
valid.append("The phone number provided is invalid.")
except phonenumbers.phonenumberutil.NumberParseException:
valid.append(False)
valid.append("There was an error validating the phone number")
return valid |
'''
Created on 31/05/2012
@author: ultrazoid_
'''
def length(lists):
lengths = 0
for ind in lists:
lengths +=1
return lengths
x=[1,2,3,4,5,6,7,8,9,0]
print length(x) |
#hello python3
print("hello pyhon3")
j = 1
i = 5
print(f"i={i}")
print("i=",i)
i = i+1
print(f"after i++; i={i}")
def print_max(a,b):
print(f"a={a}, b={b}")
if(a>b):
print("max is", a)
else:
print("max is", b)
print_max(8,11)
def global_test():
global i
i = 11
print(f"in global_test; i={i}")
global_test()
print(f"global i={i}")
def func_default_v_test(a, b=5, c=100):
print("a=", a, "b=", b, "c=", c)
func_default_v_test(1)
func_default_v_test(1,2)
func_default_v_test(1,2,3)
class Person:
def say_hi(self): #compile error if self was not given here
print("hello, how are you")
def gotoshcool(self, a):
print("my school is:", a)
p1 = Person()
print("p=",p1)
p1.say_hi()
p1.say_hi()
p1.gotoshcool("Bradfield")
class Person2:
age=0
height=170
weight=60
name="Bruce"
def print_name(self):
print("name is:", self.name)
p2 = Person2()
p2.print_name()
|
##def count_adjacent_repeats (s):
## '''
## (str) -> int
##
## Return the number of occurrences of a character and an adjacent
## character being the same.
##
## >>>count_adjacent_repeats ('abccdeffggh')
## 3
## '''
## repeats = 0
##
## for i in range(len(s)-1):
## if s[i] == s[i + 1]:
## repeats = repeats + 1
##
## return repeats
def count_adjacent_repeats (s):
'''
(str) -> int
Return the number of occurrences of a character and an adjacent
character being the same.
>>>count_adjacent_repeats ('abccdeffggh')
3
'''
repeats = 0
for i in range(1,len (s)):
if s[i] == s[i - 1]:
repeats = repeats + 1
return repeats
|
"""Frequent Words with Mismatches and Reverse Complements Problem
Find the most frequent k-mers (with mismatches and reverse complements) in a DNA string.
Given: A DNA string Text as well as integers k and d.
Return: All k-mers Pattern maximizing the sum Countd(Text, Pattern) + Countd(Text, Pattern) over all possible k-mers."""
import os
path=os.getcwd()
import itertools
from BA1_ba1h import ApproximatePatternMatching
from BA1_ba1c import ReverseComplementDNA
def FrequentWords_Hamm_rev(Text, k, d):
comb_list=list(itertools.product('ACGT',repeat=k))
flat_list=[]
for i in comb_list:
x=''.join(i)
flat_list.append(x)
max_count=1
freq_patterns=[]
for index, pattern in enumerate(flat_list):
fwd_count=len(ApproximatePatternMatching(flat_list[index],Text,d))
rev_count=len(ApproximatePatternMatching(flat_list[index],ReverseComplementDNA(Text),d))
count=fwd_count+rev_count
if count==max_count:
freq_patterns.append(pattern)
if count>max_count:
max_count=count
freq_patterns=[pattern]
return freq_patterns
# with open (path + r'/input_data/rosalind_ba1j.txt') as f:
# input=f.read().strip().split('\n')
# text=input[0]
# line2=input[1].split()
# k=int(line2[0])
# d=int(line2[1])
#
# f = open(path + r'/output_data/out_rosalind_ba1j.txt', 'w')
# f.write(' '.join(i for i in FrequentWords_Hamm(text,k,d)))
# f.close()
#
|
"""BA1_ba1b: Frequent Words Problem
Find the most frequent k-mers in a string.
Given: A DNA string Text and an integer k.
Return: All most frequent k-mers in Text (in any order)"""
import os
path=os.getcwd()
from BA1_ba1a import PatternCount
def CountDict(Text, k):
"""Generates a dictionary that counts kmers of length k where key = kmer string[index], value = kmer string count"""
Count = {}
for i in range(len(Text)-k+1):
Pattern = Text[i:i+k]
Count[i] = PatternCount(Pattern, Text)
return Count
def remove_duplicates(Items):
"""Removes duplicates from a list"""
ItemsNoDuplicates=[]
for i in Items:
if i not in ItemsNoDuplicates:
ItemsNoDuplicates.append(i)
return ItemsNoDuplicates
def FrequentWords(Text, k):
"""Generates a list of max frequency kmers of length k"""
FrequentPatterns = []
Count = CountDict(Text, k)
m = max(Count.values())
for i in Count:
if Count[i] == m:
FrequentPatterns.append(Text[i:i+k])
FrequentPatternsNoDuplicates = remove_duplicates(FrequentPatterns)
return FrequentPatternsNoDuplicates
# with open (path + r'/input_data/rosalind_ba1b.txt') as f:
# input=f.read().strip().split('\n')
# ba1b_text=input[0]
# ba1b_k=int(input[1])
#
# f = open(path + r'/output_data/out-rosalind_ba1b.txt', 'w')
# f.write(str(' '.join(FrequentWords(ba1b_text,ba1b_k))))
# f.close()
#
# print((FrequentWords(ba1b_text,ba1b_k)))
def TopHits(Text, k,n):
"""Generates a dictionary that modifies FrequentWords to return kmers of length k within frequency max-n, where key = kmer string, value = frequency"""
FrequentPatterns = {}
Count = CountDict(Text, k)
m = max(Count.values())
for i in Count:
if Count[i] >= m-n:
y=Text[i:i+k]
FrequentPatterns[y]=Count[i]
return FrequentPatterns
# print((TopHits(ba1b_text,ba1b_k,0)))
|
from disjoint_set import DisjointSet
class UnionBySizeDisjointSet(DisjointSet):
def __init__(self, n):
self.n = n
self.parent = [-1 for _ in range(n)]
def find(self, x):
while not self.parent[x] < 0:
x = self.parent[x]
return x
def union(self, x, y):
x_root = self.find(x)
y_root = self.find(y)
if x_root == y_root:
return
x_size = -self.parent[x_root]
y_size = -self.parent[y_root]
if x_size > y_size:
self.parent[y_root] = x_root
self.parent[x_root] = -(x_size + y_size)
else:
self.parent[x_root] = y_root
self.parent[y_root] = -(x_size + y_size)
if __name__ == "__main__":
disjoint_set = UnionBySizeDisjointSet(10)
disjoint_set.union(1, 2)
disjoint_set.union(3, 4)
print(disjoint_set.find(1))
print(disjoint_set.find(2))
print(disjoint_set.find(3))
print(disjoint_set.find(4))
print(disjoint_set.find(5))
|
def love(size):
for a in range(int(size/3),size,2):
for b in range(1, size - a, 2):
print(" ",end = "")
for b in range(1, a + 1):
print("*", end="")
for b in range(1, (size - a) + 1):
print(" ", end="")
for b in range(1,a):
print("*", end="")
print()
for a in range(size, 0, -1):
for b in range(a, size):
print(" ", end="")
for n in range(1, (a * 2)):
print("*", end="")
print()
cinta = int(input("How Much Is Your Love: "))
love(cinta)
|
def divisors(n):
i=1
while (i<n+1):
if(n%i==0):
print(i)
i+=1
print("please enter a number")
n=int(input())
divisors(n)
|
#IF ELSE STATEMENT
n1=20
n2=30
if n1>n2:
print("n1 is greater")
else:
print("n2 is greater") |
def sum(*n1):
sum=0
for i in n1:
sum=sum+i
print("Ans is ",sum)
sum(10,20)
sum(10,20,30) |
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
from itertools import permutations, combinations
def find_shortest_path(board, start, end):
R = len(board)
C = len(board[0])
queue = [(start, 0)]
seen = set([start])
while queue:
(r, c), steps = queue.pop(0)
DR = [-1, 1, 0, 0]
DC = [0, 0, -1, 1]
for dr, dc in zip(DR, DC):
r_ = r + dr
c_ = c + dc
if 0 <= r_ < R and 0 <= c_ < C and (r_, c_) not in seen:
if (r_, c_) == end:
return steps + 1
elif board[r_][c_] == '.':
queue.append(((r_, c_), steps + 1))
seen.add((r_, c_))
def part1(inp):
max_loc = 0
coords = {}
for r, row in enumerate(inp):
for c, val in enumerate(row):
if val not in '#.':
coords[int(val)] = (r, c)
max_loc = max(max_loc, int(val))
shortest = {}
for start, end in combinations(range(0, max_loc + 1), 2):
start_c = coords[start]
end_c = coords[end]
path_length = find_shortest_path(inp, start_c, end_c)
shortest[(start, end)] = path_length
shortest[(end, start)] = path_length
best = 1e9
for perm in permutations(range(1, max_loc + 1)):
perm = tuple([0] + list(perm))
length = 0
for a, b in zip(perm, perm[1:]):
length += shortest[(a, b)]
best = min(best, length)
return best
def part2(inp):
max_loc = 0
coords = {}
for r, row in enumerate(inp):
for c, val in enumerate(row):
if val not in '#.':
coords[int(val)] = (r, c)
max_loc = max(max_loc, int(val))
shortest = {}
for start, end in combinations(range(0, max_loc + 1), 2):
start_c = coords[start]
end_c = coords[end]
path_length = find_shortest_path(inp, start_c, end_c)
shortest[(start, end)] = path_length
shortest[(end, start)] = path_length
best = 1e9
for perm in permutations(range(1, max_loc + 1)):
perm = tuple([0] + list(perm) + [0])
length = 0
for a, b in zip(perm, perm[1:]):
length += shortest[(a, b)]
best = min(best, length)
return best
def main():
with open(f'{dir_path}/../../inputs/day24/input') as f:
inp = list(map(lambda x: x, f.read().strip().split('\n')))
print(inp)
print(part1(inp[:]))
print(part2(inp[:]))
if __name__ == '__main__':
main()
|
import sys
from collections import Counter
from typing import List
def prep(board: List[str]) -> set((int, int)):
return set([(x, y, 0)
for y, row in enumerate(board)
for x, c in enumerate(row)
if c == '#'
])
NEIGHBOURS = set([(1, 0), (-1, 0), (0, 1), (0, -1)])
def print_bugs_2d(bugs: set((int, int, int)), level: int = 0) -> None:
board = []
for _ in range(5):
board.append(["."] * 5)
for x, y, z in bugs:
if z == level:
board[y][x] = '#'
print()
for row in board:
print(''.join(row))
print()
def evolve(bugs: set((int, int, int))) -> set((int, int, int)):
counts = Counter()
for x, y, z in bugs:
counts.update(
(x + dx, y + dy, 0)
for dx, dy in NEIGHBOURS
if 0 <= x + dx <= 4 and 0 <= y + dy <= 4
)
return {
cell
for cell in counts
if counts[cell] == 1 or (counts[cell] == 2 and cell not in bugs)
}
def cell_diversity(x: int, y: int) -> int:
return 2**(y*5 + x)
def sol1(bugs: set((int, int))):
seen_states = set()
while frozenset(bugs) not in seen_states:
seen_states.add(frozenset(bugs))
bugs = evolve(bugs)
return sum([cell_diversity(x, y) for x, y, _ in bugs])
def neighbours_3d(x: int, y: int, z: int):
neighbours_2d = [(x + dx, y + dy, z) for dx, dy in NEIGHBOURS]
neighbours = []
for xn, yn, zn in neighbours_2d:
if xn < 0:
neighbours.append((1, 2, zn - 1))
elif xn > 4:
neighbours.append((3, 2, zn - 1))
elif yn < 0:
neighbours.append((2, 1, zn - 1))
elif yn > 4:
neighbours.append((2, 3, zn - 1))
elif xn == 2 and yn == 2:
if x == 1:
for ynn in range(5):
neighbours.append((0, ynn, zn + 1))
elif x == 3:
for ynn in range(5):
neighbours.append((4, ynn, zn + 1))
elif y == 1:
for xnn in range(5):
neighbours.append((xnn, 0, zn + 1))
elif y == 3:
for xnn in range(5):
neighbours.append((xnn, 4, zn + 1))
else:
neighbours.append((xn, yn, zn))
return neighbours
def print_bugs_3d(bugs: set((int, int, int)), levels: List[int]) -> None:
for level in levels:
print("Level", level)
print_bugs_2d(bugs, level)
print()
def evolve_3d(bugs: set((int, int, int))):
counts = Counter()
for x, y, z in bugs:
counts.update(
neighbours_3d(x, y, z)
)
return {
cell
for cell in counts
if counts[cell] == 1 or (counts[cell] == 2 and cell not in bugs)
}
def sol2(bugs: set((int, int, int))):
for _ in range(200):
bugs = evolve_3d(bugs)
return len(bugs)
def main():
with open(sys.argv[1]) as f:
lines = f.read().splitlines()
print(sol1(prep(lines)))
print(sol2(prep(lines)))
if __name__ == '__main__':
main() |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 5 07:47:15 2020
@author: KEV
"""
from marco import *
import tkinter as tk
from tkinter import Canvas
class ventana:
def __init__():
__marco__ = marco.__init__()
ln = tk.Label(__marco__, text ="A continución digíte el grado de la Función",bg="black",fg="yellow").pack(
padx=3,pady=3,ipadx=2,ipady=20,fill=tk.X)
cn = tk.Entry(__marco__, bg="blue",fg="yellow")
cn.pack()
__marco__.mainloop()
def cargarn():
def cargarv():
coe = list(range(labeln))
for i in range(labeln):
coe[i] = camTex[i].get()
lx = tk.Label(__marco__, text="Cargar el número a evaluar la función Función",bg="black",fg="yellow")
lx.pack()
lx.place(x=100,y= labeln*h+12*h+75)
x = tk.Entry(__marco__,bg="blue",fg="yellow")
x.pack()
x.place(x=100,y= labeln*h+12*h+100)
def evalua():
r=0
for i in range(labeln):
r = r + (float(x.get())**i) * float(coe[i])
lr = tk.Label(__marco__, text="El Resultado de la función evaluada en "+str(x.get())+" es : "+
str(r),bg="black",fg="yellow")
lr.place(x=100,y= labeln*h+12*h+160)
cargarx = tk.Button(__marco__, text="Evaluar",bg="Blue",fg="yellow",command=evalua)
cargarx.place(x=100,y= labeln*h+12*h+125)
lcoe = tk.Label(__marco__, text ="A continución digíte cada coeficiente de las variables",bg="Black",fg="yellow").pack(
padx=3,pady=3,ipadx=2,ipady=20,fill=tk.X)
labeln = int(cn.get())
h = 15
labelv = list(range(labeln))
camTex = list(range(labeln))
r = 0
for i in range(labeln):
labelv[i] = tk.Label(__marco__, text="X:"+str(i),bg="black",fg="red")
labelv[i].pack()
labelv[i].place(x=100,y=i*h+12*h)
camTex[i] = tk.Entry(__marco__, bg="blue",fg="yellow")
camTex[i].pack(ipady=30)
camTex[i].place(x=167 , y= i*h+12*h)
cargarv = tk.Button(__marco__, text="Cargar Variables",bg="Blue",fg="yellow",command=cargarv)
cargarv.pack()
cargarv.place(x=100,y= labeln*h+12*h+25)
cargarn = tk.Button(__marco__, text="Cargar El Grado de la Función",bg="Blue",fg="yellow",command=cargarn).pack(pady=5)
__marco__.mainloop() |
import geojson
import parse as p
def create_map(data_file):
# Define the GeoJSON that we are creating
geo_map = {"type": "FeatureCollection"}
# make an empty list to collect the points for plotting
item_list = []
# Iterate through the input data to make the GeoJSON document The enumerate
# function is being used here so that both the value of index and line
# are captured for each object
for index, line in enumerate(data_file):
# records with coordinate values of zero are skipped to avoid plotting
# locations that will skew the map
if line['X'] == "0" or line['Y'] == "0":
continue
# create a new dictionary for every iteration through input data
data = {}
# reads the data from the input file and assigns the line items to
# corresponding GeoJSON fields
data['type'] = 'Feature'
data['id'] = index
data['properties'] = {'title': line['Category'],
'description': line['Descript'],
'date': line['Date']}
data['geometry'] = {'type': 'Point',
'coordinates': (line['X'], line['Y'])}
# add the newly created dictionary to the item_list
item_list.append(data)
# for every point in the item_list, the point is added to the dictionary
# here setdefault creates a key called 'features' that has a value type
# of an empty list, every iteration through appends the point to that list.
for point in item_list:
geo_map.setdefault('features', []).append(point)
# Once all of the data is parsed into a GeoJSON object, it needs to be
# written to a file for presentation on gist.github.com
with open('file_sf.geojson', 'w') as f:
f.write(geojson.dumps(geo_map))
def main():
data = p.parse(p.MY_FILE, ",")
return create_map(data)
if __name__ == "__main__":
main()
|
"""
# Module 4- Example Plot of Weather Data
#### author: Radley Rigonan
In this module, I we will be using data from RadWatch's AirMonitor to create a plot that compares
counts per second (CPS) due to Bismuth-214 against the CPS of the lesser occurring isotope Cesium-137.
I will be using the following link:
https://radwatch.berkeley.edu/sites/default/files/pictures/rooftop_tmp/weather.csv
The first step in creating a plot is being aware of the format of your CSV file. This weather.csv
is organized 9 columns. The 1st column contains important timestamp information, the 2nd column
contains Bi-234 CPS, and the 5th column contains Cs-137 CPS. In addition, we are interested in
the 6th column of Bi-234 margin of error and the 9th column with Cs-137's margin of error.
"""
import csv
import io
import urllib.request
import matplotlib.pyplot as plt
import matplotlib.dates as mdates # another matplotlib convention; this extension facilitates dates as axes labels.
from datetime import datetime # we will use the datetime extension so we can group the timestamp data into manageable units of year, month, date, and time.
url = 'https://radwatch.berkeley.edu/sites/default/files/pictures/rooftop_tmp/weather.csv'
response = urllib.request.urlopen(url)
reader = csv.reader(io.TextIOWrapper(response))
timedata = []
Bi214 = []
Cs137 = []
line = 0
for row in reader:
if line != 0:
timedata.append(datetime.strptime(row[0], '%Y-%m-%d %H:%M:%S'))
#datetime.strptime is a class object that facilitates usage of date/time data in Python
Bi214.append(float(row[1]))
Cs137.append(float(row[4]))
line += 1
def weather_plot1():
fig, ax = plt.subplots() # matplotlib convention that unpacks figures into variables for ax (axis manipulation) and fig (figure manipulation)
# concise line for: fig = plt.figure()
# AND: fig.add_subplot(1,1,1)
ax.plot(timedata, Bi214, 'ro-', label="Bismuth-214")
ax.plot(timedata, Cs137, 'bs-', label="Cesium-137")
plt.title('AirMonitor Data: Bi-214 and Cs-137 CPS from %s-%s to %s-%s'
%(timedata[0].month, timedata[0].day, timedata[-1].month, timedata[-1].day))
# string interpolation (represented by %s): The '%s' are replaced by the strings given in %(-,-,-,-)
plt.xlabel('Time')
plt.ylabel('counts per second')
plt.legend(loc='best') # loc=best places the legend where it will obstruct the data the least.
# There are a few problems with this current plot. One simple fix to make the x-tick labels more visible is via rotation. We can also convey the data more objectively with a logarithmic y-axis:
def weather_plot2():
weather_plot1()
# adjustments
plt.xticks(rotation=30)
plt.yscale('log')
plt.title('AirMonitor Data: Bi-214 and Cs-137 CPS (logarithmic) from %s-%s to %s-%s'
%(timedata[0].month, timedata[0].day, timedata[-1].month, timedata[-1].day))
plt.show()
#While these plots are fine, many professional graphics thoroughly control every aspect of the plot such as in the following example. Also, this example will calculate error and include error bars (similar to error seen on the AirMonitor website).
def weather_plot3():
import numpy as np
# 1st step: plot the data
fig, ax = plt.subplots()
ax.plot(timedata, Bi214, 'ro-', label='Bismuth-214')
ax.errorbar(timedata, Bi214, yerr=np.sqrt(Bi214)/60, fmt='ro', ecolor='r')
ax.plot(timedata, Cs137, 'bs-', label='Cesium-137')
ax.errorbar(timedata, Cs137, yerr=np.sqrt(Cs137)/60, fmt='bs', ecolor='b')
# for ax.errorbar, fmt=format and is identical to corresponding plot for coherence
# ecolor=line color and is identical to corresponding plot for same reason.
# 2nd step: legend and axis manipulations:
plt.legend(loc='best')
plt.yscale('log')
# 3rd step: format ticks along axis; we will use matplotlib's built-in datetime commands to format the axis:
ax.xaxis.set_major_locator(mdates.DayLocator())
# ticks on x-axis day-by-day basis
ax.xaxis.set_major_formatter(mdates.DateFormatter('%m-%d'))
# tick labels only occur on days in the format: Month-Day
# you can customize the format, i.e. '%m-%d-%Y %H:00' would be Month-Day-Year Hour:00
ax.xaxis.set_minor_locator(mdates.HourLocator())
# minor ticks on x-axis occur on hour marks
plt.xticks(rotation=30)
# 4th step: titles and labels
plt.title('AirMonitor Data: Bi-214 and Cs-137 CPS from %s-%s to %s-%s'
%(timedata[0].month, timedata[0].day, timedata[-1].month, timedata[-1].day))
plt.xlabel('Time')
plt.ylabel('counts per second') |
# -*- coding: utf-8 -*-
"""
#### Module 7- Data Sorting and Searching
Computer scripts excel at performing repetetive tasks that would normally be tedious or uninteresting to do by hand. Therer are many useful jobs that programs can perform, but in this module I will demonstrate three common data-processing techniques: sorting, searching, and manipulating. These jobs are fundamental functions of computer scripts and are encountered in nearly any field of computational data analysis.
For this module I will be using AirMonitor's archived weather data from July 23 2015 to July 23 2016
https://www.wunderground.com/history/airport/KOAK/2015/7/23/CustomHistory.html?dayend=23&monthend=7&yearend=2016&req_city=&req_state=&req_statename=&reqdb.zip=&reqdb.magic=&reqdb.wmo=&format=1
"""
import csv
import io
import urllib.request
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime
url = 'https://www.wunderground.com/history/airport/KOAK/2015/7/23/CustomHistory.html?dayend=23&monthend=7&yearend=2016&req_city=&req_state=&req_statename=&reqdb.zip=&reqdb.magic=&reqdb.wmo=&format=1'
response= urllib.request.urlopen(url)
reader = csv.reader(io.TextIOWrapper(response))
datalist = []
timedata = []
meantemp = []
meanwind = []
rain = []
line = 0
for row in reader:
if line != 0:
datalist.append(row) # intermediate step of piling data into one list because url is a comma delimited url.
line += 1
for i in range(len(datalist)):
if i !=0:
timedata.append(datetime.strptime(datalist[i][0], '%Y-%m-%d'))
meantemp.append(float(datalist[i][2]))
meanwind.append(float(datalist[i][17]))
rain.append(datalist[i][19])
data = np.array((timedata,meantemp,meanwind,rain))
# now all the data is gathered in a multidimensional array in which the 1st column has dates, 2nd column has mean temperature, 3rd column has mean wind velocity, and 4th column has precipitation data.
def sort_func(type):
# INPUT: type is a string, either 'temp,'wind', or 'rain' to determine how how the list array is sorted
if type == 'temp':
sorted_index = np.argsort(data[1]) # argsort outputs a sorted list of indices from lowest to highest for the (1+1)nd row
sorted_data = data[:,sorted_index] # which is used to sort the columns in the multi-dimensional array
elif type == 'wind':
sorted_index = np.argsort(data[2]) # outputs a sorted list of indices from lowest to highest for the (1+2)rd row
sorted_data = data[:,sorted_index]
elif type == 'rain':
sorted_index = np.argsort(data[3]) # outputs a sorted list of indices from lowest to highest for the (1+3)th row
sorted_data = data[:,sorted_index]
else:
print('invalid input string')
return sorted_data # module outputs the sorted_data
# Note, this sort function is not entirely correct. When rainfall is detectable but not measurable, Wunderground stores the data as T for trace. Thus, a proper sorting function for rain would be [0, ..., 0, T, ..., T, 0.1, ..., etc.]
def printed_sort():
print(sort_func('temp')[1:,:9])
print(sort_func('wind')[1:,:9])
print(sort_func('rain')[1:,:9])
def search_func():
# Let's make a function that searches for the dates in which rainfall is detected (including trace amounts of rainfall, 'T')
# To do this, we can use a concept called list comprehension:
rainfall = list(data[3:,].flatten())
indices_trace = [i for i, target in enumerate(rainfall) if target == 'T']
# Next, we replace indices where 'T' appears with 0 so it doesn't interfere with next search
for index in indices_trace:
rainfall[index] = 0
rainfall = [float(j) for j in rainfall]
indices_rain = [i for i, target in enumerate(rainfall) if target > 0]
# When we combine the two indices, we place T before the numerical values
search_index = indices_trace + indices_rain
return search_index
def printed_search():
search_index = search_func()
print(data[:,search_index])
|
import random
from Trie import *
from HashTable import *
#Setting the student directory and hash table as global variables
directory = Trie()
Hash = HashTable()
#A function which adds new students to the directory
#The function also gives the students a slot in the HashTable
#The slot holds the student name and the student ID
def addStudent(Name, yearGroup, directory, Hash):
directory.addName(Name.lower())
ID = Hash.generateID(yearGroup)
Hash.put(Name.lower(), ID)
#A function to verify a password
# The function receives an input and checks it against a prestored value
def checkPassword(user_input):
password = 'ashes1'
if user_input == password:
return True
else:
return False
#A function which searches the student directory for the student name
#The function then finds the student name and associated ID in a hash table
def searchDirectory(studentName, directory, Hash):
searchNames = directory.getNodeOfLastLetter(studentName)
mylist = []
directory.findNames(searchNames,studentName, mylist)
print()
if mylist != None:
for i in mylist:
print('Name :', i, '\nID :', Hash.get(i))
print()
#This function requests inputs from the user. Based on the user's input, a student is either
#Added to the directory or a search of students is conducted on the directory.
#Password : ashes1
def accessFunction():
user_input = input('1. Add new student (Admin Only) \n2. Search for student NB: Start with First Name \
\n3. Any other number to exit(3-9)\n\n')
yeargroups = [2021,2020,2019,2018]
if int(user_input) == 1:
password = input('\nHello Administrator, enter password: ')
if checkPassword(password) == True:
name = input('\nEnter student name: ')
yearGroup = input('Enter year group: ')
if eval(yearGroup) not in yeargroups:
yearGroup = input('Enter year group, one of the following [2021,2020,2019,2018]: ')
addStudent(name, yearGroup, directory, Hash)
print(name, 'has been added to the directory')
print()
accessFunction()
else:
print('Wrong Password')
print()
accessFunction()
elif int(user_input) == 2:
studentName = input('Kindly enter student name. NB, feel free to hit enter after typing in the first few letters of the name\n\n')
print("Searching for ", studentName)
print()
searchDirectory(studentName.lower(), directory, Hash)
accessFunction()
return
def main():
#An initial list of tuples made up of the student name and their year groups
students = [('Edwin Adatsi', 2019), ('Esther Akati', 2020), ('Enam Nanemeh', 2018), ('Philip Asante', 2019),
('Kwame Osei Owusu', 2021),('Jojoe Ainoo', 2019),('Kingsley Laryeh',2018), ('Claude Tamakloe',2021),
('Samuel Bunyan', 2021), ('Mac Noble', 2019), ('Kusi Berma Asante', 2020)]
#A text file with student names
text = open("names.txt", 'r')
names = text.read().split(',')
possibleYears = [2021,2020,2019,2018]
for name in names:
i = random.randint(0,3)
students.append((name, possibleYears[i]))
print("Welcome to the Ashesi Student Directory")
print("We have ", len(students), "students and we will add them to the student directory.")
print("The students are: \n")
count = 1
for i in students:
print(count, ' Name: ', i[0], ', Year Group: ', i[1] )
count += 1
for stu in students:
addStudent(stu[0], stu[1], directory, Hash)
print('\nStudents have been successfully added to the student directory.')
print()
print('Student Directory: ')
accessFunction()
if __name__ == '__main__':
main() |
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
n = len(board)
m = len(board[0])
for i in range(n):
for j in range(m):
visited = [[False] * m for i in range(n)]
if board[i][j]==word[0]:
if self.recursive(board, word,i,j,n,m,visited):
return True
return False
def recursive(self,board, word,i,j,n,m,visited):
if len(word) == 0:
return True
if i<0 or i>=n or j<0 or j>=m:
return False
if visited[i][j] or board[i][j]!=word[0]:
return False
visited[i][j]=True
answer= self.recursive(board, word[1:],i+1,j,n,m,visited) or self.recursive(board, word[1:],i-1,j,n,m,visited) or self.recursive(board, word[1:],i,j+1,n,m,visited) or self.recursive(board, word[1:],i,j-1,n,m,visited)
visited[i][j]=False
return answer |
# we will calculate the darivative of an image
import numpy as np
import cv2
from matplotlib import pyplot as plt
def callMe():
# der()
test()
pass
def der():
img = cv2.imread("/home/hp/PycharmProjects/image/data/dog2.jpg", 0)
# cv2.imshow('Image', img)
print(img.shape)
print(img)
cv2.waitKey(0)
cv2.destroyAllWindows()
pass
# this will give the derivative element for the position
def get_element(input_matx, derivative_mask):
return np.sum(input_matx * derivative_mask)
def test():
# a = np.arange(12).reshape(4, 3)
b = np.array([[255, 255, 255, 255, 255], [255, 255, 255, 255, 255], [255, 255, 255, 255, 255], [255, 255, 255, 255, 255], [255, 255, 255, 255, 255]])
c = np.array([[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]])
# (i, j) = b.shape
# print(i, j)
# res = np.sum(b*c)
# print(res)
# print(a)
# c = a.sum()
# print(c)
pass
|
import time
start_time = time.time()
def even(list1):
list1=[int(n) for n in str(list1)]
list2= [0,2,4,6,8]
result = False
for x in list1:
for y in list2:
if x == y:
result = True
return result
return result
def candidate_range(n):
cur = 5
incr = 2
while cur < n+1:
yield cur
cur += incr
incr ^= 6 # or incr = 6-incr, or however
def sieve(end):
prime_list = [2, 3]
sieve_list = [True] * (end+1)
for each_number in candidate_range(end):
if sieve_list[each_number]:
prime_list.append(each_number)
for multiple in range(each_number*each_number, end+1, each_number):
sieve_list[multiple] = False
return prime_list
primes = sieve(10**6)
def rotation(number):
return {int(str(number)[rot:] + str(number)[:rot]) for rot in range(len(str(number)))}
good = [3,7]
for prime in primes:
if not even(prime) and rotation(prime).issubset(primes):
for i in rotation(prime):
good.append(i)
primes.remove(i)
print(prime, rotation(prime), len(good))
#the boy forgets 5 but wtv
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#__author__ = 'Ulises Olivares - uolivares@enesmorelia.unam.mx
import os
from collections import defaultdict
import csv
def readFiles():
'''
This function reads all the files contained in the data directory and returns
:return:
'''
files = []
for subdir, dirs, filenames in os.walk('./data'):
files.extend(filenames)
return files;
def findElement(annotations, element):
'''
This method searchs an element in a list of annotated elements ant returns the name
:param annotationStructure:
:param element:
:return:
'''
orig = element
# Find the | char to just obtain the first part of the ID
pos = element.find("|")
pos2 = element.find(" ")
if pos2 < pos and pos2 != -1:
element = element[0:pos2]
# Remove empty spaces
element = element.replace(" ", "")
else:
# Cut string when the char | is present
element = element[0:pos]
# Remove empty spaces
element = element.replace(" ", "")
test = next((s for s in annotations.keys() if element in s), None) # returns 'abc123'
if test == None:
print "Early Not found "
if element in annotations.keys():
return annotations[element]
else:
return "not found"
def readAnnotFile(dataPath, file):
'''
:param dataPath:
:param file:
:return:
'''
annotations = {}
with open(dataPath + file) as csvfile:
reader = csv.reader(csvfile)
count = 0
for row in reader:
if row[1][0] == 'T': # FIXME: CHECK IF THIS IS VALID FOR ALL ELEMENTS
element = ''
if ',' in row[1]: # Detect if there is more than one element
for i in row[1]:
if i != ',':
element = element + i
else:
annotations[element] = row[3].strip() # Store test seqs as key and name as value
element = ''
else: # Only one element is in the cell
# FIXME: MAKE THIS A METHOD IT IS USED MORE THAN ONCE
# Remove empty spaces
key = row[1].replace(" ","")
# Find the | char to just obtain the first part of the ID
pos = key.find("|")
# Cut string when the char | is present
key = key[0:pos]
# Cut find the
annotations[key] = row[3].replace(" ","")
else:
print "error, not a valid register" + row[0]
#print annotations
return annotations
def readColorsFile(dataPath, file, annotations):
'''
:param dataPath:
:param file:
:param annotations:
:return:
'''
colorRegisters = {}
with open(dataPath + file) as csvfile:
reader = csv.reader(csvfile)
count = 0
annotatedFile = file[0:file.find(".csv")] + "_ANNOT.csv"
with open(dataPath + annotatedFile, 'wb') as csvfile:
writer = csv.writer(csvfile)
for row in reader:
if count != 0: # Ignore first Line
colorRegisters[row[0]] = defaultdict(list)
element = ''
# Write new file with annotations
csvRow = list()
# Append first row
csvRow.append(row[0])
# Append second row
csvRow.append(row[1])
for i in row[2]: # Iterate over test seqs and replace it for the long names
if i != ',': # split the line once a comma is detected
element = element + i
else:
element = element.strip() # Remove spaces at the beginning and at the end
anotName = findElement(annotations, element)
if anotName != 'not found':
if anotName == '#NAME?':
print element
print anotName
# print str(i)+ ": " + str(anotName)
colorRegisters[row[0]][row[1]].append(anotName)
# TODO: write the information in a CSV file
csvRow.append(anotName)
#print "element found"
else:
print "Register " + element + " not found"
# print element
element = '' # reset element to an empty value
count = count + 1
#break
writer.writerow(csvRow)
else: # Just increment count for the first line
count = count + 1
csvfile.close()
return colorRegisters
def main():
'''
:return:
'''
path = os.getcwd()
dataPath = path + "/data/"
files = readFiles()
#columns = defaultdict(list)
# Structures for saving all data
colorRegisters = {}
annotations = {}
# SORT all files to read first the ANOTT file
files.sort()
for file in files:
# Read colors file
if "COLORS" in file:
colorsRegisters = readColorsFile(dataPath, file, annotations)
# Read annot file
elif "ANNOT" in file:
annotations = readAnnotFile(dataPath, file)
if __name__ == "__main__":
main()
|
# Suppose we had a list S and a number N. How can we find out whether there is a subset in S that
# adds up to N?
def f(N, S):
r = 0
if N == 0:
return 1
if not S:
return 0
for num in S:
print(f'{N} {S}')
r += f(N - num, remove(S, num))
return r
# Removes an element a from list s. I need to write this because python's built-in remove is a
# morceau de merde
# Warning: may cause 1-off error because this isn't tested.
# @param s - list
# @param a - element to be removed
# @return s - list without the element a
def remove(s, a):
index = 0
for i in range(len(s)):
if s[i] == a:
index = i
return s[0:i] + s[i + 1:len(s) + 1]
s = [1, 2, 3, 4]
print(f(20, s))
|
def quicksort(a):
if len(a) <= 1:
return a
left = []
right = []
equal = []
pivot = a[-1]
for num in a:
if num < pivot:
left.append(num)
elif num > pivot:
right.append(num)
else:
equal.append(num)
return quicksort(left) + equal + quicksort(right)
array = [5, 10, 3, 12, 5, 5, 6]
print(quicksort(array))
|
__author__ = 'Sean Moore'
"""
Problem:
Run-length encoding is a fast and simple method of encoding strings. The basic
idea is to represent repeated successive characters as a single count and
character. For example, the string "AAAABBBCCDAA" would be encoded as
"4A3B2C1D2A".
Implement run-length encoding and decoding. You can assume the string to be
encoded have no digits and consists solely of alphabetic characters. You can
assume the string to be decoded is valid.
"""
def encode(s):
"""Return a run-length encoding of string s. s must consist of only alpha
characters and must be a valid string.
"""
if not s:
return s
count = 0
last_c = s[1]
encoded = ''
for c in s:
if c == last_c:
count += 1
else:
encoded += str(count) + last_c
last_c = c
count = 1
encoded += str(count) + last_c
return encoded
|
__author__ = "Sean Moore"
"""
Problem:
Given a list of integers, write a function that returns the largest sum of
non-adjacent numbers. Numbers can be `0` or negative.
For example, `[2, 4, 6, 2, 5]` should return `13`, since we pick `2`, `6`,
and `5`. `[5, 1, 1, 5]` should return `10`, since we pick `5` and `5`.
Follow-up: Can you do this in O(N) time and constant space?
"""
"""
This looks like a combinatorics problem, which I might be able to break down
into a divide and conquer approach using memoization to compute in O(n) time
and space. Here is a recursive relationship I noticed while walking through the
example manually:
case 1: 2,4,6,2,5
- -----
case 2: 2,4,6,2,5
- ---
"""
def max_non_adjacent_sum(a):
"""Recursive solution, breaking down the problem into subproblems."""
if not a:
return 0
if len(a) == 1:
return a[0]
return max(a[0] + max_non_adjacent_sum(a[2:]),
a[1] + max_non_adjacent_sum(a[3:]))
def max_non_adjacent_sum_memoized(a):
"""Improving the runtime complexity using memoization of the subproblems."""
table = dict()
def helper(a, table, i):
if i in table:
return table[i]
if len(a) - i == 0:
table[i] = 0
elif len(a) - i == 1:
table[i] = a[i]
elif len(a) - i == 2:
table[i] = max(a[0], a[1])
else:
table[i] = max(a[i] + helper(a, table, i + 2),
a[i + 1] + helper(a, table, i + 3))
return table[i]
return helper(a, table, 0) |
__author__ = "Sean Moore"
"""
Problem:
Given an array of integers, find the first missing positive integer in linear
time and constant space. In other words, find the lowest positive integer that
does not exist in the array. The array can contain duplicates and negative
numbers as well.
For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should
give 3.
You can modify the input array in-place.
"""
def first_missing_brute(input):
"""Brute force approach, ignoring the complexity constraints. Scan the array for
existance of the lowest positive integer so far, restarting the scan with the
next LPI when found. O(n^2) time, O(1) space.
"""
lpi = 1
while lpi in input:
lpi += 1
return lpi
def first_missing_sort(input):
"""Improvement on the brute force approach by sorting the array before scanning.
O(n log n) time, O(1) space.
"""
input.sort()
lpi = 1
for x in input:
if x == lpi:
lpi += 1
elif x > lpi:
break
return lpi
def first_missing(input):
"""Set membership approach. Convert the input array, in-place, into a set. At
each index, a corresponding value represents membership. The conversion is
done by iterating over the input and swapping each value into its corresponding
index. This is a linear time operation because no element is swapped more than
once. O(n) time, O(1) space.
"""
if not input:
return 1
for i in range(len(input)):
while ( input[i] != i + 1 and
input[i] > 0 and
input[i] <= len(input) and
input[i] != input[input[i] - 1] ):
value = input[i]
input[i], input[value - 1] = input[value - 1], value
for i in range(len(input)):
if input[i] != i + 1:
return i + 1
return i + 2 |
__author__ = "Sean Moore"
"""
Problem:
Compute the running median of a sequence of numbers. That is, given a stream of
numbers, print out the median of the list so far on each new element.
Recall that the median of an even-numbered list is the average of the two
middle numbers.
For example, given the sequence [2, 1, 5, 7, 2, 0, 5], your algorithm should
print out:
2
1.5
2
3.5
2
2
2
"""
"""
To calculate the median of numbers seen so far, those numbers need to be
collected. That means we need to assume that we have enough space to store the
entire stream in the most general case. This solution makes that assumption.
If we maintain a sorted aggregation on the stream, then the median can be
calculated just by using the middle one or two numbers like this:
median = middle value if odd
average of middle values if even.
So ideally, we need to be able to access the two middle elements efficently
each time an element is added to the collection, and also keep the collection
sorted. Using insertion sort on an array could work, but the runtime complexity
would be very poor with O(n^2). A more efficient approach could use two heaps,
one max heap of values smaller than the median and one min heap of values
equal to or larger than the median. In the odd case, pick the top element of
the min heap. In the even case, average the top elements of both heaps. Keep
the heaps balanced by poping and pushing to ensure the middle elements stay
on top. Insertion on a heap is O(log n).
"""
import heapq
def running_median(number_stream):
left = [] # numbers less than the running median
right = [] # numbers greater or equal to the running median
for x in number_stream:
# add the number
if len(right) == 0 or x >= right[0]:
heapq.heappush(right, x)
else:
heapq.heappush(left, -x)
# balance the heaps
if len(left) > len(right):
heapq.heappush(right, -heapq.heappop(left))
elif len(right) > len(left) + 1:
heapq.heappush(left, -heapq.heappop(right))
# calculate the median
if (len(left) + len(right)) % 2 == 0:
median = (-left[0] + right[0]) / 2.0
else:
median = right[0]
yield median
def list_medians(numbers):
return [median for median in running_median(numbers)]
def print_medians(numbers):
for median in running_median(numbers):
print(median) |
import random
def load_words(filename):
#with open(filename, 'r') as f:
# file_string = f.read()
#words = file_string.split()
words = ['hello', 'bye', 'world']
return words
def choose_secret_word(words):
word = random.choice(words)
return word
def is_secret_guessed(secret_word, letters_guessed):
all_guessed = True
for letter in secret_word:
if letter in letters_guessed:
all_guessed = True
else:
all_guessed = False
break
return all_guessed
def get_current_guess(secret_word, letters_guessed):
result = ''
for char in secret_word:
if char in letters_guessed:
result+=char
else:
result+='_'
return result
def second_game(secret_word):
secret_word = secret_word.lower()
num_guesses = 15
letters_guessed = []
while not(is_secret_guessed(secret_word, letters_guessed)) and num_guesses!=0:
char = input("Guess a letter: ").lower()
if len(char) != 1:
print("Enter one letter only!")
continue
letters_guessed.append(char)
if is_secret_guessed(secret_word, letters_guessed):
print("You won! :)")
return 'win'
if char not in secret_word:
num_guesses-=1
print("You have " + str(num_guesses) + " guesses remaining!")
print(get_current_guess(secret_word, letters_guessed))
print("You lost! :(")
return 'lose'
filename = 'words.txt'
words = load_words(filename)
word = choose_secret_word(words)
second_game(word)
|
# created by jenny trac
# created on Nov 20 2017
# program lets user calculate average of marks
import ui
marks = []
def enter_touch_up_inside(sender):
# button to add marks to the array
global marks
try:
new_mark = int(view['input_textfield'].text)
if new_mark >= 0 and new_mark <= 100:
marks.append(new_mark)
view['marks_textview'].text = view['marks_textview'].text + '\r' + str(new_mark)
view['average_label'].text = " "
else:
view['average_label'].text = "Error: Not an acceptable input"
except:
view['average_label'].text = "Error: Not an acceptable input"
def calculate_average_touch_up_inside(sender):
# button to calculate the average
total = 0
for every_mark in marks:
total = total + every_mark
average = total / len(marks)
view['average_label'].text = "The average is: " + str(average)
view = ui.load_view()
view.present('sheet')
|
from random import sample
print('Bem-Vindo ao sorteador de ordem!')
n1 = input('Informe o primeiro nome')
n2 = input('Informe o segundo nome')
n3 = input('Informe o terceiro nome')
n4 = input('Informe o quarto nome')
lista = [n1, n2, n3, n4]
sorteados = sample(lista, 4)
print('Os alunos que apresentaram na seguinte ordem'
'{}'.format(sorteados))
|
numeros = list()
escolha = ''
while True:
num = int(input('Informe um número para a lista'))
if not num in numeros:
numeros.append(num)
print('Valor \033[32madicionado\033[m.')
else:
print('Já existe esse valor na lista, \033[31mnão\033[m será adicionado.')
escolha = input('Você quer continuar? S/N')
if escolha in 'Nn':
break
numeros.sort()
print(f'Os valores adicionador foram {numeros}')
|
lista = ('zero', 'um', 'dois', 'três', 'quatro', 'cinco', 'seis', 'sete', 'oito', 'nove', 'dez',
'onze', 'doze', 'treze', 'quatorze', 'quinze', 'dezesseis', 'dezesete', 'dezoito', 'dezenove', 'vinte')
while True:
escolha = ' '
num = int(input('Informe o número entre 0 a 20 para ser escrito por extenso'))
while num < 0 or num > 20:
num = int(input('Errado!!Você informou um valor maior que 20 e menor que 0'))
print(f'O número escolhido foi {lista[num]}')
while not escolha in 'SsNn':
escolha = str(input('Informe S/N para continuar')).strip()[0]
if escolha in 'Nn':
break
print('Volte sempre!!!')
|
from random import randint
menor = maior = 0
lista = (randint(-100,100), randint(-100,100), randint(-100,100),
randint(-100,100), randint(-100,100))
print(f'Os valores da tupla são:', end = ' ')
for u in lista:
print(f'{u}', end = ' ')
for c in range(5):
if c == 0 or lista[c] < menor:
menor = lista[c]
elif lista[c] > maior:
maior = lista[c]
print(f'\nO menor valor é {menor} e maior é {maior}')
|
import random
def jogar():
print("\n\nOla felipe vamos arrasar no python!!!!!!!")
print("***********************************************")
print("Bem-Vindo ao Jogo de Adivinhação!")
print("************************************************")
print("Nivel de dificuldade\n(1) facil numeros entre 1 a 10\n(2) médio numeros entre 1 a 50\n(3) dificil números entre 1 a 100")
dificuldade = int(input("Qual o nível ?"))
vezes = int(input("Informe quantas vezes quer chances"))
print("Você começará com 1000 pontos e perderá conforme erra")
pontos = 1000
if (dificuldade == 1):
numero_secreto = round(random.randrange(1, 11, 1))
elif (dificuldade == 2):
numero_secreto = round(random.randrange(1, 51, 1))
else:
numero_secreto = round(random.randrange(1, 101, 1))
for vezes in range(vezes,0, -1):
tentativa =int(input("Digite o seu numero entre 1 até 100: "))
while(tentativa < 1 or tentativa > 100):
tentativa =int(input("Por favor você deve digitar apenas entre 1 até 100"))
certo = tentativa == numero_secreto
maior = tentativa > numero_secreto
menor = tentativa < numero_secreto
if (certo):
print("Parabéns você acertou sua pontuação foi {}".format(pontos))
break
else:
if(maior):
print("Você errou ! O número que digitou é maior que o número secreto")
if(vezes != 1):
print("Tem mais {} chances".format(vezes-1))
pontos = round(pontos - abs(numero_secreto - tentativa) / 3)
elif(menor):
print("Você errou ! O número que digitou é menor que o número secreto")
if(vezes != 1):
print("Tem mais {} chances".format(vezes-1))
pontos = round(pontos - abs(numero_secreto - tentativa) / 3)
if(vezes == 1):
print("Suas chances acabaram o número secreto é {} sua pontuação foi {}".format(numero_secreto, pontos))
print("Fim do jogo")
if(__name__ == "__main__"):
jogar()
|
marcador = 30 * '\033[33m//\033[m'
while True:
try:
inteiro = input('Informe um número inteiro')
if inteiro.isnumeric():
inteiro = int(inteiro)
else:
inteiro = int('y')
except ValueError:
print('\033[31mERRO!!Digite o número correto\033[m')
else:
break
print(marcador)
while True:
try:
real = input('Informe um número real').strip()
if real == '':
real = float(0)
elif not real.isalpha():
if '.' in real:
real = float(real)
else:
real = float('y')
else:
real = float(real)
except ValueError:
print('\033[31mERRO!!Digite o número correto\033[m')
else:
break
print(marcador)
print(f'O número inteiro digitado foi {inteiro}')
print(f'O número real digitado foi {real}')
|
frase: str = ' Olá felipe '
print(frase.replace('Olá', 'Oi'))
print(frase.upper())
print('w' in frase)
print(frase.find('ipe'))
print(frase.split('e'))
print(frase.strip())
print('+'.join(frase))
|
from datetime import date
atual = date.today().year
maior:int = 0
menor:int = 0
for y in range(7):
nasc = int(input('Informe o ano do nascimento da {} pessoa'.format(y+1)))
idade = atual - nasc
if idade >= 21:
maior += 1
else:
menor += 1
print('{} pessoas são maiores capazes\n{} pessoas são menores incapazes'
.format(maior, menor))
|
from math import sqrt, ceil
n = float(input('Informe um número para tirar raiz quadrada'))
raiz = sqrt(n)
print('A raiz de {} é {}'.format(n, ceil(raiz)))
|
n = int(input('Informe um número inteiro'))
print('O número informado foi {}, seu sucessor é {}'.format(n, n+1), end=', ')
print('o antecessor do número é {}'.format(n-1))
|
from random import choice
print('Bem-Vindo ao sorteador de nomes')
n1 = input('Informe o nome do primeiro aluno')
n2 = input('Informe o nome do segundo aluno')
n3 = input('Informe o nome do terceiro aluno')
n4 = input('Informe o nome do quarta aluno')
lista = n1, n2, n3, n4
sorteado = choice(lista)
print('O sorteado foi {}'.format(sorteado))
|
def voto(nasc):
from datetime import date
atual = date.today().year
idade = atual - nasc
if idade < 16:
return 'Sua idade é {} não pode votar'.format(idade)
elif 16 <= idade < 18 or 65 <= idade:
return f'Sua idade é {idade} seu voto é opcional'
else:
return f'Sua idade é {idade} seu voto é obrigatorio'
ano = int(input('Informe o ano de nascimento'))
resp = voto(ano)
print(resp)
print(type(resp))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.