text
stringlengths 37
1.41M
|
---|
#This is a simple guess the password example program counting the tryouts of guessing the right word
p = "IlovePython"
x = ""
count=0
while x != p:
x = input("Password: ")
print(count)
count=count+1
print ("Congratulations, the password is right!")
|
class Integer(object):
def __init__(self, number, p):
self.number=number
self.p=p
def display(self):
if self.p:
print self.number
else:
print (self.number - self.number - self.number)
class NegativeInteger(Integer):
def __init__(self, number):
super(NegativeInteger, self).__init__(number, False)
def display(self):
Integer.display(self)
print "This is an object of the NegativeInteger class."
if __name__=="__main__":
test = Integer(3, True)
test.display()
test2 = NegativeInteger(4)
test2.display()
|
# maps a variables values based on old range and new range linearly
# source: https://stackoverflow.com/questions/929103/convert-a-number-range-to-another-range-maintaining-ratio
def variable_mapping(value, from_low, from_high, to_low, to_high):
"""
maps a variables values based on old range and new range linearly
source: https://stackoverflow.com/questions/929103/convert-a-number-range-to-another-range-maintaining-ratio
:param value: the desired value to map to the range
:param from_low: the previous range low
:param from_high: the previous range high
:param to_low: the desired range low
:param to_high: the desired range high
:return:
"""
new_range = (to_high - to_low)
old_range = (from_high - from_low)
new_value = (((value - from_low) * new_range) / old_range) + to_low
return new_value
|
"""
A Baby class and functions that use/test it.
Authors: Dave Fisher, David Mutchler, Vibha Alangar, Matt Boutell,
Mark Hays, Amanda Stouder, Derek Whitley, their colleagues,
and PUT_YOUR_NAME_HERE.
""" # TODO: 1. PUT YOUR NAME IN THE ABOVE LINE.
import random
def main():
""" Runs the tests of the Baby class. """
print("UN-comment the following TESTS, one by one, when you are ready.")
# UN-comment the following, one by one, when you are ready to TEST.
# run_test_1()
# run_test_2()
###############################################################################
# TODO: 2. In this module you will implement and test a Baby class.
# Here is an OVERVIEW of the steps you will take to do so.
# _
# Step 2 (this step): Read this overview of this module.
# Step 3: Read and understand the SPECIFICATION for the Baby class.
# Step 4: Read and understand the TESTS for the Baby class.
# We supplied those tests.
# Step 5: IMPLEMENT and TEST the Baby class.
# _
# Once you understand this OVERVIEW, mark this _TODO_ as DONE.
###############################################################################
###############################################################################
# TODO: 3. SPECIFICATION (read the following):
# Here (below) are the methods that you must implement in your Baby class:
# ----------------------------------------------------------------------------
# _
# Constructor method (that is, the __init__ method):
# What comes in:
# -- self
# -- a string for the name of the Baby
# What goes out: Nothing (i.e., None).
# Side effects:
# -- Prints "Hello baby <your baby's name>!"
# -- Sets instance variables as needed
# [YOU FIGURE OUT WHAT IS NEEDED AS YOU IMPLEMENT THE METHODS!]
# Example:
# b = Baby("McKinley")
# causes the following to be printed on the Console:
# Hello baby McKinley!
# _
# feed_baby:
# What comes in:
# -- self
# What goes out: Nothing (i.e., None).
# Side effects:
# -- Prints "Thank you for feeding baby <your baby's name>."
# -- Modifies instance variables as needed.
# Example:
# b = Baby("Joshua")
# b.feed_baby()
# causes the following to be printed on the Console:
# Hello baby Joshua!
# Thank you for feeding baby Joshua.
# _
# hour_passes
# What comes in:
# -- self
# What goes out: Nothing (i.e., None).
# Side effects:
# -- If this is the FIRST time this method has been called
# since this Baby was created or last fed, then this method prints:
# "Baby <your baby's name> is sleeping."
# _
# -- If this is the SECOND time this method has been called
# since baby was created or last fed, then this method prints:
# "Baby <your baby's name> is awake. Time for food."
# _
# -- If this is the THIRD (OR MORE) time this method has been called
# since baby was created or last fed, then this method prints:
# "Baby <your baby's name> is CRYING uncontrollably! Feed the Baby!"
# _
# -- Modifies instance variables as needed.
# _
# Examples: See the two TEST functions below.
# _
# You may find it helpful to read the two TEST functions (below) at this time.
# If reading the TEST functions below does not make this specification clear,
# ASK QUESTIONS AS NEEDED to clarify this specification.
# _
# Once you understand this SPECIFICATION, mark this _TODO_ as DONE.
###############################################################################
###############################################################################
# TODO: 4. TESTS (read the following):
# The two functions that follow this comment TEST the Baby class.
# For each of those two functions:
# 1. READ the CODE in the function.
# As you do so, PREDICT what the code will cause to be printed.
# 2. READ the doc-string for the function.
# It shows the CORRECT output when the function runs.
# 3. CONFIRM that you understand WHY the function's CODE produces
# the OUTPUT that the doc-string says that it will.
# _
# If you do not understand why the CODE produces the OUTPUT as written
# in the function's doc-string, STOP HERE and ASK QUESTIONS AS NEEDED.
# Do ** NOT ** attempt to write the Baby class
# without fully understanding both of its test functions.
# _
# Once you fully understand the TESTS below, mark this _TODO_ as DONE.
###############################################################################
def run_test_1():
"""
Running this test should cause EXACTLY the following
to be displayed (i.e. printed) on the Console:
------------ Running test #1: ------------
Hello baby Joshua!
Baby Joshua is sleeping.
Baby Joshua is awake. Time for food.
Baby Joshua is CRYING uncontrollably! Feed the Baby!
Baby Joshua is CRYING uncontrollably! Feed the Baby!
Thank you for feeding baby Joshua.
Baby Joshua is sleeping.
Baby Joshua is awake. Time for food.
Thank you for feeding baby Joshua.
Baby Joshua is sleeping.
Thank you for feeding baby Joshua.
Baby Joshua is sleeping.
Baby Joshua is awake. Time for food.
Baby Joshua is CRYING uncontrollably! Feed the Baby!
Examine the code in this test to be sure that you understand
WHY it causes the above to be printed.
"""
print()
print('------------ Running test #1: ------------ ')
b = Baby("Joshua")
b.hour_passes()
b.hour_passes()
b.hour_passes()
b.hour_passes()
print() # Just to make the output easier to read.
b.feed_baby()
b.hour_passes()
b.hour_passes()
print() # Just to make the output easier to read.
b.feed_baby()
b.hour_passes()
print() # Just to make the output easier to read.
b.feed_baby()
b.hour_passes()
b.hour_passes()
b.hour_passes()
def run_test_2():
"""
Running this test should cause EXACTLY the following
to be displayed (i.e. printed) on the Console:
------------ Running test #2: ------------
Hello baby McKinley!
Hello baby Keegan!
--- Iteration #1 ---
Baby Keegan is sleeping.
Thank you for feeding baby McKinley.
Baby McKinley is sleeping.
Baby McKinley is awake. Time for food.
Baby McKinley is CRYING uncontrollably! Feed the Baby!
Baby McKinley is CRYING uncontrollably! Feed the Baby!
Thank you for feeding baby McKinley.
Baby McKinley is sleeping.
Baby McKinley is awake. Time for food.
--- Iteration #2 ---
Baby Keegan is awake. Time for food.
Thank you for feeding baby McKinley.
Baby McKinley is sleeping.
Baby McKinley is awake. Time for food.
Baby McKinley is CRYING uncontrollably! Feed the Baby!
Baby McKinley is CRYING uncontrollably! Feed the Baby!
Thank you for feeding baby McKinley.
Baby McKinley is sleeping.
Baby McKinley is awake. Time for food.
--- Iteration #3 ---
Baby Keegan is CRYING uncontrollably! Feed the Baby!
Thank you for feeding baby McKinley.
Baby McKinley is sleeping.
Baby McKinley is awake. Time for food.
Baby McKinley is CRYING uncontrollably! Feed the Baby!
Baby McKinley is CRYING uncontrollably! Feed the Baby!
Thank you for feeding baby McKinley.
Baby McKinley is sleeping.
Baby McKinley is awake. Time for food.
Examine the code in this test to be sure that you understand
WHY it causes the above to be printed.
"""
print()
print('------------ Running test #2: ------------ ')
mckinley = Baby("McKinley")
keegan = Baby("Keegan")
for k in range(3):
print() # Just to make the output easier to read.
print("--- Iteration #{} ---".format(k + 1))
keegan.hour_passes()
mckinley.feed_baby()
for j in range(4):
mckinley.hour_passes()
mckinley.feed_baby()
mckinley.hour_passes()
mckinley.hour_passes()
###############################################################################
# TODO: 5.
# Implement the entire Baby class
# (including its 3 methods: __init__, feed_baby, and hour_passes)
# below this comment.
# _
# Here is a reminder for the syntax (notation) to define a new class:
# class NameOfClass(object):
# """ Brief description of what an object of the class 'is'. """
# _
# AFTER you have implemented the ENTIRE Baby class,
# un-comment (one-by-one) the calls in main to the two tests
# and confirm that the tests produce the output that the doc-strings
# for the tests show as the CORRECT output.
# _
# Fix errors as needed! Do not hesitate to ASK QUESTIONS AS NEEDED.
###############################################################################
# -----------------------------------------------------------------------------
# Calls main to start the ball rolling.
# -----------------------------------------------------------------------------
main()
|
#]pzGhαXAbϥΤؤPXᥬC
#]pG_@k10630819\yu
#v覡G mWХܢwDӷ~ʢwۦP覡
from turtle import *
#define funtion
def eight(s):
for i in range(8):
forward(s)
left(360/8)
def six(s):
for i in range(6):
forward(s)
left(60)
def five(s):
for i in range(5):
forward(s)
left(360/5)
def flower1(s):
for i in range(50):
eight(s)
left(36.4)
def flower2(s):
#left()
for i in range(42):
six(s)
left(60.42)
def flower3(s):
for i in range(42):
six(s)
left(61)
def flower4(s):
for i in range(40):
five(s)
left(72.5)
def flower5(s):
for i in range(35):
five(s)
left(72.7)
def flower6(s):
for i in range(48):
eight(s)
left(60.6)
speed(0)
#initialize
start_x = -200
start_y = 200
size = 40
gap = 25
n = 10
#start drawing
for j in range(n):
for i in range(n):
penup()
x = start_x + (2*size+gap)*i
y = start_y - (2*size+gap)*j
goto(x,y)
pendown()
if i==j or i+6==j or j+6==i:
flower3(27)
elif i+1==j or j+1==i or i+7==j or j+7==i:
flower4(32)
elif i+2==j or j+2==i or i+8==j or j+8==i:
flower6(20)
elif i+3==j or j+3==i or i+9==j or j+9==i:
flower2(27)
elif i+4==j or j+4==i:
flower5(32)
elif i+5==j or j+5==i:
flower1(20)
hideturtle()
done() |
def insertion_sort(arr):
for i in range(1, len(arr)):
value = arr[i]
j = i
while j > 0 and arr[j-1] > value: # while j > 0 and arr[j-1] > arr[i]
arr[j] = arr[j-1] # arr[j] is set to arr[j-1]
j += -1 # increment j by -1
arr[j] = value # arr[j] is set to arr[i]
return arr
A = [54, 26, 93, 17, 77, 31, 44, 55, 20, 4, 19, 84, -51, -14]
print(insertion_sort(A))
|
class Card:
def __init__(self, suit, rank):
self.suit = suit
self.rank = rank
def __str__(self):
return ("%s of %s" %(self.rank, self.suit))
class CardDeck:
def __init__(self):
self.deck = []
for suit in ['clubs', 'diamonds', 'hearts', 'spades']:
for rank in ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']:
self.deck += [Card(suit, rank)]
def shuffle(self):
for i in range(100):
a, b = random.randrange(len(self.deck)), random.randrange(len(self.deck))
self.deck[a], self.deck[b] = self.deck[b], self.deck[a]
def deal(self):
return self.cards.pop()
class CardHand:
def __init__(self, hand):
self.hand = hand
def get_card(self, card):
print(card)
self.deck += [card]
def full_house(self):
ranks = []
for i in range(5):
ranks += [self.hand[i].rank]
B = list(set(ranks))
return ranks.count(B[0])*ranks.count(B[1]) == 6
def flush(self):
return self.hand[0].suit == self.hand[1].suit == self.hand[2].suit == self.hand[3].suit == self.hand[4].suit
def pair(self):
ranks = []
for i in range(5):
ranks += [self.hand[i].rank]
B = set(ranks)
return len(B) == 4
|
#application form for users (part 1) and collecting them (part 2)
#part 1
current_year = 2020
minimum_age = 14
maximum_age = 61
print("This is your application form please insert your data")
name = input("Please, enter your name : ")
surname = input("Please, enter your surname : ")
year = input("Please, enter the year of your birth : ")
current_maximum_age = current_year - int(year)
print("Your age this year will be" + str(current_maximum_age) + ", so")
if current_maximum_age <= minimum_age:
print ("Dear " + name + ", Sorry you are not acceptable forv any volunteering experience, yet.")
elif current_maximum_age >= maximum_age:
print ("Dear " + name + ", You are already oldaged, please, #stayathome for your health")
else :
print ("Dear " + name + ", You are in desired age group")
gender = int(input("Choose your gender 'number' \n1. female \n2. male \n answer : "))
while gender < 1 or gender > 2:
print("Your input is not required number, please enter a proper one only".format(input=gender))
gender = int(input("Choose your gender 'number' \n1. female \n2. male \nanswer"))
else:
print("Thanks")
if gender == 1:
marriage = input("Are you married 'yes' or 'no' : ")
position = " Ms. "
else:
army_service = input("Have you served in army 'yes' or 'no' : ")
position = "Mr."
listlanguages = []
number_of_languages = int(input("Dear " + name + ", how many languages do you know? "))
for i in range(number_of_languages):
number_of_languages = i + 1
input_string = input("Enter your known language number " + str(int(i+1)) + " " )
listlanguages.append(input_string)
#PART2
print("THANK YOU")
print("Your data is stored" + position + " " + surname + " " + name)
print("Your maximum age this year is " + str(current_maximum_age))
print("Your known languages are ", listlanguages)
|
#-------------------------------------------------------------------------------
# Name: tsp_chromosome
# Purpose:
#
# Author: aaron
#
# Created: 17/04/2011
# Copyright: (c) aaron 2011
#-------------------------------------------------------------------------------
#!/usr/bin/env python
import random
class Chromosome(object):
'''represents a potential solution for a traveling-salesman problem'''
mutation_rate = .15
'''the distances are represented by a dictionary; each key is a tuple in the
form (source, destination), and the key is the distance between them'''
distances = {} # = {(i, j):(1 if i != j else None) for i in range(25) for j in range(25)}
def __init__(self, length=25, randomize=True):
'''initializes an instance
Optional 'length' argument specifies the length of the chromosome (the
number of cities); default value is 25.
Optional 'randomize' argument determines whether the solution is
randomized; default value is True.'''
self.length = length
self.data = list(range(self.length))
if randomize:
random.shuffle(self.data)
def __get_random_endpoints__(self):
'''Returns a tuple containing a random start- and
end-point within the chromosome'''
p1 = random.randint(0, self.length - 1)
p2 = p1
# make sure they are unique
while p2 == p1:
p2 = random.randint(0, self.length - 1)
# swap them so the lower value is first
return (p1, p2) if p1 < p2 else (p2, p1)
def reproduce(father, mother):
'''Creates two offspring from the specified parents
using Order Crossover Recombination'''
# get end-points
start, end = father.__get_random_endpoints__()
# create two children, using both parents in each role
return Chromosome.__reproduce__(father, mother, start, end), \
Chromosome.__reproduce__(mother, father, start, end)
def __reproduce__(father, mother, start, end):
'''Creates a single child from the specified parents
using Order Crossover Recombination'''
# copy the segment from the first parent
child_data = father.data[start:end]
# add remaining data from second parent in the order it appears
# after the second end-point
for i in mother.data[end:] + mother.data[:end]:
if i not in child_data:
child_data.append(i)
# create a new chromosome from that data
c = Chromosome(father.length)
c.data = child_data
c.__mutate__()
return c
def __mutate__(self):
'''Randomly determines whether a mutation should occur and,
if so, mutates the chromosome using Inversion Mutation'''
if random.random() > Chromosome.mutation_rate:
# don't mutate, just quit
return
# choose two unique end-points
start, end = self.__get_random_endpoints__()
# reverse the segment between end-points
self.data = self.data[:start] + self.data[start:end][::-1] + self.data[end:]
return start, end
def get_fitness(self):
distance = 0
src = self.data[0]
# this loop will give us all edges, including the end back to the
# beginning (which is why we have the weird loop target)
for dst in self.data[1:] + self.data[:1]:
distance += Chromosome.distances[(src, dst)]
src = dst
return distance
def main():
c1 = Chromosome(4, False)
Chromosome.distances = {(0,0):None, (0,1):1, (0,2):2, (0,3):3, (1,0):4, (1,1):None, (1,2):5, (1,3):6, (2,0):7, (2,1):8, (2,2):None, (2,3):9, (3,0):10, (3,1):11, (3,2):12, (3,3):None}
print(c1.get_fitness())
if __name__ == '__main__':
main() |
import re
class Solution:
def get_check_digit(self, input):
check = re.match("[0-9]-[0-9]{2}-[0-9]{6}-[a-z]$", input)
if check:
i = 0
# while(i<9):
total = 0
i = 1
for pos in input:
if pos.isdecimal():
total += i*int(pos)
i += 1
return total % 11
return -1
|
#!/usr/bin/env python
import numpy as np
def warmUpExercise(*args, **kwargs):
# warmUpExercise Example function in python
# warmUpExercise() is an example function that returns the 5x5 identity matrix
# ============= YOUR CODE HERE ==============
# Instructions: Return the 5x5 identity matrix
# In python, we return values by defining which variables
# represent the return values (at the top of the file)
# and then set them accordingly.
return np.identity(5)
# ===========================================
|
# string permutation in lexicographically order with repetition of characters in the string
def permute(input):
count_map = {}
for ch in input:
if ch in count_map.keys():
count_map[ch] = count_map[ch] + 1
else:
count_map[ch] = 1
keys = sorted(count_map)
str = []
count = []
for key in keys:
str.append(key)
count.append(count_map[key])
result = [0 for x in range(len(input))]
permute_util(str, count, result, 0)
def permute_util(str, count, result, level):
if level == len(result):
print(result)
return
for i in range(len(str)):
if count[i] == 0:
continue;
result[level] = str[i]
count[i] -= 1
permute_util(str, count, result, level + 1)
count[i] += 1
if __name__ == '__main__':
input = ['B', 'C', 'A', 'A']
permute(input)
|
"""
Problem Statement
=================
Given an array of n positive integers. Write a program to find the sum of maximum sum subsequence of the given array
such that the integers in the subsequence are in increasing order.
Complexity
----------
* Time Complexity: O(n^2)
* Space Complexity: O(n)
Video
-----
* https://youtu.be/99ssGWhLPUE
Reference
---------
* http://www.geeksforgeeks.org/dynamic-programming-set-14-maximum-sum-increasing-subsequence/
"""
def maximum_sum_subsequence(sequence):
sequence_length = len(sequence)
T = [sequence[i] for i in range(sequence_length)]
for index_i in range(1, sequence_length):
for index_j in range(0, index_i):
if sequence[index_j] < sequence[index_i]:
T[index_i] = max(T[index_i], T[index_j] + sequence[index_i])
return max(T)
if __name__ == '__main__':
sequence = [1, 101, 10, 2, 3, 100, 4]
assert 111 == maximum_sum_subsequence(sequence)
|
"""
Problem Statement
=================
Given two sequences A = [A1, A2, A3,..., An] and B = [B1, B2, B3,..., Bm], find the length of the longest common
subsequence.
Video
-----
* https://youtu.be/NnD96abizww
Complexity
----------
* Recursive Solution: O(2^n) (or O(2^m) whichever of n and m is larger).
* Dynamic Programming Solution: O(n * m)
Reference
---------
* https://en.wikipedia.org/wiki/Longest_common_subsequence_problem
* http://www.geeksforgeeks.org/dynamic-programming-set-4-longest-common-subsequence/
"""
def lcs_recursive_helper(sequence1, sequence2, index1, index2):
if (index1 == len(sequence1)) or (index2 == len(sequence2)):
return 0
if sequence1[index1] == sequence2[index2]:
return 1 + lcs_recursive_helper(sequence1, sequence2, index1 + 1, index2 + 1)
return max(lcs_recursive_helper(sequence1, sequence2, index1 + 1, index2),
lcs_recursive_helper(sequence1, sequence2, index1, index2 + 1))
def longest_common_subsequence_recursive(sequence1, sequence2):
return lcs_recursive_helper(sequence1, sequence2, 0, 0)
def longest_common_subsequence(sequence1, sequence2):
cols = len(sequence1) + 1 # Add 1 to represent 0 valued column for DP
rows = len(sequence2) + 1 # Add 1 to represent 0 valued row for DP
T = [[0 for _ in range(cols)] for _ in range(rows)]
max_length = 0
for i in range(1, rows):
for j in range(1, cols):
if sequence2[i - 1] == sequence1[j - 1]:
T[i][j] = 1 + T[i - 1][j - 1]
else:
T[i][j] = max(T[i - 1][j], T[i][j - 1])
max_length = max(max_length, T[i][j])
return max_length
if __name__ == '__main__':
sequence1 = "ABCDGHLQR"
sequence2 = "AEDPHR"
expected_length = 4
assert expected_length == longest_common_subsequence_recursive(sequence1, sequence2)
assert expected_length == longest_common_subsequence_recursive(sequence2, sequence1)
assert expected_length == longest_common_subsequence(sequence1, sequence2)
assert expected_length == longest_common_subsequence(sequence2, sequence1)
|
"""
Problem Statement
=================
Given the number of nodes N, in a pre-order sequence how many unique trees can be created? Number of tree is exactly
same as number of unique BST create with array of size n. The solution is a catalan number.
Complexity
----------
* Dynamic Programming: O(n^2)
* Recursive Solution: O(2^n)
Video
-----
* https://youtu.be/RUB5ZPfKcnY
"""
def num_trees(num_nodes):
T = [0 for _ in range(num_nodes + 1)]
T[0] = 1
T[1] = 1
for n in range(2, num_nodes + 1):
for j in range(0, n):
T[n] += T[j] * T[n - j - 1]
return T[num_nodes]
def num_trees_recursive(num_nodes):
if num_nodes == 0 or num_nodes == 1:
return 1
result = 0
for n in range(1, num_nodes + 1):
result += num_trees_recursive(n - 1) * num_trees_recursive(num_nodes - n)
return result
if __name__ == '__main__':
assert 5 == num_trees(3)
assert 14 == num_trees(4)
assert 42 == num_trees(5)
assert 5 == num_trees_recursive(3)
assert 14 == num_trees_recursive(4)
assert 42 == num_trees_recursive(5)
|
"""
Problem Statement
=================
Given a positive integer N, count all the numbers from 1 to 2^N, whose binary representation does not have consecutive
1s.
This is a simple application of fibonacci series.
Video
-----
* https://www.youtube.com/watch?v=a9-NtLIs1Kk
Complexity
----------
* Runtime Complexity: O(n)
Reference
---------
* http://www.geeksforgeeks.org/count-number-binary-strings-without-consecutive-1s/
"""
def consec_one(num_n):
f1 = f2 = 1
for _ in range(num_n):
f1, f2 = f1 + f2, f1
return f1
if __name__ == '__main__':
assert 13 == consec_one(5)
|
#dijkstra's algorithm
# java code https://github.com/mission-peace/interview/blob/master/src/com/interview/graph/DijkstraShortestPath.java
from priorityqueue import PriorityQueue
from graph import Graph
import sys
def shortest_path(graph, sourceVertex):
min_heap = PriorityQueue(True)
distance = {}
parent = {}
for vertex in graph.all_vertex.values():
min_heap.add_task(sys.maxsize, vertex)
min_heap.change_task_priority(0, sourceVertex)
distance[sourceVertex] = 0
parent[sourceVertex] = None
while min_heap.is_empty() is False:
task = min_heap.peek_task()
weight = min_heap.get_task_priority(task)
current = min_heap.pop_task()
distance[current] = weight
for edge in current.edges:
adjacent = get_other_vertex_for_edge(current, edge)
if min_heap.contains_task(adjacent) is False:
continue
new_distance = distance[current] + edge.weight;
if min_heap.get_task_priority(adjacent) > new_distance:
min_heap.change_task_priority(new_distance, adjacent)
parent[adjacent] = current
return distance
def get_other_vertex_for_edge(vertex, edge):
if edge.vertex1.id == vertex.id:
return edge.vertex2
else:
return edge.vertex1
if __name__ == '__main__':
graph = Graph(False)
graph.add_edge(1,2,5)
graph.add_edge(2,3,2)
graph.add_edge(1,4,9)
graph.add_edge(1,5,3)
graph.add_edge(5,6,2)
graph.add_edge(6,4,2)
graph.add_edge(3,4,3)
distance = shortest_path(graph, graph.all_vertex[1])
print(distance)
|
"""
Problem Statement
=================
Given different dimensions and unlimited supply of boxes for each dimension, stack boxes on top of each other such that
it has maximum height but with caveat that length and width of box on top should be strictly less than length and width
of box under it. You can rotate boxes as you like.
1) Create all rotations of boxes such that length is always greater or equal to width
2) Sort boxes by base area in non increasing order (length * width). This is because box
with more area will never ever go on top of box with less area.
3) Take T[] and result[] array of same size as total boxes after all rotations are done
4) Apply longest increasing subsequence type of algorithm to get max height.
Analysis
--------
If n number of dimensions are given total boxes after rotation will be 3n.
* Space complexity is O(n)
* Time complexity - O(nlogn) to sort boxes. O(n^2) to apply DP on it So really O(n^2)
Video
-----
* https://youtu.be/9mod_xRB-O0
References
----------
* http://www.geeksforgeeks.org/dynamic-programming-set-21-box-stacking-problem/
* http://people.cs.clemson.edu/~bcdean/dp_practice/
"""
from collections import namedtuple
from itertools import permutations
dimension = namedtuple("Dimension", "height length width")
def create_rotation(given_dimensions):
"""
A rotation is an order wherein length is greater than or equal to width. Having this constraint avoids the
repetition of same order, but with width and length switched.
For e.g (height=3, width=2, length=1) is same the same box for stacking as (height=3, width=1, length=2).
:param given_dimensions: Original box dimensions
:return: All the possible rotations of the boxes with the condition that length >= height.
"""
for current_dim in given_dimensions:
for (height, length, width) in permutations((current_dim.height, current_dim.length, current_dim.width)):
if length >= width:
yield dimension(height, length, width)
def sort_by_decreasing_area(rotations):
return sorted(rotations, key=lambda dim: dim.length * dim.width, reverse=True)
def can_stack(box1, box2):
return box1.length < box2.length and box1.width < box2.width
def box_stack_max_height(dimensions):
boxes = sort_by_decreasing_area([rotation for rotation in create_rotation(dimensions)])
num_boxes = len(boxes)
T = [rotation.height for rotation in boxes]
R = [idx for idx in range(num_boxes)]
for i in range(1, num_boxes):
for j in range(0, i):
if can_stack(boxes[i], boxes[j]):
stacked_height = T[j] + boxes[i].height
if stacked_height > T[i]:
T[i] = stacked_height
R[i] = j
max_height = max(T)
start_index = T.index(max_height)
# Prints the dimensions which were stored in R list.
while True:
print boxes[start_index]
next_index = R[start_index]
if next_index == start_index:
break
start_index = next_index
return max_height
if __name__ == '__main__':
d1 = dimension(3, 2, 5)
d2 = dimension(1, 2, 4)
assert 11 == box_stack_max_height([d1, d2])
|
#Graph class
# Java code https://github.com/mission-peace/interview/blob/master/src/com/interview/graph/Graph.java
class Graph(object):
def __init__(self, is_directed):
self.all_edges = []
self.all_vertex = {}
self.is_directed = is_directed
def add_edge(self, id1, id2, weight=0):
if id1 in self.all_vertex:
vertex1 = self.all_vertex[id1]
else:
vertex1 = Vertex(id1)
self.all_vertex[id1] = vertex1
if id2 in self.all_vertex:
vertex2 = self.all_vertex[id2]
else:
vertex2 = Vertex(id2)
self.all_vertex[id2] = vertex2
edge = Edge(vertex1, vertex2, self.is_directed, weight)
self.all_edges.append(edge)
vertex1.add_adjacent_vertex(edge, vertex2)
if self.is_directed is not True:
vertex2.add_adjacent_vertex(edge,vertex1)
class Edge(object):
def __init__(self, vertex1, vertex2, is_directed, weight):
self.vertex1 = vertex1
self.vertex2 = vertex2
self.is_directed = is_directed
self.weight = weight
def __eq__(self, other):
return self.vertex1.id == other.vertex1.id and self.vertex2.id == other.vertex2.id
def __hash(self):
return hash(vertex1) + hash(vertex2)
def __str__(self):
return "Edge " + str(self.vertex1) + " " + str(self.vertex2) + " Weight-" + str(self.weight)
def __repr__(self):
return self.__str__()
class Vertex(object):
def __init__(self, id):
self.id = id;
self.edges = []
self.adjacent_vertices = []
def add_adjacent_vertex(self, edge, vertex):
self.edges.append(edge)
self.adjacent_vertices.append(vertex)
def get_degree(self):
return len(self.edges)
def __eq__(self, other):
return self.id == other.id
def __hash__(self):
return hash(self.id)
def __str__(self):
return str("Vertex-" + str(self.id))
def __repr__(self):
return self.__str__();
def __lt__(self, other):
return self.id < other.id
def __gt__(self, other):
return self.id > other.id
if __name__ == '__main__':
g = Graph(False)
g.add_edge(1,2,10)
g.add_edge(2,3,5)
g.add_edge(1,4,6)
for edge in g.all_edges:
print(edge)
for vertex in g.all_vertex:
print("Vertex " + str(g.all_vertex[vertex]))
for edge in g.all_vertex[vertex].edges:
print("Edge " + str(edge))
|
"""
Problem Statement
=================
Ugly numbers are numbers whose only prime factors are 2, 3 or 5. The sequence 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15,
shows the first 11 ugly numbers. By convention, 1 is included.
Write a program to find the kth ugly number.
Complexity
----------
* Time Complexity O(n)
* Space Complexity O(n)
Reference
---------
* http://www.geeksforgeeks.org/ugly-numbers/
"""
def ugly_number(kth):
ugly_factors = [1] # By convention 1 is included.
factor_index = {
2: 0,
3: 0,
5: 0}
for num in range(1, kth):
minimal_factor = min(min(ugly_factors[factor_index[2]] * 2, ugly_factors[factor_index[3]] * 3),
ugly_factors[factor_index[5]] * 5)
ugly_factors.append(minimal_factor)
for factor in [2, 3, 5]:
if minimal_factor % factor == 0:
factor_index[factor] += 1
return ugly_factors[kth - 1]
if __name__ == '__main__':
assert 5832 == ugly_number(150)
|
string=""
for x in range(1,10):
string=""
for y in range(1,x+1):
if str(y) == "1":
string = string + (str(y) + "*" + str(x) + "=" + str(x*y))
else:
string = string + "\t" + (str(y) + "*" + str(x) + "=" + str(x*y))
print(string)
squares=[value**2 for value in range(1,11)]
print(squares)
print(squares[-2:])
alien_0 = {'color':'green', 'points':5}
print(alien_0['color'])
print(alien_0['points'])
user_0 = {
'username':'efermi',
'first':'enrico',
'last':'fermi',
}
for key, value in user_0.items():
print("\nKey:" + key);
print("\nValue:" + value)
alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 10, 'x':10}
alien_2 = {'color': 'red', 'points': 15}
aliens = [alien_0, alien_1, alien_2]
for alien in aliens:
print(alien)
#message=input("Tell me:")
#print(message)
def describe_pet(pet_name, animal_type='dog'):
"""显示宠物的信息"""
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet(pet_name='willie')
|
def main():
#escribe tu código abajo de esta línea
n=int(input())
c=1
suma=0
numero=0
while c<=n:
numero=float(input())
suma+=numero
promedio=suma/n
c+=1
print(promedio)
if __name__=='__main__':
main()
|
# This reads in a users height and weight and calulates their BMI
# Author: Eddie Callan (G00398815)
# The line below looks for the user to input their height and saves it in variable 'height' as an integer
height = int(input("Please enter your height in centimeters: "))
# The line below looks for the user to input their weight and saves it in the variable 'weight' as an integr
weight = int(input("Please your weight in kilograms: "))
# The line below displays the BMI for the user dividing the weight by height by height and then mutiplyng my 10000 (for cm to meteres squared)
print("The exact BMI is ", weight / (height * height) * 10000)
|
#give input like this :[2,4,32,1]
def mergesort(lst):
n = len(lst)
if n == 1 or n == 0:
return lst
else:
length = n//2
A = lst[:length]
B = lst[length:]
A = mergesort(A)
B = mergesort(B)
i, j = 0, 0
lst = []
while i < len(A) and j < len(B):
if A[i] < B[j]:
lst.append(A[i])
i += 1
else:
lst.append(B[j])
j += 1
if i == len(A):
lst += B[j:]
else:
lst += A[i:]
return lst
list = eval(input("Enter the list of numbers:"))
list = mergesort(list)
print("Your sorted list is", list) |
# Author:Chris Rios
# Finds the specified file type, either .mp3, .flac, .wav, or all 3, and copies it to a speicfied folder.
import sys
import re
import os
import shutil
music_list={}
def folder_crawler(dir_name,file_type):
'''Explores all folders and sub folders for the speicified file type, composes a dictionary of all files names,
sizes and paths'''
paths = os.listdir(dir_name)
for path in paths:
path = os.path.basename(path)
abs_path = os.path.abspath(os.path.join(dir_name,path))
if path.endswith(file_type):
if not path in music_list:
music_list[path] = (abs_path,os.path.getsize(abs_path))
elif not os.path.getsize(abs_path) == music_list[path][1]:
inserted = False;
while not inserted:
counter = 1
path=path[:path.index('.')]+'(%s)' %str(counter)+path[path.index('.'):]
if not path in music_list:
music_list[path] = (abs_path,os.path.getsize(abs_path))
inserted = True
elif not os.path.getsize(abs_path) == music_list[path][1]:
counter += 1
else:
break
music_list[path] = (abs_path,os.path.getsize(abs_path))
elif os.path.isdir(os.path.join(dir_name,path)) and not path.startswith("."):
folder_crawler(os.path.join(dir_name,path),file_type)
def copy_list(to_dir):
for song,(path,_) in music_list.items():
print("Attempting to copy %s" %song)
shutil.copy(path, os.path.join(to_dir, song))
def main():
file_type= input('Please enter file type,"mp3","."flac" or "wav", or "all"\n')
if (not file_type=='mp3' and not file_type=='flac'
and not file_type=='wav' and not file_type=='all'):
print ("%s is not a proper option" % file_type)
sys.exit(1)
source_folder=input('Please enter a folder to search\n')
if not os.path.exists(source_folder):
print ('Folder %s does not exist' % source_folder)
sys.exit(1)
destination_folder= input('Please enter a destination folder\n')
if not os.path.exists(destination_folder):
create_folder = input('Folder %s does not exist, create new folder, yes or no\n' %destination_folder)
if not create_folder =='yes' and not create_folder =='y':
print('Aborting program')
sys.exit(1)
else:
os.mkdir(destination_folder)
print('folder %s created' %destination_folder)
folder_crawler(source_folder,file_type)
else:
folder_crawler(source_folder,file_type)
copy_list(destination_folder)
if __name__ == "__main__":
main()
|
input_word = input('Enter Word: ')
if 'e' in input_word:
print('Yes')
else:
print('No') |
known_users = ['Gande', 'Emma', 'Nabem', 'Jude', 'Blessing', 'Avalumun']
while True:
user_name = input('What is your Name: ').capitalize()
print(f'Hi! {user_name} welcome to Travis')
#Check if user is in the list
if user_name in known_users:
print(f'Hello, {user_name}')
#Ask User whether they would want to be removed from the list after making it lower case
ask_remove = input('Would You like to be removed (y/n): ').lower()
#Check if the user typed in Yes or No (y or n) which will to automatically lowered case
if ask_remove == 'y':
print(known_users)
#Remove User from the List
known_users.remove(user_name)
print(f'{user_name}, You have been Removed from the System')
#Else if user input is n (No) Display message for user
elif ask_remove == 'n':
print(f'Okay {user_name}, I did not want to remove you from the system either')
else:
print(f'Hmmm {user_name} we have not met before')
#Ask User whether to be added to list
ask_add = input('Would You like to be added to the System?: (y/n) ').lower()
#Check if user input is 'y' (Yes) and then add him/her to the system
if ask_add == 'y':
#Add New User to the list
known_users.append(user_name)
print(f'{user_name}, You have now been added to the system successfully')
elif ask_add == 'n':
print(f'{user_name}, You have your right not to be added to our system')
|
from random import randrange
import time
'''
Snow animation
Snow is simply the `#` symbol here. Half of the snow moves at 1 char
per frame, while the other half moves at 0.5 chars per frame. The
program ends when all the snow reaches the bottom of the screen.
The viewing area is 80x25. It puts 100 snow flakes to output, half
fast, and half slow. Every frame it dispenses 4 flakes, 2 fast and
2 slow ones, at random locations at the top of the viewing area.
'''
screen = {'x': 80, 'y': 20}
drops = []
def createRainDrop(x, y, speed):
return {'x': x, 'y': y, 'speed': speed}
def createRandomDrops():
dropCount = 4
for i in range(dropCount):
yield createRainDrop(randrange(0, screen['x']), 0, min((i % 2) + 0.5, 1))
def moveDrops():
for drop in drops:
speed = drop['speed']
drop['y'] = drop['y'] + speed
def drawDrops():
out = [''] * screen['y']
for y in range(screen['y']):
for x in range(screen['x']):
out[y] += '#' if any([drop['x'] == x and int(drop['y']) == y for drop in drops]) else ' '
return '\n'.join(out)
def dropsOnScreen():
return any([drop['y'] < screen['y'] for drop in drops])
drops += createRandomDrops()
while dropsOnScreen():
if len(drops) < 100:
drops += createRandomDrops()
print(drawDrops())
moveDrops()
time.sleep(0.100)
|
import sys
sys.stdin = open("input_data", "r")
import math
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def start():
cases = int(input())
while cases > 0:
# list for points
points = []
N = int(input())
# creating all the points from the inputpoints
for i in range(0, N):
new_point = [int(i) for i in input().split()]
points.append(Point(new_point[0], new_point[1]))
# sorting all the points on x-coordinate descending
points.sort(key=lambda point: point.x, reverse=True)
# variables for highest piont and length of sunny parts
highest_point, sun = 0, 0
# Loop through all points stating from second one comparing with
# the previous point
for i in range(1, len(points)):
# check if point is higher than highest point and the previous point
if points[i].y > highest_point and points[i].y > points[i - 1].y:
# vector coordinates(dx, dy)
dx = points[i].x - points[i - 1].x
dy = points[i].y - points[i - 1].y
# calculate length of line(magnitude)
magnitude = math.sqrt(dx**2 + dy**2)
# calculate the y-value that is in the sun
sunny_part = points[i].y - highest_point
# calculate length of the sunny part of the mountain
sun += sunny_part * magnitude / dy
# update the highest point reached so far
highest_point = max(points[i].y, highest_point)
# print result with 2 decimals
print("%.2f" % sun)
cases -= 1
start()
|
#!/usr/bin/env python3
from itertools import product
A = input().split()
n = int(input())
## lazy hack over itertools
def main0():
S0 = ' '
for P in product(A,repeat=n):
S = ''.join(P)
d = 0
while d<n and S[d]==S0[d]:
d += 1
for i in range(d+1,n):
print(S[:i])
print(S)
S0 = S
#main0()
## custom recursion (actually simpler)
def nest(S):
if len(S)<n:
for a in A:
S.append(a)
yield ''.join(S)
yield from nest(S)
S.pop()
def main1():
for S in nest([]):
print(S)
main1()
|
#!/usr/bin/env python3
def temple(H):
if len(H)%2==0:
return False
for i in range(len(H)//2+1):
if not H[i]==H[-1-i]==i+1:
return False
return True
def main():
S = int(input())
for _ in range(S):
N = int(input())
H = list(map(int,input().split()))
print('yes' if temple(H) else 'no')
main()
|
#!/usr/bin/env python3
import rosalib
# NB: the statement explains "Why Are We Counting Modulo 134,217,727?
# (...) however, if we count modulo a large prime number"
# yet 2^27-1 = 134217727 is not prime... (-_-)
def Levenstein_align(u,v):
m,n = len(u),len(v)
T = [[max(i,j) for j in range(n+1)] for i in range(m+1)]
Nb = [[int(i==0 or j==0) for j in range(n+1)] for i in range(m+1)]
for i in range(1,m+1):
for j in range(1,n+1):
T[i][j] = min(T[i-1][j]+1,T[i][j-1]+1,T[i-1][j-1]+int(u[i-1]!=v[j-1]))
if T[i-1][j]+1==T[i][j]:
Nb[i][j] += Nb[i-1][j]
if T[i][j-1]+1==T[i][j]:
Nb[i][j] += Nb[i][j-1]
if T[i-1][j-1]+int(u[i-1]!=v[j-1])==T[i][j]:
Nb[i][j] += Nb[i-1][j-1]
return (T[m][n],Nb[m][n])
L = rosalib.parse_fasta()
_,cpt = Levenstein_align(L[0][1],L[1][1])
print(cpt % (2**27-1))
|
#!/usr/bin/env python3
# Greedy approach in O(sqrt(n))
# Key observations:
# - It is always "optimal" to "upgrade" (buy new machines/workers)
# as soon as possible: If the optimal requires to buy k ressources, then
# there is clearly a way to achieve this optimal by buying progressively
# the k ressources as fast as possible in a first phase, then accumulate
# the candies till n is reached in a second phase.
# - When buying a ressource, it is always optimal to reinforce the smallest
# value between m and w: Indeed assuming m > w, we have m*(w+1) > (m+1)*w,
# thus we should buy a worker.
# Approach: We simulate the first phase buying as much ressources as we can
# step by step (a "step" here is a minimal time lapse during enough candies
# are accumulated to buy a new ressource, each step is simulated in O(1))
# until we produce more than n in one time unit (m*w > n). At each step,
# we evaluate in O(1) the time taken for the phase 2 assuming we stop at that
# step to upgrade our production capacity. The optimal is the minimal overall
# time computed.
# This takes O(sqrt(n)) as this is the maximal number of steps needed to
# reach m ~ w ~ sqrt(n).
div_ceil = lambda n,q: (n + q-1)//q
if __name__=='__main__':
# c the current number of candies, t the time
c = t = 0
m,w,p,n = map(int,input().split())
if m<w:
m,w = w,m
res = div_ceil(n,m*w)
while m*w < n:
assert m>=w
assert c<p
# time needed to accumulate at least p candies to buy ressources
dt = div_ceil(p-c,m*w)
t += dt
c += dt * m*w
# buying a ressources
a = c//p
c %= p
# attributing ressources to w < m
d = m-w
w0 = min(d,a)
w += w0
a -= w0
# attributing remaining ressources equally to m ~ w
a2w = a//2
a2m = a-a2w
m += a2m
w += a2w
# time to produce n candies with the current production capacity
res = min(res, t+div_ceil(max(0,n-c),m*w))
print(res)
|
#!/usr/bin/env python3
# Comme vu dans INOD, ajouter une feuille a un arbre binaire non-enracine,
# c'est choisir une arete, ajouter un nouveau noeud interne au milieu
# et y connecter la nouvelle feuille. On avait n-2 noeuds internes pour n>=3
# feuilles, donc 2n-2 sommets et donc 2n-3 aretes.
# Donc b(n+1) = (2*n-3) * b(n) et b(3) = 1
M = 10**6
def b(n):
return 1 if n<=3 else ((2*n-5)*b(n-1))%M
print(b(int(input())))
|
#!/usr/bin/env python3
import rosalib
def pdist(A,B):
assert(len(A)==len(B))
return sum(int(A[i]!=B[i]) for i in range(len(A)))/len(A)
def main():
L = rosalib.parse_fasta()
for i in range(len(L)):
print(' '.join(str(pdist(L[i][1],L[j][1])) for j in range(len(L))))
main()
|
#!/usr/bin/env python
import sys
win = {0:False, 1:False}
def progdyn(n):
if n not in win:
win[n] = not progdyn(n-2) or (n>2 and not progdyn(n-3)) or (n>4 and not progdyn(n-5))
return win[n]
def main():
T = int(sys.stdin.readline())
for _ in xrange(T):
n = int(sys.stdin.readline())
if progdyn(n):
print 'First'
else:
print 'Second'
main()
|
#!/usr/bin/env python
import sys
from math import sqrt
# probleme "easy" car un lien est donne dans l'enonce vers :
# http://math.stackexchange.com/questions/124408/finding-a-primitive-root-of-a-prime-number
# les racines primitives sont les generateurs de (Z/nZ)* (d'ordre phi(n))
# s'il en existe, alors (Z/nZ)* est monogene fini donc cyclique et donc
# isomorphe a Z/phi(n)Z et donc il y en a phi(phi(n))
# il en existe toujours pour n = p premier (car alors Z/nZ = Fp et l'on sait
# que Fp* est cyclique)
# pour les trouver, on decompose phi(n) (= p-1 ici) en facteurs premiers
# phi(n) = prod(pi^ai)
# et on les cherche parmi r = 2,...,n-1 en testant : il faut et il
# suffit d'avoir r^(phi(n)/pi) != 1 mod n pour tout i pour s'assurer que
# l'ordre de r est phi(n)
def decomp(n):
F = []
m = 0
while n%2==0:
n /= 2
m += 1
if m>0:
F.append((2,m))
i = 3
s = int(sqrt(n))+1
while n>1 and i<s:
m = 0
while n%i==0:
n /= i
m += 1
if m>0:
F.append((i,m))
i += 2
if n>1:
F.append((n,1))
return F
def eulerphi(decomp):
res = 1
for (p,m) in decomp:
res *= (p-1)*p**(m-1)
return res
def primitive(r,p,Dphi):
return all(pow(r,(p-1)/f,p)!=1 for (f,_) in Dphi)
def main():
p = int(sys.stdin.readline())
phi = p-1
Dphi = decomp(phi)
phiphi = eulerphi(Dphi)
r = 2
while not primitive(r,p,Dphi):
r += 1
print r,phiphi
main()
|
#!/usr/bin/env python3
def is_pal(S):
return S==S[::-1]
def pal_index(S):
s = len(S)
for i in range(s//2):
if S[i]!=S[s-i-1]:
if is_pal(S[:i]+S[i+1:]):
return i
elif is_pal(S[:s-i-1]+S[s-i:]):
return s-i-1
return -1
return -1
def main():
T = int(input())
for _ in range(T):
S = input()
print(pal_index(S))
main()
|
#!/usr/bin/env python3
# Rajouter une feuille a un arbre binaire non-enracine, c'est
# choisir une arete, ajouter un nouveau noeud interne au milieu
# et y connecter la nouvelle feuille.
# On ajoute donc exactement 1 noeud interne par nouvelle feuille.
# Pour n = 1 ou 2 on a 0 noeud interne.
# Pour n = 3 on a exactement 1 noeud interne et a partir de la l'ecart
# entre le nombre de noeuds internes et de feuilles est constant, il y
# a donc n-2 noeud internes pour n>=3.
def internal(leaves):
return max(0,leaves-2)
n = int(input())
print(internal(n))
|
#!/usr/bin/env python3
from itertools import groupby
Uniq = list(range(1,8))+list(range(6,0,-1))
def rainbow(A):
return A==A[::-1] and [G[0] for G in groupby(A)]==Uniq
def main():
T = int(input())
for _ in range(T):
N = int(input())
A = list(map(int,input().split()))
print('yes' if rainbow(A) else 'no')
main()
|
#!/usr/bin/env python3
# pb 10040 on UVa, 2201 on Archive
# Duval's algorithm (1988) to generate Lyndon words of size <=n in lex order
# https://en.wikipedia.org/wiki/Lyndon_word
def lyndon(n):
w = [0]*n
l = 1
yield '0'
while True:
for i in range(l,n):
w[i] = w[i%l]
l = n
while l>0 and w[l-1]==1:
l -= 1
if l==0:
break
w[l-1] = 1
yield ''.join(map(str,w[:l]))
# the lex-min De Bruijn cycle of order n is the concatenation of lex-ordered
# Lyndon words of size <=n whose size divides n
# https://oeis.org/A166315
# we modify the previous algorithm to efficiently generate that cycle
def lyndon_de_bruijn(n):
w = [0]*n
l = 1
db = [0]
while True:
for i in range(l,n):
w[i] = w[i%l]
l = n
while l>0 and w[l-1]==1:
l -= 1
if l==0:
break
w[l-1] = 1
if n%l==0:
db += w[:l]
return db
def main():
DB = [lyndon_de_bruijn(n) for n in range(22)]
T = int(input())
for _ in range(T):
n,k = map(int,input().split())
res = 0
for i in range(k,k+n):
res = (res<<1) | DB[n][i%len(DB[n])]
print(res)
main()
|
#!/usr/bin/env python3
def hist_max_rect(H):
H.append(0)
S = []
res = 0
for i in range(len(H)):
x = i
while S and H[i]<=S[-1][1]:
x,h = S.pop()
# an interval of height h starts at x and ends at i-1
res = max(res,h*(i-x))
S.append((x,H[i])) # an interval of height H[i] starts from x
return res
def main():
N = int(input())
H = list(map(int,input().split()))
print(hist_max_rect(H))
main()
|
#!/usr/bin/env python3
def main():
N = int(input())
S = input()
# recursively removing "()" from S
R = []
for s in S:
if s==')' and len(R)>0 and R[-1]=='(':
R.pop()
else:
R.append(s)
# R = ")" * a + "(" * b with a+b even
a = R.count(')')
b = len(R)-a
if a==b==0:
res = 0
elif a==0 or b==0: # simple reverse one half of R
res = 1
else: # reversing the ")" part leads to the previous case
res = 2
print(res)
main()
|
#!/usr/bin/env python3
# https://en.wikipedia.org/wiki/Euler's_criterion
# for p an odd prime, a coprime to p (i.e. not a multiple of p here)
def euler_criterion(a,p):
return pow(a,(p-1)//2,p)==1
def main():
T = int(input())
for _ in range(T):
A,M = map(int,input().split())
if A==0 or M==2:
print('YES')
else:
print('YES' if euler_criterion(A,M) else 'NO')
main()
|
#!/usr/bin/env python3
# Method used here:
# 1. Use one LALIGN web interface to discover the pattern
# http://www.ebi.ac.uk/Tools/psa/lalign/nucleotide.html
# http://fasta.bioch.virginia.edu/fasta_www2/fasta_www.cgi?rm=lalign&pgm=lald
# 2. Append the discovered pattern to the FASTA input and use this script
# to count occurrences with errors
import sys
from Bio import SeqIO
# O(n*m)
def count_with_errors(S,P,errors=3):
o = 0
for i in range(len(S)-len(P)+1):
j = e = 0
while j<len(P) and e<=errors:
if P[j]!=S[i+j]:
e += 1
j += 1
if e<=errors:
o += 1
return o
DNAS = list(SeqIO.parse(sys.stdin,'fasta'))
print(count_with_errors(DNAS[0].seq,DNAS[2].seq),count_with_errors(DNAS[1].seq,DNAS[2].seq))
|
#!/usr/bin/env python3
# Appelons PAA(n) une permutation 3-anti-arithmetique de taille n
# et SAA une suite finie (qcq) 3-anti-arithmetique.
# Une SAA le reste (clairement) si l'on :
# - supprime des elements ;
# - ajoute une constante a tous les elements ;
# - multiplie tous les elements par une constante.
# Pour construire une PAA(n) :
# - on construit une SAA sur les elements pairs et une SAA sur les
# elements impairs a partir d'une PAA(n/2) et des operations precedentes ;
# - on les concatene.
# On obtient une PAA(n) car tout triplet "a cheval" sur les pairs/impairs
# contient 2 elements de meme parite, dont l'ecart est pair, tandis que l'autre
# ecart est entre un pair et un impair donc est impair.
def aaperm(n):
if n==1:
return [0]
B = aaperm((n+1)//2)
return [2*x for x in B] + [2*x+1 for x in B if 2*x+1<n]
def main():
n = int(input())
while n>0:
print('%d: %s' % (n,' '.join(map(str,aaperm(n)))))
n = int(input())
main()
|
#!/usr/bin/env python
import sys
# we simply want to count the number of iterations of the loop nest
# an iteration is determined by 1 <= i1 < i2 < ... < ik <= n
# with i2-i1 >= 1, i3-i2 >= 2, i4-i3 >= 3, ...
# let us do a simple translation:
# let j1 = i1, j2 = i2 > j1,
# j3 = i3-1 > j2 so that i3-i2 >= 2 becomes j3-j2 >= 1,
# j4 = i4-(1+2) >= i3 > j3 so that j4-j3 >= 1,
# j5 = i5-(1+2+3) >= i4-2 > j4 so that j5-j4 >= 1, etc
# so that an iteration is perfectly determined by
# 1 <= j1 < j2 < ... < jk <= n-(1+2+...+(k-2)) = n-(k-1)(k-2)/2
# without the additional constraints
# and the number of iterations is then binom(n-(k-1)(k-2)/2,k)
P = 10**9+7
def bezout(a,b):
if b==0:
return (a,1,0)
g,u,v = bezout(b,a%b)
return (g,v,u-(a/b)*v)
def inv_mod(a,n):
_,u,_ = bezout(a,n)
return u
def binom(n,p):
if p>n:
return 0
res = 1
while p>0:
res = (((res*n)%P)*inv_mod(p,P))%P
p -= 1
n -= 1
return res
def main():
n,k = map(int,sys.stdin.readline().split())
print binom(n-(k-1)*(k-2)/2,k)
main()
|
#!/usr/bin/env python3
# Si l'on considere les arbres binaires non-enracines a n feuilles etiquetees,
# alors en retirant la n-ieme feuille et en choisissant son pere comme racine,
# on obtient, sans doublon, tous les arbres binaires enracines a n-1 feuilles
# etiquetees.
# Ou reciproquement, on obtient les arbres non-enracines en connectant
# une n-ieme feuille a la racine d'un arbre binaire non enracine.
# D'ou B(n) = b(n+1) pour b() la fonction du pb CUNR.
M = 10**6
def b(n):
return 1 if n<=3 else ((2*n-5)*b(n-1))%M
def B(n):
return b(n+1)
print(B(int(input())))
|
#!/usr/bin/env python3
import rosalib
# pretty naive and lazy approach here, yet good enough
# (for sure there are more efficient and still relatively simple
# approaches using string hashing)
# see also https://en.wikipedia.org/wiki/Longest_common_substring_problem
# for a really good approach using suffix trees
def LCSub(DNAS):
L0 = len(DNAS[0])
for k in range(L0,-1,-1):
for i in range(L0-k+1):
P = DNAS[0][i:i+k]
if all(DNAS[j].find(P)>=0 for j in range(1,len(DNAS))):
return P
DNAS = sorted((DNA for _,DNA in rosalib.parse_fasta()), key=len)
print(LCSub(DNAS))
|
import numpy as np
import matplotlib.pyplot as plt
def exponential_growth(x0, k, dt, N):
X = [x0]
for _ in range(N):
X.append(X[-1]*(1+k*dt))
return X
def eplot(x0, k, dt, N):
X = np.linspace(0, N*dt, 1000)
Y = x0*np.exp(k*X)
plt.plot(X, Y)
X = np.arange(0, (N+0.1)*dt, dt)
Y = exponential_growth(x0, k, dt, N)
print(Y)
plt.plot(X, Y)
if __name__=='__main__':
eplot(1, 1, 0.1, 10)
#eplot(5, 1, 0.6, 3)
#eplot(1, 2.5, 0.1, 5)
plt.show()
|
# Code_snippets
///A. Find out number of digits in a number using python
Method 1
///
no=float(input("enter the number"))
digits=0
while(n!=0):
n=n//10
digits+=1
print("number of digits are",digits)
//Method 2:
no=int(input())
print(Len(str(no))) //convert int to string
|
#! /usr/bin/python3
import sys
lines = sys.stdin.readlines()
l, w, n, r = [int(i) for i in lines.pop(0).split()] #parse input values
ns = {}
reachable = {}
counter = 1
for li in lines:
ns[counter] = [int(i) for i in li.split()] #save coordinates of cranes into dictionary
reachable[counter] = []
counter += 1
ms = {"left": [-l, 0], "right": [l, 0], "bot": [0, -w], "top": [0, w]}
bag = {"left": False, "right": False, "bot": False, "top": False}
count = 0
for m in ms:
for n in ns:
if (ms[m][0] - 2*ns[n][0])**2 + (ms[m][1] - 2*ns[n][1])**2 <= r**2*4:
#check the distance less than or equal to r
reachable[n].append(m) #save all the walls a crane can reach
bag[m] = True #if a wall is reachable by at least one crane
if not bag[m]:
print("Impossible") #impossible when a wall is not reachable by any cranes
sys.exit()
#when a crane can reach all walls
for i in range(1, n+1):
all = set(reachable[i])
if len(all) == 4:
print(1)
sys.exit()
#when two cranes can reach all walls
for i in range(1, n+1):
for j in range(1, n+1):
all = set(reachable[i] + reachable[j])
if len(all) == 4:
print(2)
sys.exit()
#when three cranes can reach all walls
for i in range(1, n+1):
for j in range(1, n+1):
for k in range(1, n+1):
all = set(reachable[i] + reachable[j] + reachable[k])
if len(all) == 4:
print(3)
sys.exit()
#when four cranes can reach all walls
for i in range(1, n+1):
for j in range(1, n+1):
for k in range(1, n+1):
for l in range(1, n+1):
all = set(reachable[i] + reachable[j] + reachable[k] + reachable[l])
if len(all) == 4:
print(4)
sys.exit()
|
n=5
while n> 0 :
print(n)
n = n-1
print("it is done") |
import string
LOWER_LETTERS = string.ascii_lowercase
def isPalindrome(string):
def normalize_string(string):
string = string.lower()
ans = ''
for letter in string:
if letter in LOWER_LETTERS:
ans += letter
return ans
def isPal(string):
if len(string) <= 1:
return True
else:
#string[0] == string[-1] does work to reduce the problem
return string[0] == string[-1] and isPal(string[1:-1])
#this is the call for isPal
return isPal(normalize_string(string))
print(isPalindrome('Able was I, eve I saw Elba')) |
def user_numbers():
integers = input("Enter 10 integers: ").split()
return [int(number) for number in integers]
numbers = user_numbers()
def calculation(numbers):
odd_numbers = [number for number in numbers if number % 2 != 0]
return max(odd_numbers)
x = calculation(numbers)
print(x)
|
#Sum the values of the hand (ie the number of letters available to use).
#We will use this info as a check to see when we need to end the game (ie, no more letters to use)
def calculateHandlen(hand):
return sum(hand.values())
def updateHand(hand, word):
hand_copy = hand.copy()
for letter in word:
for dict_letter, frequency in hand_copy.items():
if letter == dict_letter:
hand_copy[dict_letter] = frequency -1
return hand_copy
def getWordScore(word, n):
valid_word = loadWords()
word_score = 0
if word not in valid_word:
return word_score
else:
for letter in word:
word_score += (SCRABBLE_LETTER_VALUES[letter]) * len(word)
if len(word) == n:
word_score += 50
return word_score
def isValidWord(word, hand, wordList):
if word not in wordList:
return False
hand_copy = hand.copy()
for letter in word:
if letter not in hand.keys():
return False
else:
for dict_letter, frequency in hand_copy.items():
if letter == dict_letter:
hand_copy[dict_letter] = frequency -1
for frequency in hand_copy.values():
if frequency < 0:
return False
return True
def displayHand(hand):
hand_as_string = ''
for letter, freq in hand.items():
hand_as_string += freq * (letter + ' ')
return hand_as_string
def playHand(hand, wordList, n):
#score variable on outside of loop that'll update in the while loop
total_score = 0
#while the condition is true, do the following:
while True:
#Display the current hand (shows all of the available letters)
print(f"Current hand: ", displayHand(hand))
#ask for user to enter a word or exit the game
user_word = input('Enter word, or a "." to indicate that you are finished: ')
#IF user wants to end game, then end it and return total socre
#exit the while loop by using a break statement
if user_word == '.':
print(f"Goodbye! Total score: {total_score} points.")
break
#IF the user doens't want to end the game and has entered a word, we need to see if the word is valid or not
else:
#Check if the word is valid by calling the function isValidWord.
#Notice that I needed to update the parameters I pass into isValidWord -- I pass in user_word (which is the word the user inputted) instead of "word"
if isValidWord(user_word, hand, wordList) == False:
print("Invalid word, please try again.\n")
#Word MUST be valid (based on the check above) so we enter the "else" clause
else:
#Get the score for the valid word by calling getWordScore
word_score = getWordScore(user_word, n)
#add the score for this word to total_score and print the score
total_score += word_score
print(f"{user_word} earned {word_score}. Total: {total_score} points.")
print("\n")
#Update the hand based on the letters used to form the word. Returns an updated dictionary that I'm setting = to the variable "hand"
hand = updateHand(hand, user_word)
#Check to see if the length of the hand is 0, which means we're out of letters. If len(hand) is 0 then end the game
if calculateHandlen(hand) == 0:
print(f"Run out of letters. Total score: {total_score} points.")
break
def playGame(words):
"""
Allow the user to play an arbitrary number of hands.
1) Asks the user to input 'n' or 'r' or 'e'.
* If the user inputs 'n', let the user play a new (random) hand.
* If the user inputs 'r', let the user play the last hand again.
* If the user inputs 'e', exit the game.
* If the user inputs anything else, tell them their input was invalid.
2) When done playing the hand, repeat from step 1
"""
#variable on the outside of the while loop that'll be incremented inside the while loop
count_games = 0
#keep running this while loop until a condition is False
while True:
#get user input and react based on input
user_game_choice = input("Enter n to deal a new hand, r to replay the last hand, or e to end game: ")
#End the game if user enters "e"
if user_game_choice == 'e':
break
#using a counter to see if this is the first time a user plays a game and tries to do something other than start a new game
elif count_games == 0 and user_game_choice == 'r':
print("You have not played a hand yet. Please play a new hand first!\n")
count_games += 1
#Ready to start a new game and call functions
elif (count_games > 0 and user_game_choice == 'n') or (user_game_choice == 'n'):
#dealHand is assigned to current_hand. It stays in memory unless it's reassigned
#Use a variable here b/c dealHand returns something and we need to use dealHand elsewhere (ie, in the PlayHand function call)
current_hand = dealHand(HAND_SIZE)
#Calling function playHand --> playHand has no return value so I can just call it -- I don't need to assign it to a variable.
playHand(current_hand, wordList, HAND_SIZE)
count_games += 1
print("\n")
#If the user wants to REPEAT the previously played game (from the elif above)
elif count_games > 1 and user_game_choice == 'r':
#I need to re-call playHand from the condition above. This works b/c playHand isn't assigned to a variable that's been updated.
#Instead the playHand stays the same throughout the entire iteration through the while loop.
#In other words, everything (ie, dealHand and playHand) stay the same from the condition above
#play_hand has no return value so I don't need to use a variable when I call this function (it's a side effect).
#It does something for me, there's no output value
playHand(current_hand, wordList, HAND_SIZE)
count_games += 1
else:
print("Invalid command. Try again")
print("\n")
wordList = loadWords()
(playGame(wordList))
#a while loop inside a while loop
def playGame(wordList):
count_games = 0
while True:
game_type_choice = input("Enter n to deal a new hand, r to replay the last hand, or e to end game: ")
game_type_choice_options = ['n', 'r', 'e']
valid_game_type_choice = (game_type_choice == 'n') or (game_type_choice == 'r' and count_games > 0) or (count_games > 0 and game_type_choice == 'n')
game_opponent_options = ['c', 'u']
if game_type_choice == 'e':
break
elif game_type_choice not in game_type_choice_options:
print("Invalid command. Try again")
print("\n")
elif count_games == 0 and game_type_choice == 'r':
print("You have not played a hand yet. Please play a new hand first!\n")
count_games += 1
while valid_game_type_choice:
game_opponent_input = input("Enter u to have yourself play, c to have the computer play: ")
count_games += 1
if game_opponent_input == 'u' and game_type_choice == 'n':
current_hand = dealHand(HAND_SIZE)
playHand(current_hand, wordList, HAND_SIZE)
print("\n")
break
elif game_opponent_input == 'u' and game_type_choice == 'r':
playHand(current_hand, wordList, HAND_SIZE)
break
elif game_opponent_input == 'c' and game_type_choice == 'n':
current_hand = dealHand(HAND_SIZE)
compPlayHand(current_hand, wordList, HAND_SIZE)
print("\n")
break
elif game_opponent_input == 'c' and game_type_choice == 'r':
compPlayHand(current_hand, wordList, HAND_SIZE)
break
elif game_opponent_input not in game_opponent_options:
print("Invalid command. Try again")
print("\n")
|
example = open('circle.py', 'a')
for i in range(2):
name = input("Enter name: ")
example.write(name)
example.close()
# file = 'pi_digits.py'
# with open(file) as f_object:
# lines = f_object.readlines()
# for line in lines:
# print(line.strip())
|
#monthly_payment is not passed into this function
def calculate_ending_balance(balance, annualInterestRate, monthly_payment):
month = 1
while month <= 12:
unpaid_balance = balance - monthly_payment
monthly_interest_rate = annualInterestRate / 12.0
new_balance = unpaid_balance + (monthly_interest_rate * unpaid_balance)
month += 1
balance = new_balance
ending_balance = round(balance, 2)
final_output = "Remaining balance: " + str(ending_balance)
return ending_balance
def debt_payoff(balance, annualInterestRate):
ending_balance = balance
monthly_payment = 0
while ending_balance > 0:
#calling the lower-level function inside this higher-level function in order find the total ending balance after 12 months.
#The order of incrementing the monthly payment and calling ending balance matter!
#The way it is now, I increment the monthly payment, THEN call the function. Otherwise I call the function, which could get me the result I need, then I add 10 to it
monthly_payment += 10
ending_balance = calculate_ending_balance(balance, annualInterestRate, monthly_payment)
return monthly_payment
monthly_payment = debt_payoff(3329, .2)
print(monthly_payment)
|
import random
import matplotlib.pyplot as plt
from itertools import islice
import numpy as np
#Ejercicio 1
def modulo(x):
modulo = 2**32
multiplicador = 1013904223
incremento = 1664525
return (x*multiplicador + incremento) % modulo
def random_generator(cantidad):
numeros = []
x = 96102
for i in range(cantidad):
numeros.insert(i, modulo(x)/(2.0**32))
x = modulo(x)
return numeros
def get_dice_number(x):
if (x <= 0.16):
return 1
elif(x <= 0.33):
return 2
elif(x <= 0.5):
return 3
elif(x <= 0.66):
return 4
elif(x <= 0.83):
return 5
else:
return 6
def register_dice(number,dices):
dices[number] = dices[number] + 1
def exercise_two():
quantity = 10000
releases = {}
dices = {1:0,2:0,3:0,4:0,5:0,6:0}
randoms = random_generator(quantity)
for x in range(0,quantity,2):
dice_1 = get_dice_number(randoms[x])
dice_2 = get_dice_number(randoms[x+1])
register_dice(dice_1,dices)
register_dice(dice_2,dices)
suma = dice_1 + dice_2
print("suma {}".format(suma))
if suma in releases:
releases[suma] = releases[suma] + 1
else:
releases[suma] = 1
return (dices,releases)
(dices,releases) = exercise_two()
print("releases:"+str(releases))
keys = list(releases.keys())
keys.sort()
print("keys:"+str(keys))
values = list(map(lambda key: releases[key],keys))
print("values:"+str(values))
plt.bar([str(i) for i in keys], values, color='g')
plt.show()
|
''' Q.1- Create a circle class and initialize it with radius. Make two methods getArea and getCircumference inside this class. '''
import math as m
class Circle:
'''class to get area and circumference of a circle using the radius'''
def __init__(self,r):
self.radius=r
def getArea(self):
'''method to get area of the circle'''
return m.pi*((self.radius)**2)
def getCircumference(self):
'''method to get circumference of the circle'''
return 2*(m.pi)*self.radius
r=float(input("Enter radius of circle: "))
c1=Circle(r)
print("Radius={} Area={} Circumference={}".format(c1.radius,c1.getArea(),c1.getCircumference()))
|
#Exercises
#Exercise 1
print('hello\n\thello\n\t\thello')
#Exercise 2
print('OrangeAcademy \n'*20)
#Exercise 3
x=float(1)
y=float(2.8)
z=float("3")
w=float("4.2")
"""print(x)
print(y)
print(z)
print(w)"""
print(x,y,z,w,sep='10')
#to have 10 between the value
#Exercise 4
number1=input("Enter the first number?")
number2=input("Enter the second number?")
e4=int(number1)*int(number2)
print(e4)
#Exercise 5
nubr1=int(input("Enter the number 1?"))
nubr2=int(input("Enter the number 2?"))
nubr3=int(input("Enter the number 3?"))
nubr4=int(input("Enter the number 4?"))
nubr5=int(input("Enter the number 5?"))
print((nubr1+nubr2+nubr3+nubr4+nubr5)/5)
#Exercise 6
x=1
y=2.8
z=1j
o="Orange"
A=True
print(type(x)) #int
print(type(y)) #flot
print(type(z)) #complex
print(type(o)) #str
print(type(A)) #bool
"""<class 'int'>
<class 'float'>
<class 'complex'>
<class 'str'>
<class 'bool'>"""
#Exercise 7
x,y="Orange",1
X1,Y1=100,-10
print(x)
print(y)
print(X1)
print(Y1)
"""
Orange
1
100
-10
"""
#Exercise 8
"""
5x=10
print(x5)
X_q$="orange"
print(X_q$)
A B(14)
print(A B)
Print("10"*10)
"""
x5=10 # cannot use in the beginning number
print(x5)
X_q="orange" # cannot use in the $ in name of Value
print(X_q)
AB=14 # cannot use in the space in name of Value
print(AB)
print(10*10) # cannot use print in capital p and the ""
#Exercise 9
x,y="Orange",1
X1,Y1=100,-10
print(x)
print(y)
print(X1)
print(Y1)
"""
Orange
1
100
-10
"""
#Exercise 10
"""
5x=10
print(x5)
X_q$="orange"
print(X_q$)
A B(14)
print(A B)
Print("10"*10)
"""
x5=10 # cannot use in the beginning number
print(x5)
X_q="orange" # cannot use in the $ in name of Value
print(X_q)
AB=14 # cannot use in the space in name of Value
print(AB)
print(10*10) # cannot use print in capital p and the ""
#Exercise 11
#print("Hello,World!")
print("Cheers,Mate!")#This is the program
"""Testing
The Code
"""
# the output is :- Cheers,Mate!
#Exercise 12
name=input("Enter Name?? ")
age=int(input("Enter Age (year)?? "))
e12=2119-age
print('my age after 100 years '+str(e12))
#Exercise 13
base=int(input("what is base?? "))
height=int(input("what is height?? "))
e13=base*height/2
print(e13)
#Exercise 14
x=11
y=3
print(x+y) #14
print(x-y) #8
print(x*y) #33
print(x/y) #3.6666666666666665
print(x//y) #3
print(x%y) #2
print(abs(x*-1)) #11
print(int(x)) #11
print(float(x)) #11.0
print(divmod(x,y)) #(3,2)
print(pow(x,y)) #1331
print(x**y) #1331
print(x>y) #True
print(x==y) #False
print(x!=y) #True
|
import csv
with open("Resources/election_data.csv" , "r") as fh:
import csv
csvpath = ("Resources/election_data.csv")
with open(csvpath, newline="") as csvfile:
csv_reader =csv.reader(csvfile, delimiter=",")
csv_headers = next(csv_reader, None)
#print (f"CSV Header: {csv_headers}"
# print heading
print ("Election Results")
print ("-----------------------")
# Variables
candidate_list = []
count_votes = 0
# Loop through csv_reader
for row in csv_reader:
# if value in Candidate column is not in candidate_list,
# append to candidate_list
if row[2] not in candidate_list:
count_votes += 1
candidate_list.append(row[2])
else: # if not in list, just add the vote count
count_votes += 1
# print (len(candidate_list)) = 4
# count votes per candidate
i = 0
num_candidates = len(candidate_list)
candidate_votes = [0]*num_candidates
for i in range(num_candidates):
if row[2] == candidate_list[i]:
candidate_votes[i] += 1
most_vote = max(candidate_votes)
vote_index = candidate_votes.index(most_vote)
winner = candidate_list[vote_index]
#print (winner)
# percent per candidate
j = 0
percent_of_votes = []
for j in range(num_candidates):
percent = round(candidate_votes[j]/count_votes * 100,2)
percent_of_votes.append(percent)
print ("Election Results")
print ("-----------------------------")
print (f"Total Votes: {count_votes}")
print ("-----------------------------")
print (f"Name: {candidate_list} {percent_of_votes}, {candidate_votes}")
print ("-----------------------------")
print (f"Winner: {winner}")
exportpath = ("Results.txt")
with open(exportpath, "w") as textfile:
textfile.write("Election Results")
textfile.write("-----------------------------")
textfile.write(f"Total Votes: {count_votes}")
textfile.write("-----------------------------")
textfile.write(f"Name: {candidate_list} {percent_of_votes}, {candidate_votes}")
textfile.write("-----------------------------")
textfile.write(f"Winner: {winner}")
|
import re
from urllib.parse import urlparse
def validate_url(url):
"""
Validate an HTTP(S) URL
Helper for use with Colander that validates a URL provided by a user as a
link for their profile.
Returns the normalized URL if successfully parsed else raises a ValueError
"""
parsed_url = urlparse(url)
if not parsed_url.scheme:
parsed_url = urlparse('http://{}'.format(url))
if not re.match('https?', parsed_url.scheme):
raise ValueError('Invalid URL scheme: {}'.format(parsed_url.scheme))
if not parsed_url.netloc:
raise ValueError('Invalid domain name')
return parsed_url.geturl()
|
import time
def invest(amount, rate, years):
for year in range(years):
amount += amount * (rate/100)
print(f'year {year+1}: ${amount:.2f}')
def main():
while True:
try:
amount = float(input('Amount for investment: '))
rate = float(input('Rate of investment (%): '))
years = int(input('Years of investment: '))
break
except ValueError:
print('Invalid input')
continue
invest(amount, rate, years)
time.sleep(3)
main()
|
import time
while True:
nums = input('Enter integers separate by space: ').strip().split()
try:
nums = [int(num) for num in nums]
print (f'The sum of integers equals: {sum(nums)}')
break
except ValueError:
print('Invalid input format')
continue
time.sleep(3)
|
import time
print('Task_1')
weight = 0.2
animal = 'newt'
#stdout using only string concatenation
print(str(weight) + ' kg is the weight of the ' + animal + '.')
time.sleep(3)
print('\nTask_2')
#stdout using format method
print('{} kg is the weight of the {}.'.format(weight, animal))
time.sleep(3)
print('\nTask_3')
#stdout using f-string
print(f'{weight} kg is the weight of the {animal}.')
time.sleep(3)
|
import time
def factorial(num):
global fact_count
fact_count += 1
if num <= 1:
return 1
return num * factorial(num - 1)
num = int(input("Enter a non negative number: "))
fact_count = 0
start = time.time()
factorial(num)
stop = time.time()
print("The answer is", factorial(num))
print("The number of function calls is", fact_count)
print("The time taken is", stop - start) |
'''
CN-codedemy-script-8.Loops-10.Your-Hobbies.py
Worked Oct 20, 2016
'''
hobbies = []
for i in range(3)
hobbies.append(raw_input("What are your hobbies:")
# print list when done (after 3 input)
# will print something like this: ['music', 'movies, ' books']
print hobbies
|
'''
Codecademy - Learn basic Pyhon https://www.codecademy.com/learn/python
Assignment: Battleship
File: battleship.py
'''
# Create a square board size 5, load all cells with O (letter O upper case)
board = []
for x in range(0,5):
board.append(["O"*5]
# print board to see
def print_board(board): # "board" arg is a list
for row in board:
print "".join(row)
print_board(board)
def random_row(board):
# return a random integer. This will be used as the row index of the move
# board is a list of lists, square size 5
return randint(0, len(board) - 1)
def random_col(board)
# Similar to random_row above
return randint(0, len(board) - 1)
ship_row = random_row(board)
ship_col = random_col(board)
guess_row = int(raw_input("Guess Row: "))
guess_col = int(raw_input("Guess Col: "))
print ship_row
print_ship_col
if guess_row == ship_row and guess_col == ship_col:
print "Congratulations! You sank my battleship!"
else:
if guess_row not in range(5) or guess_col not in range(5):
print "Oops, that is not even in the ocean."
elif board[guess_row][guess_col] == 'X':
print "You guessed that one already."
else:
print "You missed my battleship!"
board[guess_row][guess_col] = 'X'
print_board(board)
# end
|
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 2 20:54:14 2018
@author: akansal2
"""
#importing libraries
import numpy as np
from sklearn.metrics.pairwise import pairwise_distances
#function for calculating distance
#Euclidean Distance
def dist1(a,b):
return np.linalg.norm(a-b)
#cosine distance
def dist2(a,b):
return 1- np.dot(a,b)/(np.linalg.norm(a)*np.linalg.norm(b))
#pick a distance type
dist,metric = dist2,'cosine'
#find analgoies
#more intutive but with for loop and hence slower
def find_analogies1(w1,w2,w3):
for w in (w1,w2,w3):
if w not in word2vec:
print('%s not in dictionary' %w)
return
king = word2vec[w1]
man = word2vec[w2]
woman = word2vec[w3]
v0 = king - man + woman
min_dist = float('inf')
best_word = ''
for word,v1 in word2vec.items():
if word not in (w1,w2,w3):
d = dist(v0,v1)
if d < min_dist:
min_dist = d
best_word = word
print(w1 ,"-",w2,"=",best_word,"-",w3)
#less intutive,without for loops, a vectorzied approach and hence faster
def find_analogies(w1,w2,w3):
for word in (w1,w2,w3):
if word not in word2vec:
print('%s not in dictionary' %word)
return
king = word2vec[w1]
man = word2vec[w2]
woman = word2vec[w3]
v0 = king - man + woman
distances = pairwise_distances(v0.reshape(1,D),embedding,metric= metric).reshape(V)
idxs = distances.argsort()[:4]
for id in idxs:
word = idx2word[id]
if word not in (w1,w2,w3):
best_word = word
break
print(w1, "-", w2, "=", best_word, "-", w3)
#finding nearest neighboaurs
def nearest_neighbours(word,n):
if word not in word2vec:
print('%s not in dictionary'%word)
return
v1 = word2vec[word]
distances = pairwise_distances(v1.reshape(1,D),embedding,metric = metric).reshape(V)
idxs = distances.argsort()[1:n+1]
for id in idxs:
print(idx2word[id])
#loading pretrained vectors
print('loading pretrained vectors ....')
word2vec = {}
embedding = []
idx2word = []
with open('C:/A_stuff/Learning/Machine Learning/Udemy/NLP 2/glove.6B.50d.txt',encoding='utf-8') as f:
for line in f:
values = line.split()
word = values[0]
vec = np.asarray(values[1:],dtype = 'float32')
word2vec[word] = vec
embedding.append(vec)
idx2word.append(word)
print('Found %s word vectors'%len(word2vec))
embedding = np.asarray(embedding)
V,D = embedding.shape
find_analogies('king', 'man', 'woman')
find_analogies('france', 'paris', 'london')
find_analogies('france', 'paris', 'rome')
find_analogies('paris', 'france', 'italy')
find_analogies('france', 'french', 'english')
find_analogies('japan', 'japanese', 'chinese')
find_analogies('japan', 'japanese', 'italian')
find_analogies('water', 'ice', 'water')
nearest_neighbours('china',5)
l = (1,2)
print(type(l))
|
#Criando a matriz
matriz= []
def criando_matriz (dimensao_matriz):
for i in range (dimensao_matriz):
matriz.append([0]* dimensao_matriz )
return matriz
#Lendo a matriz
def lendo_matriz(matriz,dimensao_matriz):
for i in range (dimensao_matriz):
for j in range(dimensao_matriz):
print('Posição da linha',i+1,'da coluna',j+1)
matriz[i][j] = int(input())
return matriz
#Matriz transposta
def transposta(matriz,dimensao_matriz,matriz_result):
for i in range(dimensao_matriz):
for j in range (dimensao_matriz):
matriz_result[i][j] = matriz=[j][i]
return matriz_result
#Usuário informando a dimensão da Matriz
dimensao_matriz = int(input('Informe a dimensão da Matriz:'))
primeira_matriz = criando_matriz(dimensao_matriz)
primeira_matriz = lendo_matriz(primeira_matriz,dimensao_matriz)
mtransposta = criando_matriz(dimensao_matriz)
mtransposta = transposta (primeira_matriz,dimensao_matriz,mtransposta)
print(primeira_matriz)
print(mtransposta)
|
"""
pipe.py 管道通信
注意:
1. 管道通信只能应用于一个父子进程中
2. 管道对象在父进程中创建,子进程通过copy父进程代码获取管道
"""
from multiprocessing import Process,Pipe
"""
# 创建管道
fd1,fd2 = Pipe()
def app1():
print("启动app1,请登录")
print("请求app2 授权")
fd1.send("app1 请求登录") # 写入管道
data = fd1.recv()
if data == ("David",123):
print("{}登录成功".format(data[0]))
def app2():
data = fd2.recv() # 阻塞等待读取管道内容
print(data)
fd2.send(('David',123))
p1 = Process(target=app1)
p2 = Process(target=app2)
p1.start()
p2.start()
p1.join()
p2.join()
"""
# 若为False,表示单向管道
# fd1只能读(即调用recv),fd2只能写(即调用send)
fd1,fd2 = Pipe(duplex=False)
def app1():
print("启动app1,请登录")
print("请求app2 授权")
data = fd1.recv()
if data == ("David",123):
print("{}登录成功".format(data[0]))
def app2():
fd2.send(('David',123))
p1 = Process(target=app1)
p2 = Process(target=app2)
p1.start()
p2.start()
p1.join()
p2.join()
|
"""
栈模型的链式存储
"""
class StackError(Exception):
pass
class Node:
def __init__(self, value):
self.value = value
self.next = None
def __str__(self):
return "该节点是%s" % (self.value)
# 第一种方法:
# 该种类每次调用添加或删除方法都需要遍历链表,得到最后一个元素,
# 相比第二种方法更复杂,麻烦
"""
class LStack:
def __init__(self):
self._head = None
def push(self, value):
if self.is_empty():
self._head = Node(value)
else:
temp = self._head
while not temp.next == None:
temp = temp.next
temp.next = Node(value)
def pop(self):
temp = self._head
pre = None
if self._head == None:
raise StackError("stack is empty")
elif pre == None:
self._head = None
return temp
while temp.next is not None:
pre = temp
temp = temp.next
pre.next = None
return temp
def top(self):
if self._head == None:
return None
temp = self._head
while not temp.next == None:
temp = temp.next
return temp
def is_empty(self):
return self._head == None
l = LStack()
for i in range(10):
l.push(i)
print(l.top())
"""
class LStack:
def __init__(self):
self._top = None
def is_empty(self):
return self._top is None
def push(self, value):
node = Node(value)
node.next = self._top
self._top = node
def pop(self):
if self._top is None:
raise StackError("Stack is empty")
temp = self._top
self._top = temp.next
temp.next = None
return temp
if __name__ == '__main__':
ls = LStack()
ls.push(1)
ls.push(2)
ls.push(3)
print(ls.pop())
print(ls.pop())
print(ls.pop())
print(ls.pop())
""" |
"""
multiprocessing模块创建进程
1.编写进程函数
2.生产进程对象
3.启动进程
4.回收进程
"""
import multiprocessing as mp
from time import sleep
def fun01():
print("开始进程1")
sleep(3)
print("子进程结束")
def fun02():
print("开始进程2")
sleep(5)
print("父进程结束")
# 创建进程对象
p1 = mp.Process(target=fun01)
p1.start() # 启动进程
# 父进程事件
fun02()
p1.join() # 回收进程
# 等同于:
"""
pid = os.fork()
if pid == 0:
fun01()
os._exit()
else:
fun02()
""" |
def quick_sort(alist):
if len(alist) < 2:
return alist
first = alist[0]
alist.remove(first)
left,right = [],[]
for i in alist:
if i > first:
right.append(i)
else:
left.append(i)
res = quick_sort(left) + [first] + quick_sort(right)
return res
l1 = [6,3,2,6,8,1,2,0,123]
print(quick_sort(l1)) |
word = list("cookies")
# print(word)
joined_word = "".join(word)
new_word = []
for char in word[:2:-1]:
new_word.append(char)
print(new_word)
print(word)
# word.reverse()
# print(word)
# print(joined_word)
|
# from torch.nn import CrossEntropyLoss
from .sup_single import *
from abc import abstractmethod
class ClassificationTrainer(SupSingleModelTrainer):
"""this is a classification trainer.
"""
def __init__(self, logdir, nepochs, gpu_ids, net, opt, datasets, num_class):
super(ClassificationTrainer, self).__init__(logdir, nepochs, gpu_ids, net, opt, datasets)
self.net = net
self.opt = opt
self.datasets = datasets
self.num_class = num_class
@abstractmethod
def compute_loss(self):
"""Compute the main loss and observed values.
Compute the loss and other values shown in tensorboard scalars visualization.
You should return a main loss for doing backward propagation.
So, if you want some values visualized. Make a ``dict()`` with key name is the variable's name.
The training logic is :
self.input, self.ground_truth = self.get_data_from_batch(batch, self.device)
self.output = self.net(self.input)
self._train_iteration(self.opt, self.compute_loss, csv_filename="Train")
So, you have `self.net`, `self.input`, `self.output`, `self.ground_truth` to compute your own loss here.
.. note::
Only the main loss will do backward propagation, which is the first returned variable.
If you have the joint loss, please add them up and return one main loss.
.. note::
All of your variables in returned ``dict()`` will never do backward propagation with ``model.train()``.
However, It still compute grads, without using ``with torch.autograd.no_grad()``.
So, you can compute any grads variables for visualization.
Example::
var_dic = {}
labels = self.ground_truth.squeeze().long()
var_dic["MSE"] = loss = nn.MSELoss()(self.output, labels)
return loss, var_dic
"""
@abstractmethod
def compute_valid(self):
"""Compute the valid_epoch variables for visualization.
Compute the validations.
For the validations will only be used in tensorboard scalars visualization.
So, if you want some variables visualized. Make a ``dict()`` with key name is the variable's name.
You have `self.net`, `self.input`, `self.output`, `self.ground_truth` to compute your own validations here.
.. note::
All of your variables in returned ``dict()`` will never do backward propagation with ``model.eval()``.
However, It still compute grads, without using ``with torch.autograd.no_grad()``.
So, you can compute some grads variables for visualization.
Example::
var_dic = {}
labels = self.ground_truth.squeeze().long()
var_dic["CEP"] = nn.CrossEntropyLoss()(self.output, labels)
return var_dic
"""
def valid_epoch(self):
avg_dic = dict()
self.net.eval()
for iteration, batch in enumerate(self.datasets.loader_valid, 1):
self.input, self.ground_truth = self.get_data_from_batch(batch, self.device)
self.output = self.net(self.input).detach()
dic = self.compute_valid()
if avg_dic == {}:
avg_dic = dic
else:
# sum up
for key in dic.keys():
avg_dic[key] += dic[key]
for key in avg_dic.keys():
avg_dic[key] = avg_dic[key] / self.datasets.nsteps_valid
self.watcher.scalars(var_dict=avg_dic, global_step=self.step, tag="Valid")
self.loger.write(self.step, self.current_epoch, avg_dic, "Valid", header=self.current_epoch <= 1)
self.net.train()
def get_data_from_batch(self, batch_data, device):
"""If you have different behavior. You need to rewrite thisd method and the method `sllf.train_epoch()`
:param batch_data: A Tensor loads from dataset
:param device: compute device
:return: Tensors,
"""
input_tensor, labels_tensor = batch_data[0], batch_data[1]
return input_tensor, labels_tensor
def _watch_images(self, tag: str, grid_size: tuple = (3, 3), shuffle=False, save_file=True):
pass
@property
def configure(self):
config_dic = super(ClassificationTrainer, self).configure
config_dic["num_class"] = self.num_class
return config_dic
|
# lesson3
# Задание №3. В массиве случайных целых чисел поменять местами минимальный и максимальный элементы.
i = 1
array = []
num = int(input('Сколько элементов массива Вы хотите ввести? (ввдите целое положительно число): '))
while i <= num:
array.append(input('Введите {} целое число: '.format(i)))
i += 1
print('Ваш массив выглядит так: ', array)
min_value = array[0]
max_value = array[0]
min_index = 0
max_index = 0
for index, value in enumerate(array):
if int(min_value) > int(value):
min_value = value
min_index = index
if int(max_value) < int(value):
max_value = value
max_index = index
del array[min_index]
del array[max_index]
array.insert(min_index, max_value)
array.insert(max_index, min_value)
print('Мы поменяли местами максимальный и минимальный элементы, теперь Ваш массив выглядит так: ', array)
|
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 10 15:51:01 2017
@author: Gubynator
"""
def reverseseq(n):
ReverseSequence = []
for number in range(n, 0 , -1):
ReverseSequence.append(number)
return ReverseSequence
def reverseseq(n):
return list(range(n, 0, -1)) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 10 11:56:17 2018
@author: kaidenbillings
"""
def print_header():
print("Think of a number between 1 and 100")
print("I'm going to try to guess your number")
print("Tell me if my guess is correct by entering yes, lower or higher")
### Write the code for the ending message
def print_footer(guess, tries):
print("I got it! Your number was %s." % guess)
print("And it only took me %s tries!" % tries)
def main():
###print the greeting banner
print_header()
###set the initial values
max_number = 100
min_number = 1
answer = "Take a guess"
tries = 1
###write code for guesses
while answer != "yes":
guess = (max_number + min_number)//2
print("\nMy guess is %s" % guess)
answer = str(input("Was I right? "))
if answer == "higher":
min_number = guess + 1
tries += 1
elif answer == "lower":
max_number = guess - 1
tries += 1
print_footer(guess, tries)
main() |
#!/usr/bin/python2
# class test:
# def __init__(self):
# self.count = 1
# self.cost = None
# def test(self,cost=lambda x:1):
# self.cost = cost
# print cost
for i in range(1000):
print "hello there" |
def IsYearLeap(year):
# if the year number isn't divisible by four, it's a common year;
if year % 4 != 0:
return False
# otherwise, if the year number isn't divisible by 100, it's a leap year;
elif year % 100 != 0:
return True
# otherwise, if the year number isn't divisible by 400, it's a common year;
elif year % 400:
return False
# otherwise, it's a leap year.
else:
return True
testdata = [1900, 2000, 2016, 1987]
testresults = [False, True, True, False]
for i in range(len(testdata)):
yr = testdata[i]
print(yr,"->",end="")
result = IsYearLeap(yr)
if result == testresults[i]:
print("OK")
else:
print("Failed") |
"""
Estimated time
10-15 minutes
Level of difficulty
Easy/Medium
Objectives
Familiarize the student with:
using the if-elif-else statement;
finding the proper implementation of verbally defined rules;
testing code using sample input and output.
Scenario
As you surely know, due to some astronomical reasons, years may be leap or common. The former are 366 days long, while the latter are 365 days long.
Since the introduction of the Gregorian calendar (in 1582), the following rule is used to determine the kind of year:
if the year number isn't divisible by four, it's a common year;
otherwise, if the year number isn't divisible by 100, it's a leap year;
otherwise, if the year number isn't divisible by 400, it's a common year;
otherwise, it's a leap year.
Look at the code below - it only reads a year number, and needs to be completed with the instructions implementing the test we've just described. The code should output one of two possible messages, which are Leap year or Common year, depending on the value entered.
It would be good to verify if the entered year falls into the Gregorian era, and output a warning otherwise.
Test your code using the data we've provided.
Example input
2000
Example output
Leap year
Example input
2015
Example output
Common year
Example input
1999
Example output
Common year
Example input
1996
Example output
Leap year
Example input
1900
Example output
Common year
"""
year = int(input("Enter a year: "))
#
# put your code here
#
# if the year number isn't divisible by four, it's a common year;
if year % 4 != 0:
print("Common Year")
# otherwise, if the year number isn't divisible by 100, it's a leap year;
elif year % 100 != 0:
print("Leap Year")
# otherwise, if the year number isn't divisible by 400, it's a common year;
elif year % 400:
print("Common Year")
# otherwise, it's a leap year.
else:
print("Leap Year") |
#input a float value for variable a here
a = float(input("Enter a float: "))
#input a float value for variable b here
b = float(input("Enter another float: "))
#output the results of addition, subtraction, multiplication and division
print("addition: a + b = ", a + b)
print("subtraction: a - b = ", a - b)
print("multiplication: a * b = ", a * b)
print("division: a / b = ", a / b)
print("That's all, folks!")
x = float(input("Enter value for x: "))
# put your code here
y = 1 /(x+1/(x+1/(x+1/x)))
print("y =",y) |
initial_cost = int(input('Enter the initiation fee: $'))
monthly_cost = int(input('Enter the monthly fee: $'))
length = int(input('Enter how many months you\'d like to calculate for: '))
annual_cost = int(input('Enter the annual cost: $'))
total_cost = []
for num in range(length + 1):
if num == 0:
total_cost.append(initial_cost)
elif num == 1:
total_cost.append(monthly_cost + initial_cost)
elif num % 12 == 0:
total_cost.append(monthly_cost + total_cost[-1] + annual_cost)
else:
total_cost.append(total_cost[-1] + monthly_cost)
print(total_cost)
print(f'With an initial cost of ${initial_cost} and a monthly cost of ${monthly_cost} after {length} months your total will be ${total_cost[-1]} with a first month\'s payment of ${total_cost[1]}')
|
why=raw_input('Hey')
print 'Do you like X-TREME ROLLER COASTERS?!'+' '+why
myname='Mrs.Kipling'
print myname=='Mrs.Kipling'
print 6>=1
l=18
if(l!=18):
print 'l is less than 16'
else:
print'l is less than 16'
|
import turtle
t=turtle.Pen()
t.pensize(110)
red=1
green=0.5
blue=1
for i in range(1,10):
t.color(red,green,blue)
t.forward(200);
t.right(100);
t.forward(200);
t.right(100);
red=red - 0.1
green=0.5
blue=1
t.color(1,1,0)
t.up()
t.right(48)
t.forward(135)
t.down()
t.pensize(50)
t.circle(15)
|
# GIVEN
# Is that user enter guess secret number.
# Required
#to tell the user whether their number was too large or small.
# to tell number of tries
# Algorithm
# import random
# n = random.randint(1, 50) guess = int(input("Enter an integer from 1 to 50: "))
# while n != "guess"
#if guess < n: print ("guess is small" guess= int(input("Enter an integer from 1 to 50: ")) )
#elif guess > n: print ("guess is large" guess = int(input("Enter an integer from 1 to 50: ")))
#else: print ("you guessed it!") |
# this program calculates molecular weight of a carbohydrate
def mol_weight():
h = int(input("Enter the number of hydrogen atoms: "))
o = int(input("Enter the number of oxygen atoms: "))
c = int(input("Enter the number of carbon atoms: "))
hw, cw, ow = 1.00794, 12.0107, 15.9994
m_weight = h * hw + o * ow + c * cw
print()
print("-----------")
print("Molecular weight is", m_weight)
input("Press <Enter> to exit")
mol_weight() |
import math
def pizzaArea(r):
a = r*r * math.pi
return a
def pizzaCost(a, p):
cpcm = p / a
return cpcm
def main():
diameter = float(input("Enter diameter of the pizza: "))
price = float(input("Enter price of the pizza: "))
area = pizzaArea(diameter)
cost_per_sqcm = pizzaCost(area, price)
area_i = area * 0.393701
cost_per_sqi = pizzaCost(area_i, price)
print("The price of your pizza is ${:0.3f} per square centimeter and \
${:0.3f} per square inch".format(cost_per_sqcm, cost_per_sqi))
main()
|
def break_digits_apply_luhns(my_str):
first_list = [int(my_str[j]) for j in range(0, len(my_str), 2)]
second_list = [int(my_str[j]) for j in range(1, len(my_str), 2)]
for j in range(len(second_list)):
second_list[j] = 2 * second_list[j]
for j in range(len(second_list)):
if second_list[j] >= 10:
second_list[j] = second_list[j] - 9
total = sum(first_list) + sum(second_list)
return total
def main():
ccn = input("Enter CC number: ")
str_ccn = str(ccn)[::-1]
dig2 = str_ccn[-1] + str_ccn[-2]
#checking if CC is AMEX and if so, applying Luhn's algorithm
if dig2 in ['34', '37'] and len(str_ccn) == 15:
total = break_digits_apply_luhns(str_ccn)
if total % 10 == 0:
print("AMEX")
else:
print("INVALID")
#checking if CC is MASTERCARD and if so, applying Luhn's algorithm
elif 51 <= int(dig2) <= 55 and len(str_ccn) == 16:
total = break_digits_apply_luhns(str_ccn)
if total % 10 == 0:
print("MASTERCARD")
else:
print("INVALID")
#checking if CC is VISA and if so, applying Luhn's algorithm
elif str_ccn[-1] == '4' and len(str_ccn) in [13, 16]:
total = break_digits_apply_luhns(str_ccn)
if total % 10 == 0:
print("VISA")
else:
print("INVALID")
else:
print("INVALID")
main()
|
#leap years
def main():
year = int(input("Enter year: "))
if year % 4 == 0:
if year in list(range(100, year + 1, 100)):
if year % 400 ==0:
print("This is leap year")
else:
print("This ain't no leap year!")
else:
print("This is leap year")
else:
print("This ain't no leap year!")
main()
|
# this program determines the distance to a lightning strike based on
# the time elapsed between the flash and the sound of thunder
def lightning_strikes_twice():
t = int(input("Enter number of seconds passed since the lightning: "))
sos = 1100
distance_in_feet = t * sos
distance_in_miles = round(distance_in_feet / 5280, 2)
print()
print("--------------------")
print("Distance is", distance_in_feet, "feet")
print("--------------------")
print("Distance is", distance_in_miles, "miles")
if distance_in_miles < 1:
print()
print("!!!!!!!!!!!!!!!!!!")
print()
print("Oh boy, it hit ya, didn't it?!")
print()
print("R.I.P")
print()
print("!!!!!!!!!!!!!!!!!!")
else:
print()
print("----------------------------------")
print("You're one lucky bastud, ya know!")
print()
print()
print()
print()
input("Press <Enter> to exit")
lightning_strikes_twice() |
def plane():
x1, y1 = eval(input("Enter coordinates separated by comma: "))
x2, y2 = eval(input("Enter coordinates separated by comma: "))
slope = (y2 - y1) / (x2 - x1)
print()
print("----------------------")
print("Slope is", slope)
print()
print()
print()
input("Press<E> to quit")
plane() |
def fibonacci(n):
a, b = 1, 1
for j in range (n - 2):
a = a + b
b = a - b
return a
def main():
numero = int(input("Enter n-th number you'd like displayed: "))
print("Your number is", fibonacci(numero))
main()
|
def numSum(n):
x = 1
for j in range(2, n+1):
x = j + x
return x
def cubSum(n):
x = 1
for j in range(2, n+1):
x = j*j*j + x
return x
def main():
n = int(input("Enter final number (n): "))
print()
print(numSum(n))
print()
print(cubSum(n))
main()
|
# this program prints the sum of numbers defined by user
def average():
lops = int(input("Enter how many numbers to be summed: "))
sum = 0
print()
for n in range(lops):
n = int(input("Enter a number: "))
sum = sum + n
average = sum / lops
print()
print("---------------------")
print("The average is", float(average))
input("---------------------")
average() |
#quizz_grades
def main():
grades = ["F", "D", "C", "B", "A"]
ui = int(input("Enter quizz score: "))
if ui < 60:
print(grades[0])
elif ui in range(60, 70):
print(grades[1])
elif ui in range(70, 80):
print(grades[2])
elif ui in range(80, 90):
print(grades[3])
elif ui in range(90, 101):
print(grades[4])
main() |
'''
Given input matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],
rotate the input matrix in-place such that it becomes:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
[[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
'''
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
length = len(matrix)
for idx, l in enumerate(range(length, 1, -2)):
for i in range(l - 1):
a = (idx + l - 1 - i) % length
b = (length - idx - 1) % length
tmp = matrix[idx][idx + i]
matrix[idx][idx + i] = matrix[a][idx]
matrix[a][idx] = matrix[b][a]
matrix[b][a] = matrix[idx + i][b]
matrix[idx + i][b] = tmp |
class FizzBuzzer:
@staticmethod
def run_for(number):
if not isinstance(number, int):
raise Exception("not a number")
number = int(number)
if number % 15 == 0:
return 'fizzbuzz'
elif number % 3 == 0:
return 'fizz'
elif number % 5 == 0:
return 'buzz'
else:
return number
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.