text
stringlengths 37
1.41M
|
---|
class ListNode:
def __init__(self, value, prev=None, next=None):
self.value = value
self.prev = prev
self.next = next
def insert_after(self, value):
pass
def insert_before(self, value):
pass
def delete(self):
pass
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
self.count = 0
def iter(self):
current = self.head
while current:
node_val = current
current = current.next
yield node_val
def add_to_head(self, value):
new_node = ListNode(value, None,None)
if self.head is None:
self.head = new_node
self.tail = new_node
else:
new_node.next = self.head
self.head.prev = new_node
self.head = new_node
def remove_from_head(self):
current = self.head
self.head = current.next
self.head.prev = self.tail
def add_to_tail(self, value):
new_node = ListNode(value, None,None)
if self.head is None:
self.head = new_node
self.tail = new_node
else:
new_node.prev = self.tail
self.tail.next = new_node
self.tail = new_node
def remove_from_tail(self):
current = self.tail
self.tail = current.prev
self.tail.next = self.head
def move_to_front(self, value):
for node_val in self.iter():
if node_val.value != value:
next
else:
node_val.prev.next = node_val.next
node_val.next.prev = node_val.prev
self.head = node_val
def move_to_end(self, value):
for node_val in self.iter():
if node_val.value != value:
next
else:
node_val.prev.next = node_val.next
node_val.next.prev = node_val.prev
self.tail = node_val
def delete(self, value):
current = self.head
node_deleted = False
if current is None:
node_deleted = False
elif current.value == value:
self.head = current.next
self.head.prev = self.tail
node_deleted = True
elif self.tail.value == value:
self.tail = self.tail.prev
self.tail.next = self.head
node_deleted = True
else:
while current:
if current.value == value:
current.prev.next = current.next
current.next.prev = current.prev
node_deleted = True
current = current.next
if node_deleted:
self.count -=1
|
# Name : Yogi Halagunaki
# Assignment No : 3(Que 3)
# Questions 3:
# Write a code snippet to find the dimensions of a ndarray and its size.
import numpy as np
my_array_one = np.array([[1, 4, 7], [3, 6, 9], [1, 4, 7], [3, 6, 9]])
print("calculating Dimensions of a nd array is :", my_array_one.ndim)
print("Size of an array is :", my_array_one.size)
# Output :
# calculating Dimensions of a nd array is : 2
# Size of an array is : 12
#
# Process finished with exit code 0
|
def is_member(letter, word):
'''
arg -> letter, word
return -> returns True if the word has the letter
else False
'''
for char in word:
if char == letter:
return True
return False
letter = 'a'
word = 'Test'
print('Check whether the word', word, 'has',
letter, ':', is_member(letter, word))
|
class Event(object):
def __init__(self, sim, time):
self.sim = sim
self.time = time
def execute(self):
print('This method should be over-ridden!')
def __lt__(self, other):
return self.time < other.time
def __repr__(self):
return f'Event ({self.time})'
class PriorityEvent(Event):
def __init__(self, sim, time, priority=9):
Event.__init__(self, sim, time)
self.priority = priority
def __lt__(self, other):
if self.time == other.time:
return self.priority < other.priority
else:
return self.time < other.time
def __repr__(self):
return f'Priority event ({self.time}, {self.priority})'
if __name__ == "__main__":
e1 = Event('e', 1)
e2 = Event('e', 2)
print(e1 < e2)
p1 = PriorityEvent('e', 1.0, priority=1)
p2 = PriorityEvent('e', 1.0, priority=2)
print(p1 < p2)
|
import torch
from torch import nn
def gradient_descent(x, y):
w = 1.0
def forward(x):
y = x * w
return y
def cost(xs, ys):
# loss = 1/N * sum(y-y)**2
cost = 0
for x, y in zip(xs, ys):
pred = forward(x)
cost += (y - pred) ** 2
return cost / len(xs)
def gradient(xs, xy):
# g = 1/N *SUM(2*X(x*w-y))
grad = 0
for x, y in zip(xs, xy):
grad += 2 * x * (x * w - y)
return grad / len(xs)
for epoch in range(100):
loss = cost(x, y)
grad = gradient(x, y)
w = w - 0.01 * grad
print(f"[epoch:{epoch}] [w={w}][loss={loss}]")
def torch_descent(x,y):
w = torch.Tensor([1.0])
w.requires_grad = True
def forward(x):
return x*w
def loss(x,y):
y_pred = forward(x)
return (y_pred-y)**2
for epoch in range(20):
for _x,_y in zip(x,y):
l = loss(_x,_y)
l.backward()
print(_x,_y,w.grad.item(),l.data)
print(w.data)
w.data = w.data - 0.01*w.grad.data
print(w.data)
w.grad.data.zero_()
if __name__ == '__main__':
x = torch.Tensor([i for i in range(1, 5)])
y = torch.Tensor([i * 2 for i in range(1, 5)])
#gradient_descent(x, y)
torch_descent(x, y)
|
import pandas as pd
import langdetect
def country(textstring):
lang=langdetect.detect(textstring)
print(lang)
return lang
df = pd.read_csv("amazon_review_full_csv/test.csv")
df["Detected Language"] = df["review"].apply(country)
df.to_csv("articles_lang.csv", index=False)
print(df.to_string()) |
"""
(c) January 2016 by Daniel Seita
This will run ridge regression using python's sklearn library.
"""
import numpy as np
from sklearn import linear_model
def do_regression(data, alpha=0.1):
"""
Perform regression using ridge regression, and *returns* the predictions.
:alpha: The parameter used to determine the weight of the coefficients, to prevent overfitting.
"""
print("\nNow on ridge regression with alpha = {}.".format(alpha))
X_train,y_train = data[0]
X_val,y_val = data[1]
regressor = linear_model.Ridge(alpha=alpha)
# Fit model, use clipping to ensure output in [0,1], and evaluate. Return 'predictions'.
predictions = regressor.fit(X_train, y_train).predict(X_val)
mse = np.mean( (np.clip(predictions,0,1) - y_val) ** 2 )
mae = np.mean( np.absolute(np.clip(predictions,0,1) - y_val) )
print("M.S.E. = {:.5f}".format(mse))
print("M.A.E. = {:.5f}".format(mae))
# Before returning our actual predictions, first analyze by discretizing the data. Need indices first.
thresh1 = np.percentile(y_val, 33)
thresh2 = np.percentile(y_val, 66)
indices1 = np.where(y_val < thresh1)[0]
tmp1 = np.where(y_val >= thresh1)[0]
tmp2 = np.where(y_val < thresh2)[0]
indices2 = np.intersect1d(tmp1,tmp2)
indices3 = np.where(y_val >= thresh2)[0]
# Using indices, extract the appropriate values, clip, take absolute value, then print.
predictions1 = predictions[indices1]
y_val1 = y_val[indices1]
results1 = np.mean(np.absolute(np.clip(predictions1,0,1)-y_val1))
print("For bottom third, avg abs diff = {:.5f}.".format(results1))
predictions2 = predictions[indices2]
y_val2 = y_val[indices2]
results2 = np.mean(np.absolute(np.clip(predictions2,0,1)-y_val2))
print("For middle third, avg abs diff = {:.5f}.".format(results2))
predictions3 = predictions[indices3]
y_val3 = y_val[indices3]
results3 = np.mean(np.absolute(np.clip(predictions3,0,1)-y_val3))
print("For top third, avg abs diff = {:.5f}.".format(results3))
# Whew. I'll need to put the above in another method but this will do for now. Return predictions.
return predictions
if __name__ == '__main__':
print("We should not be calling this!")
|
import sys
def main(argv):
if len(argv) != 1:
sys.exit('No valido')
list_prime=[]
d=2
n=int(sys.argv[1])
print "D: " +str(d)
while d*d <= n:
if (n % d) == 0:
list_prime.append(d)
n //= d
d=d+1
if n > 1:
list_prime.append(n)
for i in list_prime:
print "Primo: " +str(i)
if __name__ == "__main__":
main(sys.argv[1:]) |
#!/usr/bin/python
import numpy
def outlierCleaner(predictions, ages, net_worths):
"""
Clean away the 10% of points that have the largest
residual errors (difference between the prediction
and the actual net worth).
Return a list of tuples named cleaned_data where
each tuple is of the form (age, net_worth, error).
"""
cleaned_data = []
### your code goes here
residual = 0.0
data = ()
for ix in numpy.ndindex(*predictions.shape):
residual = abs(predictions [ix]- net_worths[ix])
data = (ages[ix], net_worths[ix], float(residual))
cleaned_data.append(data)
cleaned_data = sorted(cleaned_data, key = lambda x: x[2])
percent_limit = int(len(cleaned_data) *0.9)
cleaned_data = cleaned_data[0:percent_limit]
return cleaned_data
|
'''
requires PIL for image transformation
'''
import os
from PIL import Image
from tkinter import filedialog
def tiff_to_jpeg(calidad=75):
'''
Allows you to choose a folder in order to transform tiff images within the folder into new jpeg files
(creates a new file that shares name with initial tiff document)
'''
directorio = filedialog.askdirectory()
for archivo in os.listdir(directorio):
if archivo.endswith('.tif'):
fin=archivo.index('.')
nombre=''
nombre_final = ''
for letra in range(0,fin):
nombre += archivo[letra]
nombre_final = nombre + '.jpg'
try:
print(f'transformando {nombre}')
imagen = Image.open(os.path.join(directorio,archivo))
imagen.thumbnail(imagen.size)
directorio_final = os.path.join(directorio, nombre_final)
imagen.save(directorio_final, format='JPEG', quality=calidad)
except:
pass
tiff_to_jpeg()
|
# QuickSort using median-of-median (group 5) as a pivot.
# Input: Array which contains elements from Input.txt file
# Output: Sorted array written in output.txt file
import os, sys
import copy
import datetime
def median_quick(q, n):
sublist = []
median = []
pivot = None
if len(q) >= 1:
for i in range(0, n, 5):
sublist.append(q[i:i + 5]) # # divide the array into subarrays of 5 elements each
for j in sublist:
s = sorted(j)
if len(s) > 0:
median.append(s[(len(s) // 2)]) # median array which store median element of all subarrays
if len(median) <= 5:
sorted(median)
pivot = median[len(median) // 2] # MoM element as a pivot selection
else:
sorted(median)
pivot = median_quick(median, len(median) // 2) # recursive call to find MoM element as a pivot selection
return pivot
def quicksort(A, p, r):
if p < r:
q = median_quick(A[p: r+1], len(A))
par = partition(A, p, r, q)
quicksort(A, p, par - 1)
quicksort(A, par + 1, r)
def partition(A, l, r, pivot): # Fix pivot position in an array.
for i in range(0, r+1):
if A[i] == pivot:
break
A[i], A[r] = A[r], A[i]
x = A[r]
i = l - 1
for j in range(l, r):
if A[j] <= x:
i += 1
A[i], A[j] = A[j], A[i]
A[i + 1], A[r] = A[r], A[i + 1]
return i + 1
if __name__ == '__main__':
quick = []
count = 0
file = open('Input.txt', 'r')
for val in file.read().split():
count += 1
quick.append(int(val)) # Copy all numbers from Input.txt file into array quick.
quick_copy = copy.deepcopy(quick)
start = datetime.datetime.now() # Execution start time of quicksort
quicksort(quick, 0, count - 1)
finish = datetime.datetime.now() # Execution finish time of quicksort
print("\n Overall Execution Time of QuickSort: ", (finish - start))
fileOutput = open('Output.txt', 'w')
for i in quick:
fileOutput.write(str(i) + str("\n")) # Write sorted array in Output.txt file.
start = datetime.datetime.now() # Execution start time of inbuilt sort
quick_copy.sort() # Inbuilt sort function.
finish = datetime.datetime.now() # Execution finish time of inbuilt sort
print("\n Overall Execution Time of Inbuilt Sort: ", (finish - start))
for index in range(len(quick)): # To check all numbers of an array quick is in sorted increasing order.
if quick[index] != quick_copy[index]: # Compared the sorted quick array with inbuilt sorted array.
print(index)
file.close()
|
a=input()
count=0
for k in range(0,len(a)):
if(a[k]=='0' or a[k]=='1'):
count+=1
if count==len(a):
print("yes")
else:print("no")
|
'''
Para correr el archivo, usar este comando
python -m unittest unit_tests.py
Desarrolla y/o documenta una implementación apropiada para las siguientes clases: STACK (lifo), QUEUE (fifo),
TABLE/HASH/Hash (order),.. (* las puedes implementar “desde 0” o usar alguna librería “pública” *)
Las clases deben contener métodos para soportar las principales operaciones de acceso y manipulación (clásicas).
'''
from stack import Stack
from queue import Queue
from hash import Hash
import unittest
class TestStack(unittest.TestCase):
def test_push(self):
s = Stack()
self.assertEqual(s.push(1), True)
self.assertEqual(s.push("Hello"), True)
def test_pop(self):
s = Stack()
s.push(1)
self.assertEqual(s.pop(), 1)
s.push(2)
self.assertEqual(s.pop(), 2)
def test_top(self):
s = Stack()
s.push(1)
self.assertEqual(s.top(), 1)
s.push(2)
self.assertEqual(s.top(), 2)
def test_isEmpty(self):
s = Stack()
self.assertEqual(s.isEmpty(), True)
s.push(1)
self.assertEqual(s.isEmpty(), False)
class TestQueue(unittest.TestCase):
def test_push(self):
q = Queue()
self.assertEqual(q.push(1), True)
self.assertEqual(q.push("Hello"), True)
def test_pop(self):
q = Queue()
q.push(1)
self.assertEqual(q.pop(), 1)
q.push(2)
self.assertEqual(q.pop(), 2)
def test_front(self):
q = Queue()
q.push(1)
self.assertEqual(q.front(), 1)
q.push(1)
self.assertEqual(q.front(), 1)
q.pop()
q.pop()
q.push(2)
self.assertEqual(q.front(), 2)
def test_isEmpty(self):
q = Queue()
self.assertEqual(q.isEmpty(), True)
q.push(1)
self.assertEqual(q.isEmpty(), False)
class TestHash(unittest.TestCase):
def test_add(self):
h = Hash()
self.assertEqual(h.add(1, 2), True)
self.assertEqual(h.get(1), 2)
h.add(1, 3)
self.assertEqual(h.get(1), 3)
def test_position(self):
h = Hash()
h.add(1, 1)
h.add(0, 0)
h.add(3, 3)
h.add(2, 2)
self.assertEqual(h.position(1), 1)
def test_get(self):
h = Hash()
h.add(1, "one")
h.add(0, "zero")
h.add(3, "three")
h.add(2, "two")
self.assertEqual(h.get(1), "one")
def delete(self):
h = Hash()
h.add(1, "one")
self.assertEqual(len(h.zeys), 1)
h.delete(1)
self.assertEqual(len(h.zeys), 0)
|
#! /usr/bin/python3
from sys import argv
# python 2.x
#IP = raw_input('Enter IP address in format 10.10.10.10/24: ')
#python 3.x
#IP = input('Enter IP address in format 10.10.10.10/24: ')
IP = argv[1]
IP_b =[]
mask = IP.split("/")[1]
mask_d=[]
IP = IP.split("/")[0].split(".")
for i in range(0, len(IP)) :
IP[i]= '{:10}'.format(IP[i])
IP_b.append('{:08b}'.format(int(IP[i],10)))
mask_b = list('{:0<32}'.format('1'*int(mask)))
for i in range(0,4):
mask_b[i]= "".join(mask_b[i*8:(i+1)*8])
mask_d.append('{:<10}'.format(int(mask_b[i],2)))
mask_b = mask_b[0:4]
print ("Host IP:")
print ("".join(IP))
print (" ".join(IP_b))
#преобразование в IP сети
IP_b = list('{:0<32}'.format("".join(IP_b)[0:int(mask)]))
for i in range(0,4):
IP_b[i] = "".join(IP_b[i*8:(i+1)*8])
IP[i] = '{:<10}'.format(int(str(IP_b[i]),2))
IP_b=IP_b[0:4]
print ("\n" "Network:")
print ("".join(IP))
print (" ".join(IP_b))
print ("\n" "Mask:")
print ("/{}".format(mask))
print ("".join(mask_d))
print (" ".join(mask_b))
|
class Solution(object):
def searchInsert(self, nums, target):
l, r = 0, len(nums) - 1
while l <= r:
mid = (l + r)/2
if nums[mid] == target:
return mid
elif target < nums[mid]:
if mid > 0 and target > nums[mid - 1]:
return mid
elif mid == 0:
return 0
else:
r = mid - 1
else:
if mid < len(nums) - 1 and target < nums[mid + 1]:
return mid + 1
elif mid == len(nums) - 1:
return len(nums)
else:
l = mid + 1
s = Solution()
print s.searchInsert([1,3,5,6], 0)
|
from Util import ListNode
class Solution(object):
def swapPairs(self, head):
if head is None or head.next is None:
return head
second = head.next
head.next = self.swapPairs(second.next)
second.next = head
return second
a = ListNode(1)
b = ListNode(3)
c = ListNode(7)
d = ListNode(2)
e = ListNode(5)
a.next = b
b.next = c
c.next = d
d.next = e
s = Solution()
s.swapPairs(a).show()
|
from Util import ListNode
class Solution():
def mergeTwoLists(self, l1, l2):
if l1 is None:
return l2
if l2 is None:
return l1
if l1.val < l2.val:
head = l1
l1 = l1.next
else:
head = l2
l2 = l2.next
curr = head
while l1 is not None and l2 is not None:
if l1.val <= l2.val:
curr.next = l1
l1 = l1.next
else:
curr.next = l2
l2 = l2.next
curr = curr.next
if l1 is None:
curr.next = l2
if l2 is None:
curr.next = l1
return head
a = ListNode(1)
b = ListNode(3)
c = ListNode(7)
d = ListNode(2)
e = ListNode(5)
a.next = b
b.next = c
d.next = e
s = Solution()
s.mergeTwoLists(a,d).show()
|
txt = 'but soft by yonder window breaks'
words = txt.split()
print (txt)
print (words)
t = list()
for word in words :
t.append((len(word),word))
print(t)
t.sort(reverse=True)
print(t)
res = list()
for length, word in t :
res.append(word)
print(res) |
m = []
while True:
n = input('enter a phrase: ')
if n == 'done' : break
m.append(n)
print (m)
crazy = m.split(';')
print (crazy) |
"""
Solution of Counting Sundays
https://www.hackerrank.com/contests/projecteuler/challenges/euler019
"""
def is_leap_year(year):
""" retunrs if 'year' is a leap year """
return year % 400 == 0 or (year % 4 == 0 and year % 100 != 0)
def days_before_beginning_of_year(year):
""" returns days count between 1900/01/01 to specified year """
if year <= 1900:
return 0
delta = year - 1900
days = delta * 365
days += ((delta - 1) // 4 + 1)
days -= ((delta - 1) // 100 + 1)
days += ((delta + 299) // 400)
return days
def days_of_month(year):
""" returns a list of days of each month in specified year """
return [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] \
if is_leap_year(year) else \
[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
def days_after_1990(year, month, day):
""" returns days count between 1900/01/01 to specfied date """
return days_before_beginning_of_year(year) + \
sum(days_of_month(year)[:(month-1)]) + \
min(days_of_month(year)[month-1], day)
def increase_month(year, month):
""" increase month by 1 and adjust year if necessary """
if month <= 11:
return year, month + 1
else:
return year + 1, 1
def main():
""" main function """
test_count = int(input().strip())
for _ in range(test_count):
year_b, month_b, day_b = list(map(int, input().strip().split()))
year_e, month_e, _ = list(map(int, input().strip().split()))
if day_b != 1:
year_b, month_b = increase_month(year_b, month_b)
year_e, month_e = increase_month(year_e, month_e)
year, month = year_b, month_b
days_count = days_after_1990(year, month, 1)
sunday_count = 0
while year != year_e or month != month_e:
if days_count % 7 == 0:
sunday_count += 1
days_count += days_of_month(year)[month - 1]
year, month = increase_month(year, month)
print(sunday_count)
if __name__ == '__main__':
main()
|
class Inventory():
"""docstring for Inventory."""
def __init__(self, d=None):
if not d:
self.coin = {'cp': 0, 'sp': 0, 'ep': 0, 'gp': 0, 'pp': 0}
self.weapon = {'spife': 'It\'s a spoon-knife imbued with flavor from the inside of the last person\'s mouth who owned it.'}
self.armor = {'rags':'You\'re poor. At least, you\'re not naked?'}
self.other = {'trinket': 'Because for some reason, DnD really wants you to have some weird kitchy piece of shit with a inordinately complex backstory-- also it\'s fun!'}
if d:
self.coin = d['coin']
self.weapon = d['weapon']
self.armor = d['armor']
self.other = d['other']
def p(self):
for key in self.__dict__:
print("{}: {}".format(key,self.__dict__[key]))
|
# importing relevant libraries
import os # For operative system commands
import random # For random number generator
# user chooses number of decks of cards to use
decks = input("Enter number of decks to use: ")
# possible amount of decks
deck = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]*(int(decks)*4)
# initialize scores
bank = 200
winnings = 0
wins = 0
losses = 0
""" function for giving a card in the deck """
def deal(deck):
# Hand array starts out empty
hand = []
for i in range(2):
# shuffles the deck
random.shuffle(deck)
try:
# chooses a random card in the deck
card = deck.pop()
# checks if there are no more cards in the deck
except IndexError as e:
print("No more cards in the deck!")
exit()
# if the card numbers are above 10, they get their representive
# face card name
if card == 11:card = "J"
if card == 12:card = "Q"
if card == 13:card = "K"
if card == 14:card = "A"
# put chosen card in the hand array
hand.append(card)
# hand array is returned
return hand
""" If the player wants to play again, they can type Y or N (yes or no),
this function handles if the user wants to play again or quit """
def play_again():
# user can input their choice
again = input("Do you want to play again? (Y/N) : ").lower()
# if user types y, the dealer and player hand empties, and we get a new deck
if again == "y":
dealer_hand = []
player_hand = []
deck = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]*4
game()
# if user input is n, the program exits
else:
print("Bye!")
exit()
""" Function that adds and calculates the total hand value """
def total(hand):
# we keep track of the total hand value
total = 0
for card in hand:
# any face card will equal to 10 in total
if card == "J" or card == "Q" or card == "K":
total+= 10
# Here we control if the Ace is 1 or 11 so we don't bust
elif card == "A":
if total >= 11: total+= 1
else: total+= 11
else: total += card
return total
""" This function handles if the user wants to hit (draw a new card) """
def hit(hand):
# new card is drawn
card = deck.pop()
# Naming the numered cards their proper card names
if card == 11:card = "J"
if card == 12:card = "Q"
if card == 13:card = "K"
if card == 14:card = "A"
# card is added to the hand
hand.append(card)
return hand
""" Function that clears the terminal """
def clear():
# all depending on if the user is using NT or POSIX operative system interface,
# it uses either CLS or clear to clean the terminal
if os.name == 'nt':
os.system('CLS')
if os.name == 'posix':
os.system('clear')
""" Function that handles the scoring system (and makes it look fancy!) """
def print_results(dealer_hand, player_hand):
clear()
# scoring system for wins and losses
print("\n WELCOME TO BLACKJACK!\n")
print("-"*30+"\n")
print(" \033[1;32;40mWINS: \033[1;37;40m%s \033[1;31;40mLOSSES: \033[1;37;40m%s\n" % (wins, losses))
# scoring system for money
print("-"*30+"\n")
print ("The dealer has a " + str(dealer_hand) + " for a total of " + str(total(dealer_hand)))
print ("You have a " + str(player_hand) + " for a total of " + str(total(player_hand)))
""" Function to handle anybody who gets a blackjack """
def blackjack(dealer_hand, player_hand):
global wins
global losses
global bank
global winnings
global bet
if total(player_hand) == 21:
print_results(dealer_hand, player_hand)
print ("You got a Blackjack!\n")
wins += 1
# bet times 1.5 is returned due to the rules that say
# if you get a blackjack your winnings times 1.5 of your bet is given
bank += bet *1.5
winnings += bet *1.5
play_again()
elif total(dealer_hand) == 21:
print_results(dealer_hand, player_hand)
print ("You lose. The dealer got a blackjack.\n")
losses += 1
bank -= bet
winnings -= bet
play_again()
""" Function to handle anybody who gets a blackjack """
def score(dealer_hand, player_hand):
# score function written global win/loss variables
global wins
global losses
global bank
global winnings
global bet
if total(player_hand) == 21:
print_results(dealer_hand, player_hand)
print ("You got a Blackjack!\n")
wins += 1
bank += bet * 1.5
winnings += bet * 1.5
elif total(dealer_hand) == 21:
print_results(dealer_hand, player_hand)
print ("You lose. The dealer got a blackjack.\n")
losses += 1
bank -= bet
winnings -= bet
elif total(player_hand) > 21:
print_results(dealer_hand, player_hand)
print ("You busted. You lose.\n")
losses += 1
bank -= bet
winnings -= bet
elif total(dealer_hand) > 21:
print_results(dealer_hand, player_hand)
print ("Dealer busts. You win!\n")
wins += 1
bank += bet
winnings += bet
elif total(player_hand) < total(dealer_hand):
print_results(dealer_hand, player_hand)
print ("Your score isn't higher than the dealer. You lose.\n")
losses += 1
bank -= bet
winnings -= bet
elif total(player_hand) > total(dealer_hand):
print_results(dealer_hand, player_hand)
print ("Your score is higher than the dealer. You win!\n")
wins += 1
bank += bet
winnings += bet
""" Now we use all the functions we made and use them in the game function """
def game():
global wins
global losses
global bank
global winnings
global bet
choice = 0
clear()
print("\n WELCOME TO BLACKJACK!\n")
print("-"*30+"\n")
print(" \033[1;32;40mWINS: \033[1;37;40m%s \033[1;31;40mLOSSES: \033[1;37;40m%s\n" % (wins, losses))
print("-"*30+"\n")
print(" \033[1;32;40mBANK: \033[1;37;40m%s \033[1;31;40mWINNINGS: \033[1;37;40m%s\n" % (bank, winnings))
print("-"*30+"\n")
dealer_hand = deal(deck)
player_hand = deal(deck)
bet = int(input("How much do you want to bet?: "))
print ("The dealer is showing a " + str(dealer_hand[0]))
print ("You have a " + str(player_hand) + " for a total of " + str(total(player_hand)))
blackjack(dealer_hand, player_hand)
quit = False
while not quit:
choice = input("Do you want to [H]it, [S]tand, or [Q]uit: ").lower()
if choice == 'h':
hit(player_hand)
print(player_hand)
print("Hand total: " + str(total(player_hand)))
# Checks if the user input is a positive number
while True:
try:
bet += int(input("How much do you want to bet?: "))
if bet <= 0:
raise ValueError
break
except ValueError:
print("The number was not positive, please try again.")
if total(player_hand)>21:
print('You busted')
losses += 1
bank -= bet
winnings -= bet
play_again()
elif choice== 's':
while total(dealer_hand)<17:
hit(dealer_hand)
print(dealer_hand)
if total(dealer_hand)>21:
print('Dealer busts, you win!')
wins += 1
bank += bet
winnings += bet
play_again()
score(dealer_hand,player_hand)
play_again()
elif choice == "q":
print("Bye!")
quit = True
exit()
""" excecute the program """
if __name__ == "__main__":
game()
|
from collections import OrderedDict, defaultdict
def topo_reader(file):
'''
read topology file from DCell format, convert to ordered dictionary
file: str, path to topology file
return OrderedDict, keys = [term]['GENES'] or [term]['TERMS'], in topological order (root at last)
'''
topo = OrderedDict()
with open(file) as f:
x = f.readlines()
x = [i.rstrip('\n') for i in x]
for i in range(len(x)):
if 'ROOT:' in x[i]:
term = x[i].split(' ')[1]
topo[term] = {}
gene_list = x[i+1].replace('GENES: ','')
if len(gene_list) > 0:
topo[term]['GENES'] = gene_list.split(' ')
else:
topo[term]['GENES'] = []
term_list = x[i+2].replace('TERMS: ','')
if len(term_list) > 0:
topo[term]['TERMS'] = term_list.split(' ')
else:
topo[term]['TERMS']= []
return topo
def included_genes(topo):
'''returns genes included in topology'''
all_gene = set()
for t in topo.keys():
if 'GENES' in topo[t].keys():
all_gene = all_gene.union(set(topo[t]['GENES']))
return all_gene |
from random import randint
GAME_RULE = 'Find the greatest common divisor of given numbers.'
MAX_NUM = 100
def gcd(n1, n2):
while n2:
n1, n2 = n2, n1 % n2
return n1
def round():
num1 = randint(0, MAX_NUM)
num2 = randint(0, MAX_NUM)
correct_answer = str(gcd(num1, num2))
question = '{0} {1}'.format(num1, num2)
return question, correct_answer
|
import asyncio
async def print_number():
for i in range(1,11):
print(i)
await asyncio.sleep(1)
async def fetch_data():
print("Start fetching")
await asyncio.sleep(2)
data = {"student_id":1, "student_name": "Patrick"}
print("Done fetching")
return data
async def main():
task_print_number = asyncio.create_task(print_number())
task_fetch_data = asyncio.create_task(fetch_data())
data = await task_fetch_data
await task_print_number
print("hello")
print(data)
asyncio.run(main())
|
for item in range(1, 20001):
if item % 2 != 0:
print "Number is", item, "This is an odd number."
else:
print "Number is", item, "This is an even number." |
persons = ["Anna","Kevin","Amy","Robert"]
age = ['101','102','103','104']
country =['United States', 'Canada', 'Mexico', 'Russia']
language =['Python','Java','Javascript']
# print persons
# print "My age is "+ age[0]
# print "My country of birth is The "+ country[0]
# print "My favorite language is "+ language[0]
# profile = zip(persons, age, country, language)
# print profile[0]
def myName(i,persons,age,country):
print 'My name is '+persons[i]
print 'My age is ' +age[i]
print "My country of birth is The "+country[i]
print 'My favorite language is '+language[i]
myName(2,persons,age,country)
|
#Code for domain retrieval of entered url
from urllib.parse import urlsplit
url = input ('Enter url: ')
base_url = "{0.scheme}://{0.netloc}/".format(urlsplit(url))
print(base_url)
|
'''
Author: Matthew Mettler
Project Euler, Problem 23
https://projecteuler.net/problem=23
A perfect number is a number for which the sum of its proper divisors is
exactly equal to the number. For example, the sum of the proper divisors
of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect
number.
A number whose proper divisors are less than the number is called
deficient and a number whose proper divisors exceed the number is called
abundant.
As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the
smallest number that can be written as the sum of two abundant numbers is
24. By mathematical analysis, it can be shown that all integers greater
than 28123 can be written as the sum of two abundant numbers. However,
this upper limit cannot be reduced any further by analysis even though it
is known that the greatest number that cannot be expressed as the sum of
two abundant numbers is less than this limit.
#Every integer greater than 20161 can be written as the sum of two abundant numbers.
#According to wiki
Find the sum of all the positive integers which cannot be written as the
sum of two abundant numbers.
Status: Correct
'''
import math
import itertools
from collections import Counter
primeNumbers = []
primeFactors = {}
abundantNumbers = []
nonSum = [] #numbers to add together for final answer
upperLimit = 28123
#upperLimit = 100
def isPrime(n):
if n <= 0: return False
return not [x for x in xrange(2, int(math.sqrt(n))+1) if n%x == 0]
def generatePrimes(upperLimit):
for n in range(2, upperLimit+1):
if not [x for x in xrange(2, int(math.sqrt(n))+1) if n%x == 0]:
primeNumbers.append(n)
def getPrimeFactors(n):
if n < 0 or n > upperLimit:
return []
if n in primeFactors:
return primeFactors[n]
primes = []
if n in primeNumbers:
primes.append(n)
#else, not prime
else:
for x in primeNumbers:
if x > n: break
if n % x == 0:
primes.append(x)
list = getPrimeFactors(n/x)
for i in list:
primes.append(i)
break
return primes
def sumOfProperDivisors(n):
dict = Counter(getPrimeFactors(n))
keyproduct = 1
for k, v in dict.items():
keysum = 0
for i in range(0,v+1):
keysum += k**i
keyproduct *= keysum
result = keyproduct - n
return result
def isAbundant(n):
if n in primeNumbers:
return False #all prime numbers are deficient
return sumOfProperDivisors(n) > n
def getNonSum():
count = 0
nonSum = range(upperLimit)
#print(len(nonSum))
for x in abundantNumbers:
for y in abundantNumbers:
if x + y >= upperLimit:
break
nonSum[x+y] = 0
print("Sum is " + str(sum(nonSum)))
#generate abundant number
def generateAbundantNumbers(upperLimit):
for i in range(12,upperLimit):
if isAbundant(i):
abundantNumbers.append(i)
def main():
generatePrimes(upperLimit)
generateAbundantNumbers(upperLimit)
print("Generated %s abundantNumbers" % len(abundantNumbers))
getNonSum()
if __name__ == "__main__":
main() |
'''
Author: Matthew Mettler
Project Euler, Problem 1
If we list all the natural numbers below 10 that are multiples of 3 or 5,
we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of
all the multiples of 3 or 5 below 1000.
Status: Correct
'''
print(sum(x for x in range(1000) if x % 3 == 0 or x % 5 == 0)) |
'''
Author: Matthew Mettler
Project Euler, Problem 5
2520 is the smallest number that can be divided by each of the numbers from 1
to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the
numbers from 1 to 20?
Status: Correct
'''
low = 1
high = 20
# Don't need to check lower terms since being divided by 20 implies
# divisibility by 1, 2, etc.
def getRange(low, high):
values = range(low, high+1)
for i in range(high, low-1, -1):
for j in range(low, i):
if i % j == 0:
if j in values: values.remove(j)
return values
divide_range = getRange(low, high)
def divisible(low, high, number):
for i in divide_range:
if number % i != 0:
return False
return True
def smallestPossible(low, high):
num = high
while(not divisible(low, high, num)): num += high
print(num)
smallestPossible(low, high) |
from matplotlib import pyplot as plt
import collections
mentions = [500,505]
years = [2013, 2014]
plt.bar([2012.6, 2013.6], mentions, 0.8)
plt.xticks(years)
plt.ylabel("# of times I heard someone say 'data science'")
# if you don't do this, matplotlib will label the x-axis 0, 1
# and then add a +2.013e3 off in the corner (bad matplotlib!)
plt.ticklabel_format(useOffset=False)
# misleading y-axis only shows the part above 500
#plt.axis([2012.5,2014.5,499,506]) #wrong bar height
plt.axis([2012.5,2014.5,0,550]) #better
plt.title("Look at the 'Huge' Increase!")
plt.show() |
from matplotlib import pyplot as plt
movies = ["Saw 1", "Spiderman", "Ironman", "Alicia en el pais de las maravillas", "Gandhi"]
numberOfOscars = [2,4,6,3,2]
# bars are by default width 0.8, so we'll add 0.1 to the left coordinates so that each bar is centered
xs = [i + 0.1 for i, _ in enumerate(movies)]
# plot bars with left x-coordinates [xs], heights [num_oscars]
plt.bar(xs, numberOfOscars)
plt.xlabel("Movies")
plt.ylabel("Number of Oscars")
plt.title("My favorite movies")
# label x-axis with movie names at bar centers
plt.xticks([i + 0.5 for i, _ in enumerate(movies)], movies)
plt.show() |
def selection_sort(arr):
for i in range(len(arr)):
smallest_index = i
for j in range(i+1, len(arr)):
if arr[smallest_index] > arr[j]:
smallest_index = j
arr[smallest_index], arr[i] = arr[i], arr[smallest_index]
return arr
|
import matplotlib.pyplot as plt
import csv
def convert_date(date):
""" Takes a date 'YYYYMMDD' and converts it to 'YYYY/MM/DD' """
date = [date[0:4], date[4:6], date[6:8]] # Split in year, month, day respectively
return "/".join(date)
def read_data(year, plot=False):
""" Write the temperature data of a certain year to a file. """
with open("DeBilt.txt", "r") as f:
lines = f.readlines()
data = []
for line in lines:
# Text, we can skip this.
if line[0] == '#':
continue
line = line.split(',')
if line[1][0:4] == str(year): # take the input year
data.append((convert_date(line[1]), line[2][0:-1]))
if plot: # Default is False, only to check the html/javascript with.
graph_year(data, year)
with open('data.csv', 'wb') as f:
writer = csv.writer(f)
for date, temp in data:
writer.writerow([date, temp])
def graph_year(data, year):
""" Plot function to check if my html/javascript was correct. """
temp_list = []
for date, temp in data:
temp_list.append(int(temp))
plt.plot(range(len(temp_list)), temp_list)
plt.title("Maximum temperature in De Bilt (NL) in {0}".format(year))
plt.xlabel("Day in year")
plt.ylabel("Temperature in 0.1 degrees Celcius")
plt.show()
if __name__ == '__main__':
read_data(2014, False)
|
# Bounce effect
# The bounce() function creates a bounce effect and accepts the r, g and b parameters to set the color, and the waiting time.
# The waiting time determines how fast the bouncing effect is.
from machine import Pin
from neopixel import NeoPixel
import time
from all.functions import clear
# clear
clear(32)
pin = 4 # pin digital out
n = 32 # number of leds
np = NeoPixel(Pin(pin,Pin.OUT), n)
def bounce(r, g, b, wait):
for i in range(4 * n):
for j in range(n):
np[j] = (r, g, b)
if (i // n) % 2 == 0:
np[i % n] = (0, 0, 0)
else:
np[n - 1 - (i % n)] = (0, 0, 0)
np.write()
time.sleep_ms(wait)
bounce(1,1,1,10) |
# -*- coding: utf-8 -*-
"""
UnitTest for Millipede
"""
import unittest
import millipede
class TestMillipedeSize(unittest.TestCase):
"Test size parameter on millipede function"
def test_negative(self):
"Test with negative integer value"
self.assertEqual(
millipede.millipede(-1),
" ╚⊙ ⊙╝\n"
)
def test_positive(self):
"Test with positive integer value"
self.assertEqual(
millipede.millipede(1),
""" ╚⊙ ⊙╝\n"""
""" ╚═(███)═╝\n"""
)
def test_zero(self):
"Test with 0"
self.assertEqual(
millipede.millipede(0),
" ╚⊙ ⊙╝\n"
)
def test_padding(self):
"Test padding on sufficient size"
self.assertEqual(
millipede.millipede(10),
""" ╚⊙ ⊙╝\n"""
""" ╚═(███)═╝\n"""
""" ╚═(███)═╝\n"""
"""╚═(███)═╝\n"""
""" ╚═(███)═╝\n"""
""" ╚═(███)═╝\n"""
""" ╚═(███)═╝\n"""
""" ╚═(███)═╝\n"""
""" ╚═(███)═╝\n"""
""" ╚═(███)═╝\n"""
""" ╚═(███)═╝\n"""
)
class TestMillipedePosition(unittest.TestCase):
"Test position parameter on millipede function"
def test_initial(self):
"Test initial position"
self.assertEqual(
millipede.millipede(0),
" ╚⊙ ⊙╝\n"
)
def test_zero(self):
"Test position zero"
self.assertEqual(
millipede.millipede(0, position=0),
" ╚⊙ ⊙╝\n"
)
def test_negative(self):
"Test negative position"
self.assertEqual(
millipede.millipede(0, position=-42),
" ╚⊙ ⊙╝\n"
)
def test_positive(self):
"Test positive position"
self.assertEqual(
millipede.millipede(0, position=42),
" ╚⊙ ⊙╝\n"
)
def test_body(self):
"Test that the body is doing fine as well"
self.assertEqual(
millipede.millipede(10, position=42),
""" ╚⊙ ⊙╝\n"""
""" ╚═(███)═╝\n"""
""" ╚═(███)═╝\n"""
""" ╚═(███)═╝\n"""
""" ╚═(███)═╝\n"""
""" ╚═(███)═╝\n"""
"""╚═(███)═╝\n"""
""" ╚═(███)═╝\n"""
""" ╚═(███)═╝\n"""
""" ╚═(███)═╝\n"""
""" ╚═(███)═╝\n"""
)
class TestMillipedeComment(unittest.TestCase):
"Test comment parameter on millipede function"
def test_empty(self):
"Test with empty comment"
self.assertEqual(
millipede.millipede(0, comment=""),
" ╚⊙ ⊙╝\n"
)
def test_coucou(self):
"Test with comment `coucou'"
self.assertEqual(
millipede.millipede(0, comment="coucou"),
"coucou\n\n ╚⊙ ⊙╝\n"
)
class TestMillipedeReverse(unittest.TestCase):
"Test reverse parameter on millipede function"
def test_reverse(self):
"Test with reverse enabled"
self.assertEqual(
millipede.millipede(1, reverse=True),
""" ╔═(███)═╗\n"""
""" ╔⊙ ⊙╗\n"""
)
def test_reverse_comment(self):
"Test a comment with reverse enabled"
self.assertEqual(
millipede.millipede(1, comment="coucou", reverse=True),
""" ╔═(███)═╗\n"""
""" ╔⊙ ⊙╗\n\n"""
"""coucou\n"""
)
class TestMillipedeOpposite(unittest.TestCase):
"Test opposite parameter on millipede function"
def test_opposite(self):
"Test with opposite enabled"
self.assertEqual(
millipede.millipede(1, opposite=True),
""" ╚⊙ ⊙╝\n"""
""" ╚═(███)═╝\n"""
)
def test_opposite(self):
"Test with opposite and reverse enabled"
self.assertEqual(
millipede.millipede(1, opposite=True, reverse=True),
""" ╔═(███)═╗\n"""
""" ╔⊙ ⊙╗\n"""
)
|
import itertools
# FA. For all
# EQ. Equivalence <->
################################################################################
# Extensionality
# FA. u(U in X <-> U in Y) <-> X = Y
################################################################################
X = set(range(1, 5)) # {1, 2, 3, 4)
Y = {1, 2, 3, 4, 1, 2, 3, 4}
X == Y # Sets are equals because duplicate information in not recorded.
################################################################################
# Pairing
# FA. a FA. b Ex. c FA. x (x in c <-> x = a or x = b)
################################################################################
# We define a small domain of integer value as the universe.
universe = set(range(1, 1001))
a = 10
b = 500
# Based on the definition of pairing:
{x for x in universe if x == a or x == b}
# OrderedSet
# Start with ordered list:
osl = [x for x in range(4, 16)]
osl = [3, 1, 5, 2, 6, 12]
# In python Orderset Does not exist by default. According to axiomatic set
# theory:
# An ordered set such as (a, b) can be written as {{a}, {a, b}}
# Same logic for (a, b, c): {{a}, {a, b}, {a, b, c}}
oslx = [osl[0:i] for i in range(1, len(osl) + 1)]
os = set(map(frozenset, oslx))
# Get the order of all items in the set:
fs = frozenset.intersection(*os).difference(fs)
os.remove(fs)
os = set(map(frozenset, oslx))
def get_order(v, dif = None):
val = []
fs = frozenset.intersection(*v)
if dif:
rem = fs.difference(dif)
else:
rem = fs
v.remove(fs)
val.append(list(rem))
if len(v):
val += get_order(v, dif = fs)
return val
a = get_order(os.copy())
|
n=int(input("enter the number"))
temp=n
rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
if(temp==rev):
print("The number is a palindrom!")
else:
print("the number is not a palindrom!")
|
# Copyright 2012 Google Inc. All Rights Reserved.
"""Module representation.
A module is a simple namespace of rules, serving no purpose other than to allow
for easier organization of projects.
Rules may refer to other rules in the same module with a shorthand (':foo') or
rules in other modules by specifying a module-relative path
('stuff/other.py:bar').
TODO(benvanik): details on path resolution
"""
__author__ = '[email protected] (Ben Vanik)'
import ast
import glob2
import io
import os
import anvil.rule
from anvil.rule import RuleNamespace
class Module(object):
"""A rule module.
Modules are a flat namespace of rules. The actual resolution of rules occurs
later on and is done using all of the modules in a project, allowing for
cycles/lazy evaluation/etc.
"""
def __init__(self, path, rules=None):
"""Initializes a module.
Args:
path: A path for the module - should be the path on disk or some other
string that is used for referencing.
rules: A list of rules to add to the module.
"""
self.path = path
self.rules = {}
if rules and len(rules):
self.add_rules(rules)
def add_rule(self, rule):
"""Adds a rule to the module.
Args:
rule: A rule to add. Must have a unique name.
Raises:
KeyError: A rule with the given name already exists in the module.
"""
self.add_rules([rule])
def add_rules(self, rules):
"""Adds a list of rules to the module.
Args:
rules: A list of rules to add. Each must have a unique name.
Raises:
KeyError: A rule with the given name already exists in the module.
"""
for rule in rules:
if self.rules.get(rule.name, None):
raise KeyError('A rule with the name "%s" is already defined' % (
rule.name))
for rule in rules:
self.rules[rule.name] = rule
rule.set_parent_module(self)
def get_rule(self, rule_name):
"""Gets a rule by name.
Args:
rule_name: Name of the rule to find. May include leading semicolon.
Returns:
The rule with the given name or None if it was not found.
Raises:
NameError: The given rule name was invalid.
"""
if len(rule_name) and rule_name[0] == ':':
rule_name = rule_name[1:]
if not len(rule_name):
raise NameError('Rule name "%s" is invalid' % (rule_name))
return self.rules.get(rule_name, None)
def rule_list(self):
"""Gets a list of all rules in the module.
Returns:
A list of all rules.
"""
return self.rules.values()
def rule_iter(self):
"""Iterates over all rules in the module."""
for rule_name in self.rules:
yield self.rules[rule_name]
class ModuleLoader(object):
"""A utility type that handles loading modules from files.
A loader should only be used to load a single module and then be discarded.
"""
def __init__(self, path, rule_namespace=None, modes=None):
"""Initializes a loader.
Args:
path: File-system path to the module.
rule_namespace: Rule namespace to use for rule definitions.
"""
self.path = path
self.rule_namespace = rule_namespace
if not self.rule_namespace:
self.rule_namespace = RuleNamespace()
self.rule_namespace.discover()
self.modes = {}
if modes:
for mode in modes:
if self.modes.has_key(mode):
raise KeyError('Duplicate mode "%s" defined' % (mode))
self.modes[mode] = True
self.code_str = None
self.code_ast = None
self.code_obj = None
self._current_scope = None
def load(self, source_string=None):
"""Loads the module from the given path and prepares it for execution.
Args:
source_string: A string to use as the source. If not provided the file
will be loaded at the initialized path.
Raises:
IOError: The file could not be loaded or read.
SyntaxError: An error occurred parsing the module.
"""
if self.code_str:
raise Exception('ModuleLoader load called multiple times')
# Read the source as a string
if source_string is None:
try:
with io.open(self.path, 'r') as f:
self.code_str = f.read()
except Exception as e:
raise IOError('Unable to find or read %s' % (self.path))
else:
self.code_str = source_string
# Parse the AST
# This will raise errors if it is not valid
self.code_ast = ast.parse(self.code_str, self.path, 'exec')
# Compile
self.code_obj = compile(self.code_ast, self.path, 'exec')
def execute(self):
"""Executes the module and returns a Module instance.
Returns:
A new Module instance with all of the rules.
Raises:
NameError: A function or variable name was not found.
"""
all_rules = None
anvil.rule.begin_capturing_emitted_rules()
try:
# Setup scope
scope = {}
self._current_scope = scope
self.rule_namespace.populate_scope(scope)
self._add_builtins(scope)
# Execute!
exec self.code_obj in scope
finally:
self._current_scope = None
all_rules = anvil.rule.end_capturing_emitted_rules()
# Gather rules and build the module
module = Module(self.path)
module.add_rules(all_rules)
return module
def _add_builtins(self, scope):
"""Adds builtin functions and types to a scope.
Args:
scope: Scope dictionary.
"""
scope['glob'] = self.glob
scope['include_rules'] = self.include_rules
scope['select_one'] = self.select_one
scope['select_any'] = self.select_any
scope['select_many'] = self.select_many
def glob(self, expr):
"""Globs the given expression with the base path of the module.
This uses the glob2 module and supports recursive globs ('**/*').
Args:
expr: Glob expression.
Returns:
A list of all files that match the glob expression.
"""
if not expr or not len(expr):
return []
base_path = os.path.dirname(self.path)
glob_path = os.path.join(base_path, expr)
return list(glob2.iglob(glob_path))
def include_rules(self, srcs):
"""Scans the given paths for rules to include.
Source strings must currently be file paths. Future versions may support
referencing other rules.
Args:
srcs: A list of source strings or a single source string.
"""
base_path = os.path.dirname(self.path)
if isinstance(srcs, str):
srcs = [srcs]
for src in srcs:
# TODO(benvanik): support references - requires making the module loader
# reentrant so that the referenced module can be loaded inline
src = os.path.normpath(os.path.join(base_path, src))
self.rule_namespace.discover_in_file(src)
# Repopulate the scope so future statements pick up the new rules
self.rule_namespace.populate_scope(self._current_scope)
def select_one(self, d, default_value):
"""Selects a single value from the given tuple list based on the current
mode settings.
This is similar to select_any, only it ensures a reliable ordering in the
case of multiple modes being matched.
If 'A' and 'B' are two non-exclusive modes, then pass
[('A', ...), ('B', ...)] to ensure ordering. If only A or B is defined then
the respective values will be selected, and if both are defined then the
last matching tuple will be returned - in the case of both A and B being
defined, the value of 'B'.
Args:
d: A list of (key, value) tuples.
default_value: The value to return if nothing matches.
Returns:
A value from the given dictionary based on the current mode, and if none
match default_value.
Raises:
KeyError: Multiple keys were matched in the given dictionary.
"""
value = None
any_match = False
for mode_tuple in d:
if self.modes.has_key(mode_tuple[0]):
any_match = True
value = mode_tuple[1]
if not any_match:
return default_value
return value
def select_any(self, d, default_value):
"""Selects a single value from the given dictionary based on the current
mode settings.
If multiple keys match modes, then a random value will be returned.
If you want to ensure consistent return behavior prefer select_one. This is
only useful for exclusive modes (such as 'RELEASE' and 'DEBUG').
For example, if 'DEBUG' and 'RELEASE' are exclusive modes, one can use a
dictionary that has 'DEBUG' and 'RELEASE' as keys and if both DEBUG and
RELEASE are defined as modes then a KeyError will be raised.
Args:
d: Dictionary of mode key-value pairs.
default_value: The value to return if nothing matches.
Returns:
A value from the given dictionary based on the current mode, and if none
match default_value.
Raises:
KeyError: Multiple keys were matched in the given dictionary.
"""
value = None
any_match = False
for mode in d:
if self.modes.has_key(mode):
if any_match:
raise KeyError(
'Multiple modes match in the given dictionary - use select_one '
'instead to ensure ordering')
any_match = True
value = d[mode]
if not any_match:
return default_value
return value
def select_many(self, d, default_value):
"""Selects as many values from the given dictionary as match the current
mode settings.
This expects the values of the keys in the dictionary to be uniform (for
example, all lists, dictionaries, or primitives). If any do not match a
TypeError is thrown.
If values are dictionaries then the result will be a dictionary that is
an aggregate of all matching values. If the values are lists then a single
combined list is returned. All other types are placed into a list that is
returned.
Args:
d: Dictionary of mode key-value pairs.
default_value: The value to return if nothing matches.
Returns:
A list or dictionary of combined values that match any modes, or the
default_value.
Raises:
TypeError: The type of a value does not match the expected type.
"""
if isinstance(default_value, list):
results = []
elif isinstance(default_value, dict):
results = {}
else:
results = []
any_match = False
for mode in d:
if self.modes.has_key(mode):
any_match = True
mode_value = d[mode]
if isinstance(mode_value, list):
if type(mode_value) != type(default_value):
raise TypeError('Type mismatch in dictionary (expected list)')
results.extend(mode_value)
elif isinstance(mode_value, dict):
if type(mode_value) != type(default_value):
raise TypeError('Type mismatch in dictionary (expected dict)')
results.update(mode_value)
else:
if type(default_value) == list:
raise TypeError('Type mismatch in dictionary (expected list)')
elif type(default_value) == dict:
raise TypeError('Type mismatch in dictionary (expected dict)')
results.append(mode_value)
if not any_match:
if default_value is None:
return None
elif isinstance(default_value, list):
results.extend(default_value)
elif isinstance(default_value, dict):
results.update(default_value)
else:
results.append(default_value)
return results
|
#!/usr/bin/python3
# Problem Statement #1 {{{
"""
In this assignment you will implement one or more algorithms for the all-pairs shortest-path problem.
Here are data files describing three graphs: g1.txt g2.txt g3.txt
The first line indicates the number of vertices and edges, respectively. Each subsequent line
describes an edge (the first two numbers are its tail and head, respectively)
and its length (the third number).
NOTE: some of the edge lengths are negative. NOTE: These graphs may or may not have negative-cost cycles.
Your task is to compute the "shortest shortest path". Precisely, you must first identify which, if any,
of the three graphs have no negative cycles. For each such graph, you should compute all-pairs shortest
paths and remember the smallest one (i.e., compute minu,v∈V d(u,v), where d(u,v) denotes the
shortest-path distance from u to v).
If each of the three graphs has a negative-cost cycle, then enter "NULL" in the box below.
If exactly one graph has no negative-cost cycles, then enter the length of its shortest shortest
path in the box below. If two or more of the graphs have no negative-cost cycles, then enter the
smallest of the lengths of their shortest shortest paths in the box below.
OPTIONAL: You can use whatever algorithm you like to solve this question. If you have extra time,
try comparing the performance of different all-pairs shortest-path algorithms!
OPTIONAL: Here is a bigger data set to play with: large.txt
For fun, try computing the shortest shortest path of the graph in the file above.
- problem answer: -19
g1 (errors): -2071316704362602850764451004124039207993124859771173604577175248860775411028888922664524986188001790136114155283438314033691018392021047994731790457806377243835009479894659117406571018059776
g2 (errors): -3899702161487579445697468714183694474757193767112950599934066599841558021597174060881825621692985562330024072811163886203876136521954175232371611332763598101631790481408
g3: -19
"""
# }}}
# vim:foldmethod=marker:foldlevel=0
|
#!/usr/bin/python3
# Problem Statement #1 {{{
"""
In this programming problem you'll code up the dynamic programming algorithm
for computing a maximum-weight independent set of a path graph.
Download the text file below (mwis.txt).
This file describes the weights of the vertices in a path graph
(with the weights listed in the order in which vertices appear in the path).
It has the following format:
[number_of_vertices]
[weight of first vertex]
[weight of second vertex]
...
For example, the third line of the file is "6395702," indicating that the
weight of the second vertex of the graph is 6395702.
Your task in this problem is to run the dynamic programming algorithm
(and the reconstruction procedure) from lecture on this data set.
The question is: of the vertices 1, 2, 3, 4, 17, 117, 517, and 997, which ones
belong to the maximum-weight independent set? (By "vertex 1" we mean the
first vertex of the graph---there is no vertex 0.) In the box below,
enter a 8-bit string, where the ith bit should be 1 if the ith of these 8 vertices
is in the maximum-weight independent set, and 0 otherwise.
For example, if you think that the vertices 1, 4, 17, and 517 are in the maximum-weight
independent set and the other four vertices are not, then you should enter the string
10011010 in the box below.
- problem#1 answer: 10100110
"""
# }}}
# vim:foldmethod=marker:foldlevel=0
|
import random
print("Welcome to Nanda's Number Guessing game")
number = random.randint(1,9)
chances = 0
print("Guess a number(between 1-9):")
while chances < 5:
guess=="answermode":
guess=int(input("Enter your guess:-"))
if guess == number:
print("CONGRATULATIONS YOU WON!")
break
elif guess < number:
print("Your guess was too low.Guess a number higher than",guess)
else guess > number:
print("Your guess was too high.Guess a number smaller than",guess)
chances += 1
if not chances < 5:
print("You Lose!The number is ",number)
|
# Given an object/dictionary with keys and values that consist of both strings and integers, design
# an algorithm to calculate and return the sum of all of the numeric values.
# For example, given the following object/dictionary as input:
data = {
"cat": "bob",
"dog": 23,
19: 18,
90: "fish"
}
# Your algorithm should return 41, the sum of the values 23 and 18.
def sum_object(data):
total = 0
for item in data:
if type(data[item]) == int:
total = total + data[item]
return total
# print(sum_object(data))
# print(data.values())
array = [56, 349, 22, -54, 0, 5]
def sort_array(array):
new_array = []
for item in range():
if array[item] > array[item + 1]:
new_array[item] = array[item+1]
new_array[item+1] = array[item]
else:
new_array.append[item]
new_array.append[item + 1]
return new_array
def count(n):
if n== 0:
return
count(n-1)
print(n)
return
count(4) |
import random
options = ['rock','paper','scissor']
user_sc , comp_sc = int(0),int(0)
while (user_sc != 5 or comp_sc != 5):
comp_ch = random.choice(options)
user_ch = input(str('Enter your choice: rock,paper or scissor ')).lower()
if(user_ch == 'rock'):
if(comp_ch == 'scissor'):
print("Computer's choice is ",comp_ch)
print("You win a point!")
user_sc += 1
continue
elif(comp_ch == 'paper'):
print("Computer's choice is ",comp_ch)
print("Computer wins a point!")
comp_sc += 1
continue
else:
print("Computer's choice is ",comp_ch)
print("It's a tie!")
continue
elif(user_ch == 'paper'):
if(comp_ch == 'scissor'):
print("Computer's choice is ",comp_ch)
print("Computer wins a point!")
comp_sc += 1
continue
elif(comp_ch == 'rock'):
print("Computer's choice is ",comp_ch)
print("You win a point!")
user_sc += 1
continue
else:
print("Computer's choice is ",comp_ch)
print("It's a tie!")
continue
elif(user_ch == 'scissor'):
if(comp_ch == 'rock'):
print("Computer's choice is ",comp_ch)
print("Computer wins a point!")
comp_sc += 1
continue
elif(comp_ch == 'paper'):
print("Computer's choice is ",comp_ch)
print("You win a point!")
user_sc += 1
continue
else:
print("Computer's choice is ",comp_ch)
print("It's a tie!")
continue
else:
print("Please enter a valid option")
print("Game over ")
if(user_sc == 5):
print("You won the game")
else:
print("You lost the game")
|
"""
You should write all of your functions in this file. That way we can
use parts of this file later in the course.
"""
# this line imports numpy as np, csv, os, etc.
from util import *
################################ Constants ####################################
# degree -> salaries
# college -> salaries
# Note that we do not save the percent change between starting/mid salary.
START_SAL, MED_SAL, MID_10, MID_25, MID_75, MID_90 = range(6)
################################ Loading ######################################
"""
Write your load_degrees(...) function here.
Hints:
- use f.readline() to read the first line, then
- use csv.reader() to parse the rest of the file
- use s.replace(old, new) to remove commas from the dollar amounts
- use s.strip(characters) to remove leading/trailing characters like $ sign
- use items.index(s) to find the index of a particular string.
- use items.pop(n) to remove the nth element from the string (indexed from 0)
- if your list of strings is called line,
use line[1:] to access the second element onwards
"""
def load_degrees(degree_fpath):
degree_dict = {}
headers = []
# your code here
return headers, degree_dict
"""
Write your load_colleges(...) function here.
Hints:
- some schools appear in both CSVs, but their salary values are the
same in both sheets. However, you should make sure you still parse those
lines as they will contain information about the school region or type.
- the headers for the college_dict values will
be the same as those for the degree_dict from load_degrees(...), so we
do not need to redefine those.
- ```type``` is a keyword, so use a different name (e.g., college_type)
- N/A should be represented as -1.
- For the latter two dictionaries, check if the type/region exists in
the dictionary first. If it doesn't, create an empty list as the value.
Then add the college name to the list.
- If a school already exists in college_dict, you can either use the
```continue``` keyword to go to the next line, or you can encapsulate what
you have in a conditional.
"""
def load_colleges(salaries_type_fpath ,salaries_region_fpath):
college_dict, type_to_colleges, region_to_colleges = {}, {}, {}
# your code here
return college_dict, type_to_colleges, region_to_colleges
"""
Write your write_colleges(...) function here.
The CSV should be sorted by the name of the college.
Hints:
- Create a new dictionary with college names as the keys, and
the college region and college type as values.
- The default is N/A for both college region and college type.
- Go through the college keys in **sorted order** and create
a list of lists, where each sublist is a row of the target csv.
- Use the write_csv function from util that you implemented in lecture.
"""
def write_colleges(college_fpath, salary_headers,
college_dict, type_to_colleges, region_to_colleges):
tups = []
# your code here
write_csv(college_fpath, tups, log=True)
|
'''
This exercise is designed to get you familiar with
reading python's extensive documentation.
time's documentation link: https://docs.python.org/3/library/time.html
'''
import time
'''
Exercise 1:
Write a function that prints out the current time in military time.
Input: nothing
Returns: nothing
'''
# define and write your function here
'''
Exercise 2:
Write a function that prints out the current time in hh:mm AM or hh:mm PM.
Input: nothing
Returns: nothing
'''
# define and write your function here
'''
Exercise 3:
Write a function that, given a day, month, and year,
returns a list of MM/DD/YY hh:00 (24-hour clock)
for every single hour during the day.
Create a time object using the function arguments and manipulate
it to create your list.
Input:
day: an integer
month: an integer
year: an integer
Returns: list of strings
'''
# define and write your function here
'''
Exercise 4:
Write a function that, given a list, prints out
each element on a different line.
Then use this function to print out the list you generated
in exercise 3.
Input: list of strings
Returns: nothing
'''
# define and write your function here
if __name__ == "__main__":
# call your functions here after you've defined them above.
pass
|
from typing import List
# Given an array of size n, find the majority element.
# The majority element is the element that appears more than ⌊ n/2 ⌋ times.
# You may assume that the array is non-empty and the majority element
# always exist in the array.
class Solution:
def majorityElement(self, nums: List[int]) -> int:
hashMap = {}
length = len(nums)//2
for ele in nums:
if ele not in hashMap.keys():
hashMap[ele] = 1
else:
hashMap[ele] += 1
if hashMap[ele] > length:
return ele
for i in hashMap.keys():
if hashMap[i] > length:
return i
s = Solution()
print(s.majorityElement([2,2,1,1,2,2])) |
import math
class Solution:
def reverse(self, x: int) -> int:
sign = 1 if x >= 0 else -1
x = abs(x)
rev = 0
while( x > 0 ):
dig = x % 10
rev = rev * 10 + dig
x = x // 10
if(rev > 0 and math.ceil(math.log(rev, 2)) > 31):
return 0
return rev * sign
solution = Solution()
print(solution.reverse(0))
|
#We will be making a code to calculate the total amount of purchase
#04/03/2019
#CTI-110 P2HW2 - Meal Tip Calculator
#Richard T Buffalo
#
#Get their input with the chargeTotal variable.
chargeTotal = float(input('Enter the amount of meal: '))
#Tie in the variables tip and amount and do your calculations.
tip = chargeTotal * .15
amount = chargeTotal + tip
#Display the amount + tip and format it to two decimals out and float
print('Your total is $ ',format(chargeTotal + tip, '.2f'))
chargeTotal = float(input('Enter the amount of meal: '))
tip = chargeTotal * .18
amount = chargeTotal + tip
print('Your total comes out to be $ ',format(chargeTotal + tip, '.2f'))
chargeTotal = float(input('Enter the amount of meal: '))
tip = chargeTotal * .20
amount = chargeTotal + tip
print('Wow you really eat alot. I hope you tip for that.. $',format(chargeTotal + tip, '.2f'))
|
# LIFO Stack
# Initialise variables
instruction = ""
stack = []
while instruction != "exit":
instruction = str(input("Pick an operation: push, pop, or view (or type exit): ")).strip()
if instruction == "push":
item = str(input("Enter the value to push on to the stack: ")).strip()
stack.append(item)
elif instruction == "pop":
if len(stack) > 0:
print("This value was popped off the stack: ", stack.pop())
else:
print("Oops, this stack is empty - try pushing a value on to it before popping!")
elif instruction == "view":
if len(stack) > 0:
# Format the stack in an intuitive visual
temp_stack = stack.copy()
temp_stack.reverse()
print("Here is the stack: ", *temp_stack, sep = "\n")
else:
print("Oops, this stack is empty - try pushing a value on to it before viewing!")
|
'''
A combination is a selection of all or part of a set of objects,
without regard to the order in which objects are selected.
Each possible selection would be an example of a combination.
derivation:
n(P)r = permutation
n(P)r = c(r(P)r)
c = n(P)r / r(P)r
c = n!/(n-r)!r! = combination
c = (n r)'
'''
"""
Example: How many committies of 2 chemists and 1 physicist
can be formed from 4 chemists and 3 physicists?
"""
from Permutation import factorial_of
def combination(n, r):
'''
Combination is similar to permutaion with the multiplication of r!
in the divisor.
formula: n! / ((n-r)! * r!)
'''
return factorial_of(n)/((factorial_of(n - r))*(factorial_of(r)))
print('The answer is: {}'.format(combination(4, 2) * combination(3, 1)))
|
#AUTHOR: Manish NArwal
#PROFESSOR: Dr.Carlo Lipizzi
#ASSIGNMENT: Mid-term
#SECTION 2: CODE CHECKING
#PROBLEM #6
#Issues with Code:
#1)If you run it straight away then it is printing output as list
#2)And even output is not proper because L is multiplied by 3 at end of program
#Reason:
#1)Mutliplied by 3 at end of code
#2)The code does not convert list into string
#Changes made by me:
#1)Multiply letters by 3 within loop so that each letter is printed thrice (eg: If you enter 'Of' it will be printed 'OOOfff' and not 'OfOfOf')
#2)Convert list into string by using map method
N = input("Enter your characters: ")
L = []
for letters in N:
letters.split()
L.append(letters*3)
#Convert list to string
b="".join(map(str,L))
print (b)
#PROBLEM #7
#Issue with the code:
#1) The list was not sorted and hence out of top 3 the largest word appeared in the last
#2) The words were repeated hence not unique
#3)Minor error at last line of code where top3 was printed outside print parentheses
#Reason
#1) Reverse argument of sort was not set to True
#2) There was no condition to take only unique values in the top3
#Changes made by me:
#1)Reverse argument set to True so now the largest word will come first followed by 2nd and 3rd largest word
#2) I put a condition that if the word is not in top3 then only put word in top3 list. In this way only unique words will come
#3) Took top3 inside print parentheses
handle =open('word_list.csv','r')
top3 = ["","",""]
for line in handle:
#For each line in the file, strip the input and put it into the word variable
word = line.strip()
#Compare the length of each incoming word to the length of each word in each position
for i in range(0,3):
#Sorts list in descending order
top3.sort(key = len,reverse=True)
if (len(word) > len(top3[i])):
#To get only unique values
if word not in top3:
top3[i] = word
#Print the words
print ("\nThe 3 longest words are:",top3)
#PROBLEM #8
#What was wrong with the original code:
#1)When you enter any string of length 1 even just a space then it prints out 'True'
#2)'Y' is not a vowel
#3)Even for single special character it prints 'True'
#Reason: I think maybe its because of incorrect use of boolean operator 'OR'
#Correction made by me:
#1) Made sure it catches special characters as Invalid input.
#2) Made proper use of boolean operator "OR"
#3) Made sure that irrespective of user entering vowels in upper or lower case the code prints 'True'
#4) I put a break at end to stop the loop
#Put all special characters as string
special_characters = "!@#$%^&*()-+~`_={}\|[]:;''<>,.?/"
#Upper and Lower case vowels
vow="aeiouAEIOU"
while True:
#prompts and receives user input
char = input('Please enter an alphabetical character:')
if char.isdigit(): #checks if input is numerical
print ('Invalid input.')
else:
#checks if input is more than one character
if len(char) > 1:
print ('Invalid input.')
else:
#Check for special character
if char in special_characters:
print('Invalid input.')
else:
#Accept vowel whether its lower case or upper case
if char in vow:
print ('True')
else:
print ('False')
break
#SECTION 3: Writing a Code
#PROBLEM #9
import operator
import itertools
import matplotlib.pyplot as plt
#Opening the stopwords file and converting it into flat list
#Because every single word in stopwords_en became separate list
#So I made list of list into one single list so that problem becomes less complicated
with open("stopwords_en.txt","r") as file1:
stopwords_list=[word for line in file1 for word in line.split()]
#Opening the ai_trends file and converting it into flat list as well
#Because every paragraph in ai_trends became separate list
#So I made list of list into one single list so that problem becomes less complicated
with open("ai_trends.txt","r") as file2:
#words in ai_trends needed to be converted to lower case because stopwords to be removed are lower case
ai_list=[word.lower() for line in file2 for word in line.split()]
#If contents of ai_list is not found in stopwords_list then add it to final_list
final_list = [i for i in ai_list if i not in stopwords_list]
#Create empty dictionary to put words as keys and number of occurrences as values
d=dict()
#Go through each word from final_list if the same word occurs again then increment else count of it will remain 1
for word in final_list:
if word in d:
d[word]=d[word]+1
else:
d[word]=1
#Key is word and d[key] is value which is number of times that word has occured in final_list
for key in list(d.keys()):
key,":",d[key]
#Initialize counter to count number of occurrences of words
count=0
#Loop through each values in dictionary 'd'
for val in d.values():
count = count + val
#Average=count of words/total length of dictionary
count=count/len(d)
print("The average occurrences of the words is:",count)
print("\n")
#Empty list to get words
longest_word = []
#Sort dictionary in descending order and add to list
longest_word =sorted(d, key=len, reverse=True)
#Print top 2 longest words
print("The longest 2 words are:",longest_word[0:2])
print("\n")
#Empty list 'lister' to word length of each distinct word
lister = []
#Length of each distinct word is appended to "lister"
for words in d.keys():
lister.append(len(words))
#Sum of word count in 'lister'
sum_words = sum(lister)
#Average word length = sum of word lengths/length of list
avg_word_length = sum_words/len(lister)
print("The average word length is:",avg_word_length)
print("\n")
#Sorting dictionary in descending order
sorted_d = dict(sorted(d.items(), key=operator.itemgetter(1),reverse=True))
#We are using itertools.islice to slice piece of iterable which is top 10 occurring word which we want to plot
graph_val = dict(itertools.islice(sorted_d.items(), 10))
#Adjust graph size
plt.figure(figsize = (10,6))
#title of bar plot
plt.title("Top 10 most frequent words",fontsize=25)
#Extracting keys for X-axis
keys = graph_val.keys()
#X-axis label
plt.xlabel("WORDS",fontsize=13)
#Extracting values for Y-axis
values = graph_val.values()
#Y-axis label
plt.ylabel("COUNT",fontsize=13)
#Plotting bar graph
plt.bar(keys, values)
#Keeping text of X-axis vertical
plt.xticks(rotation=90)
#PROBLEM #10
import pandas as pd
#Open CSV file in pandas structure
file=pd.read_csv("cars.csv")
file
#Printing first 3 rows of the dataset
print(file.head(3))
#Printing last 3 rows of the dataset
print(file.tail(3))
#Sorting average mileage in ascending order to get lowest 3 values
a=file.sort_values('average-mileage',ascending=True)
#Print top 3 values which are the lowest average mileage
print("The 3 cars with the lowest average-mileage are:")
print(a[['company','body-style','average-mileage']][0:3])
print("\n")
#Sorting average mileage in descending order to get highest 3 values
a=file.sort_values('average-mileage',ascending=False)
#Print top 3 values which are the highest average mileage
print("The 3 cars with the highest average-mileage are:")
print(a[['company','body-style','average-mileage']][0:3]) |
#-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: Shoblin
#
# Created: 02.01.2020
# Copyright: (c) Shoblin 2020
# Licence: <your licence>
#-------------------------------------------------------------------------------
import lib.functions_au as fa
from lib.intcode import Computer
class Robot_painter:
'''
Class of Robot
Attributes:
'''
def __init__ (self, input_vals, init_color = 0):
self.computer = Computer(input_vals)
self.direction = 0
self.x, self.y = 0, 0
self.painted = {(self.x, self.y): init_color}
def paint(self):
while not self.computer.done:
current_color = self.painted[(self.x, self.y)] if (self.x, self.y) in self.painted else 0
self.painted[(self.x, self.y)] = self.computer.calculate(current_color)
self.change_direction(self.computer.calculate())
self.rotate()
def change_direction(self, rotate_direction):
if rotate_direction == 0:
self.direction = (self.direction - 1) % 4
else:
self.direction = (self.direction + 1) % 4
def rotate(self):
if self.direction == 0:
self.y += 1
elif self.direction == 1:
self.x += 1
elif self.direction == 2:
self.y -= 1
elif self.direction == 3:
self.x -= 1
def show_painting(self):
data = [["." for _ in range(50)] for _ in range(6)]
for x, y in self.painted.keys():
color = self.painted[(x, y)]
data[abs(y)][x] = "." if color == 0 else "#"
for row in data:
print(''.join(row))
def main():
opcode_list = fa.read_input_values('day11_puzzle_input.txt')
opcode_list = [int(thing) for thing in opcode_list]
painting = Robot_painter(opcode_list)
painting.paint()
print(f"Part 1: {len(painting.painted.keys())}")
letter_painting = Robot_painter(opcode_list[:], 1)
letter_painting.paint()
print(f"Part 1: {len(letter_painting.painted.keys())}")
letter_painting.show_painting()
if __name__ == '__main__':
main()
|
#-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: atopolskiy
#
# Created: 07.01.2021
# Copyright: (c) atopolskiy 2021
# Licence: <your licence>
#-------------------------------------------------------------------------------
def read_file(filename):
data = []
with open(filename, 'r') as fl:
for line in fl:
data.append(int(line))
return data
def main():
curr_jolt = 0
jolts_1, jolts_3 = 0, 1
data = read_file('data/day10_puzzle_input.txt')
data.sort()
## print(data)
for nxt_jolt in data:
delta = nxt_jolt - curr_jolt
## print(curr_jolt, nxt_jolt, delta)
if delta == 1:
jolts_1 += 1
elif delta == 3:
jolts_3 += 1
curr_jolt = nxt_jolt
print ('Solution part1:',jolts_1 * jolts_3)
sol = {0:1}
for line in data:
sol[line] = 0
if line - 1 in sol:
sol[line] += sol[line - 1]
if line - 2 in sol:
sol[line] += sol[line - 2]
if line - 3 in sol:
sol[line] += sol[line - 3]
print(sol[max(data)])
if __name__ == '__main__':
main()
|
#-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: atopolskiy
#
# Created: 07.12.2019
# Copyright: (c) atopolskiy 2019
# Licence: <your licence>
#-------------------------------------------------------------------------------
import lib.functions_au as fa
import operator
def build_wire(list, wire):
'''
Function to create two lists with coordinates of points
'''
x, y = 0, 0
steps = 0
for code in list:
lenght = int(code[1:])
for _ in range(lenght):
if code[0] == 'R':
x += 1
elif code[0] == 'L':
x -= 1
elif code[0] == 'U':
y += 1
elif code[0] == 'D':
y -= 1
steps += 1
wire[(x,y)] = steps
return wire
def manhattan_distance(coord):
return abs(coord[0]) + abs(coord[1])
def main():
template = "Part{} Answer: {}"
list1 = fa.read_input_values('day3_puzzle_input.txt')
list2 = fa.read_input_values('day3_puzzle_input.txt', 1)
wire1 = build_wire(list1, {})
wire2 = build_wire(list2, {})
cross_wire = list(set(wire1.keys()) & set(wire2.keys()))
result1 = manhattan_distance(cross_wire[0])
for coord in cross_wire:
result1 = min(result1, manhattan_distance(coord))
print(template.format(1, result1))
steps = wire1[cross_wire[0]] + wire2[cross_wire[0]]
for coord in cross_wire:
if steps > wire1[coord] + wire2[coord]:
steps = wire1[coord] + wire2[coord]
print(template.format(2, steps))
if __name__ == '__main__':
main()
|
valid = False
cont = True
counter = 1
while (valid == False):
userI = int(input("Enter how many users will be using the program: "))
run = userI
if (run < 1):
print("Invalid input! Input must be greater then 0!")
valid = False
else:
valid = True
while (counter <= run):
subtotal = 0
tax = 0
taxsub = 0
taxrate = 0
cont = True
itemP = 0
itemQ = 0
itemN = 0
additional = " "
while (valid == False or cont == True):
userI = input("User "+str(counter)+", do you have"+additional+"items in your cart (Y/N): ").upper()
valid = True
if (userI == "Y" and valid == True):
valid = False
while (valid == False):
itemN = float(input("Enter the item number (100-499): "))
if (itemN >= 100 and itemN <= 499):
valid = True
valid2 = False
while (valid2 == False):
itemQ = float(input("Enter the quantity of the item: "))
if (itemQ >= 1):
valid2 = True
valid3 = False
while (valid3 == False):
itemP = float(input("Enter the price of the item: "))
if (itemP >= 0):
valid3 = True
if (itemN >= 100 and itemN <= 199):
taxrate = 0
elif (itemN >= 200 and itemN <= 299):
taxrate = 0.05
elif (itemN >= 300 and itemN <= 399):
taxrate = 0.07
elif (itemN >= 400 and itemN <= 499):
taxrate = 0.12
print("")
print("Item(s) Price "+"Item(s) Tax "+"Item(s) total")
print(str(itemP * itemQ)+" "+str((itemP * itemQ) * taxrate)+" "+str((itemP * itemQ) + ((itemP * itemQ) * taxrate)))
subtotal = subtotal + (itemP * itemQ)
tax = tax + ((itemP * itemQ) * taxrate)
taxsub = taxsub + ((itemP * itemQ) + ((itemP * itemQ) * taxrate))
additional = " additional "
print("")
print("Subtotal Before Tax "+"Total Tax "+"Subtotal Plus Tax")
print(str(subtotal)+" "+str(tax)+" "+str(taxsub))
print("")
else:
valid3 = False
print("Invalid! Price must be a non-negative!")
else:
valid2 = False
print("Invalid! Must have a quantity greater then 0")
else:
valid = False
print("Invalid! Item number must be between 100 and 499!")
elif (userI == "N"):
cont = False
print(" ")
if (counter == run):
print("All users have finished. Program terminating")
else:
print("User "+str(counter)+" has finished, user "+str(counter+1)+", please begin.")
counter = counter + 1
else:
print(userI+" is an invalid option! Must be Y or N!")
|
def square(num):
return num**2
nums = [1, 2, 3, 4, 5]
# print(list(map(square, nums)))
# Lambda
print(list(map(lambda num: num ** 2, nums)))
def check_even(num):
return num % 2 == 0
even = list(filter(check_even, nums))
# print(even)
|
import math
class Line():
def __init__(self, coor1, coor2):
self.coor1 = coor1
self.coor2 = coor2
def distance(self):
x1,y1 = self.coor1
x2,y2 = self.coor2
p1 = (x2 - x1) ** 2
p2 = (y2 - y1) ** 2
return (p1 + p2) ** 0.5
def slope(self):
x1,y1 = self.coor1
x2,y2 = self.coor2
p1 = (y2 - y1)
p2 = (x2 - x1)
return p1 / p2
li = Line((3,2), (8,10))
print(li.distance())
print(li.slope())
|
##############################################
# The MIT License (MIT)
# Copyright (c) 2016 Kevin Walchko
# see LICENSE for full details
##############################################
class Servo(object):
"""
Servo hold the parameters of a servo, it doesn't talk to real servos. This
class does the conversion between DH angles to real servo angles
"""
def __init__(self, ID, offset=150):
self.offset = offset
# self.minAngle = minmax[0] # DH space
# self.maxAngle = minmax[1] # DH space
self.id = ID
def DH2Servo(self, angle):
"""
Sets the servo angle and clamps it between [limitMinAngle, limitMaxAngle].
"""
sangle = angle+self.offset
if sangle > 300 or sangle < 0:
raise Exception('{} angle out of range DH[-150,150]: {:.1f} Servo[0,300]: {:.1f} deg'.format(self.id, angle, sangle))
return sangle
|
def control_car(num):
if(num==1):
PressKey(W)
time.sleep(1)
ReleaseKey(W)
print("직진")
elif(num==2):
PressKey(A)
PressKey(W)
time.sleep(1)
ReleaseKey(A)
PressKey(W)
time.sleep(1)
ReleaseKey(W)
print("좌회전")
elif(num==3):
PressKey(D)
PressKey(W)
time.sleep(1)
ReleaseKey(D)
PressKey(W)
time.sleep(1)
ReleaseKey(W)
print("우회전")
elif(num==5):
ReleaseKey(D)
ReleaseKey(W)
ReleaseKey(A)
ReleaseKey(S)
time.sleep(1)
print("충돌위험으로 제동")
else:
PressKey(S)
time.sleep(3)
ReleaseKey(S)
PressKey(W)
time.sleep(1)
ReleaseKey(W)
print("후진") |
#!/usr/bin/env python
from random import randint, sample, uniform
from acme import Product
import random as rand
# Useful to use with random.sample to generate names
ADJECTIVES = ['Awesome', 'Shiny', 'Impressive', 'Portable', 'Improved']
NOUNS = ['Anvil', 'Catapult', 'Disguise', 'Mousetrap', '???']
Products = []
def generate_products(num_products=30):
for num_products in range(num_products):
prod = rand.choice(ADJECTIVES) + rand.choice(NOUNS)
Products.append(prod)
return Products
def inventory_report(Products):
pass
if __name__ == '__main__':
inventory_report(generate_products()) |
# create code w/following requirements
# 1. Variable 'confused' should be present in 3 scopes
# 2. Use 'global' or 'nonlocal' keyword
import sys
import string
import random
from colorama import init
init()
from colorama import Fore, Back, Style
confusion = "confused"
_global = "nonlocal"
_local = ""
class Scramble:
"""Instantiate confusion"""
def __init__(self, rows=12):
self.rows = [row+1 for row in range(rows)]
def createScrambleList(self):
"""Create a nested list of scrambled ascii characters"""
aToZ = string.ascii_letters + _global
scrambleList = [random.sample(aToZ,len(self.rows)) for row in self.rows]
return scrambleList
def findGlobal(self):
"""Create a scrambled nested list and iterate over it.
Add characters to the global _local string variable
as they are found.
"""
global _global
scrambleList = self.createScrambleList()
confusion = list(_global)
letterIndex = 0
currentLetter = confusion[letterIndex]
def unnecessaryInnerFunction(letterList):
global _local
nonlocal confusion
nonlocal currentLetter
nonlocal letterIndex
for array in scrambleList:
i = 0
while letterIndex < len(confusion) and i < len(scrambleList):
if _global.upper() == _local.upper():
break
elif array[i].upper() == currentLetter.upper():
if letterIndex == len(confusion)-1:
_local += array[i]
currentLetter = confusion[letterIndex]
print(array[0:i], Fore.GREEN + Style.BRIGHT + Back.CYAN + str([array[i]]) + Style.RESET_ALL, array[i+1:])
break
_local += array[i]
letterIndex += 1
currentLetter = confusion[letterIndex]
print(array[0:i], Fore.GREEN + Style.BRIGHT + Back.CYAN + str([array[i]]) + Style.RESET_ALL, array[i+1:])
break
else:
currentLetter = confusion[letterIndex]
i += 1
unnecessaryInnerFunction(scrambleList)
def determineConfusion(self):
"""Update the confusion string variable based on
whether it finds a match between _global and _local
"""
global confusion
self.findGlobal()
if _global.upper() == _local.upper():
confusion = "slightly less confused"
else:
confusion = "still really confused"
new_scramble_obj = Scramble()
new_scramble_obj.determineConfusion()
print("Global equals "+_global+" and local equals "+_local+", so I'm "+confusion)
|
"""
Email BOT
----------------------------------------
This is my simple email bot that interact with you with voice and listen to you.
!! Note !!
if you want to use this bot you need give permission to from your google account.
you need to import SpeechRecognition, PyAudio, pyttsx3
"""
import smtplib
import speech_recognition as sr
import pyttsx3
from email.message import EmailMessage
listener = sr.Recognizer()
engine = pyttsx3.init()
def talk(text):
engine.say(text)
engine.runAndWait()
def get_info():
try:
with sr.Microphone() as source:
print('listening to you...')
voice = listener.listen(source)
info = listener.recognize_google(voice)
print(info)
return info.lower()
except:
pass
email_list ={
'dip' or 'deep': '[email protected]'
}
def send_email(receiver, subject, message):
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login('Your Email ID','password')
email = EmailMessage()
email['From'] = '[email protected]'
email['To'] = receiver
email['Subject'] = subject
email.set_content(message)
server.send_message(email)
def get_email_info():
talk('To whom you want to send email')
name = get_info()
receiver = email_list[name]
print(receiver)
talk('What is the subject of your email')
subject = get_info()
talk('Tell me the content of your email')
message = get_info()
send_email(receiver, subject,message)
get_email_info()
|
'''
#二回ループを回していて効率が悪い
#文が無駄に長くなっているので、変数に代入して整理する
#出力が指定の通りになっていれば問題ないらしい
n = int(input())
num_list = list()
for num in range(n):
num_list.append(int(input()))
for num in range(n-1):
if num_list[num + 1] == num_list[num]:
print('stay')
elif num_list[num + 1] < num_list[num]:
print('down[{0}]'.format(num_list[num] - num_list[num + 1]))
elif num_list[num + 1] > num_list[num]:
print('up[{0}]'.format(num_list[num + 1] - num_list[num]))
'''
n = int(input())
x = int(input())
for i in range(n-1):
y = int(input())
if x>y:
print("down",x-y)
elif x==y:
print("stay")
else:
print("up",y-x)
x = y
|
'''
Created on 22/10/2013
@author: CARLOS1
'''
#Write the Conversion of Celcius Grade to Farenheit Grade
#Read Temperature en Celsius
NCelcius = int(raw_input("Enter Celsius Grade (C): "))
#Convert to Farenheit
NFarenheit = NCelcius*1.8 + 32
#Write Farenheit Temperature
print "Farenheit Grade(F): " + str (NFarenheit)
|
# -*- coding: utf-8 -*-
import numpy as np
#a = np.arange(1,10)
a = np.array([1,3,5,7,9,11])
a = a.reshape(2,3)
print(a)
print(a.dtype)
print(a.ndim)
b = np.array([[1,3],[5,7],[9,11]])
print(b)
print(b.ndim)
|
"""
A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example,
the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.
A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant
if this sum exceeds n.
As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum
of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can
be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis
even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is
less than this limit.
Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.
"""
import time
start_time = time.time()
def get_divisors(n):
divisors = []
for i in range(1, int(n**0.5) + 1):
if n % i == 0:
divisors.append(i)
if n/i != 1:
divisors.append(int(n/i))
return divisors
def get_proper_divisors(n):
proper_divisors = get_divisors(n)
proper_divisors.remove(n)
proper_divisors = list(set(proper_divisors))
return proper_divisors
def is_abundant_number(n):
"""
returns True for abundant numbers
"""
if sum(get_proper_divisors(n)) > n:
return True
else:
return False
limit = 28124
abundant_list = []
for i in range(2, limit):
if is_abundant_number(i):
abundant_list.append(i)
non_abundant = set(list(range(1, limit)))
for i in abundant_list:
for j in abundant_list:
if i + j in non_abundant:
non_abundant.remove(i+j)
print("Answer = %s" % sum(non_abundant))
print("--- %s seconds ---" % (time.time() - start_time))
|
"""
We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once;
for example, the 5-digit number, 15234, is 1 through 5 pandigital.
The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing multiplicand, multiplier, and product
is 1 through 9 pandigital.
Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital.
HINT: Some products can be obtained in more than one way so be sure to only include it once in your sum.
"""
import time
start_time = time.time()
pandigital_products = set()
def has_pandigital_product_identity(i, j):
pandigital_str = str(i) + str(j) + str(i*j)
if len(pandigital_str) != 9:
return False
else:
digit_set = ['1','2','3','4','5','6','7','8','9']
for digit in digit_set:
if digit not in pandigital_str:
return False
return True
for i in range(1, 10000):
for j in range(1, 10000):
if has_pandigital_product_identity(i, j):
pandigital_products.add(i*j)
print("Answer = %s " % sum(pandigital_products))
print("--- %s seconds ---" % (time.time() - start_time))
|
"""
70 colored balls are placed in an urn, 10 for each of the seven rainbow colors.
What is the expected number of distinct colors in 20 randomly picked balls?
Give your answer with nine digits after the decimal point (a.bcdefghij).
"""
import time
start_time = time.time()
"""
WORK
Expected value of pick 1 is 1
Expected value of pick 2 is (9/69) * 1 + (60/69) * 2
Expected value of pick 3 is (9/69)(8/68) * 1 + (60/69)(18/68) * 2 + (60/69)(42/68) * 3
Expected value of pick 4 is (9/69)(8/68)(7/67) * 1 + (60/69)(18/68)(17/67) * 2 + (60/69)(42/68)(27/67) * 3 +
(60/69)(42/68)(16/67) * 4
"""
print("--- %s seconds ---" % (time.time() - start_time))
|
# import turtle
import turtle
# defining colors
colors = ['red', 'yellow', 'green', 'purple', 'blue', 'orange']
# setup turtle pen
t= turtle.Pen()
# changes the speed of the turtle
t.speed(10)
# changes the background color
turtle.bgcolor("black")
# make spiral_web
for x in range(200):
t.pencolor(colors[x%6]) # setting color
t.width(x/100 + 1) # setting width
t.forward(x) # moving forward
t.left(59) # moving left
turtle.done()
t.speed(10)
turtle.bgcolor("black") # changes the background color
# make spiral_web
for x in range(200):
t.pencolor(colors[x%6]) # setting color
t.width(x/100 + 1) # setting width
t.forward(x) # moving forward
t.left(59) # moving left
turtle.done()
|
bursttime=[]
print("Enter number of process: ")
n=int(input())
processes=[]
for (i=0; i=n; i++)
processes.insert(i,i+1)
print("Enter the burst time of the processes: ")
for i in range(0,len(bursttime)-1):
for j in range(0,len(bursttime)-i-1):
if(bursttime[j]>bursttime[j+1]):
temp=bursttime[j]
bursttime[j]=bursttime[j+1]
bursttime[j+1]=temp
temp=processes[j]
processes[j]=processes[j+1]
processes[j+1]=temp
waitingtime=[]
avgwaitingtime=0
turnaroundtime=[]
avgturnaroundtime=0
int avgwaitingtime= avgwaitingtime+waitingtime[i]
int avgturnaroundtime=avgturnaroundtime+turnaroundtime[i]
float avgwaitingtime=(avgwaitingtime)/n
float avgturnaroundtime=(avgturnaroundtime)/n
print("Process\t Burst Time\t Waiting Time\t Turn Around Time")
for (i=0; i=n; i++)
print((i)"\t" (bursttime[i]) "\t" (waitingtime[i]) "\t" (turnaroundtime[i]))
print("Average Waiting time is:" (avgwaitingtime))
print("Average Turn Arount Time is:" (avgturnaroundtime)) |
def main(array):
quickSort(0,len(array)-1,array)
def quickSort(start, end, array):
if start < end :
p = partition(start, end, array)
quickSort(start, p-1, array)
quickSort(p+1, end, array)
def partition(start, end, array):
# taking start element as a pivot
pivotIndex = start
pivot = array[pivotIndex]
while start < end:
while start < len(array) and array[start] <= pivot:
start += 1
while array[end] > pivot:
end -= 1
if(start < end):
array[start], array[end] = array[end], array[start]
array[end], array[pivotIndex] =array[pivotIndex],array[end]
return end
if __name__ == "__main__":
lst0 = [9,7,5,3,1,8,6,4,3,0,34,65,343,79,90,85,21,79,57,49,61,62,63,88,77,66,55,44,33,22,11,100,99]
main(lst0)
print(lst0)
|
def findstr(str,pattern):
tmp=str.find(pattern)
str2=str[0:tmp] + str[(tmp+len(pattern)):]
print(str2)
str=input("Enter a string: ")
pattern=input("Input a Pattern: ")
findstr(str,pattern) |
def allConstruct(targetString,wordBank):
if targetString == 0 : return []
a = []
for word in wordBank:
if targetString.find(word) == 0 :
suffix = targetString[len(word):]
result = allConstruct(suffix,wordBank)
a += result
return a
print(allConstruct("purple",["purp","p","le","ur","purpl","purple"])) |
def binarySearch(arr, left, right, key):
if right >= left:
mid = left + (right - left) // 2
if arr[mid] == key:
return mid
if arr[mid] > key :
return binarySearch(arr, left, mid-1, key)
else:
return binarySearch(arr, mid+1, right, key)
else:
return -1
x = [1,2,3,4,5,6,7,8,9]
print(binarySearch(x,0,len(x)-1, 8)) |
def memo(func):
memory={}
def inner(num):
if num not in memory:
memory[num]=func(num)
return memory[num]
return inner
@memo
def facto(n):
if n==1:
return 1
else:
return n*facto(n-1)
print(facto(20)) |
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 8 15:08:14 2020
@author: gulbarin
Student Name: Gülbarin Maçin
ID: 69163
"""
import random
#this method create random list which is a original list
def random_list():
n=random.randint(3,21)
randomlist = []
for i in range(n):
elt = random.randint(1,100)
randomlist.append(elt)
print("My list lenght is", n)
return randomlist
#thanks to this method we can easily sum 3 numbers
def create_sum_of_neighbors_list(list1):
a=len(list1)
list2=[]
for i in range(a):
if i==0:
elt=list1[i]+list1[i+1]
list2.append(elt)
elif i==a-1:
elt=list1[i]+list1[i-1]
list2.append(elt)
else:
elt=list1[i-1]+list1[i]+list1[i+1]
list2.append(elt)
return list2
#merged 2 list to create 3rd list
def merged_list(list1, list2):
list3 = []
len1 = len(list1)
for i in range(len1):
list3 += [list1[i]]
list3 += [list2[i]]
return list3
#this removeing odd numbers
def del_odd_value(lst):
for i in lst[:]:
if i % 2 != 0:
lst.remove(i)
return lst
def sum_two_sides(lst):
new_list=[]
if len(lst) % 2 == 0:
for i in range(len(lst)//2):
elt=lst[i]+lst[len(lst)-i-1]
new_list.append(elt)
else:
n=(len(lst)+2)//2
m=lst[n-1]
for i in range(len(lst)//2):
elt=lst[i]+lst[len(lst)-i-1]
new_list.append(elt)
new_list.append(m)
return new_list
list1= random_list()
print("List1(Original List)")
print(list1)
list2=create_sum_of_neighbors_list(list1)
print("List2 (Sum of neighbors of List1):")
print(list2)
list3= merged_list(list1,list2)
print("List3 (List1 and List2 merged):")
print(list3)
print("List3 with odd numbers removed:")
list3=del_odd_value(list3)
print(list3)
print("List4 (Summing List3 from two sides):")
list4=sum_two_sides(list3)
print(list4)
print("List4 sorted in descending order:")
list4.sort()
print(list4[::-1]) #this print numbers descending order |
def getFarthestDistanceBetweenVertices( positions ):
if len(positions) <= 1:
return 0
edgeList = []
# add all edges and their cost to the list
while positions:
state = positions[0]
del positions[0]
# add all the edges from leading from the current state to all the other states
edgeList.extend(map(lambda x: (util.manhattanDistance(state, x), state, x), positions))
return max(edge[0] for edge in edgeList)
def calcShortestPathsLengthSum(positions):
"""
:param positions: a list of positions (x,y) pacman should go reach
:return: the sum of path lengths in a minimum spanning tree
"""
# we use Kruskal's algorithm to calculate the minimum spanning tree
# step 1) put all the edges and in the graph, with their cost, into a list of tuples (cost, vertice1, vertice2)
if len(positions) <= 1:
return 0
edgeList = []
# add all edges and their cost to the list
while positions:
state = positions[0]
del positions[0]
# add all the edges from leading from the current state to all the other states
edgeList.extend(map(lambda x: (util.manhattanDistance(state, x), state, x), positions))
# calculate a list of edges in a min spanning tree
edgeList = calcMinSpanningTree(edgeList)
# return the sum of edge costs in the MST
return sum(edge[0] for edge in edgeList)
def calcMinSpanningTree(allEdgeList):
""" calculate a minimum spanning tree list of edges via Kruskal's algorithm"""
# remove all self referencing edges
allEdgeList = filter(lambda z: z[0]!=0, allEdgeList)
# sort the list of edges by their cost
allEdgeList = sorted(allEdgeList)
vertexSet = set()
groupIdentifier = dict()
identCounter = 0
edgeList = []
# build the minimum spanning tree - we rely on edgeList being sorted by cost
for edge in allEdgeList:
# add only edges connecting separate forests
id1 = groupIdentifier.get(edge[1], -1)
id2 = groupIdentifier.get(edge[2], -1)
if id1 == id2 == -1:
groupIdentifier[edge[1]] = identCounter
groupIdentifier[edge[2]] = identCounter
identCounter += 1
elif id1 == id2:
continue # they're in the same tree
elif id1 == -1:
groupIdentifier[edge[1]] = groupIdentifier[edge[2]]
elif id2 == -1:
groupIdentifier[edge[2]] = groupIdentifier[edge[1]]
else:
for vertex in vertexSet:
if groupIdentifier[vertex] == id2:
groupIdentifier[vertex] = id1
edgeList.append(edge)
vertexSet.add(edge[1])
vertexSet.add(edge[2])
return edgeList |
# self and static method
class User:
username = ""
password = ""
def __init__(self, username="admin", password="1234"):
self.username = username
self.password = password
@staticmethod # บอกว่า function นี้เป็น static method
def test():
print("5678")
User.test() # เรียกตรง ๆ ได้เลย ไม่ต้องประกาศ Object
user = User()
print(user.username) |
import helper
import rsa_encryption as rsa
import factoring as factor
import time
import sympy
def countTime(func, t):
start = time.time()
p, q = func(t)
print (p, q)
end = time.time()
return end - start
def readFile(file="pq.txt"):
f = open(file, "r")
for line in f:
p, q = line.split()
n = int(p)*int(q)
print(p, q, n)
print("pollard rho:", countTime(factor.quadSieve, n))
#print("Quad Sieve:", countTime(factor.quadSieve, n))
#print("Trivial", countTime(factor.trivial, n))
#print("Trivial2", countTime(factor.trivial2, n))
#print("Fermat", countTime(factor.fermat, n))
readFile()
# print("pollard rho:", countTime(f.pollardrho, 56421059))
# print("Quad Sieve:", countTime(f.quadSieve, n))
# print("Trivial", countTime(f.trivial, n))
# print("Trivial2", countTime(f.trivial2, n))
#print("Fermat", countTime(factor.fermat, 14))
|
# -*- coding: UTF-8 -*-
def merge(seq1, seq2):
seq = []
h = j = 0
while h < len(seq1) and j < len(seq2):
if seq1[h] < seq2[j]:
seq.append(seq1[h])
h = h+1
else:
seq.append(seq2[j])
j = j+1
if h == len(seq1):
for i in seq2[j:]:
seq.append(i)
elif j == len(seq2):
for i in seq1[h:]:
seq.append(i)
return seq |
# -*- coding: UTF-8 -*-
def insertion_sort(seq):
for i in range(1, len(seq)):
key = seq[i]
j = i - 1
while j >= 0:
if seq[j] > key:
seq[j+1] = seq[j]
seq[j] = key
j = j -1
return seq
if __name__ == '__main__':
seq = [12, 3, 56, 43, 27, 59, 84, 15]
print insertion_sort(seq) |
"""Parse data from AmazonTestData.csv into a list of asin values
Assumptions:
-product information in csv file is accurate ie. corresponding ASIN matches correctly with title/product
"""
import csv
my_file = "/Users/Thoshi64/bottle/AmazonTestData.csv" #testing
def parse(raw_file, delimiter):
"""parses csv file into list format and return list variable"""
opened_file = open(raw_file)
csv_data = csv.reader(opened_file, delimiter=delimiter)
parsed_data = []
#pull headers from csv
headers = csv_data.next()
#pull data into list of dictionaries --> more workable to pull ASIN out
for row in csv_data:
parsed_data.append(dict(zip(headers, row)))
ASIN_list = []
#pull ASIN out from parsed_data
for product in parsed_data:
ASIN_list.append(product["ASIN"])
opened_file.close()
return ASIN_list
def main(): #testing
list = parse(my_file, ',')
print list
if __name__ == "__main__":
main()
|
import matplotlib.pyplot as plt
import matplotlib
# from matplotlib import mpl
import numpy as np
# import matplotlib.animation as animation
import random
import math
def loadMap():
dataset="map.json"
import json
dataFile = open(dataset)
s = dataFile.read()
data = json.loads(s)
dataFile.close()
return data["map"]
# make values from -5 to 5, for this example
zvals = loadMap()
print (zvals)
class Map(object):
def __init__(self, map):
self._map = map
self._agent = np.array([7,7])
self._target = np.array([8,8])
# self._map[self._target[0]][self._target[1]] = 1
obstacles = []
obstacles.append([2, 3])
obstacles.append([3, 7])
obstacles.append([-4, 6])
obstacles.append([-7, -6])
obstacles.append([-6, -6])
self._obstacles = np.array(obstacles)+8.0 # shift coordinates
self._bounds = np.array([[0,0], [15,15]])
self._markerSize = 25
def reset(self):
self._agent = np.array([random.randint(0,15),random.randint(0,15)])
def getAgentLocalState(self):
"""
Returns a vector of value [-1,1]
"""
st_ = self._map[(self._agent[0]-1)::2, (self._agent[1]-1)::2] # submatrix around agent location
st_ = np.reshape(st_, (1,)) # Make vector
return st_
def move(self, action):
"""
action in [0,1,2,3,4,5,6,7]
"""
return {
0: [-1,0],
1: [-1,1],
2: [0,1],
3: [1,1],
4: [1,0],
5: [1,-1],
6: [0,-1],
7: [-1,-1],
}.get(action, [-1,0])
def act(self, action):
move = np.array(self.move(action))
# loc = self._agent + (move * random.uniform(0.5,1.0))
loc = self._agent + (move)
if (((loc[0] < self._bounds[0][0]) or (loc[0] > self._bounds[1][0]) or
(loc[1] < self._bounds[0][1]) or (loc[1] > self._bounds[1][1])) or
self.collision(loc) or
self.fall(loc)):
# Can't move ouloct of map
return self.reward() + -8
# if self._map[loc[0]-1][loc[1]-1] == 1:
# Can't walk onto obstacles
# return self.reward() +-5
self._agent = loc
return self.reward()
def actContinuous(self, action):
move = np.array(action)
# loc = self._agent + (move * random.uniform(0.5,1.0))
loc = self._agent + (move)
if (((loc[0] < self._bounds[0][0]) or (loc[0] > self._bounds[1][0]) or
(loc[1] < self._bounds[0][1]) or (loc[1] > self._bounds[1][1])) or
self.collision(loc) or
self.fall(loc)):
# Can't move out of map
return -8
# if self._map[loc[0]-1][loc[1]-1] == 1:
# Can't walk onto obstacles
# return self.reward() +-5
self._agent = loc
return self.reward()
def fall(self, loc):
# Check to see if collision at loc with any obstacles
# print (int(math.floor(loc[0])), int(math.floor(loc[1])))
if self._map[int(math.floor(loc[0]))][ int(math.floor(loc[1]))] < 0:
return True
return False
def collision(self, loc):
# Check to see if collision at loc with any obstacles
for obs in self._obstacles:
a=(loc - obs)
d = np.sqrt((a*a).sum(axis=0))
if d < 0.3:
# print ("Found collision")
return True
return False
def reward(self):
# More like a cost function for distance away from target
# print ("Agent Loc: " + str(self._agent))
# print ("Target Loc: " + str(self._target))
a=(self._agent - self._target)
d = np.sqrt((a*a).sum(axis=0))
# print ("Dist Vector: " + str(a) + " Distance: " + str(d))
if d < 0.3:
return 16.0
return 0
def getState(self):
return self._agent
def setState(self, st):
self._agent = st
def init(self, U, V, Q):
colours = ['gray','black','blue']
cmap = matplotlib.colors.ListedColormap(['gray','black','blue'])
bounds=[-1,-1,1,1]
norm = matplotlib.colors.BoundaryNorm(bounds, cmap.N)
plt.ion()
# Two subplots, unpack the axes array immediately
self._fig, (self._map_ax, self._policy_ax) = plt.subplots(1, 2, sharey=False)
self._fig.set_size_inches(18.5, 10.5, forward=True)
self._map_ax.set_title('Map')
self._particles, = self._map_ax.plot([self._agent[0]], [self._agent[1]], 'bo', ms=self._markerSize)
self._map_ax.plot([self._target[0]], [self._target[1]], 'ro', ms=self._markerSize)
self._map_ax.plot(self._obstacles[:,0], self._obstacles[:,1], 'gs', ms=28)
# self._line1, = self._ax.plot(x, y, 'r-') # Returns a tuple of line objects, thus the comma
cmap2 = matplotlib.colors.LinearSegmentedColormap.from_list('my_colormap',
colours,
256)
img1 = self._map_ax.imshow(self._map,interpolation='nearest',
cmap = cmap2,
origin='lower')
img2 = self._policy_ax.imshow(np.array(self._map)*0.0,interpolation='nearest',
cmap = cmap2,
origin='lower')
# make a color bar
# self._map_ax.colorbar(img2,cmap=cmap,
# norm=norm,boundaries=bounds,ticks=[-1,0,1])
self._map_ax.grid(True,color='white')
# self._policy_ax.grid(True,color='white')
# fig = plt.figure()
#fig.subplots_adjust(left=0, right=1, bottom=0, top=1)
#ax = fig.add_subplot(111, aspect='equal', autoscale_on=False,
# xlim=(-3.2, 3.2), ylim=(-2.4, 2.4))
# particles holds the locations of the particles
self._policy_ax.set_title('Policy')
X,Y = np.mgrid[0:self._bounds[1][0]+1,0:self._bounds[1][0]+1]
print (X,Y)
# self._policy = self._policy_ax.quiver(X[::2, ::2],Y[::2, ::2],U[::2, ::2],V[::2, ::2], linewidth=0.5, pivot='mid', edgecolor='k', headaxislength=5, facecolor='None')
textstr = """$\max q=%.2f$\n$\min q=%.2f$"""%(np.max(Q), np.min(Q))
props = dict(boxstyle='round', facecolor='wheat', alpha=0.75)
# place a text box in upper left in axes coords
self._policyText = self._policy_ax.text(0.05, 0.95, textstr, transform=self._policy_ax.transAxes, fontsize=14,
verticalalignment='top', bbox=props)
q_max = np.max(Q)
q_min = np.min(Q)
Q = (Q - q_min)/ (q_max-q_min)
self._policy2 = self._policy_ax.quiver(X,Y,U,V,Q, alpha=.75, linewidth=1.0, pivot='mid', angles='xy', linestyles='-', scale=25.0)
self._policy = self._policy_ax.quiver(X,Y,U,V, linewidth=0.5, pivot='mid', edgecolor='k', headaxislength=3, facecolor='None', angles='xy', linestyles='-', scale=25.0)
# self._policy_ax.set_aspect(1.)
def update(self):
"""perform animation step"""
# update pieces of the animation
# self._agent = self._agent + np.array([0.1,0.1])
# print ("Agent loc: " + str(self._agent))
self._particles.set_data(self._agent[0], self._agent[1] )
self._particles.set_markersize(self._markerSize)
# self._line1.set_ydata(np.sin(x + phase))
self._fig.canvas.draw()
def updatePolicy(self, U, V, Q):
# self._policy.set_UVC(U[::2, ::2],V[::2, ::2])
textstr = """$\max q=%.2f$\n$\min q=%.2f$"""%(np.max(Q), np.min(Q))
self._policyText.set_text(textstr)
q_max = np.max(Q)
q_min = np.min(Q)
Q = (Q - q_min)/ (q_max-q_min)
self._policy2.set_UVC(U, V, Q)
# self._policy2.set_vmin(1.0)
"""
self._policy2.update_scalarmappable()
print ("cmap " + str(self._policy2.cmap) )
print ("Face colours" + str(self._policy2.get_facecolor()))
colours = ['gray','black','blue']
cmap2 = mpl.colors.LinearSegmentedColormap.from_list('my_colormap',
colours,
256)
self._policy2.cmap._set_extremes()
"""
self._policy.set_UVC(U, V)
self._fig.canvas.draw()
def reachedTarget(self):
# Might be a little touchy because floats are used
a=(self._agent - self._target)
d = np.sqrt((a*a).sum(axis=0))
return d <= 0.4
def saveVisual(self, fileName):
# plt.savefig(fileName+".svg")
self._fig.savefig(fileName+".svg") |
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 1 19:53:02 2019
@author: Mohammad Shahin
"""
class Text(object):
def __init__(self,text='',font=''):
self.text=text
self.font=font
def addText(self,text):
self.text=self.text+text
def getText(self):
return self.text
def setFont(self,font):
self.font=font
def getFont(self):
return self.font
def show(self):
return '['+self.getFont()+']'+self.getText()+'['+self.getFont()+']'
class SaveText(object):
numberVersion=0
dic_version={}
def save_text(self,Text):
SaveText.dic_version[SaveText.numberVersion]={"Font":Text.getFont(),"Text":Text.getText()}
SaveText.numberVersion+=1
def get_version(self,number):
return SaveText.dic_version[number]['Text']
text=Text()
saver=SaveText()
text.addText("there was nothing ")
text.setFont("Arial")
saver.save_text(text)
print(text.show())
print(saver.get_version(0))
|
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 19 20:00:25 2019
@author: Mohammad Shahin
"""
def interlaced(st1,st2):
print(len(st2))
small=''
if len(st1)>len(st2):
x=st1[len(st2):]
small=st2[:]
elif len(st2)>len(st1):
x=st2[len(st1):]
small=st1[:]
res=''
for i in range(len(small)):
res+=st1[i]+st2[i]
print(res+x)
interlaced("aaaa","bb")
|
import torch
# sigmoid activation function using pytorch
def sigmoid_activation(z):
return 1 / (1 + torch.exp(-z))
# function to calculate the derivative of activation
def sigmoid_delta(x):
return x * (1 - x)
n_input, n_hidden, n_output = 5,3,1
x = torch.randn((1, n_input))
y = torch.rand((1, n_output))
# hidden and output layer weights
w1 = torch.randn(n_input,n_hidden)
w2 = torch.randn(n_hidden, n_output)
# Initialize tensor variables for bias terms
b1 = torch.randn((1,n_hidden)) # Bias for hidden layer
b2 = torch.randn((1,n_output)) # bias for output layer
print("Old bias terms")
print(b1)
print(b2)
# activation of hidden layer
z1 = torch.mm(x, w1) + b1
a1 = sigmoid_activation(z1)
# activation (output) of final layer
z2 = torch.mm(a1, w2) + b2
output = sigmoid_activation(z2)
loss = y - output
# compute derivative of error terms
delta_output = sigmoid_delta(output)
delta_hidden = sigmoid_delta(a1)
# backpass the changes to previous layers
d_outp = loss * delta_output
loss_h = torch.mm(d_outp, w2.t())
d_hidn = loss_h * delta_hidden
learning_rate = 0.3
w2 += torch.mm(a1.t(), d_outp) * learning_rate
w1 += torch.mm(x.t(), d_hidn) * learning_rate
b2 += d_outp.sum() * learning_rate
b1 += d_hidn.sum() * learning_rate
print("new bias terms")
print(b1)
print(b2)
|
'''
Plotting libray, using Tkinter for expEYES
Author : Ajith Kumar B.P, [email protected]
License : GNU GPL version 3
'''
import gettext, sys
gettext.bindtextdomain("expeyes")
gettext.textdomain('expeyes')
_ = gettext.gettext
VER = sys.version[0]
if VER == '3':
from tkinter import *
else:
from Tkinter import *
import os, sys
AXWIDTH = 30 # width of the axis display canvas
AYWIDTH = 50 # width of the axis display canvas
NUMDIVX = 5
NGRID1X = 10
NUMDIVY = 5
NGRID1Y = 10
NGRID2 = 5
BGCOL = 'white'
PLOTBGCOL = 'white'
LINEWIDTH = 1.5
LINECOL = ['black', 'red', 'blue', 'magenta', 'cyan', 'green', 'yellow', 'orange','gray', 'gray2']
LABELCOL = 'blue'
TEXTCOL = 'black'
GRIDCOL = 'gray'
class graph:
'''
Class for displaying items in a canvas using a world coordinate system. The range of the
world coordinate system is specified by calling the setWorld method.
'''
border = 2
pad = 0
bordcol = 'grey' # Border color
gridcol = 'grey' # Grid color
bgcolor = '#dbdbdb' # background color for all
plotbg = 'ivory' # Plot window background color
textcolor = 'blue'
traces = []
xtext = []
ytext = []
legendtext = []
scaletext = []
markerval = []
markertext = None
xlabel = _('mSec') # Default axis lables
ylabel = 'V'
markers = []
drawYlab = False
helpwin = None
def __init__(self, parent, width=400., height=300.,color = 'white', labels = True, bip=True, drawYlab=True):
self.parent = parent
self.labels = labels
self.SCX = width
self.SCY = height
self.plotbg = color
self.bipolar = bip
self.drawYlab = drawYlab
if labels == False:
f = Frame(self.parent, bg = 'black', borderwidth = self.border, relief = FLAT)
f.pack(side=TOP, anchor = S)
self.canvas = Canvas(f, bg = self.plotbg, width = width, height = height)
self.canvas.pack(side = TOP, anchor = S)
else:
f = Frame(parent, bg = self.bgcolor)
f.pack(side=TOP)
if self.drawYlab:
self.yaxis = Canvas(f, width = AYWIDTH, height = height, bg = self.bgcolor)
self.yaxis.pack(side = LEFT, anchor = N, pady = self.border)
f1 = Frame(f)
f1.pack(side=LEFT)
self.canvas = Canvas(f1, bg = self.plotbg, width = width, height = height, bd =0, relief=FLAT)
self.canvas.pack(side = TOP)
self.canvas.bind("<Button-1>", self.show_xy)
self.xaxis = Canvas(f1, width = width, height = AXWIDTH, bg = self.bgcolor)
self.xaxis.pack(side = LEFT, anchor = N, padx = self.border)
self.canvas.create_rectangle ([(1,1),(width,height)], outline = self.bordcol)
Canvas(f, width = 4, height = height, bg = self.bgcolor).pack(side=LEFT) # spacer only
self.setWorld(0 , 0, self.SCX, self.SCY, self.xlabel, self.ylabel) # initialize scale factors
self.grid()
#----------------------- Another window ---------------------
def clear_fm(self):
try:
self.canvas.delete(self.msg_window)
except:
pass
def disp(self, msg):
self.clear_fm()
win = Button(text = msg, bg = 'yellow', fg='blue', font=("Helvetica", 30), command=self.clear_fm)
self.msg_window = self.canvas.create_window(self.SCX/4, self.SCY/10, window=win, anchor=NW)
#--------------------------------- Manage the Marker's --------------------------------------
def enable_marker(self, marker_max = 3):
self.canvas.bind("<Button-3>", self.show_marker)
self.CURMAX = marker_max
def clear_markers(self):
for k in self.markers:
self.canvas.delete(k[2]) #third item is the text on the canvas
self.markers = []
def show_marker(self, event):
if len(self.markers) >= self.CURMAX:
self.clear_markers()
return
ix = self.canvas.canvasx(event.x) - self.border
iy = self.SCY - self.canvas.canvasy(event.y) #- self.border
x = ix * self.xscale + self.xmin
y = iy * self.yscale + self.ymin
m = self.canvas.create_text(ix, self.SCY-iy, text = 'x', fill = 'red')
self.markers.append((x,y,m))
#print x,y
def get_markers(self):
x = []
y = []
for k in self.markers:
x.append(k[0])
y.append(k[1])
return x,y
#--------------------------------------------------------------------------------
def setWorld(self, x1, y1, x2, y2, xlabel, ylabel):
'''
Calculates the scale factors for world to screen coordinate transformation.
'''
self.xlabel = xlabel
self.ylabel = ylabel
self.xmin = float(x1)
self.ymin = float(y1)
self.xmax = float(x2)
self.ymax = float(y2)
self.xscale = (self.xmax - self.xmin) / (self.SCX)
self.yscale = (self.ymax - self.ymin) / (self.SCY)
self.mark_labels()
if self.labels == True:
return
try:
for txt in self.scaletext:
self.canvas.delete(txt)
self.scaletext = []
except:
pass
s = _('%3.2f %s/div')%( (self.xmax-self.xmin)/NGRID1X, xlabel)
t = self.canvas.create_text(2, self.SCY*11/20, anchor = SW, justify = LEFT, \
fill = LABELCOL, text = s)
self.scaletext.append(t)
s = _('%3.2f %s/div')%( (self.ymax-self.ymin)/NGRID1Y, ylabel)
t = self.canvas.create_text(self.SCX/2, self.SCY-10,anchor = SW, justify = LEFT, \
fill = LABELCOL, text = s)
self.scaletext.append(t)
def mark_labels(self):
'''
Draws the X and Y axis divisions and labels. Only used internally.
'''
if self.labels == False:
return
for t in self.xtext: # display after dividing by scale factors
self.xaxis.delete(t)
if self.drawYlab:
for t in self.ytext: self.yaxis.delete(t)
self.xtext = []
self.ytext = []
self.xtext.append(self.xaxis.create_text(int(self.SCX/2), AXWIDTH-2, \
text = self.xlabel, anchor=S, fill = self.textcolor))
dx = float(self.SCX)/NUMDIVX
for x in range(0,NUMDIVX+1):
a = x *(self.xmax - self.xmin)/NUMDIVX + self.xmin
s = '%4.1f'%(a)
adjust = 0
if x == 0: adjust = 6
if x == NUMDIVX: adjust = -10
t = self.xaxis.create_text(int(x*dx)+adjust,1,text = s, anchor=N, fill = self.textcolor)
self.xtext.append(t)
if self.drawYlab:
self.ytext.append(self.yaxis.create_text(2,self.SCY/2,text = self.ylabel, anchor=W, fill = self.textcolor))
dy = float(self.SCY)/NUMDIVY
for y in range(0,NUMDIVY+1):
a = y*(self.ymax - self.ymin)/5 # + self.ymin
if self.ymax > 99:
s = '%4.0f'%(self.ymax-a)
else:
s = '%4.1f'%(self.ymax-a)
adjust = 0
if y == 0: adjust = 6
if y == NUMDIVY: adjust = -5
t = self.yaxis.create_text(AYWIDTH, int(y*dy)+adjust,text = s,anchor = E, fill = self.textcolor)
self.ytext.append(t)
def show_xy(self,event): #Prints the XY coordinates of the current cursor position
ix = self.canvas.canvasx(event.x) - self.border
iy = self.SCY - self.canvas.canvasy(event.y) #- self.border
x = ix * self.xscale + self.xmin
y = iy * self.yscale + self.ymin
s = 'x = %5.3f\ny = %5.3f' % (x,y)
try:
self.canvas.delete(self.markertext)
except:
pass
self.markertext = self.canvas.create_text(self.border + 1,\
self.SCY-1, anchor = SW, justify = LEFT, text = s)
self.markerval = [x,y]
def grid(self):
dx = (self.xmax - self.xmin) / NGRID1X
if self.drawYlab:
dy = (self.ymax - self.ymin) / NGRID1Y
else:
dy = (self.ymax - self.ymin) / (NGRID1Y-2) # make 8 vertical divisions only, used by the oscilloscope
x = self.xmin + dx
#print self.ymin
if self.bipolar == True:
ip = self.w2s((self.xmax/2,self.xmax/2),(self.ymin,self.ymax))
self.canvas.create_line(ip, fill=self.gridcol, width=LINEWIDTH)
ip = self.w2s((self.xmin,self.xmax),(self.ymax/2,self.ymax/2))
self.canvas.create_line(ip, fill=self.gridcol, width=LINEWIDTH)
while x < self.xmax:
ip = self.w2s((x,x),(self.ymin,self.ymax))
self.canvas.create_line(ip, fill=self.gridcol, dash= (1,int(dy/NGRID2)-1), width=LINEWIDTH)
x = x +dx
y = self.ymin + dy
while y < self.ymax:
ip = self.w2s( (self.xmin,self.xmax), (y,y) )
self.canvas.create_line(ip, fill=GRIDCOL, dash= (1,int(dx/NGRID2)-1), width=LINEWIDTH)
y = y +dy
def w2s(self, x,y): # World to Screen xy conversion before plotting anything
ip = []
for i in range(len(x)):
ix = self.border + int( (x[i] - self.xmin) / self.xscale)
iy = self.border + int( (y[i] - self.ymin) / self.yscale)
iy = self.SCY - iy
ip.append((ix,iy))
return ip
def round4axis(self,n):
if n == 0:
return n
sign = 1
if n < 0:
sign = -1
n = -1 * n
div = 0
if n > 10:
while n > 10:
n = n/10
div = div + 1
res = (int(n)+1)* 10**div
return sign * float(res)
elif n <= 10:
while n < 1:
n = n*10
div = div + 1
res = (int(n)+1)
return sign * float(res) / 10**div
def auto_scale(self, x,y):
'''
Sets the range of the world co-ordinate system from two lists of x and y.
The range of y-coordinates are rounded. (for ymin=5 and ymax=95 will set the
limits from 0 to 100)
'''
xmin = x[0]
xmax = x[-1]
ymin = 1.0e10
ymax = 1.0e-10
for k in y:
if k > ymax: ymax = k
if k < ymin: ymin = k
#ymin = self.round4axis(ymin)
#ymax = self.round4axis(ymax)
if ymin == ymax: # avoid a divide by zero error
return
self.setWorld(xmin,ymin,xmax,ymax,self.xlabel,self.ylabel)
def box(self, x1, y1, x2, y2, col):
ip = self.w2s((x1,y1),(x2,y2))
self.canvas.create_rectangle(ip, outline=col)
def text(self, x, y, text, col=0):
ip = self.w2s( [float(x)],[float(y)])
x = ip[0][0]
t = self.canvas.create_text(ip[0][0],ip[0][1], text = text,\
anchor = W, fill = LINECOL[col%len(LINECOL)])
self.legendtext.append(t)
def delete_text(self):
for t in self.legendtext:
self.canvas.delete(t)
self.legendtext = []
def line(self, x,y, col=0, smooth = True):
ip = self.w2s(x,y)
t = self.canvas.create_line(ip, fill=LINECOL[col%len(LINECOL)], width=LINEWIDTH, smooth = smooth)
self.traces.append(t)
def delete_lines(self):
for t in self.traces:
self.canvas.delete(t)
self.traces = []
#------------------------------- graph class end ---------------------------
class CreateToolTip(object):
'''
create a tooltip for a given widget
'''
def __init__(self, widget, text='widget info'):
self.widget = widget
self.text = text
self.widget.bind("<Enter>", self.enter)
self.widget.bind("<Leave>", self.close)
def enter(self, event=None):
x = y = 0
x, y, cx, cy = self.widget.bbox("insert")
x += self.widget.winfo_rootx() + 25
y += self.widget.winfo_rooty() + 20
# creates a toplevel window
self.tw = Toplevel(self.widget)
# Leaves only the label and removes the app window
self.tw.wm_overrideredirect(True)
self.tw.wm_geometry("+%d+%d" % (x, y))
label = Label(self.tw, text=self.text, justify='left', bg='lightgreen',
relief='solid', borderwidth=1, font=("helvetica", "9"),wraplength=100)
label.pack(ipadx=1)
def close(self, event=None):
if self.tw:
self.tw.destroy()
def plot(x,y,title = None, xl = None, yl = None, col = 'black', drawYlab=True):
# plot the x,y coordinate list to a new , non-blocking, window.
if title==None:
title=_('EYES plot')
if xl==None:
xl=_('mS')
if yl==None:
yl=_('V')
w = Tk()
w.title(title)
g = graph(w, width=600, height=400)
g.xlabel = xl
g.ylabel = yl
g.auto_scale(x,y)
g.line(x,y,col)
return g
#------------- popup window to displaying image -----------------
'''
def pop_image(sch, title = _('Schematic')):
top = Toplevel()
top.title(title)
try:
fn = os.path.join(os.path.dirname(sys.argv[0]), 'pics', sch)
photo = PhotoImage(file=fn)
photo_label = Label(top,image=photo)
photo_label.pack()
photo_label.image = photo
except:
Label(top, text = _('Failed to load schematic')).pack()
'''
def pop_help(name, title = _('Schematic')): # Help for scope based experiments
top = Toplevel()
top.title(title)
try:
fn = os.path.join(os.path.dirname(sys.argv[0]), 'pics', name+'.png')
photo = PhotoImage(file=fn)
photo_label = Label(top,image=photo)
photo_label.pack(side=TOP)
photo_label.image = photo
except:
try:
import PIL.Image
import PIL.ImageTk
fn = os.path.join(os.path.dirname(sys.argv[0]), 'pics', name+'.png')
im = PIL.Image.open(fn)
photo = PIL.ImageTk.PhotoImage(im)
photo_label = Label(top,image=photo)
photo_label.pack(side=TOP)
photo_label.image = photo
except:
top.title(_('Failed to load PNG Image'))
return top
try:
text = Text(top,height=5, fg='blue',font=("Helvetica", 14))
text.pack(side=TOP, fill = BOTH, expand = 1)
fn = os.path.join(os.path.dirname(sys.argv[0]), 'help', name+'.txt')
f = open(fn, 'r')
s = f.read()
text.insert(END, s)
return top
except:
Label(top, text = _('No help file found'),font=("Helvetica", 20)).pack()
return top
def grace(data, xlab = '', ylab = '', title = ''):
'''
Input data is of the form, [ [x1,y1], [x2,y2],....] where x and y are vectors
'''
try:
import pygrace
pg = pygrace.grace()
for xy in data:
pg.plot(xy[0],xy[1])
pg.hold(1) # Do not erase the old data
pg.xlabel(xlab)
pg.ylabel(ylab)
pg.title(title)
return True
except:
return False
|
# Write a procedure, speed_fraction, which takes as its inputs the result of
# a traceroute (in ms) and distance (in km) between two points. It should
# return the speed the data travels as a decimal fraction of the speed of
# light.
speed_of_light = 300000. # km per second
def speed_fraction(trace_time, distance):
time_in_seconds = trace_time / 1000.0
speed = (2 * distance) / time_in_seconds
return speed / speed_of_light
print speed_fraction(50, 5000)
#>>> 0.666666666667
print speed_fraction(50, 10000)
#>>> 1.33333333333 # Any thoughts about this answer, or these inputs?
|
filename = input('input a filename:')
f_exten = filename.split('.')
print('The extension of the file is:' + repr(f_exten[-1])) # repr()将对象转化为string格式,输出的字符带有引号.
|
import random
import time
whoBats="NONE";
print("Welcome to Hand-cricket game!!")
print("RULES ****IF ANY PLAYER ENTER GREATER THAN 6,BATSMAN WILL GET OUT****")
print("1.Heads 2.Tails")
print("Choose Your option")
toss=int(input())
while(toss!=None):
if(toss>2):
print("Invalid option")
break
toss1=random.randint(1,2)
print("Processing......")
time.sleep(2)
if(toss1==1):
print("you have won the toss")
print("Choose Batting(1) or Bowling(2)")
decision=int(input())
if(decision>2):
print("Invalid option")
break
if(decision==1):
whoBats="YOU"
time.sleep(0.5)
print("You decided to bat first")
elif(decision==2):
time.sleep(0.5)
whoBats="CPU"
print("You decided to bowl first")
elif(toss1==2):
print("CPU won the toss")
decision1=random.randint(1,2)
if(decision1==1):
whoBats="CPU"
time.sleep(0.5)
print("CPU Decided to bat first")
elif(decision1==2):
whoBats="YOU"
time.sleep(0.5)
print("CPU Decided to bowl first")
score_user=0
score_cpu=0
def hand():
global score_user
global score_cpu
user=int(input("you:"))
cpu=random.randint(1,6)
print("CPU:",cpu)
if(cpu!=user and user<=6):
score_user=score_user+user
score_cpu=score_cpu+cpu
hand()
hand()
def calculate():
if(score_cpu1<score_user):
print("CPU score:",score_cpu1)
print("You won the game")
print("CPU lose the game")
elif(score_cpu1>score_user):
print("CPU won the game")
print("You lose the game")
elif(score_cpu1==score_user):
print("Match tied")
def calculate1():
if(score_user1<score_cpu):
print("your score:",score_user1)
print("CPU won the game")
print("You lose the game")
elif(score_user1>score_cpu):
print("You won the game")
print("CPU lose the game")
elif(score_user1==score_cpu):
print("Match tied")
score_cpu1=0
def hand1():#cpu Batting
global score_cpu1
user=int(input("you:"))
cpu=random.randint(1,6)
print("CPU:",cpu)
if(cpu!=user and user<=6):
score_cpu1=score_cpu1+cpu
if(score_cpu1<target1):
hand1()
else:
calculate()
else:
calculate()
score_user1=0
def hand2():#me
global score_user1
user=int(input("you:"))
cpu=random.randint(1,6)
print("CPU:",cpu)
if(cpu!=user and user<=6 and cpu<=6):
score_user1=score_user1+user
if(score_user1<target2):
hand2()
else:
calculate1()
else:
calculate1()
if(whoBats=="YOU"):
print("ohhh....it's Out!!!")
print("Your Score : ",score_user)
target1=score_user+1
print("CPU needs",target1,"runs to win")
hand1()
elif(whoBats=="CPU"):
print("CPU Out!!!")
print("CPU Score : ",score_cpu)
target2=score_cpu+1
print("You need",target2,"runs to win")
hand2()
break
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/6/1 下午12:26
# @Author : ziyi
# @File : time_test.py
# @Software: PyCharm
# import time
# import datetime
#
# # d = datetime.datetime.now()
# # print(d.month, d.day, d.time())
# nowtime = datetime.datetime.now()
# print(str(nowtime .time()).split(':'))
# # deadline_time = time.strftime("截止%d日%H点%M分", time.localtime(time.time()))
# deadline_time = '截止{}日{}点{}分'.format(nowtime.day, str(nowtime.time()).split(':')[0], str(nowtime.time()).split(':')[1])
# print(deadline_time)
# # print(str(d).split(' ')[-1].split(':')[0])
# # if int(str(d).split(' ')[-1].split(':')[0]) > 0 and int(str(d).split(' ')[-1].split(':')[0]) < 8:
# # nowday = datetime.date.today()
# # print(nowday.weekday())
# # today = '今天是{}年{}月{}日'.format(nowday.year, nowday.month, nowday.day)
# # print(today)
# # else:
# # tomorrowday = datetime.date.today() + datetime.timedelta(days=1)
# # today = '今天是{}年{}月{}日'.format(tomorrowday.year, tomorrowday.month, tomorrowday.day)
# # print(tomorrowday.weekday())
# # print(today)
#
# now = datetime.datetime.now()
# next = now + datetime.timedelta(seconds=5)
# while True:
# now = datetime.datetime.now()
# print(now, next)
# if ((now.hour == next.hour) and (now.minute == next.minute) and (now.second == next.second)):
# print('成功啦')
# time.sleep(1) # 每次判断间隔1s,避免多次触发事件
#
sum = 0
n = 1
while n <= 100:
sum = sum + n
n = n + 1
print(sum)
|
#三元运算符
# data = input("请输入:")
# val = int(data) if data.isdecimal() else None
word = "ase123qweasdw234eqas324dwqe213asd12"
temp=""
nums=[]
index = 0
while (index != len(word)):
target = word[index:index+1]
if (target.isdigit()):
temp += target
if (index == len(word) - 1):
nums.append(temp)
elif (not word[index + 1 : index + 2].isdigit()):
nums.append(temp)
temp=""
index +=1
a = 1
def parseDta():
res1 = []
res2 = []
res3 = []
with open("../base1/log.txt",mode="r",encoding="utf-8") as file:
for item in file:
lineArr = item.strip().split("|")
res1.append(item.strip())
res2.append(lineArr)
lineDict={}
lineDict["name"] = lineArr[0]
lineDict["age"] = lineArr[2]
lineDict["pwd"] = lineArr[1]
res3.append(lineDict)
print(res1)
print(res2)
print(res3)
global a
a=2
file.close()
#函数高级
#分页
# numList = range(1,345)
# max_page_num,a = divmod(len(numList),10)
# page = int(input("输入"))
# for item in numList[(page - 1) * 10:page * 10]:
# print(item)
def func(args):
print(args)
func_list = {func,func,func}
info = {
"f1":func,
"f2":func
}
def show():
return func
#密码不显示
# import getpass
# pwd = getpass.getpass("输入密码")
# print(pwd)
#import hashlib #加密
#装饰器
def func(arg):
def inner():
print("inner before")
v = arg()
print("inner after")
return v
return inner
#执行func函数 并且将发f1作为参数传入func函数 func(f1) f1 ==func(f1)
@func
def f1():
print(123)
return 666
v = f1()
def deco(func):
def inner():
v1 = func()
return v1
return inner
#sys 模块
import sys
import time
# for i in range(1,101):
# print("%s%%"%i)
# time.sleep(0.05)
with open("../base1/log.txt",mode="r",encoding="utf-8") as f1:
for index in f1:
print(index)
import os
print(os.path.dirname(os.path.abspath("base1.py")))
print(os.path.basename("base1.py"))
abpath= os.path.abspath("base1.py")
dirname = os.path.dirname(abpath)
print(os.path.join(dirname, "a.py"))
print("==============")
res = os.walk("/Users/saybot/SKipper_HOME/python/pythonProject")
for baseDir,innerDir,c in res:
# print(os.path.join(baseDir,c))
for item in c:
print(os.path.join(baseDir,item))
print(baseDir)
#print(os.listdir("D:\codespace\project\pythonProject"))
|
a = input("Tast inn et heltall! ")
b = int(a)
if b < 10:
print(b + "Hei!") #Dette går ikke. Man kan ikke addere et heltall og en string.
#1. Dette er ikke lovlig kode. Man kan ikke addere et heltall og en string.
#2. Når vi kjører denne koden kommer vi til å få en feilmelding om linje 4.
|
#!/usr/bin/env python
#coding: utf-8
def feb(n):
if n < 1:
print("输入错误!")
return 1
n1 = 1
n2 = 1
n3 = 1
while (n-2) > 0:
n3 = n1 + n2
n1 = n2
n2 = n3
n -= 1
return n3
number = int(input("请输入一个正整数:"))
feb1 = feb(number)
print(feb1)
|
#-*- coding: utf-8 -*-
def fib(max):
n, a, b = 0, 0, 1
while n < max:
#print(b)
yield b ### print(b)改为yield b,函数就变成了一个生成器;
a, b = b,a + b
n = n + 1
return 'done'
fib(10)
|
print("Welcome to shop calculator")
DISCOUNT = 0.9
num = int(input("Please enter the number of item: "))
while num <= 0:
print("You have entered an invalid number")
num = int(input("Please enter the number of item: "))
total = 0.0
for i in range (0, num):
price = float(input("Please enter price of the item: "))
total += price
print("price= $", price,"Total= $", total)
if total <= 100:
total = DISCOUNT * total
print("Number of item: ", num)
print("Total= $", total)
|
""" Programming II colour code """
COLOUR = {"AliceBlue": "#f0f8ff", "AntiqueWhite": "#faebd7", "AntiqueWhite1": " #ffefdb", "AntiqueWhite2": "#eedfcc",
"AntiqueWhite3": "#cdc0b0", "AntiqueWhite4": "#8b8378", "aquamarine1": "#7fffd4", "aquamarine2": "#76eec6",
"aquamarine4": "#458b740", "azure1": "#f0ffff", "azure2": "#e0eeee", "azure3": "#c1cdcd", "azure4": "#838b8b"}
MENU = ['AliceBlue', 'AntiqueWhite', 'AntiqueWhite', 'AntiqueWhite2', 'AntiqueWhite3', 'AntiqueWhite4', 'aquamarine1',
'aquamarine2', 'aquamarine4', 'azure1', 'azure2', 'azure3', 'azure4']
def main():
print("Welcome to colour code")
for index, element in enumerate(MENU):
print("{:<2}".format(index), "{:<15s}".format(element))
print("\n")
choice = input("Please select your colour: \n>>> ")
for key, value in COLOUR.items():
if choice in key:
print("The code for ", key, "is", value)
main()
|
from prac_06.programming_language import ProgrammingLanguage
def main():
ruby = ProgrammingLanguage("Ruby", "Dynamic", True, 1995)
python = ProgrammingLanguage("Python", "Dynamic", True, 1991)
visual_basic = ProgrammingLanguage("Visual Basic", "Static", False, 1991)
print(ruby)
print(python)
print(visual_basic)
store = [ruby, python, visual_basic]
print("\nThe Dynamically typed language are: ")
for i in store:
if i.is_dynamic() is True:
print(i.name)
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.