text
stringlengths 37
1.41M
|
---|
a=int(input())
if a>0:
if a%2==0:
print('Even')
else:print('Odd')
else:print('Invalid')
|
from unittest import TestCase
from mainte import Gun
import sys
sys.tracebacklimit = 0
one_gun = Gun(10)
class Test_Gun(TestCase):
def setUp(self):
print(self._testMethodDoc)
def tearDown(self):
pass
def test_lock_gun(self):
"""-- Test lokc gun"""
msg = "The gun is unlock"
one_gun.lock()
self.assertTrue(one_gun.isLock, msg = msg)
def test_the_lock_of_gun(self):
"""-- Test the lock of the gun"""
msg = "The safe of gun is unlock"
one_gun.unlock()
self.assertFalse(one_gun.isLock, msg = msg)
def test_correct_type_safe(self):
"""-- Test correct type of safe"""
msg = "The correct value for bool is not returned"
self.assertIsInstance(one_gun.isLock, bool, msg = msg)
def test_gun_shoot(self):
"""-- Test gun shoot"""
msg = "The gun can shoot because the safe is open"
one_gun.shoot()
self.assertFalse(one_gun.isLock, msg = msg)
def test_reload_gun(self):
"""-- Test reload gun"""
msg = "The gun can not reload"
self.assertEquals(one_gun.reload(9),0,msg= msg)
|
def whatFlavors(cost, money):
cash = {}
for i, integ in enumerate(cost):
if money - integ in cash:
print(cash[money - integ], end=" ")
cash[integ] = i + 1
print(cash[integ])
cash[integ] = i + 1
if __name__ == '__main__':
t = int(input())
for t_itr in range(t):
money = int(input())
n = int(input())
cost = list(map(int, input().rstrip().split()))
whatFlavors(cost, money) |
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the largestRectangle function below.
def largestRectangle(h):
max_area = 1
for i in range(0, len(h)):
left_cnt = 0
right_cnt = 0
if h[i] == 1:
max_area = max(max_area, 1 * len(h))
continue
for left in range(i - 1, -1, -1):
if h[left] < h[i]:
break
left_cnt += 1
for right in range(i + 1, len(h)):
if h[right] < h[i]:
break
right_cnt += 1
max_area = max(max_area, h[i] * (left_cnt + right_cnt + 1))
return max_area
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
h = list(map(int, input().rstrip().split()))
result = largestRectangle(h)
fptr.write(str(result) + '\n')
fptr.close()
|
class Solution:
def largestPerimeter(self, A):
A.sort(reverse=True)
while((len(A)>2)):
if A[0] < (A[1]+A[2]):
return sum(A[:3])
else:
A.pop(0)
return 0 |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# Binaray Search Tree 성질 : inorder -> 오름차순 정렬이 됨!
def getMinimumDifference(self, root: 'TreeNode') -> 'int':
L: List[int] = list()
def inorder(root):
if root is None:
return
inorder(root.left)
L.append(root.val)
inorder(root.right)
inorder(root)
return min(abs(a - b) for a, b in zip(L, L[1:]))
|
# Decision Tree Regressor
# Importing the libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.tree import DecisionTreeRegressor
# Importing the dataset
dataset = pd.read_csv("Position_Salaries.csv")
X = dataset.iloc[:, [1]].values
y = dataset.iloc[:, [2]].values
# Fitting the model
regressor = DecisionTreeRegressor(random_state=0)
regressor.fit(X, y)
# Predicting a new result
y_pred = regressor.predict([[6.5]])
# Visualising the Decision Tree Regression
plt.scatter(X, y, color='red')
plt.plot(X, regressor.predict(X), color='blue')
plt.title("Decision Tree Regression")
plt.xlabel("Position Level")
plt.ylabel("Salary")
plt.show()
# Visualising the Decision Tree Regression (higher resolution)
X_grid = np.arange(min(X), max(X), 0.1)
X_grid = X_grid.reshape(-1, 1)
plt.scatter(X, y, color='red')
plt.plot(X_grid, regressor.predict(X_grid), color='blue')
plt.title("Decision Tree Regression")
plt.xlabel("Position Level")
plt.ylabel("Salary")
plt.show()
|
#!/usr/bin/python
def parse_instruction(instruction_list, index_max) :
accumulator = 0
current_index = 0
while 1 :
try : ins, value = instruction_list[current_index].split()
except AttributeError : return ['loop', accumulator]
except IndexError : return ['OK', accumulator]
else :
if ins == "acc" :
instruction_list[current_index] = None
accumulator += int(value)
current_index += 1
elif ins == "jmp" :
instruction_list[current_index] = None
current_index += int(value)
elif ins == "nop" :
instruction_list[current_index] = None
current_index += 1
else :
break
if __name__ == "__main__" :
with open("input") as a :
data = a.read().split("\n")
a.close()
# Part Two
last_modif = -1
out = 'loop'
while out == 'loop' :
modif_data = list(data)
for i in range(last_modif+1, len(modif_data)) :
ins, value = modif_data[i].split()
if ins == 'jmp' :
modif_data[i] = modif_data[i].replace('jmp', 'nop')
last_modif = i
break
elif ins == 'nop':
modif_data[i] = modif_data[i].replace('nop', 'jmp')
last_modif = i
break
else : break
out, accumulator = parse_instruction(modif_data, len(data))
print(out, " - ", accumulator)
# Part One
print(parse_instruction(data, len(data))[1])
|
#!/usr/bin/python
def checkpwd_step_one(min, max, neededLetters, pwd) :
cpt = 0
for l in pwd :
if l == neededLetters : cpt += 1
if min <= cpt <= max :
#print("{} {} - {}".format(min, max, cpt))
return 1
else : return 0
def checkpwd_step_two(pos1, pos2, neededLetters, pwd) :
if pwd[pos1 - 1] == neededLetters and pwd[pos2 - 1] == neededLetters : return 0
elif pwd[pos1 - 1] == neededLetters or pwd[pos2 - 1] == neededLetters : return 1
else : return 0
if __name__ == "__main__" :
with open("input") as a :
data = a.readlines()
a.close()
validPWD_one = 0
validPWD_two = 0
for i in data :
sp = i.split()
val1, val2 = sp[0].split("-")
val1, val2 = int(val1), int(val2)
neededLetters = sp[1].replace(":", "")
pwd = sp[2]
validPWD_one += checkpwd_step_one(val1, val2, neededLetters, pwd)
validPWD_two += checkpwd_step_two(val1, val2, neededLetters, pwd)
print(validPWD_one)
print(validPWD_two)
|
from FSM import *
"""
ISA description from https://en.wikipedia.org/wiki/Little_man_computer
Implementation detail questions:
- How do we deal with overflow of PC?
- How do we deal with over/underflow on ADD/SUB?
-> Implemented -ve flag. Set on underflow. Cleared on positive result for
SUB instruction only.
- How do we deal with negative numbers in INPUT?
- How does BRP (Branch If Positive) ever NOT take the branch if there are no negative numbers?
http://www.peterhigginson.co.uk/LMC/help.html
https://www.gwegogledd.cymru/wp-content/uploads/2018/04/RISC-Simulator-Design.pdf ???
"""
class LMC_RTL :
def __init__(self, memory) :
self.program_counter = 0
self.instruction_register = 0
self.accumulator = 0
self.memory_address_register = 0
self.memory_data_register = 0
self.negative_flag = False
self.input_register = 0
self.output_register = 0
self.RTL_model = FSM()
# memory passed as a mutable list. We take advantage of this by copying a
# reference to it, then modifying any value in the list directly
self.memory = memory
self.clock_cycles = 0
self.instruction_cycles = 0
self.init_processor_flow_control_states()
self.init_fetch_states()
self.init_decode_states()
self.init_execute_states()
self.init_retire_states()
self.reset()
def get_current_state(self) :
return self.RTL_model.get_current_state()
def get_memory_image(self) :
return self.memory
def get_elapsed_clock_cycles(self) :
return self.clock_cycles
def get_elapsed_instruction_cycles(self) :
return self.instruction_cycles
def get_program_counter(self) :
return self.program_counter
def get_instruction_register(self) :
return self.instruction_register
def get_accumulator(self) :
return self.accumulator
def get_memory_address_register(self) :
return self.memory_address_register
def get_memory_data_register(self) :
return self.memory_data_register
def get_formatted_memory_image(self) :
# Better format than this? Deal with negative numbers?
output_string = ""
for i in range(10) :
if self.memory[i * 10] < 100 :
output_string += "0"
if self.memory[i * 10] < 10 :
output_string += "0"
output_string += str(self.memory[i * 10])
for j in range(1, 10) :
output_string += " "
if self.memory[i * 10 + j] < 100 :
output_string += "0"
if self.memory[i * 10 + j] < 10 :
output_string += "0"
output_string += str(self.memory[i * 10 + j])
if i < 9 :
output_string += "\n"
return output_string
def reset(self) :
self.program_counter = 0
self.instruction_register = 0
self.accumulator = 0
self.memory_address_register = 0
self.memory_data_register = 0
self.input_register = 0
self.output_register = 0
self.negative_flag = False
self.RTL_model.set_current_state("Reset")
def clock(self, single_step = False, single_cycle = False) :
self.RTL_model.transition_states(self.decode_instruction())
self.clock_cycles += 1
def init_processor_flow_control_states(self) :
def monitor_instruction_cycles() :
self.instruction_cycles += 1
self.RTL_model.add_state("Reset", "Always", "Fetch", monitor_instruction_cycles)
self.RTL_model.add_state("Halt", "Always", "Halt", monitor_instruction_cycles)
def init_fetch_states(self) :
def fetch_instruction() :
self.memory_address_register = self.program_counter
self.memory_data_register = self.memory[self.memory_address_register]
self.instruction_register = self.memory_data_register
self.program_counter = self.program_counter + 1
if self.program_counter > 99 :
# Handle overflow of program counter. This doesn't seem to be defined?
self.program_counter = 0
self.RTL_model.add_state("Fetch", "Always", "Decode", fetch_instruction)
def init_decode_states(self) :
self.RTL_model.add_state("Decode", "Addition", "Execute Addition")
self.RTL_model.add_state("Decode", "Subtraction", "Execute Subtraction")
self.RTL_model.add_state("Decode", "Store", "Execute Store")
self.RTL_model.add_state("Decode", "Load", "Execute Load")
self.RTL_model.add_state("Decode", "Branch Unconditionally", "Execute Branch Unconditionally")
self.RTL_model.add_state("Decode", "Branch If Zero", "Execute Branch If Zero")
self.RTL_model.add_state("Decode", "Branch If Positive", "Execute Branch If Positive")
self.RTL_model.add_state("Decode", "Input", "Execute Input")
self.RTL_model.add_state("Decode", "Output", "Execute Output")
self.RTL_model.add_state("Decode", "Halt", "Execute Halt")
self.RTL_model.add_state("Decode", "No Operation", "Execute No Operation")
def init_execute_states(self) :
def execute_addition_instruction() :
self.memory_address_register = self.get_address_from_instruction_register()
self.memory_data_register = self.memory[self.memory_address_register]
# Overflow behaviour doesn't seem to be defined, although BRP instruction implies
# negative results are possible. Here, we just wrap to 0 > 999
self.accumulator = (self.accumulator + self.memory_data_register) % 1000
def execute_subtraction_instruction() :
self.memory_address_register = self.get_address_from_instruction_register()
self.memory_data_register = self.memory[self.memory_address_register]
# Underflow isn't defined either
self.accumulator = self.accumulator - self.memory_data_register
if self.accumulator < 0 :
self.negative_flag = True
else :
self.negative_flag = False
self.accumulator = self.accumulator % 1000
def execute_store_instruction() :
self.memory_address_register = self.get_address_from_instruction_register()
self.memory_data_register = self.accumulator
self.memory[self.memory_address_register] = self.memory_data_register
def execute_load_instruction() :
self.memory_address_register = self.get_address_from_instruction_register()
self.memory_data_register = self.memory[self.memory_address_register]
self.accumulator = self.memory_data_register
def execute_unconditional_branch_instruction() :
self.program_counter = self.get_address_from_instruction_register()
def execute_branch_if_zero_instruction() :
if self.accumulator == 0 :
self.program_counter = self.get_address_from_instruction_register()
def execute_branch_if_positive_instruction() :
if self.negative_flag is False :
print "Taking branch!"
self.program_counter = self.get_address_from_instruction_register()
def execute_input_instruction() :
# Better handling of inputs? Reject bad input?
self.input_register = input("Input: ")
self.accumulator = self.input_register
def execute_output_instruction() :
# Better display negative numbers?
self.output_register = self.accumulator
output_string = ""
if self.output_register < 100 :
output_string += "0"
if self.output_register < 10 :
output_string += "0"
print "Output: " + output_string + str(self.output_register)
self.RTL_model.add_state("Execute Addition", "Always", "Retire", execute_addition_instruction)
self.RTL_model.add_state("Execute Subtraction", "Always", "Retire", execute_subtraction_instruction)
self.RTL_model.add_state("Execute Store", "Always", "Retire", execute_store_instruction)
self.RTL_model.add_state("Execute Load", "Always", "Retire", execute_load_instruction)
self.RTL_model.add_state("Execute Branch Unconditionally", "Always", "Retire", execute_unconditional_branch_instruction)
self.RTL_model.add_state("Execute Branch If Zero", "Always", "Retire", execute_branch_if_zero_instruction)
self.RTL_model.add_state("Execute Branch If Positive", "Always", "Retire", execute_branch_if_positive_instruction)
self.RTL_model.add_state("Execute Input", "Always", "Retire", execute_input_instruction)
self.RTL_model.add_state("Execute Output", "Always", "Retire", execute_output_instruction)
self.RTL_model.add_state("Execute Halt", "Always", "Halt")
self.RTL_model.add_state("Execute No Operation", "Always", "Retire")
def init_retire_states(self) :
def monitor_instruction_cycles() :
self.instruction_cycles += 1
self.RTL_model.add_state("Retire", "Always", "Fetch", monitor_instruction_cycles)
def decode_instruction(self) :
if (self.instruction_register >= 100) and \
(self.instruction_register <= 199) :
return "Addition"
if (self.instruction_register >= 200) and \
(self.instruction_register <= 299) :
return "Subtraction"
if (self.instruction_register >= 300) and \
(self.instruction_register <= 399) :
return "Store"
if (self.instruction_register >= 500) and \
(self.instruction_register <= 599) :
return "Load"
if (self.instruction_register >= 600) and \
(self.instruction_register <= 699) :
return "Branch Unconditionally"
if (self.instruction_register >= 700) and \
(self.instruction_register <= 799) :
return "Branch If Zero"
if (self.instruction_register >= 800) and \
(self.instruction_register <= 899) :
return "Branch If Positive"
if (self.instruction_register == 901) :
return "Input"
if (self.instruction_register == 902) :
return "Output"
if (self.instruction_register == 000) :
return "Halt"
return "No Operation"
def get_address_from_instruction_register(self) :
if self.decode_instruction() == "Addition" :
return self.instruction_register - 100
if self.decode_instruction() == "Subtraction" :
return self.instruction_register - 200
if self.decode_instruction() == "Store" :
return self.instruction_register - 300
if self.decode_instruction() == "Load" :
return self.instruction_register - 500
if self.decode_instruction() == "Branch Unconditionally" :
return self.instruction_register - 600
if self.decode_instruction() == "Branch If Zero" :
return self.instruction_register - 700
if self.decode_instruction() == "Branch If Positive" :
return self.instruction_register - 800
|
'''
This is one of the more expensive algorithms time wise, but constant base.
We keep on sending maximum value to the last by comparing adjucent elements
Time Complexity: O(n^2)
Space Complexity: O(1)
for more: https://en.wikipedia.org/wiki/Bubble_sort
'''
def bubbleSort(arr):
for i in range(len(arr)-1):
for j in range(len(arr)-i-1):
if arr[j]>arr[j+1]:
arr[j],arr[j+1]=arr[j+1],arr[j]
return arr
#Let's check with example:
print(bubbleSort([7,4,8,6,2,15,5]) |
class Node:
def __init__(self,data):
self.data = data
self.next = None
class List:
###here tail_prev keeps record of the immediate
###second last element
def __init__(self):
self.head = None
self.tail = None
self.tail_prev = None
self.size = 0
###function for adding an element at last
###if head is null then head is the last element
###else add one after the tail O(1)
def add_last(self,node_value):
node = Node(node_value)
if not self.head:
self.head = node
self.tail = self.head
else:
self.tail.next = node
self.tail_prev = self.tail
self.tail = node
self.size += 1
###function for adding an element at first
###if head is null then head is the first element
###else add one before the head O(1)
def add_first(self,node_value):
node = Node(node_value)
if not self.head:
self.head = node
self.tail = self.head
else:
node.next = self.head
self.head = node
self.size += 1
###function for printing the list element O(n)
def print(self):
temp = self.head
if not temp:
print('list is empty')
return
while temp:
print(temp.data,end = ' ')
temp = temp.next
print()
###function that return the given positioned value O(n)
def at(self,i):
if i < 0 or i >= self.size:
return -10**6
f=0
res = self.head
while f<i:
f += 1
res = res.next
return res.data
###function insert at given position O(n)
def insert_at(self,i,data):
###if invalid position, return
if i < 0 or i >= self.size:
return
###if insertion being at 1st position,
###calling the built function add_first
if i == 0:
self.add_first(data)
###if insertion being at last position,
###calling the built function add_last
elif i == self.size - 1:
self.add_last(data)
###else finding the given positoned node and
###the node before that.Then add the given node
###between them
else:
flag = 0
temp = self.head
node = Node(data)
pre = None
while flag < i-1:
if flag < i:
pre = temp
temp = temp.next
flag += 1
node.next = temp
pre.next = node
###function delete at given position O(n)
def remove(self,i):
###check for invalid position
if not self.head:
return
###if first position to be deleted then,
###make the head as the current heads next
if i == 0:
self.head = self.head.next
###if last position to be deleted then,
###make the previous node pointer of tial as null
elif i == self.size - 1:
self.tail_prev.next = None
###else find the node before and after the given
###positioned node and connect them
else:
flag = 0
temp = self.head
pre = None
while flag <= i:
if flag < i:
pre = temp
temp = temp.next
flag += 1
pre.next = temp
self.size -= 1
###funtion for deleting all the element from the list O(n)
def remove_all(self):
while self.head:
self.remove(self.size)
self.size = 0
###function for reverse the whole list O(n)
def reverse(self):
if not self.head:
return
self.tail = self.head
prev = None
cur = self.head
d = 0
while cur:
if d == 0:
self.tail_prev = cur.next
nxt = cur.next
cur.next = prev
prev = cur
cur = nxt
d += 1
self.head = prev
if __name__ == '__main__':
ls = List()
ls.print()
ls.add_last(1)
ls.add_last(12)
ls.print()
ls.add_last(-4)
ls.add_last(8)
ls.print()
ls.add_first(56)
ls.add_first(102)
ls.print()
print(ls.size)
print(ls.at(4))
print(ls.at(0))
ls.insert_at(0,102)
ls.insert_at(6,-1025)
ls.insert_at(4,-25)
ls.print()
ls.remove(0)
ls.print()
ls.remove(7)
ls.print()
ls.remove(3)
ls.print()
#ls.remove_all()
ls.print()
print(ls.size)
ls.add_last(669)
ls.print()
print(ls.size)
ls.reverse()
ls.print()
print(ls.tail.data,ls.tail_prev.data,ls.head.data)
|
print("Is your number even or odd??")
print("I will tell you !!!!")
a = int(input("What number do you want to examine???"))
if a % 2 == 0:
print("That number is even")
else:
print("That is an odd number")
|
import sys
class PythonLogic_1(object):
'''
Given three ints, a b c, return True if two or more of them have the same
rightmost digit. The ints are non-negative.
lastDigit(23, 19, 13) -> True
lastDigit(23, 19, 12) -> False
lastDigit(23, 19, 3) -> True
'''
def lastDigit(ld1, ld2, ld3):
lastDigit1 = ld1%10
lastDigit2 = ld2%10
lastDigit3 = ld3%10
return lastDigit1 == lastDigit2 or lastDigit1 == lastDigit3 or lastDigit2 == lastDigit3
'''
Given three ints, a b c, return True if two or more of them have the same
rightmost digit. The ints are non-negative.
lastDigit2(23, 19, 13) -> True
lastDigit2(23, 19, 12) -> False
lastDigit2(23, 19, 3) -> True
'''
def lastDigit2(*args):
ld2Set = set()
for arg in args:
ld2digit = arg % 10
if ld2digit in ld2Set:
return True
else:
ld2Set.add(ld2digit)
return False
'''
Given three ints, a b c, return True if one of them is 10 or more less than
one of the others.
lessBy10(1, 7, 11) -> True
lessBy10(1, 7, 10) -> False
lessBy10(11, 1, 7) -> True
'''
def lessBy10(lbtA, lbtB, lbtC):
lbtAB = abs(lbtA - lbtB)
lbtAC = abs(lbtA - lbtC)
lbtBC = abs(lbtB - lbtC)
return max(lbtAB, max(lbtAC, lbtBC)) >= 10
'''
Given three ints, a b c, return True if one of them is 10 or more less than
one of the others.
lessBy102(1, 7, 11) -> True
lessBy102(1, 7, 10) -> False
lessBy102(11, 1, 7) -> True
'''
def lessBy102(*args):
return max(args) - min(args) >= 10
'''
Return the sum of two 6-sided dice rolls, each in the range 1..6.
However, if noDoubles is True, if the two dice show the same value,
increment one die to the next value, wrapping around to 1 if its value was 6.
withoutDoubles(2, 3, True) -> 5
withoutDoubles(3, 3, True) -> 7
withoutDoubles(3, 3, False) -> 6
'''
def withoutDoubles(die1, die2, noDoubles):
if noDoubles and (die1 == die2):
if die1 == 6:
die1 = 1
else:
die1 += 1
return die1 + die2
'''
Given two int values, return whichever value is larger.
However if the two values have the same remainder when divided by 5,
then the return the smaller value. However, in all cases, if the two
values are the same, return 0.
maxMod5(25, 15) -> 15
maxMod5(6, 2) -> 6
maxMod5(3, 3) -> 0
'''
def maxMod5(mm5A, mm5B):
if mm5A == mm5B:
return 0
elif mm5A % 5 == mm5B % 5:
return min(mm5A, mm5B)
else:
return max(mm5A, mm5B)
'''
You have a red lottery ticket showing ints a, b, and c, each of which
is 0, 1, or 2. If they are all the value 2, the result is 10. Otherwise
if they are all the same, the result is 5. Otherwise so long as both
b and c are different from a, the result is 1. Otherwise the result is 0.
redTicket(2, 2, 2) -> 10
redTicket(2, 2, 1) -> 0
redTicket(0, 0, 0) -> 5
'''
def redTicket(rtA, rtB, rtC):
if rtA == 2 and rtB == 2 and rtC == 2:
return 10
elif rtA == rtB == rtC:
return 5
elif rtA != rtB and rtA != rtC:
return 1
else:
return 0
'''
You have a green lottery ticket, with ints a, b, and c on it.
If the numbers are all different from each other, the result is 0.
If all of the numbers are the same, the result is 20.
If two of the numbers are the same, the result is 10.
greenTicket(1, 2, 3) -> 0
greenTicket(2, 2, 2) -> 20
greenTicket(1, 1, 2) -> 10
'''
def greenTicket(gtA, gtB, gtC):
if gtA != gtB and gtA != gtC and gtB != gtC:
return 0
elif gtA == gtB == gtC:
return 20
else:
return 10
'''
You have a green lottery ticket, with ints a, b, and c on it.
If the numbers are all different from each other, the result is 0.
If all of the numbers are the same, the result is 20.
If two of the numbers are the same, the result is 10.
greenTicket2(1, 2, 3) -> 0
greenTicket2(2, 2, 2) -> 20
greenTicket2(1, 1, 2) -> 10
'''
def greenTicket2(*args):
gtSet = set(args)
gtCount = len(gtSet)
if gtCount == 3:
return 0
elif gtCount == 2:
return 10
else:
return 20
'''
You have a blue lottery ticket, with ints a, b, and c on it.
This makes three pairs, which we'll call ab, bc, and ac.
Consider the sum of the numbers in each pair.
If any pair sums to exactly 10, the result is 10.
Otherwise if the ab sum is exactly 10 more than either bc or ac sums,
the result is 5. Otherwise the result is 0.
blueTicket(9, 1, 0) -> 10
blueTicket(9, 2, 0) -> 0
blueTicket(14, 1, 4) -> 5
'''
def blueTicket(btA, btB, btC):
btAB = btA + btB
btAC = btA + btC
btBC = btB + btC
if btAB == 10 or btAB == 10 or btBC == 10:
return 10
elif btAB - btAC == 10 or btAB - btBC == 10:
return 5
else:
return 0
'''
Given two ints, each in the range 10..99, return True if there is
a digit that appears in both numbers, such as the 2 in 12 and 23.
shareDigit(90, 0) -> True
shareDigit(12, 23) -> False
shareDigit(12, 34) -> False
'''
def shareDigit(sd1, sd2):
sdSet = set()
while True:
sdSet.add(sd1%10)
sd1 //= 10
if sd1 == 0:
break
while True:
if sd2%10 in sdSet:
return True
sd2 //= 10
if sd2 == 0:
break
return False
'''
Given two ints, each in the range 10..99, return True if there is
a digit that appears in both numbers, such as the 2 in 12 and 23.
shareDigit2(90, 0) -> True
shareDigit2(12, 23) -> False
shareDigit2(12, 34) -> False
'''
def shareDigit2(sd21, sd22):
sd21Str = str(sd21)
sd22Str = str(sd22)
for ch in sd21Str:
if ch in sd22Str:
return True
return False
'''
Calculate the sum and the maximum of the passed-in values.
If the sum and maximum have the same number of digits then
return the sum, otherwise return the maximum.
sumLimit(2, 3) -> 5
sumLimit(8, 3) -> 8
sumLimit(-12, 3) -> -9
'''
def sumLimit(sl1, sl2):
slSum = sl1 + sl2
slMax = max(sl1, sl2)
slSumStr = str(abs(slSum))
slMaxStr = str(abs(slMax))
if len(slSumStr) == len(slMaxStr):
return slSum
else:
return slMax
print("lastDigit")
print(lastDigit(23, 19, 13) == True)
print(lastDigit(23, 19, 12) == False)
print(lastDigit(23, 19, 3) == True)
print("lastDigit2")
print(lastDigit2(23, 19, 13) == True)
print(lastDigit2(23, 19, 12) == False)
print(lastDigit2(23, 19, 3) == True)
print("lessBy10")
print(lessBy10(1, 7, 11) == True)
print(lessBy10(1, 7, 10) == False)
print(lessBy10(11, 1, 7) == True)
print("lessBy102")
print(lessBy102(1, 7, 11) == True)
print(lessBy102(1, 7, 10) == False)
print(lessBy102(11, 1, 7) == True)
print("withoutDoubles")
print(withoutDoubles(6, 6, True) == 7)
print(withoutDoubles(2, 3, True) == 5)
print(withoutDoubles(3, 3, True) == 7)
print(withoutDoubles(3, 3, False) == 6)
print("maxMod5")
print(maxMod5(25, 15) == 15)
print(maxMod5(6, 2) == 6)
print(maxMod5(3, 3) == 0)
print("redTicket")
print(redTicket(2, 2, 2) == 10)
print(redTicket(2, 2, 1) == 0)
print(redTicket(0, 0, 0) == 5)
print("greenTicket")
print(greenTicket(1, 2, 3) == 0)
print(greenTicket(2, 2, 2) == 20)
print(greenTicket(1, 1, 2) == 10)
print("greenTicket2")
print(greenTicket2(1, 2, 3) == 0)
print(greenTicket2(2, 2, 2) == 20)
print(greenTicket2(1, 1, 2) == 10)
print("blueTicket")
print(blueTicket(14, 1, 4) == 5)
print(blueTicket(9, 1, 0) == 10)
print(blueTicket(9, 2, 0) == 0)
print("shareDigit")
print(shareDigit(90, 0) == True)
print(shareDigit(12, 23) == True)
print(shareDigit(12, 34) == False)
print("shareDigit2")
print(shareDigit2(90, 0) == True)
print(shareDigit2(12, 23) == True)
print(shareDigit2(12, 34) == False)
print("sumLimit")
print(sumLimit(-12, 3) == -9)
print(sumLimit(2, 3) == 5)
print(sumLimit(8, 3) == 8) |
#!/usr/bin/env python3
"""
CS373: Quiz #7 (5 pts) <Prateek>
"""
""" ----------------------------------------------------------------------
1. What is the output of the following?
(4 pts)
m1 f1 f2 m2 m4 m5 m6
m1 f1 m3 m5 m6
"""
def f (b) :
print("f1", end = " ")
if b :
raise Exception()
print("f2", end = " ")
try :
print("m1", end = " ")
f(False)
print("m2", end = " ")
except Exception :
print("m3", end = " ")
else :
print("m4", end = " ")
finally :
print("m5", end = " ")
print("m6")
try :
print("m1", end = " ")
f(True)
print("m2", end = " ")
except Exception :
print("m3", end = " ")
else :
print("m4", end = " ")
finally :
print("m5", end = " ")
print("m6")
|
#!/usr/bin/env python3
# ----------
# Project.py
# ----------
print("Project.py")
def project_1 (r, a) :
x = []
for v in r :
y = {}
for w in a :
if w in v :
y[w] = v[w]
x.append(y)
return x
def project_2 (r, a) :
return [{w : v[w] for w in a if w in v} for v in r]
r = [ \
{"A" : 1, "B" : 6},
{"A" : 2, "B" : 7},
{"A" : 3, "B" : 8}]
assert(len(r) == 3)
s = [ \
{"A" : 4, "C" : 6},
{"A" : 1, "C" : 7},
{"A" : 2, "C" : 8},
{"A" : 2, "C" : 9}]
assert(len(s) == 4)
def test (f) :
x = f(r, ["B"])
assert(len(x) == 3)
assert(x ==
[{'B': 6},
{'B': 7},
{'B': 8}])
test(project_1)
test(project_2)
print("Done.")
|
#!/usr/bin/env python3
"""
CS373: Quiz #11 (5 pts) <Prateek>
"""
""" ----------------------------------------------------------------------
1. In the paper, "A Bug and a Crash" about the Ariane 5, what was the
software bug?
(1 pt)
the conversion of a 64-bit number to a 16-bit number
"""
""" ----------------------------------------------------------------------
2. In the paper, "Mariner 1", what was the software bug?
(1 pt)
the ommission of a hyphen
"""
""" ----------------------------------------------------------------------
3. Define the function map().
(2 pts)
"""
def sqre (x) :
return x * x
def cube (x) :
return x * x * x
def map (f, a) :
return (f(v) for v in a)
assert(list(map(sqre, [])) == [])
assert(list(map(sqre, [2])) == [4])
assert(list(map(sqre, [2, 3])) == [4, 9])
assert(list(map(cube, [])) == [])
assert(list(map(cube, [2])) == [8])
assert(list(map(cube, [2, 3])) == [8, 27])
|
#!/usr/bin/env python3
"""
CS373: Quiz #17 (5 pts) <Prateek>
"""
""" ----------------------------------------------------------------------
1. What is the output of the following?
(4 pts)
"""
from copy import copy, deepcopy
class A :
def __init__ (self) :
self.a = [2, [3], 4]
x = A()
y = copy(x)
print(x.a is y.a)
# True
print(x.a[1] is y.a[1])
# True
# Recursively copies the entired obj x, now both are two different objs with same values
z = deepcopy(x)
print(x.a is z.a)
# False
print(x.a[1] is z.a[1])
# False |
for x in [y for y in xrange(0,11) if y % 2 == 0]:
print x
"""
Boilerplate:
for x in mylist:
if y % 2 == 0:
print x
"""
"""
newList = [y for y in mylist if y % 2 == 0]
print newList
""" |
myword = "superword"
def subtractLetter(thestring):
while thestring:
# NOTE TO SELF: Explain the [0:-1] syntax
thestring = thestring[0:-1]
yield thestring
for astring in subtractLetter(myword):
print astring
"""
Explain:
range vs xrange!
""" |
"""
Napisz program, który wyświetla liczby od 1 do 100. Dla liczb podzielnych przez 3 niech program wyświetli `Fizz`;
dla liczb podzielnych przez 5 niech wyświetli `Buzz`; a dla liczb podzielnych przez 15 niech wyświetli `FizzBuzz`.
"""
for i in range(1,101):
flag = False
print (f"{i}",end='')
if i % 5 == 0:
print(" Fizz",end='')
flag=True
if i % 3 == 0:
if not flag:
print(" ",end='')
print("Buzz",end='')
print()
|
"""
Napisz program, który prosi użytkownika (przez `input()`), żeby podał, ile kosztuje kilo ziemniaków. Niech program policzy i wyświetli,
ile trzeba będzie zapłacić za pięć kilo ziemniaków.
Potem napisz program, który prosi użytkownika (przez `input()`), żeby podał, ile kosztuje kilo ziemniaków i ile kilo chce kupić.
Niech program policzy i wyświetli, ile trzeba będzie zapłacić za te ziemniaki.
Potem napisz program, który prosi użytkownika (przez `input()`), żeby podał, ile kosztuje kilo ziemniaków, ile kilo ziemniaków chce kupić,
ile kosztuje kilo bananów i ile kilo bananów chce kupić. Niech program policzy i wyświetli, ile trzeba będzie zapłacić za te ziemniaki i banany razem.
I niech program sprawdzi i powie, za co trzeba będzie zapłacić więcej - za banany czy za ziemniaki.
"""
cena_1kg_ziemniakow = float(input('ile kosztuje kilo ziemniaków [PLN]: '))
print(f" w takim razie za 5 kg zapłacisz {round(5*cena_1kg_ziemniakow,2)} PLN")
cena_1kg_ziemniakow, ilosc_kg = input('podaj odzielajac przecinkiem cenę za kg ziemniaków [PLN] i ile chcesz kupić[kg]: ').split(',')
print(f" w takim razie za 5 kg zapłacisz {round(float(ilosc_kg)*float(cena_1kg_ziemniakow),2)} PLN")
cena_1kg_ziemniakow, ilosc_kg_z = input('podaj odzielajac przecinkiem cenę za kg ziemniaków [PLN] i ile chcesz kupić[kg]: ').split(',')
cena_1kg_bananow, ilosc_kg_b = input('podaj odzielajac przecinkiem cenę za kg bananów [PLN] i ile chcesz kupić[kg]: ').split(',')
koszt_ziemniakow=float(ilosc_kg_z)*float(cena_1kg_ziemniakow)
koszt_bananow=float(ilosc_kg_b)*float(cena_1kg_bananow)
if koszt_ziemniakow > koszt_bananow:
print (f"za ziemniaki trzeba zaplacić więcej o {round(koszt_ziemniakow - koszt_bananow,2)} PLN")
elif koszt_ziemniakow < koszt_bananow:
print(f"za ziemniaki trzeba zaplacić więcej 0 {round(koszt_bananow - koszt_ziemniakow,2) } PLN")
else:
print(f"banany i ziemniaki będą w tym samym koszcie {koszt_bananow} PLN ")
|
"""
Napisz program obliczający średnią wartość temperatury w danym tygodniu na podstawie temperatur wprowadzonych przez użytkownika.
"""
import statistics
a = list(map(float,input("podaj temeperatury ze wszystkich pomiarów z tyg oddzielone przecinkiem: ").strip().split(',')))
print (f"średnia podanych temperatur wynosi {statistics.mean(a)}")
|
n1 = int(input("첫번째 숫자 입력 : "))
n2 = int(input("두번째 숫자 입력 : "))
n3 = int(input("세번째 숫자 입력 : "))
sum = n1 + n2 + n3
avg = sum / 3
print(sum, avg) |
def has(a, *b):
for i in b[0]:
if a == i:
return True
return False
def intersect(a, b):
s = set()
for i in a:
if has(i, list(b)):
s.add(i)
return s
a = {1, 2, 3}
b = {2, 3, 4}
print(intersect(a, b)) # {2, 3}을 출력
|
#entering different elements in a list
list1=[]
i=int(input("Enter number: "))
j=0
for j in range (0,i+1):
inp=input("Enter element to be appended: ")
list1.append(inp)
j+=1
print (list1)
#accessing elements from a tuple
tup1=(1,2,3)
for i in tup1:
print (i)
#deleting elements from a dictionary
food={1:"Pizza",2:"dry fruits",3:"Chaat"}
del food[2]
print (food)
|
init_str=input('Введите строку: ')
sum_num=0
for num in init_str:
if num.isdigit():
sum_num+=int(num)
print('Сумма цифр в строке равна: ',sum_num)
|
#!/bin/python
#https://www.hackerrank.com/challenges/30-binary-trees
"""
# Day 23: BST Level-Order Traversal
#
# Objective
#
# Today, we're going further with Binary Search Trees. Check out the Tutorial tab for learning
# materials and an instructional video!
#
# Task
#
# A level-order traversal, also known as a breadth-first search, visits each level of a tree's
# nodes from left to right, top to bottom. You are given a pointer, root, pointing to the root
# of a binary search tree. Complete the levelOrder function provided in your editor so that it
# prints the level-order traversal of the binary search tree.
#
# Hint: You'll find a queue helpful in completing this challenge.
#
# Input Format
#
# The locked stub code in your editor reads the following inputs and assembles them into a BST:
# The first line contains an integer, T (the number of test cases).
# The T subsequent lines each contain an integer, data, denoting the value of an element that must be added to the BST.
#
# Output Format
#
# Print the data value of each node in the tree's level-order traversal as a single line of N space-separated integers.
#
# Sample Input
#
# 6
# 3
# 5
# 4
# 7
# 2
# 1
#
# Sample Output
#
# 3 2 5 1 4 7
#
# Explanation
#
# The input forms the following binary search tree:
#
# https://s3.amazonaws.com/hr-challenge-images/17176/1461696188-8eddd12300-BST.png
#
# We traverse each level of the tree from the root downward, and we process the nodes at each
# level from left to right. The resulting level-order traversal is 3 -> 2 -> 5 -> 1 -> 4 -> 7,
# and we print these data values as a single line of space-separated integers.
#
#
"""
#// ---------------------------- locked code below ------------------------------
import sys
class Node:
def __init__(self,data):
self.right=self.left=None
self.data = data
class Solution:
def insert(self,root,data):
if root==None:
return Node(data)
else:
if data<=root.data:
cur=self.insert(root.left,data)
root.left=cur
else:
cur=self.insert(root.right,data)
root.right=cur
return root
#// ---------------------------- locked code above ------------------------------
def bst_traverse(self,ar,far):
if len(ar)!=0:
node = ar.pop(0)
print node.data,
# far.append(node)
if node.left!=None: ar.append(node.left)
if node.right!=None: ar.append(node.right)
self.bst_traverse(ar, far)
def levelOrder(self,root):
#Write your code here
ar=[root]
far=[]
self.bst_traverse(ar,far)
print
# for i in xrange(len(far)):
# print far[i].data, "..",
# print
###################################################################
print "to run: python ./day-23-BST-level-order-traversal.py < day-23-BST-level-order-traversal.txt"
###################################################################
#// ---------------------------- locked code below ------------------------------
T=int(raw_input())
myTree=Solution()
root=None
for i in range(T):
data=int(raw_input())
root=myTree.insert(root,data)
myTree.levelOrder(root)
|
#!/bin/python
#https://www.hackerrank.com/challenges/30-linked-list
"""
# Day 15: Linked List
#
# Objective
#
# Today we're working with Linked Lists. Check out the Tutorial tab for learning materials and
# an instructional video!
#
# A Node class is provided for you in the editor. A Node object has an integer data field, data,
# and a Node instance pointer, next, pointing to another node (i.e.: the next node in a list).
#
# A Node insert function is also declared in your editor. It has two parameters: a pointer, head,
# pointing to the first node of a linked list, and an integer data value that must be added to
# the end of the list as a new Node object.
#
# Task
#
# Complete the insert function in your editor so that it creates a new Node (pass data as the
# Node constructor argument) and inserts it at the tail of the linked list referenced by the head
# parameter. Once the new node is added, return the reference to the head node.
#
# Note: If the head argument passed to the insert function is null, then the initial list is empty.
#
# Input Format
#
# The insert function has 2 parameters: a pointer to a Node named head, and an integer value, data.
# The constructor for Node has 1 parameter: an integer value for the data field.
#
# You do not need to read anything from stdin.
#
# Output Format
#
# Your insert function should return a reference to the head node of the linked list.
#
# Sample Input
#
# The following input is handled for you by the locked code in the editor:
# The first line contains T, the number of test cases.
# The T subsequent lines of test cases each contain an integer to be inserted at the list's tail.
#
# 4
# 2
# 3
# 4
# 1
#
# Sample Output
#
# The locked code in your editor prints the ordered data values for each element in your list as
# a single line of space-separated integers:
#
# 2 3 4 1
#
# Explanation
#
# T = 4, so the locked code in the editor will be inserting 4 nodes.
# The list is initially empty, so head is null; accounting for this, our code returns a new node containing the data value 2 as the head of our list. We then create and insert nodes 3, 4, and 1 at the tail of our list. The resulting list returned by the last call to insert is [2,3,4,1], so the printed output is 2 3 4 1.
#
# LinkedListExplanation.png
#
"""
#// ---------------------------- locked code below ------------------------------
class Node:
def __init__(self,data):
self.data = data
self.next = None
class Solution:
def display(self,head):
current = head
while current:
print current.data,
current = current.next
#// ---------------------------- locked code above ------------------------------
def insert(self,head,data):
#Complete this method
if head==None:
head = Node(data)
else:
p = head
while p.next != None:
p = p.next
p.next = Node(data)
return head
#// ---------------------------- locked code below ------------------------------
###################################################################
print "to run: python ./day-15-linked-list.py < day-15-linked-list.txt"
###################################################################
mylist= Solution()
T=int(input())
head=None
for i in range(T):
data=int(input())
head=mylist.insert(head,data)
mylist.display(head);
|
"""
https://leetcode.com/contest/leetcode-weekly-contest-12/problems/validate-ip-address/
#
# 468. Validate IP Address
#
# In this problem, your job to write a function to check whether a input string is a valid IPv4
# address or IPv6 address or neither.
#
# IPv4 addresses are canonically represented in dot-decimal notation, which consists of four
# decimal numbers, each ranging from 0 to 255, separated by dots ("."), e.g.,172.16.254.1;
#
# Besides, you need to keep in mind that leading zeros in the IPv4 is illegal. For example,
# the address 172.16.254.01 is illegal.
#
# IPv6 addresses are represented as eight groups of four hexadecimal digits, each group
# representing 16 bits. The groups are separated by colons (":"). For example, the address
# 2001:0db8:85a3:0000:0000:8a2e:0370:7334 is a legal one. Also, we could omit some leading zeros
# among four hexadecimal digits and some low-case characters in the address to upper-case ones,
# so 2001:db8:85a3:0:0:8A2E:0370:7334 is also a valid IPv6 address(Omit leading zeros and using
# upper cases).
#
# However, we don't replace a consecutive group of zero value with a single empty group using
# two consecutive colons (::) to pursue simplicity. For example, 2001:0db8:85a3::8A2E:0370:7334
# is an invalid IPv6 address.
#
# Besides, you need to keep in mind that extra leading zeros in the IPv6 is also illegal. For
# example, the address 02001:0db8:85a3:0000:0000:8a2e:0370:7334 is also illegal.
#
# Note: You could assume there is no extra space in the test cases and there may some special
# characters in the input string.
#
# Example 1:
#
# Input: "172.16.254.1"
#
# Output: "IPv4"
#
# Explanation: This is a valid IPv4 address, return "IPv4".
#
# Example 2:
#
# Input: "2001:0db8:85a3:0:0:8A2E:0370:7334"
#
# Output: "IPv6"
#
# Explanation: This is a valid IPv6 address, return "IPv6".
#
# Example 3:
#
# Input: "256.256.256.256"
#
# Output: "Neither"
#
# Explanation: This is neither a IPv4 address nor a IPv6 address.
#
"""
#/* testcases
# *
testcases = [
[ "172.16.254.1" , "IPv4" ],
[ "192.168.100.1" , "IPv4" ],
[ "192.168.100.01" , "Neither" ],
[ "256.256.266.256" , "Neither" ],
[ "192.0.0.1" , "IPv4" ],
[ "2001:0db8:85a3:0:0:8A2E:0370:7334" , "IPv6" ],
[ "2001:0db8:85a3:0000:0000:8A2E:0370:7334" , "IPv6" ],
[ "2001:0db8:85a3:0:0000:8A2E:0370:7334" , "IPv6" ],
[ "2001:0db8:85a3:00:0000:8A2E:0370:7334" , "IPv6" ],
[ "2001:0db8:85a3:000:00:8A2E:0370:7334" , "IPv6" ],
[ "2001:0db8:85a3:0000:00000:8A2E:0370:7334" , "IPv6" ],
[ "2001:0db8:85a3:033:0:8A2E:0370:7334" , "IPv6" ],
[ "2001:0db8:85a3:00000:0:8A2E:0370:7334" , "Neither" ],
[ "2001:db8:85a3:0::8a2E:0370:7334" , "Neither" ],
]
# *
# */
class Solution(object):
def validIPAddress(self, IP):
"""
:type IP: str
:rtype: str
"""
sIPv4="0123456789"
sIPv6="0123456789abcdefABCDEF"
#
cIPv4 = IP.split('.')
if len(cIPv4) == 4:
# possible IPv4
bIPv4 = True
# invalid leading zero
for i in range(0,4):
if len(cIPv4[i])>1 and cIPv4[i][0] not in "123456789":
bIPv4 = False
break
if bIPv4==True:
# first octet must be between 1..255
try:
#print "cIPv4[0]=", int(cIPv4[0])
if 0<int(cIPv4[0]) and int(cIPv4[0])<256:
for i in range(1,4):
#print "cIPv4[", i, "]=", int(cIPv4[i])
if not (0<=int(cIPv4[i]) and int(cIPv4[i])<256):
#print "bIPv4=False"
bIPv4 = False
break
else: bIPv4 = False
except:
bIPv4 = False
if bIPv4==True: return "IPv4"
# not an IPv4 address
cIPv6 = IP.split(':')
if len(cIPv6) == 8:
# possible IPv6
bIPv6 = True
for i in range(0,8):
# validate individual field
if cIPv6[i]=='0' or cIPv6[i]=='00' or cIPv6[i]=='000' or cIPv6[i]=='0000':
# ok
pass
elif len(cIPv6[i])==0 or len(cIPv6[i])>4:
bIPv6 = False
break
else:
for j in range(len(cIPv6[i])):
if cIPv6[i][j] not in sIPv6:
bIPv6 = False
break
# continue to next field?
if bIPv6 != True: break
if bIPv6==True: return "IPv6"
#
return "Neither"
#--- main ---
s = Solution()
for tcase in testcases:
print tcase[0], ": ", s.validIPAddress(tcase[0]), "expected:", tcase[1]
|
#!/bin/python
#https://www.hackerrank.com/challenges/30-binary-numbers
"""
# Day 10: Binary Numbers
#
# Objective
#
# Today, we're working with binary numbers. Check out the Tutorial tab for learning materials and an instructional video!
#
# Task
#
# Given a base-10 integer, n, convert it to binary (base-2). Then find and print the base-10
# integer denoting the maximum number of consecutive 1's in n's binary representation.
#
# Input Format
#
# A single integer, n.
#
# Constraints
#
# * 1 <= n <= 10**6
#
# Output Format
#
# Print a single base-10 integer denoting the maximum number of consecutive 1's in the binary representation of n.
#
# Sample Input 1
#
# 5
#
# Sample Output 1
#
# 1
#
# Sample Input 2
#
# 13
#
# Sample Output 2
#
# 2
#
# Explanation
#
# Sample Case 1:
# The binary representation of 5 is 101, so the maximum number of consecutive 1's is 1.
#
# Sample Case 2:
# The binary representation of 13 is 1101 , so the maximum number of consecutive 1's is 2.
#
"""
###################################################################
print "provide an integer n:",
###################################################################
import sys
def tobits(n):
nar=[]
while n>0:
nar.append(n%2)
n=n/2
# nar.reverse()
return nar
def count1s(ar):
count=0
for i in ar:
if i==1: count+=1
return count
def countC1s(ar):
count=0
maxc=0
for i in ar:
if i==1:
count+=1
else: # i==0
if count>maxc: maxc=count
count=0
# "ternary" expressions -- i.e. condense oneline if-else
return maxc if count<=maxc else count
n = int(raw_input().strip())
## print "tobits(%d): %s" % (n, tobits(n)),
## print count1s(tobits(n))
print countC1s(tobits(n))
|
# Double-base palindromes
# https://projecteuler.net/problem=36
# Checks if number is a palindrome (without string functions)
def isPalindromeNumber(n):
num = n
rev = 0
while n > 0:
rev = rev * 10 + n % 10
n //= 10
return num == rev
# Converts number from base 10 to base k
def baseConversion(n, k):
answer = ''
currentPlace = 0
while n > 0:
answer = str(n % k) + answer
currentPlace += 1
n //= k
answer = int(answer)
return answer
# Converts number from base 10 to base 2 (uses python bin function)
def base2Conversion(n):
return int(str(bin(n))[2:])
# Returns sum of palindromes in base 10 and base 2 under n
def sumOfPalindromesInBase10AndBase2(n):
total = 0
for number in range(1, n):
if isPalindromeNumber(number) and isPalindromeNumber(base2Conversion(number)):
total += number
return total
print(sumOfPalindromesInBase10AndBase2(1000000))
|
# Spiral primes
# https://projecteuler.net/problem=58
import math
# Checks if n is prime
def isPrime(n):
if n < 2: return False
if n == 2: return True
for factor in range(2, math.ceil(math.sqrt(n)) + 1):
if n % factor == 0:
return False
return True
# Returns side length of the square spiral for which the ratio of primes along both diagonals first falls below percentage
def spiralPrimeDiagonals(percentage):
sideLength = 3
value = 9
numPrimes = 3
while numPrimes / (2 * sideLength - 1) >= percentage:
for corner in range(0, 3):
value += (sideLength + 1)
if isPrime(value):
numPrimes += 1
# Don't have to check 4th corner, we know it's an odd square on the bottom right diagonal
value += (sideLength + 1)
sideLength += 2
return sideLength
print(spiralPrimeDiagonals(0.1)) |
# Circular primes
# https://projecteuler.net/problem=35
import math
# Sieve of Erastosthenes returning primes up to including n
def sieveOfErastosthenes(n):
isPrime = [True] * (n + 1)
isPrime[0] = isPrime[1] = False
primes = []
for value in range(n + 1):
if isPrime[value]:
primes.append(value)
for multiple in range(value * 2, n + 1, value):
isPrime[multiple] = False
return primes
# Returns whether n is prime
def isPrime(n):
if n < 2: return False
if n == 2: return True
else:
for factor in range(2, math.ceil(math.sqrt(n)) + 1):
if n % factor == 0:
return False
return True
# Returns list of circle numbers for n
def circleNumbers(n):
circleList = []
numDigits = 0
num = n
while num > 0:
numDigits += 1
num //= 10
numCircles = numDigits
while numCircles > 0:
n = (n - (n % 10)) // 10 + ((n % 10) * 10 ** (numDigits - 1))
circleList.append(n)
numCircles -= 1
return circleList
# Returns number of circular primes below n
def numCircularPrimes(n):
count = 0
for prime in sieveOfErastosthenes(n):
isCirclePrime = True
for circleNum in circleNumbers(prime):
if not isPrime(circleNum):
isCirclePrime = False
break
if isCirclePrime:
count += 1
return count
print(numCircularPrimes(1000000))
|
# Amicable numbers
# https://projecteuler.net/problem=21
# Returns all divisors of n, not including n, in a list
def getDivisors(n):
divisors = [1]
for number in range(2, n // 2 + 1):
if n % number == 0:
divisors.append(number)
return divisors
# Returns amicable numbers under n in a list
def amicableNumbers(n):
amicableMap = {}
for number in range(2, n):
amicableMap[number] = None
amicables = []
for number1 in range(2, n):
if amicableMap[number1] == None:
number2 = sum(getDivisors(number1))
if number2 < n:
divisorSumOfNumber2 = sum(getDivisors(number2))
if number1 == divisorSumOfNumber2 and number1 != number2:
amicableMap[number1] = True
amicableMap[number2] = True
amicables.extend((number1, number2))
else:
amicableMap[number1] = False
amicableMap[number2] = False
return amicables
print(sum(amicableNumbers(10000)))
|
import datetime
import random
import time
import balloon
def time_stamp():
today = datetime.datetime.now().strftime("%d-%m-%Y")
return today
def write_todo_list(things):
if things == "DONE":
push_me()
else:
today = time_stamp()
f = open("TODO.txt", "a")
f.write("[" + today + "]\t" + things.ljust(20) + "\t not done"+"\n")
f.close()
return True
def slice_it(my_line):
text = my_line.split('\t')
return text[1]
def getme():
lines = open('TODO.txt').read().splitlines()
myline = random.choice(lines)
return myline
def ask_and_write(things):
if write_todo_list(things) is not True:
return
# push_me()
def send_message():
while True:
things = raw_input("Things TODO :").upper()
ask_and_write(things)
def push_me():
while True:
my_line = getme()
push = slice_it(my_line)
print push
text = str(push)
balloon.balloon_tip("Did you do", text)
time.sleep(10)
send_message()
# push_me()
|
import torch
import torchvision.transforms as transforms
import torchvision.datasets as datasets
from torch.utils.data import Dataset, DataLoader
"""
PyTorch: COmpute mean and standard deviation of dataset.
Refer-
https://www.youtube.com/watch?v=y6IEcEBRZks
"""
# Load CIFAR-10 dataset-
train_dataset = datasets.CIFAR10(
root = 'data/', train = True,
transform = transforms.ToTensor(), download = True
)
test_dataset = datasets.CIFAR10(
root = 'data/', train = False,
transform = transforms.ToTensor(), download = True
)
train_loader = DataLoader(
dataset = train_dataset, batch_size = 256,
shuffle = True
)
test_loader = DataLoader(
dataset = test_dataset, batch_size = 256,
shuffle = True
)
def calculate_mean_stddev(data_loader):
'''
Compute mean and standard-deviation across all channels for the input
data loader.
'''
# VAR(X) = E(X^2) - E(X) ^ 2
channels_sum, channels_squared_sum, num_batches = 0, 0, 0
for data, _ in data_loader:
channels_sum += torch.mean(data, dim = [0, 2, 3])
# We don't want mean across channels (1st dimension), hence it is ignored.
channels_squared_sum += torch.mean(data ** 2, dim = [0, 2, 3])
num_batches += 1
mean = channels_sum / num_batches
std_dev = (channels_squared_sum / num_batches - (mean ** 2)) * 0.5
# You cannot sum the standard deviation as it is not a linear operation.
return mean, std_dev
mean_train, std_dev_train = calculate_mean_stddev(data_loader = train_loader)
mean_test, std_dev_test = calculate_mean_stddev(data_loader = test_loader)
print(f"CIFAR-10 train dataset: mean = {mean_train} & std-dev = {std_dev_train}")
# CIFAR-10 train dataset: mean = tensor([0.4914, 0.4821, 0.4465]) & std-dev = tensor([0.0305, 0.0296, 0.0342])
print(f"CIFAR-10 train dataset: mean = {mean_test} & std-dev = {std_dev_test}")
# CIFAR-10 train dataset: mean = tensor([0.4942, 0.4846, 0.4498]) & std-dev = tensor([0.0304, 0.0295, 0.0342])
|
import torch
import torch.nn as nn
import numpy as np
import matplotlib.pyplot as plt
"""
Example code to implement Fully Connected (FC) layer(s) as Convolutional
layer(s)
For use in 'Convolutional Implementation of Sliding Windows Object Detection'
algorithm.
"""
# Define random input-
x = torch.rand((5, 3, 14, 14))
# (batch size, channel, height, width)
x.shape
# torch.Size([5, 3, 14, 14])
# Define a convolutional layer-
c1 = nn.Conv2d(in_channels=3, out_channels=16, kernel_size=5, stride=1, padding = 0, bias = True)
# Output of a conv layer (O) = ((W - K + 2P) / S) + 1
# Pass the input through the conv layer-
x_c1 = c1(x)
x_c1.shape
# torch.Size([5, 16, 10, 10])
# Define a max pooling layer-
max_pool = nn.MaxPool2d(kernel_size=2, stride=2, padding=0)
# Output of a max pool layer (W') = ((W - f) / S) + 1
# Pass the input volume through the max pooling layer-
x_pool = max_pool(x_c1)
x_pool.shape
# torch.Size([5, 16, 5, 5])
'''
The first FC layer normally has 400 neurons in it. It is now being implemented
as a convolutional layer using:
1.) filter size = 5 x 5
2.) stride = 1
3.) padding = 0
4.) number of filters = 400
'''
fc_as_c2 = nn.Conv2d(in_channels=16, out_channels=400, kernel_size=5, stride=1, padding=0, bias=True)
x_c2 = fc_as_c2(x_pool)
x_c2.shape
# torch.Size([5, 400, 1, 1])
'''
Similarly, the second FC layer normally having 400 neurons in it is also being
implemented as a convolutional layer using:
1.) filter size = 1 x 1
2.) stride = 1
3.) padding = 0
4.) number of filters = 400
'''
fc_as_c3 = nn.Conv2d(in_channels=400, out_channels=400, kernel_size=1, stride=1, padding=0, bias = True)
x_c3 = fc_as_c3(x_c2)
x_c3.shape
# torch.Size([5, 400, 1, 1])
'''
Finally, the output layer normally having 4 neurons in it is being implemented
as a convolutional layer using:
1.) filter size = 1 x 1
2.) stride = 1
3.) padding = 0
4.) number of filters = 4
'''
op_as_c4 = nn.Conv2d(in_channels=400, out_channels=4, kernel_size=1, stride=1, padding=0, bias = True)
x_op = op_as_c4(x_c3)
x_op.shape
# torch.Size([5, 4, 1, 1])
# To view the output of the first image as computed by the output layer as a
# conv layer-
x_op.detach().numpy()[0]
'''
array([[[ 0.07920169]],
[[ 0.06151699]],
[[-0.01613115]],
[[-0.08001155]]], dtype=float32)
'''
# Reshape into a vector of dimension = 4
x_op.detach().numpy()[0].reshape(4)
# array([ 0.07920169, 0.06151699, -0.01613115, -0.08001155], dtype=float32)
# Output the index having the largest value for the third image-
np.argmax(x_op.detach().numpy()[2])
# 0
'''
NOTE:
While defining the conv net, softmax function is NOT included since it's
included in the loss function.
The cross-entropy loss applies softmax function for us.
loss = nn.CrossEntropyLoss() # applies softmax for us!
'''
|
''' 12) Swap Values '''
# Write a function that will swap the first and last values of any given array.
# The default minimum length of the array is 2. (e.g. [1,5,10,-2] will become [-2,5,10,1]).
myList = [1,5,10,-2]
def swap(x):
x[0], x[len(x) - 1] = x[len(x) - 1], x[0]
print x
swap(myList) |
'''
Nth-to-Last
Return the element that is N-from-array's-end.
'''
myList = list(range(0,1000)) # create a list with a range of 0 - 1000
def nthToLast(a,n): # define a function with 2 arguments
print a[len(a) - n] # print out the result
nthToLast(myList,500) # call the function and pass in the arguments
'''
In this case the result would be 500. n can be changed to any number 0-1000
''' |
class Restaurant():
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.number_served = 0
def describe_restaurant(self):
print(f'The name of the restaurant is {self.restaurant_name}.')
print(f'The cuisine of the restaurant is {self.cuisine_type}.')
def open_restaurant(self):
print(f'The restaurant {self.restaurant_name} is open!')
def set_number_served(self, number_served):
self.number_served = number_served
def increment_number_served(self, set_number):
self.number_served += set_number
# resto = Restaurant('Vizit', 'Ukraine')
#
# resto.set_number_served(5)
# resto.set_number_served(5)
#
# resto.increment_number_served(5)
# resto.increment_number_served(60)
#
# print(resto.number_served)
#
# #
# wite_rabbit = Restaurant('Rabbit', 'Traditional American')
#
# print(wite_rabbit.restaurant_name)
# print(wite_rabbit.cuisine_type)
#
# wite_rabbit.open_restaurant()
# wite_rabbit.describe_restaurant()
class IceCreamStand(Restaurant):
def __init__(self, restaurant_name, cuisine_type):
super().__init__(restaurant_name, cuisine_type)
self.flavors = []
def flavors_list(self):
print(self.flavors)
ice_cream = IceCreamStand('Sweet Ice Cream', 'Sweety')
# ice_cream.flavors = ['chokolate', 'milk', 'banana']
ice_cream.flavors_list()
|
#第三个练习 - 判断是否为酒后驾车
print("为了您和他人的生命安全,严禁酒后驾驶车辆!")
#提示输入每100毫升血液的酒精含量
alcohol_content = float(input("请输入每100毫升血液的酒精含量(单位mg):"))
#判断含量是否超标
if alcohol_content < 20:
print("您还不构成饮酒行为,可以开车,请注意安全!")
elif alcohol_content < 80:
print("您已经达到酒后驾车的认定标准,请勿开车!")
else:
print("您已经达到醉驾的认定标准,千万不能开车!")
#本例可以改为用if的嵌套格式,如下:
'''
if alcohol_content < 20:
print("您还不构成饮酒行为,可以开车,请注意安全!")
else:
if alcohol_content < 80:
print("您已经达到酒后驾车的认定标准,请勿开车!")
else:
print("您已经达到醉驾的认定标准,千万不能开车!")
''' |
#第十个练习 - 猜数字游戏
#生成一个随机数需要用到random
import random
a = random.randint(1,100)
print("-------猜数字游戏-------")
b = int(input("请输入1~100之间的任一个数(退出游戏请输入-1):\n"))
while b != a:
if b == -1:
break
elif b < a:
b = int(input("太小,请重新输入:\n"))
continue
else:
b = int(input("太大,请重新输入:\n"))
continue
if b == a:
print("恭喜你,你赢了,猜中的数字是:" + str(b))
print("--------游戏结束-------")
#改用for循环实现
'''
import random
a = random.randint(1,100)
print("-------猜数字游戏-------")
b = int(input("请输入1~100之间的任一个数(退出游戏请输入-1):\n"))
for i in range(1,10000):#为防止有人一直猜一个数,因此将范围定的尽量大
if b == -1:
break
elif b == a:
print("恭喜你,你赢了,猜中的数字是:" + str(b))
break
elif b < a:
b = int(input("太小,请重新输入:\n"))
continue
else:
b = int(input("太大,请重新输入:\n"))
continue
print("--------游戏结束-------")
''' |
# --------------------------------------------------------------------------
# --- Systems analysis and decision support methods in Computer Science ---
# --------------------------------------------------------------------------
# Assignment 4: The Final Assignment
# autorzy: A. Gonczarek, J. Kaczmar, S. Zareba
# 2019
# --------------------------------------------------------------------------
import pickle as pkl
import numpy as np
def predict(x):
"""
Function takes images as the argument. They are stored in the matrix X (NxD).
Function returns a vector y (Nx1), where each element of the vector is a class numer {0, ..., 9} associated with recognized type of cloth.
:param x: matrix NxD
:return: vector Nx1
"""
return np.zeros(shape=(x.shape[0],))
|
#run length encoding of a list
from itertools import groupby
def encode(li):
def aux(k, g):
l=len(list(g))
if l>1:
return [l,k]
else:
return k
return [aux(key,group) for key, group in groupby(li)]
print(encode("aaassssssstttteeee"))
|
import math
#prime factors and their frequency
def prime(k):
i=2;
fac=[]
while i*i<=k:
if k%i:
i+=1
else:
k//=i
fac.append(i)
if k>1:
fac.append(k)
return sorted([fact,fac.count(fact)]for fact in set(fac))
print(prime(130))
|
#inserting into a list
def insert_at(x,li,n):
return li[:n-1]+[x]+li[n-1:]
print(insert_at(6,[1,2,3,4],4))
|
#modified encoding
from itertools import groupby
def encode_modified(alist):
def aux(lg):
if len(lg)>1:
return [len(lg), lg[0]]
else:
return lg[0]
return [aux(list(group)) for key, group in groupby(alist)]
print(encode_modified("aaaabbbbccccdddddd"))
|
NOT_CONNECTED = 0
CONNECTED = 1
class Vertex(object):
def __init__(self, prop):
self.prop = prop
class Graph(object):
def __init__(self, n):
self.__n = n
self.__m = 0
self.__matrix = [[NOT_CONNECTED for _ in range(n)] for _ in range(n)]
self.__vertices = [Vertex(-1) for _ in range(n)]
def __str__(self):
txt = "Graph with {} vertices\nAnd {} edges\n".format(self.__n, self.__m)
for row in self.__matrix:
for cell in row:
txt += str(cell)
txt += "\n"
return txt
def get_subgraph(self, vertex_set):
subgraph = Graph(0)
for vertex in vertex_set:
subgraph.add_vertex(vertex)
for vertex in vertex_set:
for neigh in self.get_neighbours(vertex):
if neigh in vertex_set and not subgraph.is_connected(vertex, neigh):
subgraph.add_edge(vertex, neigh)
return subgraph
def add_vertex(self, v):
self.__n += 1
self.__vertices.append(v)
for row in self.__matrix:
row.append(NOT_CONNECTED)
self.__matrix.append([NOT_CONNECTED for _ in range(self.__n)])
return self.__n
def add_edge(self, v1, v2):
index_v1 = self.__vertices.index(v1)
index_v2 = self.__vertices.index(v2)
assert self.__matrix[index_v1][index_v2] == NOT_CONNECTED, "Edge exists!"
self.__m += 1
self.__matrix[index_v1][index_v2] = CONNECTED
self.__matrix[index_v2][index_v1] = CONNECTED
def get_vertices(self):
return self.__vertices
def is_connected(self, v1, v2):
"""
Method checks if there is an edge connecting v1 and v2.
Returns false if v1 and v2 are the same vertex.
:param v1:
:param v2:
:return:
"""
index_v1 = self.__vertices.index(v1)
index_v2 = self.__vertices.index(v2)
return True if self.__matrix[index_v1][index_v2] == 1 else False
def get_degree(self, v):
index = self.__vertices.index(v)
degree = sum(self.__matrix[index])
return degree
def get_neighbours(self, v):
index = self.__vertices.index(v)
neighbours = [vertex for vertex in self.__vertices
if self.__matrix[index][self.__vertices.index(vertex)] == CONNECTED]
return neighbours
def get_not_neighbours(self, v):
index = self.__vertices.index(v)
not_neighbours = [vertex for vertex in self.__vertices
if self.__matrix[index][self.__vertices.index(vertex)] == NOT_CONNECTED]
return not_neighbours
def get_n(self):
return self.__n
def get_m(self):
return self.__m
def get_vertex_index(self, v):
return self.__vertices.index(v)
def get_complement(self):
rev = Graph(0)
for vertex in self.__vertices:
rev.add_vertex(vertex)
rev.__m = self.__n * (self.__n - 1) / 2 - self.__m
for i in range(len(self.__matrix)):
for j in range(len(self.__matrix[i])):
if self.__matrix[i][j] == NOT_CONNECTED:
rev.__matrix[i][j] = CONNECTED
else:
rev.__matrix[i][j] = NOT_CONNECTED
return rev
|
def str_path(p):
"""Return the string representation of a path if it is of class Path."""
if isinstance(p, Path):
return p.strPath
else:
return p
class Path(object):
"""This class represents a path in a JSON value."""
strPath = ""
@staticmethod
def rootPath():
"""Return the root path's string representation."""
return "."
def __init__(self, path):
"""Make a new path based on the string representation in `path`."""
self.strPath = path
|
import datetime
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
def hist(data, bins, margin=1, label='Distribution'):
bins = sorted(bins)
length = len(bins)
intervals = np.zeros(length+1)
for value in data:
i = 0
while i < length and value >= bins[i]:
i += 1
intervals[i] += 1
intervals = intervals / float(len(data))
plt.xlim(min(bins) - margin, max(bins) + margin)
bins.insert(0, -999)
plt.title("probability-distribution")
plt.xlabel('Interval')
plt.ylabel('Probability')
plt.bar(bins, intervals, color=['b'], label=label)
plt.legend()
plt.show() |
# Testing data
ZOO = {
'question' : 'Does it live on land?',
'yes' : {
'question' : 'Does it live on a farm?',
'no' : 'LION',
'yes' : 'COW'
},
'no' : 'FISH'
}
def add_new_animal(parent_node,ans_to_change,new_animal,new_question,ans_for_new_animal):
# TODO: your code here
pass
print(ZOO)
node = ZOO # Does it live on land?
add_new_animal(node,'no','OCTOPUS','Does it have 8 arms?','yes')
print(ZOO)
node = ZOO['yes'] # Would you find it on a farm?
add_new_animal(node,'yes','CHICKEN','Do you milk it?','no')
print(ZOO)
|
# Dictionaries
d = {'name':'chris','age':25}
e = {
'name': 'fred',
'age': 30
}
d['age'] = 45 # Changing a value
d['cool'] = True # Adding a mapping
a = d['age'] # Looking up a value
del d['cool'] # Deleting a mapping
if 'cool' in d: # Check for a key
print('yes')
for k in d: # Iterate over keys
print('key',k)
for k,v in d.items(): # Iterate over all mappings
print('key=',k,'value=',v)
s = len(k) # Number of mappings
|
import unittest
from tictactoe import TicTacToeBoard
class TestTicTacToeBoard(unittest.TestCase):
def test_can_make_move(self):
board = TicTacToeBoard()
self.assertTrue(board.get_location(0)==' ')
board.make_move(0,'X')
self.assertTrue(board.get_location(0)=='X')
def test_board_starts_empty(self):
# A loop here would be nice.
pass
def test_move_range_negative(self):
board = TicTacToeBoard()
# Be specific ... show why
self.assertRaises(IndexError,board.make_move,-1,'X')
with self.assertRaises(IndexError) as ctx:
board.make_move(-1,'X')
ex = ctx.exception
# Notice the coma
self.assertTrue(ex.args == ('Must be 0 to 8',))
# Easier
self.assertTrue(str(ex) == 'Must be 0 to 8')
# Usually
self.assertTrue(str(ctx.exception) == 'Must be 0 to 8')
# TODO develop these together.
def test_move_range_too_high(self):
pass
def test_move_taken(self):
pass
def test_tokens_other_than_X_O(self):
pass
def test_win_x(self):
pass
def test_win_o(self):
pass
def test_tie(self):
pass
if __name__ == '__main__':
unittest.main() |
import math
c = 300000000 # Speed of light
# c = 3e8 # Python also support scientific notation
def get_moving_length(l0,v):
# A moving object shrinks in the direction of travel.
# This formula calculates the new length base on the
# original length and the speed.
d = 1 - (v*v) / (c*c)
d = math.sqrt(d)
# d = d**0.5 # This would have worked too ... without the math library
return l0 * d
# Did you solve the equation to isolate v? That's the right
# way to do it.
# Here is another way: just try some values and narrow in on
# on a solution
#n = get_moving_length(12,100000000) # 11.3137 ... not fast enough
#n = get_moving_length(12,250000000) # 6.6332 Fits! But we can get closer to 10
n = get_moving_length(12,166000000) # 9.9955 Close enough for me
# Using the web to convert m/s to miles/hour:
# 230,734,650 miles/hour
print(n)
|
class Robot:
def __init__(self,x,y):
self.x_pos = x
self.y_pos = y
def _move_left_leg(self):
pass
def _move_right_leg(self):
pass
def say_hi(self):
print('Beep boob beep from',self.x_pos,self.y_pos)
def walk_to(self,x,y):
self._move_left_leg()
self._move_right_leg()
self.x_pos = x
self.y_pos = y
def fire_laser(self,power):
print('Sterilize')
class ImprovedRobot(Robot):
def fire_torpedos(self):
print('Torpedos away')
def walk_to(self,x,y):
print("I'd rather fly!")
# activate thrusters
self.x_pos = x
self.y_pos = y
def cleanse_covid(r,x,y):
r.say_hi()
r.walk_to(x,y)
r.say_hi()
r.fire_laser(1)
r.walk_to(0,0)
hank = ImprovedRobot(1,1)
hank.say_hi() # Can I do this?
hank.fire_laser(.5)
hank.fire_torpedos()
rob = Robot(0,0)
cleanse_covid(rob,100,200)
|
def get_number():
while True:
r = input('Give me a number between 1 and 100: ')
try:
r = int(r)
if r>=1 and r<=100:
return r
else:
print('That is not between 1 and 100')
except:
print('That is not a number')
a = get_number()
print('You gave me',a) |
from collections import defaultdict
import levenshtein as Lev
"""An Amino Acid"""
class Amino:
def __init__(self, tsvRow):
self.tsvRow = tsvRow
self.name = tsvRow["uc"]
self.mass = float(tsvRow["mass"])
def __str__(self):
return self.name;
def __repr__(self):
return self.name;
def __hash__(self):
return hash(self.name)
def __eq__(self, other):
if not isinstance(self, Amino) or not isinstance(other, Amino):
return False
return self.name == other.name
"""A grab bag of amino acids. ID'd to allow fast hash/eq lookups. You must manually intern these objects to use their faster behavior."""
class AminoComposition:
idGen = 0
def __init__(self, aminoDict):
self.ID = AminoComposition.idGen
AminoComposition.idGen += 1
self.aminoDict = aminoDict
def __hash__(self):
return hash(self.ID)
def __eq__(self, other):
return self.__class__ == other.__class__ and self.ID == other.ID
"""The language of amino acids used in construction of cyclopeptides"""
class AminoLanguage:
MASS_EPSILON = 0.02 #Da -- This is the maximum difference between a mass and the amino acid we will label that mass as. This should be defined based on the accuracy/precision of the mass spectrometer in use.
compositionSet = {} #Allows interning of AminoCompositions for faster lookup and equality
def __init__(self, sortedAminos):
self.sortedAminos = sortedAminos
self.fastLookup = {} #Caches and returns results of the toCanonicalName function
self.fastLookupAmino = {}
"""The canonical name of a mass is a unique string defining the set of all amino acids within MASS_EPSILON of that mass"""
def toCanonicalName(self, mass):
s = ""
if mass in self.fastLookup:
return self.fastLookup[mass]
#todo - use binary search
for amino in self.sortedAminos:
if mass > amino.mass + AminoLanguage.MASS_EPSILON:
continue
if mass < amino.mass - AminoLanguage.MASS_EPSILON:
break
if s == "":
s += amino.name
else:
s += "/" + amino.name
if s == "":
s = "?!?" #If you want to keep running with this unknown mass and not corrupt your results, add it to the amino list with a unique 3 letter code.
raise Exception("Unexpected Amino Weight")
self.fastLookup[mass] = s
return s
def toCanonicalAmino(self, mass):
val = None
if mass in self.fastLookupAmino:
return self.fastLookupAmino[mass]
for amino in self.sortedAminos:
if mass > amino.mass + AminoLanguage.MASS_EPSILON:
continue
if mass < amino.mass - AminoLanguage.MASS_EPSILON:
break
if val == None:
val = amino
else:
print("Warning, mass " + str(mass) + " mapped to multiple amino acids, picking " + val.name)
if val == None:
raise Exception("Unknown Amino Weight: " + str(mass))
self.fastLookupAmino[mass] = val
return val
"""The canonical name of an array of masses is an array of strings that each uniquely represent amino acids within MASS_EPSILON of each mass"""
def toCanonicalNameArr(self, massList):
result = []
for m in massList:
result.append(self.toCanonicalName(m))
return result
def toCanonicalAminoArr(self, massList):
result = []
for m in massList:
result.append(self.toCanonicalAmino(m))
return result
def toMassList(self, aminoArr):
result = []
for aa in aminoArr:
result.append(aa.mass)
return result
"""The set of canonical name array spins is what you get by rotating the strings in a canonical name array. Because we are working with cyclopeptides, all of these spins are considered identical"""
def generateAllCanonicalNameSpins(self, canonicalNameArr):
allSpins = []
for i in range(len(canonicalNameArr)):
allSpins.append(canonicalNameArr[i:] + canonicalNameArr[:i])
return allSpins
"""To quickly identify spins of the same cyclopeptide, all spin sets can be converted to a spinInvariantCanonicalNameArr. This is the rotation of the cyclopeptide that results in the least value string, sorted lexicographically. For maintaining this interface, all that matters is that all rotations of a canonical name arr are assigned the same string value, but cyclopeptides that are not considered equal must generate different spin invariant canonical names"""
def toSpinInvariant(self, canonicalNameArr):
if len(canonicalNameArr) <= 1:
return list(canonicalNameArr)
allSpins = self.generateAllCanonicalNameSpins(canonicalNameArr)
allSpins.sort(key=lambda x: str(x))
return allSpins[0]
"""A composition is a dictionary from amino acids to counts. By interning one of these dictionaries, you can later quickly compare them for equality or use them as keys in hashmaps"""
def internComposition(self, aminoDict):
#Interns compositions like they are strings
list = []
for key in sorted(aminoDict.keys()):
list.append((key, aminoDict[key]))
strVal = str(list)
if strVal not in AminoLanguage.compositionSet:
AminoLanguage.compositionSet[strVal] = AminoComposition(aminoDict)
return AminoLanguage.compositionSet[strVal]
"""Counts the amino acids in a canonical name array and returns an interned AminoComposition object containing these counts"""
def toCanonicalCounts(self, canonicalNameArr):
aminoCounter = defaultdict(int)
for amino in canonicalNameArr:
aminoCounter[amino] += 1
return self.internComposition(aminoCounter)
def couldBeRelated(self, aCounts, bCounts, maxIndels):
delta = {}
allKeys = set([])
for key in aCounts.aminoDict:
allKeys.add(key)
for key in bCounts.aminoDict:
allKeys.add(key)
for key in allKeys:
diff = bCounts.aminoDict[key] - aCounts.aminoDict[key]
if diff != 0:
delta[key] = diff
#Now that we have a set of adds and deletes, let's ensure that it is possible to do in maxIndels. If adds or deletes of any amino acid requires more than maxIndels,
#we can't possibly do it, so we can fail out early.
for key in delta:
if abs(delta[key]) > maxIndels:
return False
#Imagine these compositions of A and B existing in an ||L|| dimensional space with axes named by each amino acid.
#We have computed the difference between these two compositions stored it into this delta dictionary.
#Since we are counting indels, ADDs and DELs shift a point by 1 along some axis.
#SWAPs are diagonal lines in this space, a combined DEL+ADD.
#The shortest path between two compositions is the path with the most SWAPs, as that can be as low as half the length of path created with ADDs and DELs.
#This means that the minimum possible path length between two compositions is the sum of the absolute values of all values in the delta dictionary, divided by 2.
addDelLength = 0
for key in delta:
addDelLength += abs(delta[key])
minPathLength = addDelLength / 2.0
if minPathLength > maxIndels:
return False
return True
""" Removes duplicate entities in a list. Duplicate is determined by hash and equality of string value of each item """
def removeStrDups(self, l):
dupRemover = set([])
resultList = []
for item in l:
itemStr = str(item)
if itemStr in dupRemover:
continue
dupRemover.add(itemStr)
resultList.append(item)
return resultList
"""Computes cyclic levenshtein distance ignoring any maximum delta"""
def computeCyclicEditDist(self, candA, candB):
spins = self.generateAllCanonicalNameSpins(candA.name)
maxDist = max(len(candA.name), len(candB.name))
closestDist = maxDist
for candASpin in spins:
dist = Lev.compute2(candASpin, candB.name, maxDist)
if dist is not None:
closestDist = min(closestDist, dist)
return closestDist
|
class Student:
def __init__(self, x,y,z):
self.name=x
self.rollno=y
self.marks=z
def display(self):
print("Student Name:{}\nRollno:{}\nMarks:{}".format(self.name, self.rollno, self.marks))
s1=Student("rishabh", 17, 97)
s1.display()
s2=Student("pandey", 88, 90)
s2.display()
|
import random
import string
def again():
question = input("Would you like to generate another one? (Y/N): ")
if question == "y" or "Y":
main_func()
else:
print("Goodbye.")
exit()
def random_ascii(stringLength):
characters = string.ascii_letters + string.digits + '&*-#$!^_=+@~'
final = ''.join(random.choice(characters) for i in range (stringLength))
print(final)
f = open('random_pw.txt', 'w')
f.write(final)
f.close()
again()
def main_func():
how_many = int(input("How many characters?: "))
random_ascii(how_many)
main_func() |
#num=int(input("Enter the number:"))
num=123
rev =0
while(num>0):
reminder=num%10
rev=(rev*10)+reminder
num=num//10
print(rev)
print(r'c:\docs\navin')
name='my name'
print(len(name))
nums=[2,14,25,36,95]
nums.pop(2)
print(nums)
fru=['aaaad','bdsss','cssffg']
print(fru[-1][-1])
a=10
print(id(a))
b=a
print(id(b))
a=2
print(a,b)
a=5
b=int(a)
k=float(b)
print(type(b),k)
a,b=5,6
print(a,b)
n=7
x=3
print(n==x)
print("----")
print(10<<5)
if False:
print("hi")
name='sav'
print("************")
for i in range(44,11,2):
print("&&&")
print(i)
|
#greater number in two variables
a=int(input("enter first number"))
b=int(input("enter second number"))
if(a>b):
print(a,"is greater than",b)
else:
print(b,"is greater than",a)
|
#write a program to demonstrate use of relational operators
x=int(input("enter first number"))
y=int(input("enter second number"))
print(str(x)+"<"+str(y)+"="+str(x<y))
print(str(x)+"=="+str(y)+"="+str(x==y))
print(str(x)+"!="+str(y)+"="+str(x!=y))
print(str(x)+">="+str(y)+"="+str(x>=y))
print(str(x)+"<="+str(y)+"="+str(x<=y))
|
#write a prgram to convert a floating point number into integer and vice-a-versa
a=float(input("enter floating point number"))
print(int(a))
b=int(input("enter integer type of number"))
print(float(b))
|
def find_max_min(numbers):
if not isinstance(numbers, list):
raise ValueError('Parameter must be a list')
minimum, maximum = min(numbers), max(numbers)
return [len(numbers)] if minimum == maximum else [minimum, maximum]
|
# Example of a list, with tuples inside
coordinates = [(4, 5), (6, 7), (80, 34)]
print(coordinates[1])
# We cannot do this
coordinates[1][1] = 10
|
def longestWord(text):
word_split = re.findall(r"[\w']+", text)
longest_word = ''
for word in word_split:
if len(word) > len(longest_word) and word.isalpha():
longest_word = word
return longest_word |
def isBeautifulString(inputString):
counter = [inputString.count(i) for i in string.ascii_lowercase]
return counter[::-1] == sorted(counter) |
"""Some people are standing in a row in a park. There are trees between them which cannot be moved.
Your task is to rearrange the people by their heights in a non-descending order without moving the trees.
People can be very tall!
Example:
- For a = [-1, 150, 190, 170, -1, -1, 160, 180], the output should be sortByHeight(a) = [-1, 150, 160, 170, -1, -1, 180, 190]."""
def sortByHeight(a):
# Step 1: We begin by creating a counter, starting from 0, that will be used in the subsequent for-loop.
j = 0
# Step 2: We also create a new array, called "a_sort", where we sort (in ascending order) all elements of the given array "a"
# that are not "trees" (i.e. do not have a value of -1).
a_sort = sorted([i for i in a if i != -1])
# Step 3: By implementing a for-loop, we investigate all elements of the given array "a" (NOT a_sort!) and check:
# if the element i in array "a" is equal to -1, the for-loop continues. Otherwise, the element i in array "a" should be
# the same as element j in array "a_sort" (starting from 0 index, as defined in step 1).
# You can think of it as working through elements of array "a", disregarding the "trees" (-1s) and sorting the rest
# of the elements in ascending order (as in a_sort).
for i in range(len(a)):
if a[i] == -1:
pass
else:
a[i] = a_sort[j]
j += 1
# Step 4: The final step is the return of the modified array "a".
return a
|
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 29 08:00:16 2018
@author: Binish125
"""
import random
class ceaser:
key=0
def __init__(self):
self.key=random.randint(0,26)
def encrypt(self,plain_text):
print("\nEncryption Key:\t"+str(self.key))
cipher_list=[]
plain_list=list(plain_text)
for chara in plain_list:
if(ord(chara)!=32):
char_code=ord(chara)%97
cipher_value=((char_code+self.key)%26)+97
cipher_char=chr(cipher_value)
else:
cipher_char=" "
cipher_list.append(cipher_char)
cipher_text=''.join(cipher_list)
return(cipher_text)
def decrypt(self,cipher_text):
plain_list=[]
cipher_list=list(cipher_text)
for chara in cipher_list:
if(ord(chara)!=32):
char_code=ord(chara)%97
plain_value=((char_code-self.key)%26)+97
plain_char=chr(plain_value)
else:
plain_char=" "
plain_list.append(plain_char)
plain_text="".join(plain_list)
return(plain_text)
plain_text=input("\nEnter your text : ")
x=ceaser()
cipher=x.encrypt(plain_text)
print("\n\nCipher text : \t"+cipher)
plain=x.decrypt(cipher)
print("\n\nPlain_text : \t"+plain) |
# Магическое число.
import random
random_number = random.randint(1, 100)
x = int()
attempts = 0
while x != random_number:
x = int(input("Enter a number: "))
if random_number > x:
print("More")
attempts += 1
elif random_number == x:
print("Bingo, ", "attempts :",attempts )
else:
print("less")
attempts += 1
# Алгоритм Эвклида. НОД - наибольший общий делитель
a = int(input("Enter a number: "))
b = int(input("Enter a number: "))
while a != 0 and b != 0:
if a > b:
a = a % b
else:
b = b % a
print(a + b) |
#Esta clase es la que define el reloj del juego
from tkinter import *
class Reloj:
# Our time structure [horas, segundos, centidegundos]
timer = [0, 0, 0, 0]
pattern = '{0:02d}:{1:02d}:{2:02d}'
# Simple status flag
# False mean the timer is not running
# True means the timer is running (counting)
state = False
def __init__(self, ventana):
self.ventana = ventana
self.tiempo = Label(ventana, text="00:00:00", font=("Helvetica", 20))
self.tiempo.grid()
def update_timeText(self):
if (self.state):
self.timer
#incrementa 1 centisegundo
self.timer[3] += 1
# Cada 100 centisegundos es igual a un segundo
if (self.timer[3] >= 100):
self.timer[3] = 0
self.timer[2] += 1
# Cada 60 segundos es igual a 1 minuto
if (self.timer[2] >= 60):
self.timer[1] += 1
self.timer[2] = 0
# Cada 60 minutos es igual a 1 hora
if (self.timer[1] >= 60):
self.timer[0] += 1
self.timer[1] = 0
# We create our time string here
self.timeString = self.pattern.format(self.timer[0], self.timer[1],
self.timer[2])
# Update the timeText Label box with the current time
self.tiempo.configure(text=self.timeString)
# Call the update_timeText() function after 1 centisecond
self.ventana.after(10, self.update_timeText)
# To start the kitchen timer
def start(self):
self.state = True
# To pause the kitchen timer
def pause(self):
self.state = False
# To reset the timer to 00:00:00
def reset(self):
self.timer = [0, 0, 0]
self.tiempo.configure(text='00:00:00')
|
import sys
def part_one(lines):
offsetX = 0
offsetY = 0
width = 0
height = 0
areas = {}
for line in lines:
split_line = line.split(" ")
offsetX = int(split_line[2].split(",")[0])
offsetY = int(split_line[2].split(",")[1].replace(":", ""))
width = int(split_line[3].split("x")[0])
height = int(split_line[3].split("x")[1].replace("\n", ""))
for i in range(width):
for j in range(height):
x = i + offsetX
y = j + offsetY
if (x,y) in areas:
areas[(x,y)].append("x")
else:
areas[(x,y)] = ["x"]
print("part one")
total = 0
for a in areas:
if len(areas[a]) >= 2:
total += 1
print(total)
def part_two(lines):
offsetX = 0
offsetY = 0
width = 0
height = 0
areas = {}
valid_areas = set()
for line_number, line in enumerate(lines):
line_number += 1
valid_areas.add(line_number) # line numbers start at 1
split_line = line.split(" ")
offsetX = int(split_line[2].split(",")[0])
offsetY = int(split_line[2].split(",")[1].replace(":", ""))
width = int(split_line[3].split("x")[0])
height = int(split_line[3].split("x")[1].replace("\n", ""))
for i in range(width):
for j in range(height):
x = i + offsetX
y = j + offsetY
if (x,y) in areas:
areas[(x,y)].append(line_number)
else:
areas[(x,y)] = [line_number]
print("part two")
for a in areas:
if len(areas[a]) >= 2:
for i in areas[a]:
if i in valid_areas:
valid_areas.remove(i)
print(valid_areas)
pass
def main():
input_lines = []
if len(sys.argv) > 1:
for line in sys.argv[1:]:
input_lines.append(line)
else:
for line in sys.stdin:
input_lines.append(line)
part_one(input_lines)
part_two(input_lines)
if __name__ == "__main__":
main()
|
s1,s2,s3=input().split()
if(s2=='/'):
print(int(s1)//int(s3))
else:
print(int(s1)%int(s3))
|
import matplotlib.pyplot as plt
import numpy as np
import math
# values
v0 = float(input("Podaj predkosc poczatkowa: "))
alpha = float(input("Podaj kat rzutu: "))
alpha = math.radians(alpha)
g = 9.81
v0x = v0 * math.cos(alpha)
v0y = v0 * math.sin(alpha)
h_max = (v0y**2)/(2*g)
print("Maksymalna wysokosc na jaka wzniesie sie cialo: ", h_max)
x_max = ((v0**2)*math.sin(2*alpha))/g
print("Zasieg rzutu: ", x_max)
time_total = (2*v0*math.sin(alpha))/g
print("Czas całkowity: ", time_total)
time = list(np.arange(0, time_total+0.01, 0.01))
vx_t = [v0x for t in time]
vy_t = [v0y-g*t for t in time]
x_t = [v0x*t for t in time]
y_t = [v0y*t-(g*(t**2)/2) for t in time]
y_x = [(X*math.tan(alpha))-(g*(X**2)/(2*(v0x**2))) for X in x_t]
fig, (p1, p2, p3) = plt.subplots(3)
p1.plot(time, vx_t, time, vy_t)
p1.set(xlabel="t [s]", ylabel="v [m/s]")
p1.legend(["vx(t)", "vy(t)"])
p1.title.set_text("Predkosc chwilowa w kierunku pionowym i poziomym po czasie t")
p1.grid()
p2.plot(time, x_t, time, y_t)
p2.set(xlabel="t [s]", ylabel="x,y [m]")
p2.legend(["x(t)", "y(t)"])
p2.title.set_text("Polozenie od czasu")
p2.grid()
p3.plot(x_t, y_x)
p3.set(ylabel="y [m]", xlabel="x [m]")
p3.title.set_text("Tor rzutu ukosnego")
p3.grid()
plt.tight_layout()
plt.show()
|
digits = {
"zero": 0, "jeden": 1, "dwa": 2, "trzy": 3, "cztery": 4, "pięć": 5, "sześć": 6, "siedem": 7, "osiem": 8,
"dziewięć": 9, "dziesięć": 10, "dwadzieścia": 20, "trzydzieści": 30, "czterdzieści": 40, "pięćdziesiąt": 50,
"jedenaście": 11, "dwanaście": 12, "trzynaście": 13, "czternaście": 14, "piętnaście": 15, "szesnaście": 16,
"siedemnaście": 17, "osiemnaście": 18, "dziewiętnaście": 19
}
digit = {
"zero": 0, "jeden": 1, "dwa": 2, "trzy": 3, "cztery": 4, "pięć": 5, "sześć": 6, "siedem": 7, "osiem": 8,
"dziewięć": 9
}
def word_to_number(d, j=""):
l1 = 0
l2 = 0
if d in digits:
l1 = digits.get(d)
if j in digit:
l2 = digit.get(j)
print(l1+l2)
number = input("Podaj liczbe od 0 do 59 (slownie): ")
n1 = number.split()
word_to_number(n1[0], n1[1]) |
def encrypt(string, key):
result = ""
for char in string:
if ord(char) < 91 and ord(char) > 64:
result += chr((ord(char) + key - 65) % 26 + 65)
elif ord(char) < 123 and ord(char) > 96:
result += chr((ord(char) + key - 97) % 26 + 97)
else:
result += char
return result
def decrypt(string, key):
result = ""
for char in string:
if ord(char) < 91 and ord(char) > 64:
result += chr((ord(char) - key - 65) % 26 + 65)
elif ord(char) < 123 and ord(char) > 96:
result += chr((ord(char) - key - 97) % 26 + 97)
else:
result += char
return result |
def same_frequency(num1, num2):
"""Do these nums have same frequencies of digits?
>>> same_frequency(551122, 221515)
True
>>> same_frequency(321142, 3212215)
False
>>> same_frequency(1212, 2211)
True
"""
num1_string = str(num1)
num2_string = str(num2)
num1_count = {}
num2_count = {}
for num in num1_string:
if num in num1_count:
sum = num1_count.get(num)
sum += 1
num1_count[num] = sum
else:
num1_count[num] = 1
for num in num2_string:
if num in num2_count:
sum = num2_count.get(num)
sum += 1
num2_count[num] = sum
else:
num2_count[num] = 1
for key in num1_count.keys():
if num1_count.get(key) != num2_count.get(key):
return False
return True |
n = list(map(int, input("").split()))
r = 'D' if n==sorted(n, reverse=True) else 'N'
print('C' if n == sorted(n) else r) |
class Solution:
def multiply(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
if num1 == "0" or num2 == "0":
return "0"
num1 = num1[::-1]
num2 = num2[::-1]
str_res = [0 for _ in range(len(num1)+len(num2))]
for i in range(len(num1)):
for j in range(len(num2)):
str_res[i+j] += int(num1[i])*int(num2[j])
# 进位处理(从低到高)
result = ""
up = 0
for i in str_res:
now = i + up
cur = now % 10
up = int(now / 10)
result = str(cur) + result
return result.lstrip('0')
|
# Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]).
# Return the running sum of nums.
class Solution:
def runningSum(self, nums: List[int]) -> List[int]:
out = []
out.append(nums[0])
for i in range(1, len(nums)):
num = nums[i]
variable = (out[i - 1])
out.append(out[i - 1] + nums[i])
return out |
###############################################################################################################
# DESAFIO: 019
# TÍTULO: Sorteando uma ordem na lista
# AULA:
# EXERCÍCIO: O mesmo professor do desafio anterior quer sortear a ordem da apresentação de trabalhos dos alunos.
# Faça um programa que leia o nome dos quatro alunos e mostre a ordem sorteada.
###############################################################################################################
import random
aluno1 = str(input("Nome do Aluno 01: "))
aluno2 = str(input("Nome do Aluno 02: "))
aluno3 = str(input("Nome do Aluno 03: "))
aluno4 = str(input("Nome do Aluno 04: "))
lista = [aluno1, aluno2, aluno3, aluno4]
random.shuffle(lista)
print("Ordem de apresentação: {}.".format(lista)) |
###############################################################################################################
# DESAFIO: 015
# TÍTULO: Aluguel de Carros
# AULA: 07
# EXERCÍCIO: Escreve um programa que pergunte a quantidade de Km percorridos por um carro alugado e a quantidade
# de dias pelos quais ele foi alugado. Calcule o preço a pagar. Sabendo que o carro custa R$60,00 por dia e
# R$0,15 por KM rodado.
###############################################################################################################
dias = int(input("Qtde de dias alugados: "))
km = float(input("Quantos KM rodados?: "))
pgto = (dias * 60) + (km * 0.15)
print("-" * 26)
print(" Total a pagar: R${:.2f}".format(pgto))
print("-" * 26) |
#Level 1 - to read the numbers in a file called "Stocktake1.txt and add them all, then print the total
total = 0
my_file = open('stocktake1.txt')
for line in my_file.readlines():
total = total + int(line)
print(f"The total of the numbers in the file is {total}") |
'''
Reading and slicing times
For this exercise, we have read in the same data file using three different approaches:
df1 = pd.read_csv(filename)
df2 = pd.read_csv(filename, parse_dates=['Date'])
df3 = pd.read_csv(filename, index_col='Date', parse_dates=True)
Use the .head() and .info() methods in the IPython Shell to inspect the DataFrames. Then, try to index each DataFrame with a datetime string. Which of the resulting DataFrames allows you to easily index and slice data by dates using, for example, df1.loc['2010-Aug-01']?
INSTRUCTIONS
50XP
Possible Answers
df1.
press 1
df1 and df2.
press 2
df2.
press 3
df2 and df3.
press 4
df3.
press 5
'''
df3 |
'''
What method should we use to read the data?
The first step in our analysis is to read in the data. Upon inspection with a certain system tool, we find that the data appears to be ASCII encoded with comma delimited columns, but has no header and no column labels. Which of the following is the best method to start with to read the data files?
ANSWER THE QUESTION
50XP
Possible Answers
pd.read_csv()
press 1
pd.to_csv()
press 2
pd.read_hdf()
press 3
np.load()
press 4
'''
pd.read_csv()
|
import codecademylib3
from sklearn import preprocessing
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import numpy as np
# load in financial data
financial_data = pd.read_csv('financial_data.csv')
# code goes here
print(financial_data.head())
# Seperate variables for all three columns
month = financial_data['Month']
revenue = financial_data['Revenue']
expenses = financial_data['Expenses']
# Plot for monthly revenue
plt.plot(month,revenue)
plt.xlabel('Month')
plt.ylabel('Amount ($)')
plt.title('Revenue')
plt.show()
plt.clf()
# Plot for monthly expenses
plt.plot(month,expenses)
plt.xlabel('Month')
plt.ylabel('Amount ($)')
plt.title('Expenses')
plt.show()
# load in expenses file
expense_overview = pd.read_csv('expenses.csv')
# Analyse first 7 rows
print(expense_overview.head(7))
# Assigning columns 'Expense' and 'Proportion' variables.
expense_categories = expense_overview['Expense']
proportions = expense_overview['Proportion']
# Collapsing categories less than 5% into a single category 'Others'
expense_categories = ['Salaries','Advertising','Office Rent', 'Other']
proportions = [0.62,0.15,0.15,0.08]
# Pie chart of expenses
plt.clf()
plt.pie(proportions, labels = expense_categories)
plt.title('Proportion Of Expenses')
plt.axis('Equal')
plt.tight_layout()
plt.show()
# expense cut suggestion
expense_cut = 'Salaries'
# load in employees file and analyse first 5 rows
employees = pd.read_csv('employees.csv')
print(employees.head())
# Sort employee productivity column in ascending order
sorted_productivity = employees.sort_values(by= ['Productivity'])
print(sorted_productivity)
# Selecting 100 least productive employees
employees_cut = sorted_productivity.head(100)
print(employees_cut)
# How to explore relationship between 'Income' and 'Productivity' which are on two vastly different scales, moreover there are outliers in the data which add an additional layer of complecity.
transformation = 'standardization'
# Storing commute time column
commute_times = employees['Commute Time']
# Data is skewed to the right, we have to apply log transformation to make the data more symmetrical
commute_times_log = np.log(commute_times)
print(commute_times.describe())
# Working from home will save an average of 33minutes commute time
# Explore shape of commute time using histogram
plt.clf()
plt.hist(commute_times_log)
plt.xlabel('Time')
plt.ylabel('Counts')
plt.title('Employee Commute Time')
plt.show()
|
from sys import argv
script, stuff, things, that = argv
name = raw_input("What is your name?")
print "So your name is %r." % name
print "The script is called:", script
print "Your first variable is:", stuff
print "Your second variable is:", things
print "Your third variable is:", that
|
#!/usr/bin/python3
def best_score(a_dictionary):
if not a_dictionary or a_dictionary == {}:
return None
max = list(a_dictionary.keys())[0]
for i in a_dictionary:
if a_dictionary[i] > a_dictionary[max]:
max = i
return max
|
#!/usr/bin/python3
if __name__ == "__main__":
from sys import argv
lenav = len(argv)
add = 0
for i in range(lenav):
if i < 1:
continue
add = add + int(argv[i])
print("{:d}".format(add))
|
import csv
def create_csv(path,head):
with open(path,"w+",newline="",encoding="utf8") as file:
csv_file = csv.writer(file)
csv_file.writerow(head)
def append_csv(path,data):
with open(path,"a+",newline='',encoding="utf8") as file:
csv_file = csv.writer(file)
csv_file.writerows(data) |
#encoding: UTF-8
# Autor: Oswaldo Morales Rodriguez, A01378566
# Conociendo x e y calcular la hipotrnusa y el angulo
from math import atan2, pi
x=int(input("valor de x"))
y=int(input("valor de y"))
r=((x**2)+(y**2))**0.5
ang=atan2(y,x)
z=atan2(y,x)
ang=(180*z)/pi
print("Hipotenusa es",r,"angulo es",ang) |
from __future__ import print_function
import tensorflow
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout
from tensorflow.keras.optimizers import RMSprop
import numpy as np
import matplotlib.pyplot as plt
# Let's explore the dataset a little bit
# In[4]:
import tensorflow
tensorflow.__version__
# In[5]:
# Load the data, shuffled and split between train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# In[6]:
x_train[0].shape
# In[7]:
#Let's just look at a particular example to see what is inside
#x_train[333] ## Just a 28 x 28 numpy array of ints from 0 to 255
# In[8]:
# What is the corresponding label in the training set?
y_train[333]
# this is the shape of the np.array x_train
# it is 3 dimensional.
print(x_train.shape, 'train samples')
print(x_test.shape, 'test samples')
# In[11]:
## For our purposes, these images are just a vector of 784 inputs, so let's convert
x_train = x_train.reshape(len(x_train), 28*28)
x_test = x_test.reshape(len(x_test), 28*28)
## Keras works with floats, so we must cast the numbers to floats
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
## Normalize the inputs so they are between 0 and 1
x_train /= 255
x_test /= 255
# In[13]:
y_train[0:10]
# In[14]:
# convert class vectors to binary class matrices
num_classes = 10
y_train = tensorflow.keras.utils.to_categorical(y_train, num_classes)
y_test = tensorflow.keras.utils.to_categorical(y_test, num_classes)
y_train[333] # now the digit k is represented by a 1 in the kth entry (0-indexed) of the length 10 vector
# In[15]:
y_train[0:10]
# In[16]:
# We will build a model with two hidden layers of size 512
# Fully connected inputs at each layer
# We will use dropout of .2 to help regularize
model_1 = Sequential()
model_1.add(Dense(64, activation='relu', input_shape=(784,)))
model_1.add(Dropout(0.2))
model_1.add(Dense(64, activation='relu'))
model_1.add(Dropout(0.2))
model_1.add(Dense(10, activation='softmax'))
# In[17]:
## Note that this model has a LOT of parameters
model_1.summary()
# In[18]:
# Let's compile the model
learning_rate = .001
model_1.compile(loss='categorical_crossentropy',
optimizer=RMSprop(lr=learning_rate),
metrics=['accuracy'])
# note that `categorical cross entropy` is the natural generalization
# of the loss function we had in binary classification case, to multi class case
# In[19]:
# And now let's fit.
batch_size = 128 # mini-batch with 128 examples
epochs = 30
history = model_1.fit(
x_train, y_train,
batch_size=batch_size,
epochs=epochs,
verbose=1,
validation_data=(x_test, y_test))
# In[20]:
## We will use Keras evaluate function to evaluate performance on the test set
score = model_1.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
|
My_info = {"Name": "Joey", "Age": 31, "State": "Kansas", "Pet": "Yogi"}
#This was my first the first function I made for this problem but after reviewing the solution code, I prefer using iteritems()
def Dict_Info(dict):
print "Hello my name is", dict["Name"], "and I am", dict["Age"], "years old!"
print "I am from the state of", dict["State"], "and reside in the state of", dict["State"], "."
print "I have a dog named", dict["Pet"], "."
Dict_Info(My_info)
def print_dictionary_values(dic):
for some_key, some_value in dic.iteritems():
if some_key is "Name":
print "Hello my {} is {}.".format(some_key, some_value)
elif some_key is "State":
print "I am from the {} of {}.".format(some_key, some_value)
elif some_key is "Age":
print "My {} is {} years old.".format(some_key, some_value)
else:
print "My {} is named {}.".format(some_key, some_value)
print_dictionary_values(My_info) |
'''
Create a class called Car.
In the__init__(), allow the user to specify the following attributes: price, speed, fuel, mileage.
If the price is greater than 10,000, set the tax to be 15%. Otherwise, set the tax to be 12%.
Create six different instances of the class Car.
In the class have a method called display_all() that returns all the information about the car as a string.
In your __init__(), call this display_all() method to display information about the car once the attributes have been defined.
'''
class Car(object):
def __init__(self, name, price, speed, fuel, milage):
self.name = name
self.price = price
self.speed = speed
self.fuel = fuel
self.milage = milage
def display_all(self):
if self.price > 10000:
taxes = "15%"
total = self.price * .15
after_tax_price = total + self.price
else:
taxes = "12%"
total = self.price * .12
after_tax_price = total + self.price
print "Name: {}".format(self.name)
print "Price: {}".format(self.price)
print "Speed: {}".format(self.speed)
print "Fuel: {}".format(self.fuel)
print "Milage: {}".format(self.milage)
print "Taxes: {}".format(taxes)
print "After Tax Price: {}\n".format(after_tax_price)
return self
car1 = Car("Buick", 15000, 100, "Not Full", 35000)
car1.display_all()
car2 = Car("Mercedes",75000,160,"Full Tank",0)
car2.display_all()
car3= Car("Ford", 18000, 120, "Half Full", 45000)
car3.display_all()
car4 = Car("Subaru", 5000, 100, "Empty", 175000)
car4.display_all()
car5 = Car("Chevrolet", 25000, 140, "Full Tank", 65000)
car5.display_all()
car6 = Car("Dodge", 7500,95,"Quarter of a Tank", 115000)
car6.display_all()
|
class Product(object):
def __init__(self, price, name, weight, brand, cost, status):
self.price = price
self.name = name
self.weight = weight
self.brand = brand
self.cost = self.price * self.weight
self.status = status
self.status = "For Sale"
def Sell(self):
self.status = "Sold"
return self
def AddTax(self):
tax = self.cost *.09
self.cost = self.cost + tax
if self.cost < 0:
self.cost = 0
return self
def Return(self):
print "If the return is defective, type 'defective'. If the product is in the box, type 'in the box'\n"
message = raw_input('product is: \n')
if message == "defective":
self.status = "defective"
self.cost = 0
print "Return allowed.\n"
return self
elif message == "in the box":
self.status ="For Sale"
discount= self.cost * .20
self.cost = self.cost - discount
print "Return allowed.\n"
return self
else:
print "Return not allowed.\n"
return self
def display_all(self):
print "Item Brand: {}".format(self.brand)
print "Item Name: {}".format(self.name)
print "Item Price per Pound: {}".format(self.price)
print "Item Weight in Pounds: {}".format(self.weight)
print "Item Cost: {}".format(self.cost)
print "Item Status: {}\n".format(self.status)
return self
banana = Product(1, "Banana",2, "Aldi", 2, "For Sale")
banana.AddTax().Sell().display_all()
apple = Product(2.85, "Apple", 3, "HyVee", 7,"For Sale")
apple.display_all().AddTax().Sell().Return().display_all()
carrot= Product(.55, "Carrot", 4, "Price Chopper", 2, "For Sale")
carrot.display_all().AddTax().Sell().Return().AddTax().Sell().display_all()
|
#Exercise 3 of conditional statements
def computegrade(grade):
while 1:
try:
if grade <= 0:
print('Score out of range')
return grade
elif grade < 0.6:
print('F')
return grade
elif grade < 0.7:
print('D')
return grade
elif grade < 0.8:
print('C')
return grade
elif grade < 0.9:
print('B')
return grade
elif grade < 1:
print('A')
return grade
elif grade <= 1:
print('Score out of range')
return grade
else:
print('Bad score')
return grade
except:
print('Bad score')
#loops the whole program
while 1:
try:
#gets the value of input and comapres it
grade = float(input('Enter score: '))
computegrade(grade)
if grade >0 and grade < 1:
break
except:
print('Bad score')
continue
|
import sys
fileName = input("Enter the file name: ")
if fileName == "na na boo boo":
print("NA NA BOO BOO TO YOU - You have been punk'd!")
sys.exit(0)
try:
file = open(fileName, 'r')
except:
print("File cannot be opened: " + fileName)
sys.exit(1)
linesList = [line.strip("\n") for line in file]
def countedSubjectLines(data):
counter = 0
for line in linesList:
if line.startswith("Subject"):
counter += 1
print(counter)
countedSubjectLines(linesList)
|
'''
DP
Longest Increasing Subsequence
https://practice.geeksforgeeks.org/problems/longest-increasing-subsequence/0
'''
def main():
# LISs
T = int(input()) # type: int
while(T>0):
T-=1
n = int(input())
seq = []
subseq = []
for i in range(n):
seq.append(int(input()))
dp_list = []
dp_subseq_list = [] # this is for finding actual list
max_j = 0
max_length = 0
max_index_j = 0
max_index = 0
for i in range(n):
max_j = 0
max_index_j = 0
for j in range(i):
if dp_list[j] > max_j:
if seq[i] > seq[j]:
max_j = dp_list[j]
max_index_j = j
dp_list.append(max_j+1)
if len(dp_subseq_list) > max_index_j:
dp_subseq_list.append(dp_subseq_list[max_index_j]+[seq[i]])
else:
dp_subseq_list.append([seq[i]])
if dp_list[-1] > max_length:
max_length = dp_list[-1]
max_index = i
print (max_length)
print(dp_subseq_list[max_index])
if __name__ == '__main__':
main()
|
from unittest import TestCase, main
from queue import Queue
class QueueTest(TestCase):
def test_queue_init(self):
q = Queue()
self.assertEqual(len(q), 0)
def test_queue_enqueue(self):
q = Queue()
for i in range(5):
q.enqueue(i)
self.assertEqual(len(q), 5)
def test_queue_peek_empty(self):
q = Queue()
with self.assertRaises(Exception):
q.peek()
def test_queue_is_empty(self):
q = Queue()
self.assertTrue(q.is_empty())
def test_dequeue(self):
q = Queue()
for i in range(5):
q.enqueue(i)
val = q.dequeue()
self.assertEqual(val, 4)
for i in range(4):
q.dequeue()
self.assertTrue(q.is_empty())
with self.assertRaises(Exception):
q.dequeue()
q.enqueue(6)
self.assertEqual(len(q), 1)
def test_peek_value(self):
q = Queue()
for i in range(5):
q.enqueue(i)
self.assertEqual(q.peek(), 4)
q.dequeue()
q.dequeue()
self.assertEqual(q.peek(), 2)
def test_str(self):
q = Queue()
for i in range(5):
q.enqueue(i)
tmp = [i for i in range(5)]
expected = "queue: " + str(tmp)
self.assertEqual(str(q), expected)
#
# if __name__ == "__main__":
# main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.