text
stringlengths 37
1.41M
|
---|
import math
from collections import defaultdict
# Part 1
with open('day-1-input.txt') as f:
frequencies = [int(line.strip()) for line in f]
sum_frequencies = sum(frequencies)
print(sum_frequencies)
# Part 2
"""
from the n frequencies {f1, ... fn} we get sums {S1, ... Sn}
iterated = {S1, ... Sn, S1 + SUM, ... Sn + SUM, S1 + SUM*2, ... }
what is the first time that two sums are the same?
ie what is the first time that Sa + SUM*c = Sb + SUM*d, where Sa, Sb in {S1, ... Sn} and WLOG d >= c >= 0?
=> what is the first time that Sa = Sb + SUM(d - c)?
=> what is the smallest k for which there exist Sa, Sb such that Sa = Sb + SUM*k?
For each i in 0...(SUM - 1), we can find all S in {S1, ... Sn} ~= i % SUM.
Then for each set, we can find the smallest difference between two sums.
If there is a tie, we want the pair where the SMALLER number occurs the earliest.
"""
sums = [0]
for f in frequencies:
sums.append(f + sums[-1])
sums = sums[1:] # 0 isn't included in the sums that are iterated upon
congruence_classes = defaultdict(list)
for s in sums:
congruence_classes[s % sum_frequencies].append(s)
congruence_classes = [sorted(v) for v in congruence_classes.values() if len(v) > 1]
min_diff = math.inf
min_index = math.inf
for cclass in congruence_classes:
for i in range(len(cclass) - 1):
diff = cclass[i + 1] - cclass[i]
index = sums.index(cclass[i]) # again, we want the index of the SMALLER sum
if diff < min_diff:
min_diff = diff
min_index = index
elif diff == min_diff:
min_index = min(min_index, index)
index_a = min_index
freq_a = sums[min_index]
freq_b = freq_a + min_diff
index_b = sums.index(freq_b)
print("sums[{}]={}, sums[{}]={}. {} is the first repeated frequency"
.format(index_a, freq_a, index_b, freq_b, freq_b)
)
|
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
Segment = namedtuple('Segment', ['point1', 'point2'])
Intersection = namedtuple('Intersection', ['wire1_segment', 'wire2_segment', 'point'])
with open('day-3-input.txt') as f:
wire_descriptions = [line.strip().split(',') for line in f]
wires = []
for wire_description in wire_descriptions:
current_point = Point(0, 0)
segments = []
for segment_description in wire_description:
direction, length = segment_description[0], int(segment_description[1:])
if direction in ['L', 'D']:
length *= -1
if direction in ['R', 'L']: # horizontal segment
next_point = Point(current_point.x + length, current_point.y)
else: # vertical segment
next_point = Point(current_point.x, current_point.y + length)
segments.append(Segment(current_point, next_point))
current_point = next_point
wires.append(segments)
# we can filter a bit to reduce the number of comparisons needed
wire2_vertical_segments = [s for s in wires[1] if s.point1.x == s.point2.x]
wire2_horizontal_segments = [s for s in wires[1] if s.point1.y == s.point2.y]
# for each segment in the first wire, look for
# intersecting segments of the second wire
intersections = []
for segment in wires[0]:
if segment.point1.y == segment.point2.y: # horizontal
left_x, right_x = sorted([segment.point1.x, segment.point2.x])
for other_segment in wire2_vertical_segments:
bottom_y, top_y = sorted([other_segment.point1.y, other_segment.point2.y])
if (left_x < other_segment.point1.x < right_x and
bottom_y < segment.point1.y < top_y):
intersections.append(
Intersection(segment, other_segment, Point(other_segment.point1.x, segment.point1.y))
)
else: # vertical
bottom_y, top_y = sorted([segment.point1.y, segment.point2.y])
for other_segment in wire2_horizontal_segments:
left_x, right_x = sorted([other_segment.point1.x, other_segment.point2.x])
if (bottom_y < other_segment.point1.y < top_y and
left_x < segment.point1.x < right_x):
intersections.append(
Intersection(segment, other_segment, Point(segment.point1.x, other_segment.point1.y))
)
def dist(point1, point2):
"""
Calculate the Manhattan distance between two points.
"""
return abs(point2.x - point1.x) + abs(point2.y - point1.y)
# Part 1
origin = Point(0, 0)
min_cross_distance = min([dist(origin, i.point) for i in intersections])
print(min_cross_distance)
# Part 2
distances_along_wires = []
for intersection in intersections:
# wire length up to but not including intersecting segment
index1 = wires[0].index(intersection.wire1_segment)
index2 = wires[1].index(intersection.wire2_segment)
wire1_length = sum([dist(s.point1, s.point2) for s in wires[0][:index1]])
wire2_length = sum([dist(s.point1, s.point2) for s in wires[1][:index2]])
# plus the partial lengths of intersecting segments
wire1_length += dist(intersection.wire1_segment.point1, intersection.point)
wire2_length += dist(intersection.wire2_segment.point1, intersection.point)
distances_along_wires.append(wire1_length + wire2_length)
min_cross_distance = min(distances_along_wires)
print(min_cross_distance)
|
#Elizabeth Lin
#Word Jumble Program
#This game will give a random word(the order is random)from a list of words
#Then user need to guess the word
import random
#save some words which are chosen from the topic meteorology(Here use a tuple)
WORDS=("atmosphere","tornado","precipitation",
"convection","avalanche")
HINTS=("It is all around the Earth", "It is a violently rotating column of air."
,"It is any product of the condensation of atmospheric water vapor that falls under gravity"
,"It si teh concerted, collective movement of groups or aggregates of molecules"
+"within fluids.","It is a rapid flow of show down a sloping surface.")
#give hints to each word
#pick a word randomly using a random index
index=random.randint(0,len(WORDS)-1)
word=WORDS[index]
new_hint=HINTS[index]#match every word
#save a variable to save the shosen word in order that the while loop is work.
correct=word
#save a jumbled version of the word
Save_word=""#start with an empty string
while word: #the while loop runs until the word is the empty string
position = random.randrange(len(word))
Save_word += word[position]
word = word[:position]+word[(position+1):]
#Start the game
#Intro.
print("We have a new game now!")
print("Word of Jumble!!!")
print("There will be a word with random characters.")
print("Your goal is to guess the word.")
print("Let's play now!")
print("The jumble is:",Save_word)
#Let user guess and check
count=0
guess=input("\nEnter your guess>")
count=count+1
while(guess!=correct and guess!=""):#when the answer is not correct, start while loop."
print("Sorry, that's not it.")
answer=input("Do you need a hint?")#ask users if they need a hint
if answer=="yes":#if they need, print the hint.
print(new_hint)#the hints is from the tuple.
guess=input("\nEnter your guess>")
count=count+1
if guess==correct:#when the guess is correct, the
print("That's the right answer. You get it.!!!")
print("you take "+str(count)+ " times.")
else:
print("This is the word you did not get.--"+correct)
print("Thanks for join us.")
input("\n\nPress ENTER to exit.")
|
import pandas as pd
class Order:
id = 0
def __init__ (self, quantity, price,buy = True):
self.quantity = quantity
self.price = price
self.buy = buy
self.ID = Order.id
Order.id += 1
def __repr__ (self):
return "Order(%s, %s, %s)" % (self.quantity, self.price, self.ID)
def __eq__(self, other):
return other and self.quantity == other.quantity and self.price == other.price
def __lt__(self, other): #self < other
return self.price < other.price
def quantity(self):
return self.quantity if self.buy else - self.quantity
class Book:
def __init__(self,name):
self.name = name
self.buyList = list()
self.sellList = list()
def __repr__(self):
print("---------SellList---------")
d = {'quantity':[order.quantity for order in self.sellList], 'price':[order.price for order in self.sellList], 'ID':[order.ID for order in self.sellList]}
df_sell = pd.DataFrame(data = d)
print(df_sell)
print("\n---------BuyList----------")
d = {'quantity':[order.quantity for order in self.buyList], 'price':[order.price for order in self.buyList], 'ID':[order.ID for order in self.buyList]}
df_buy = pd.DataFrame(data = d)
print(df_buy)
res = "\n----------------Next Step----------------\n"
return res
def insertBuy(self, quantity, price):
order = Order(quantity, price, True)
print("--Insert BUY " + repr(order) + " on " + self.name + "\n")
i=0
if not self.sellList: #sellList is empty
self.buyList.append(order)
else: #sellList is not empty
self.sortSellList()
while True :
if order.price >= self.sellList[i].price and order.quantity > 0 : #if we can execute the order
if order.quantity - self.sellList[i].quantity >= 0 :
order.quantity = order.quantity - self.sellList[i].quantity
print("Execute " + str(self.sellList[i].quantity) + " at " + str(self.sellList[i].price))
self.sellList.pop(i) #delete sell order
else: # order.quantity - self.sellList[i].quantity < 0
self.sellList[i].quantity = self.sellList[i].quantity - order.quantity
print("Execute " + str(order.quantity) + " at " + str(self.sellList[i].price))
order.quantity = 0
else : #we can't execute the order and we just add it to the book
if order.quantity > 0:
self.buyList.append(order)
self.sortBuyList()
break
print(repr(self))
def insertSell(self, quantity, price):
order = Order(quantity, price, False)
print("--Insert SELL " + repr(order) + " on " + self.name + "\n")
i = 0
if not self.buyList: #buyList is empty
self.sellList.append(order)
else: #buyList is not empty
self.sortBuyList()
while True:
if order.price <= self.buyList[i].price and order.quantity > 0 :
#on execute l'odre
if order.quantity - self.buyList[i].quantity >= 0:
order.quantity = order.quantity - self.buyList[i].quantity
print("Execute " + str(self.buyList[i].quantity) + " at " + str(self.buyList[i].price))
self.buyList.pop(i) #delete buy order
else:
self.buyList[i].quantity = self.buyList[i].quantity - order.quantity
print("Execute " + str(order.quantity) + " at " + str(self.buyList[i].price))
order.quantity = 0
else : #we can't execute the order and we just add it to the book
if order.quantity > 0:
self.sellList.append(order)
self.sortSellList()
break
print(repr(self))
def sortBuyList(self): #We want to sort data in function of price (decreasing) and then id(increasing)
self.buyList.sort(key=lambda x : x.price, reverse= True)
def sortSellList(self):
self.sellList.sort(key=lambda x : x.price, reverse= False)
if __name__ == "__main__":
book = Book("TEST")
book.insertBuy(10, 10.0)
book.insertSell(120, 12.0)
book.insertBuy(5, 10.0)
book.insertBuy(2, 11.0)
book.insertSell(1, 10.0)
book.insertSell(10, 10.0)
|
class Road:
__v = 25
def ves(self, _a, _l, _h):
print(f'Вес покрытия: {int(_a) * int(_l) * self.__v * int(_h)} тон')
Road_1 = Road()
z = input(' Введите параметры: ширина(м), длина(м), толщина(см): ').split(' ')
[_a, _l, _h] = z
Road_1.ves(_a, _l, _h)
|
from Calculator.Calculator import *
class Median:
@staticmethod
def median(data):
length = len(data)
s_data = sorted(data)
if length % 2 == 0:
median1 = s_data[length // 2]
median2 = s_data[length // 2 - 1]
median = Division.quotient(Addition.sum(median1,median2), 2)
return median
else:
median = s_data[length // 2]
return median
|
import sys
import unittest
from lootbag import LootBag
# Items can be added to bag, and assigned to a child.
# Items can be removed from bag, per child. Removing ball from the bag should not be allowed. A child's name must be specified.
# Must be able to list all children who are getting a toy.
# Must be able to list all toys for a given child's name.
# Must be able to set the delivered property of a child, which defaults to false to true.
class TestLootBag(unittest.TestCase):
@classmethod
def setUpClass(self):
self.bag = LootBag()
def test_can_list_toys_from_bag_for_child(self):
toy = "ball"
mikey_toys = self.bag.list_child_toys("Mikey")
self.assertIn(toy, mikey_toys)
def test_setting_child(self):
lootin = LootBag()
with open("data/children.txt", "r") as children:
self.assertFalse("Megan" in children.read())
lootin.set_child("Megan")
self.assertTrue("Megan" in children.read())
def test_add_toy_to_bag(self):
bag = LootBag()
toy = "ball"
self.assertEqual(bag.add_toy("ball", "Mikey"), "Toy added to bag")
# toy = "truck"
# toy_list = self.bag.list_child_toys("Mikey")
# self.assertNotIn(toy, toy_list)
# self.bag.add_toy("truck", "Mikey")
# self.bag.list_child_toys("Mikey")
# self.assertIn(toy, toy_list)
if __name__ == '__main__':
unittest.main() |
songs = {
('Nickelback', 'How You Remind Me'),
('Will.i.am', 'That Power'),
('Miles Davis', 'Stella by Starlight'),
('Nickelback', 'Animals')
}
# Set Comprehension: Correct Solution
good_songs = {(song[0], song[1]) for song in songs if song[0] != 'Nickelback'}
print(good_songs)
print(type(good_songs))
# Dictionary Comprehension: Outside scope of this lesson (Solution 1)
# dictionary_songs = dict(songs)
# no_nickel = {}
# for artist, song in dictionary_songs.items():
# no_nickel_local = {}
# if artist != 'Nickelback':
# no_nickel_local.update({artist: song})
# no_nickel.update(no_nickel_local)
# print(no_nickel)
|
#data önişlemleri için
import pandas as pd
#arraylerde işlemler yapmak için
import numpy as np
#dataseti yükledik
dataset = pd.read_csv('Social_Network_Ads.csv')
#id numarası gereksiz olduğu için atıyoruz
dataset =dataset.drop(['User ID'],axis=1)
#editting column name
dataset.rename(columns={'Gender':'cinsiyet','Age':'yas','EstimatedSalary':
'fiyat','Purchased':'satis'},inplace=True)
#feature daki nanları bulmak
dataset['fiyat'].value_counts(dropna=False)
dataset['fiyat'].dropna(inplace=True)
assert dataset['fiyat'].notnull().all()
dataset['fiyat'].fillna('empty',inplace=True)
print(dataset.info())
'''
DataFrame.isna
Indicate missing values.
DataFrame.notna
Indicate existing (non-missing) values.
DataFrame.fillna
Replace missing values.
Series.dropna
Drop missing values.
Index.dropna
Drop missing indices.
'''
#2.yol
from sklearn.preprocessing import Imputer
imputer = Imputer(missing_values='NaN',strategy='mean',axis=0)
yas = dataset.iloc[:,1:3]
imputer =imputer.fit(yas)
yas =imputer.transform(yas)
|
'''
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return the number of distinct solutions to the n-queens puzzle.
Example:
Input: 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown below.
[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
'''
class Solution(object):
def totalNQueens(self, n):
"""
:type n: int
:rtype: int
"""
def dfs(queens,dif,sum_):
p = len(queens)
if p == n:
result.append(queens)
for q in range(n):
if q not in queens and p-q not in dif and q+p not in sum_:
dfs(queens+[q],dif+[p-q],sum_+[p+q])
result = []
dfs([],[],[])
return len(result) |
'''
Given two strings A and B of lowercase letters, return true if and only if we can swap two letters in A so that the result equals B.
Example 1:
Input: A = "ab", B = "ba"
Output: true
Example 2:
Input: A = "ab", B = "ab"
Output: false
Example 3:
Input: A = "aa", B = "aa"
Output: true
Example 4:
Input: A = "aaaaaaabc", B = "aaaaaaacb"
Output: true
Example 5:
Input: A = "", B = "aa"
Output: false
Note:
0 <= A.length <= 20000
0 <= B.length <= 20000
A and B consist only of lowercase letters.
'''
class Solution(object):
def buddyStrings(self, A, B):
"""
:type A: str
:type B: str
:rtype: bool
"""
if A == B and len(set(A)) < len(A): return True
diff = [(a, b) for a, b in zip(A, B) if a != b]
return len(diff) == 2 and diff[0] == diff[1][::-1]
|
'''
In a group of N people (labelled 0, 1, 2, ..., N-1), each person has different amounts of money, and different levels of quietness.
For convenience, we'll call the person with label x, simply "person x".
We'll say that richer[i] = [x, y] if person x definitely has more money than person y. Note that richer may only be a subset of valid observations.
Also, we'll say quiet[x] = q if person x has quietness q.
Now, return answer, where answer[x] = y if y is the least quiet person (that is, the person y with the smallest value of quiet[y]), among all people who definitely have equal to or more money than person x.
Example 1:
Input: richer = [[1,0],[2,1],[3,1],[3,7],[4,3],[5,3],[6,3]], quiet = [3,2,5,4,6,1,7,0]
Output: [5,5,2,5,4,5,6,7]
Explanation:
answer[0] = 5.
Person 5 has more money than 3, which has more money than 1, which has more money than 0.
The only person who is quieter (has lower quiet[x]) is person 7, but
it isn't clear if they have more money than person 0.
answer[7] = 7.
Among all people that definitely have equal to or more money than person 7
(which could be persons 3, 4, 5, 6, or 7), the person who is the quietest (has lower quiet[x])
is person 7.
The other answers can be filled out with similar reasoning.
Note:
1 <= quiet.length = N <= 500
0 <= quiet[i] < N, all quiet[i] are different.
0 <= richer.length <= N * (N-1) / 2
0 <= richer[i][j] < N
richer[i][0] != richer[i][1]
richer[i]'s are all different.
The observations in richer are all logically consistent.
'''
|
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def largestValues(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root: return []
qa, ans = [root], []
while qa:
maxn = None
qb = []
for i in qa:
maxn = max(i.val, maxn)
if i.left: qb.append(i.left)
if i.right: qb.append(i.right)
ans.append(maxn)
qa = qb
return ans
|
'''
Write a function that takes a string as input and reverse only the vowels of a string.
Example 1:
Input: "hello"
Output: "holle"
Example 2:
Input: "leetcode"
Output: "leotcede"
Note:
The vowels does not include the letter "y".
'''
class Solution(object):
def reverseVowels(self, s):
"""
:type s: str
:rtype: str
"""
if not s: return s
vowel = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
ans = list(s)
i,j=0,len(s)-1
while i < j:
if ans[i] not in vowel:
i += 1
if ans[j] not in vowel:
j -= 1
if ans[i] in vowel and ans[j] in vowel:
ans[i],ans[j]=ans[j],ans[i]
i +=1
j -= 1
return ''.join(ans) |
import collections
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def findFrequentTreeSum(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
cnt = collections.Counter()
def subTreeSum(root):
if not root: return 0
return root.val + subTreeSum(root.left) + subTreeSum(root.right)
def traverse(root):
if not root: return
cnt[subTreeSum(root)] += 1
traverse(root.left)
traverse(root.right)
traverse(root)
maxfr = max(cnt.values())
return [k for k,v in cnt.iteritems() if v == maxfr] |
'''
Given two strings s1, s2, find the lowest ASCII sum of deleted characters to make two strings equal.
Example 1:
Input: s1 = "sea", s2 = "eat"
Output: 231
Explanation: Deleting "s" from "sea" adds the ASCII value of "s" (115) to the sum.
Deleting "t" from "eat" adds 116 to the sum.
At the end, both strings are equal, and 115 + 116 = 231 is the minimum sum possible to achieve this.
Example 2:
Input: s1 = "delete", s2 = "leet"
Output: 403
Explanation: Deleting "dee" from "delete" to turn the string into "let",
adds 100[d]+101[e]+101[e] to the sum. Deleting "e" from "leet" adds 101[e] to the sum.
At the end, both strings are equal to "let", and the answer is 100+101+101+101 = 403.
If instead we turned both strings into "lee" or "eet", we would get answers of 433 or 417, which are higher.
Note:
0 < s1.length, s2.length <= 1000.
All elements of each string will have an ASCII value in [97, 122].
'''
|
'''
Given a linked list, remove the n-th node from the end of list and return its head.
Example:
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Follow up:
Could you do this in one pass?
'''
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
dummpy = ListNode(None)
dummpy.next = head
def delete(node):
if not node: return 0
index = delete(node.next) + 1
if index == n+1:
node.next = node.next.next
return index
delete(dummpy)
return dummpy.next |
'''
Given a sorted linked list, delete all duplicates such that each element appear only once.
Example 1:
Input: 1->1->2
Output: 1->2
Example 2:
Input: 1->1->2->3->3
Output: 1->2->3
'''
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
startnode = ListNode(None)
startnode.next = head
have = None
pre = None
while head:
if head.val == have:
pre.next = head.next
head = head.next
else:
have = head.val
pre = head
head = head.next
return startnode.next
class Solution:
def removeNthFromEnd(self, head, n):
fast = slow = head
for _ in range(n):
fast = fast.next
if not fast:
return head.next
while fast.next:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return head |
'''
Given a string s, find the longest palindromic subsequence's length in s. You may assume that the maximum length of s is 1000.
Example 1:
Input:
"bbbab"
Output:
4
One possible longest palindromic subsequence is "bbbb".
Example 2:
Input:
"cbbd"
Output:
2
One possible longest palindromic subsequence is "bb".
'''
|
'''
Given a string, your task is to count how many palindromic substrings in this string.
The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.
Example 1:
Input: "abc"
Output: 3
Explanation: Three palindromic strings: "a", "b", "c".
Example 2:
Input: "aaa"
Output: 6
Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
Note:
The input string length won't exceed 1000.
'''
class Solution(object):
def countSubstrings(self, s):
"""
:type s: str
:rtype: int
"""
size = len(s)
queue = collections.deque((i, i) for i in range(size))
for i in range(size - 1):
if s[i] == s[i + 1]:
queue.append((i, i + 1))
ans = 0
while queue:
x, y = queue.popleft()
ans += 1
if x - 1 >= 0 and y + 1 < size and s[x - 1] == s[y + 1]:
queue.append((x - 1, y + 1))
return ans
|
# Uses python3
import sys
def get_optimal_value(capacity, weights, values):
value = 0.
for (v, w) in sorted([(v / w, w) for (w, v) in zip(weights, values)], reverse=True):
value += min(capacity, w) * v
capacity -= w
if (capacity <= 0):
break
return value
if __name__ == "__main__":
data = list(map(int, sys.stdin.read().split()))
n, capacity = data[0:2]
values = data[2:(2 * n + 2):2]
weights = data[3:(2 * n + 2):2]
opt_value = get_optimal_value(capacity, weights, values)
print("{:.10f}".format(opt_value))
|
weight = int(input("weight: "))
unit = input("lbs or kgs:choose L or K ")
if unit.upper() == "L":
conversion_1 = weight / 2.2
print(f'You are {conversion_1} kgs')
else:
conversion_2 = weight * 2.2
print(f'You are {conversion_2} lbs') |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
"""Several planned features that are under discussion / not implemented yet."""
from __future__ import annotations
from .annotation import MutableAnnotation
from .mutable import LabeledMutable, MutableSymbol, Categorical, Numerical
def randint(label: str, lower: int, upper: int) -> Categorical[int]:
"""Choosing a random integer between lower (inclusive) and upper (exclusive).
Currently it is translated to a :func:`choice`.
This behavior might change in future releases.
Examples
--------
>>> nni.randint('x', 1, 5)
Categorical([1, 2, 3, 4], label='x')
"""
return RandomInteger(lower, upper, label=label)
def lognormal(label: str, mu: float, sigma: float) -> Numerical:
"""Log-normal (in the context of NNI) is defined as the exponential transformation of a normal random variable,
with mean ``mu`` and deviation ``sigma``. That is::
exp(normal(mu, sigma))
In another word, the logarithm of the return value is normally distributed.
Examples
--------
>>> nni.lognormal('x', 4., 2.)
Numerical(-inf, inf, mu=4.0, sigma=2.0, log_distributed=True, label='x')
>>> nni.lognormal('x', 0., 1.).random()
2.3308575497749584
>>> np.log(x) for x in nni.lognormal('x', 4., 2.).grid(granularity=2)]
[2.6510204996078364, 4.0, 5.348979500392163]
"""
return Numerical(mu=mu, sigma=sigma, log_distributed=True, label=label)
def qlognormal(label: str, mu: float, sigma: float, quantize: float) -> Numerical:
"""A combination of :func:`qnormal` and :func:`lognormal`.
Similar to :func:`qloguniform`, the quantize is done **after** the sample is drawn from the log-normal distribution.
Examples
--------
>>> nni.qlognormal('x', 4., 2., 1.)
Numerical(-inf, inf, mu=4.0, sigma=2.0, q=1.0, log_distributed=True, label='x')
"""
return Numerical(mu=mu, sigma=sigma, log_distributed=True, quantize=quantize, label=label)
class Permutation(MutableSymbol):
"""Get a permutation of several values.
Not implemented. Kept as a placeholder.
"""
class RandomInteger(Categorical[int]):
"""Sample from a list of consecutive integers.
Kept as a placeholder.
:class:`Categorical` is a more general version of this class,
but this class gives better semantics,
and is consistent with the old ``randint``.
"""
def __init__(self, lower: int, upper: int, label: str | None = None) -> None:
if not isinstance(lower, int) or not isinstance(upper, int):
raise TypeError('lower and upper must be integers.')
if lower >= upper:
raise ValueError('lower must be strictly smaller than upper.')
super().__init__(list(range(lower, upper)), label=label)
class NonNegativeRandomInteger(RandomInteger):
"""Sample from a list of consecutive natural integers, counting from 0.
Kept as a placeholder.
:class:`Categorical` and :class:`RandomInteger`
can be simplified to this class for simpler processing.
"""
pass
class UnitUniform(Numerical):
"""Sample from a uniform distribution in [0, 1).
Not implemented yet.
:class:`Numerical` can be simplified to this class for simpler processing.
"""
def __init__(self, *, label: str | None = None) -> None:
super().__init__(low=0.0, high=1.0, label=label)
class JointDistribution(MutableAnnotation):
"""Mutual-correlated distribution among multiple variables.
Not implemented yet.
"""
pass
class Graph(LabeledMutable):
"""Graph structure.
Not implemented yet.
"""
pass
class GraphAnnotation(MutableAnnotation):
"""When a graph is broken down into simple :class:`MutableSymbol` and :class:`MutableAnnotation`.
Not implemented yet."""
pass
|
"""
Hello, NAS!
===========
This is the 101 tutorial of Neural Architecture Search (NAS) on NNI.
In this tutorial, we will search for a neural architecture on MNIST dataset with the help of NAS framework of NNI, i.e., *Retiarii*.
We use multi-trial NAS as an example to show how to construct and explore a model space.
There are mainly three crucial components for a neural architecture search task, namely,
* Model search space that defines a set of models to explore.
* A proper strategy as the method to explore this model space.
* A model evaluator that reports the performance of every model in the space.
Currently, PyTorch is the only supported framework by Retiarii, and we have only tested **PyTorch 1.9 to 1.13**.
This tutorial assumes PyTorch context but it should also apply to other frameworks, which is in our future plan.
Define your Model Space
-----------------------
Model space is defined by users to express a set of models that users want to explore, which contains potentially good-performing models.
In this framework, a model space is defined with two parts: a base model and possible mutations on the base model.
"""
# %%
#
# Define Base Model
# ^^^^^^^^^^^^^^^^^
#
# Defining a base model is almost the same as defining a PyTorch (or TensorFlow) model.
#
# Below is a very simple example of defining a base model.
import torch
import torch.nn as nn
import torch.nn.functional as F
import nni
from nni.nas.nn.pytorch import LayerChoice, ModelSpace, MutableDropout, MutableLinear
class Net(ModelSpace): # should inherit ModelSpace rather than nn.Module
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(1, 32, 3, 1)
self.conv2 = nn.Conv2d(32, 64, 3, 1)
self.dropout1 = nn.Dropout(0.25)
self.dropout2 = nn.Dropout(0.5)
self.fc1 = nn.Linear(9216, 128)
self.fc2 = nn.Linear(128, 10)
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.max_pool2d(self.conv2(x), 2)
x = torch.flatten(self.dropout1(x), 1)
x = self.fc2(self.dropout2(F.relu(self.fc1(x))))
output = F.log_softmax(x, dim=1)
return output
# %%
#
# Define Model Variations
# ^^^^^^^^^^^^^^^^^^^^^^^
#
# A base model is only one concrete model not a model space. We provide :doc:`API and Primitives </nas/construct_space>`
# for users to express how the base model can be mutated. That is, to build a model space which includes many models.
#
# Based on the above base model, we can define a model space as below.
#
# .. code-block:: diff
#
# class Net(ModelSpace):
# def __init__(self):
# super().__init__()
# self.conv1 = nn.Conv2d(1, 32, 3, 1)
# - self.conv2 = nn.Conv2d(32, 64, 3, 1)
# + self.conv2 = LayerChoice([
# + nn.Conv2d(32, 64, 3, 1),
# + DepthwiseSeparableConv(32, 64)
# + ], label='conv2)
# - self.dropout1 = nn.Dropout(0.25)
# + self.dropout1 = MutableDropout(nni.choice('dropout', [0.25, 0.5, 0.75]))
# self.dropout2 = nn.Dropout(0.5)
# - self.fc1 = nn.Linear(9216, 128)
# - self.fc2 = nn.Linear(128, 10)
# + feature = nni.choice('feature', [64, 128, 256])
# + self.fc1 = MutableLinear(9216, feature)
# + self.fc2 = MutableLinear(feature, 10)
#
# def forward(self, x):
# x = F.relu(self.conv1(x))
# x = F.max_pool2d(self.conv2(x), 2)
# x = torch.flatten(self.dropout1(x), 1)
# x = self.fc2(self.dropout2(F.relu(self.fc1(x))))
# output = F.log_softmax(x, dim=1)
# return output
#
# This results in the following code:
class DepthwiseSeparableConv(nn.Module):
def __init__(self, in_ch, out_ch):
super().__init__()
self.depthwise = nn.Conv2d(in_ch, in_ch, kernel_size=3, groups=in_ch)
self.pointwise = nn.Conv2d(in_ch, out_ch, kernel_size=1)
def forward(self, x):
return self.pointwise(self.depthwise(x))
class MyModelSpace(ModelSpace):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(1, 32, 3, 1)
# LayerChoice is used to select a layer between Conv2d and DwConv.
self.conv2 = LayerChoice([
nn.Conv2d(32, 64, 3, 1),
DepthwiseSeparableConv(32, 64)
], label='conv2')
# nni.choice is used to select a dropout rate.
# The result can be used as parameters of `MutableXXX`.
self.dropout1 = MutableDropout(nni.choice('dropout', [0.25, 0.5, 0.75])) # choose dropout rate from 0.25, 0.5 and 0.75
self.dropout2 = nn.Dropout(0.5)
feature = nni.choice('feature', [64, 128, 256])
self.fc1 = MutableLinear(9216, feature)
self.fc2 = MutableLinear(feature, 10)
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.max_pool2d(self.conv2(x), 2)
x = torch.flatten(self.dropout1(x), 1)
x = self.fc2(self.dropout2(F.relu(self.fc1(x))))
output = F.log_softmax(x, dim=1)
return output
model_space = MyModelSpace()
model_space
# %%
# This example uses two mutation APIs,
# :class:`nn.LayerChoice <nni.nas.nn.pytorch.LayerChoice>` and
# :func:`nni.choice`.
# :class:`nn.LayerChoice <nni.nas.nn.pytorch.LayerChoice>`
# takes a list of candidate modules (two in this example), one will be chosen for each sampled model.
# It can be used like normal PyTorch module.
# :func:`nni.choice` is used as parameter of `MutableDropout`, which then takes the result as dropout rate.
#
# More detailed API description and usage can be found :doc:`here </nas/construct_space>`.
#
# .. note::
#
# We are actively enriching the mutation APIs, to facilitate easy construction of model space.
# If the currently supported mutation APIs cannot express your model space,
# please refer to :doc:`this doc </nas/mutator>` for customizing mutators.
#
# Explore the Defined Model Space
# -------------------------------
#
# There are basically two exploration approaches: (1) search by evaluating each sampled model independently,
# which is the search approach in :ref:`multi-trial NAS <multi-trial-nas>`
# and (2) one-shot weight-sharing based search, which is used in one-shot NAS.
# We demonstrate the first approach in this tutorial. Users can refer to :ref:`here <one-shot-nas>` for the second approach.
#
# First, users need to pick a proper exploration strategy to explore the defined model space.
# Second, users need to pick or customize a model evaluator to evaluate the performance of each explored model.
#
# Pick an exploration strategy
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#
# NNI NAS supports many :doc:`exploration strategies </nas/exploration_strategy>`.
#
# Simply choosing (i.e., instantiate) an exploration strategy as below.
import nni.nas.strategy as strategy
search_strategy = strategy.Random() # dedup=False if deduplication is not wanted
# %%
# Pick or customize a model evaluator
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#
# In the exploration process, the exploration strategy repeatedly generates new models. A model evaluator is for training
# and validating each generated model to obtain the model's performance.
# The performance is sent to the exploration strategy for the strategy to generate better models.
#
# NNI NAS has provided :doc:`built-in model evaluators </nas/evaluator>`, but to start with,
# it is recommended to use :class:`FunctionalEvaluator <nni.nas.evaluator.FunctionalEvaluator>`,
# that is, to wrap your own training and evaluation code with one single function.
# This function should receive one single model class and uses :func:`nni.report_final_result` to report the final score of this model.
#
# An example here creates a simple evaluator that runs on MNIST dataset, trains for 2 epochs, and reports its validation accuracy.
import nni
from torchvision import transforms
from torchvision.datasets import MNIST
from torch.utils.data import DataLoader
def train_epoch(model, device, train_loader, optimizer, epoch):
loss_fn = torch.nn.CrossEntropyLoss()
model.train()
for batch_idx, (data, target) in enumerate(train_loader):
data, target = data.to(device), target.to(device)
optimizer.zero_grad()
output = model(data)
loss = loss_fn(output, target)
loss.backward()
optimizer.step()
if batch_idx % 10 == 0:
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
epoch, batch_idx * len(data), len(train_loader.dataset),
100. * batch_idx / len(train_loader), loss.item()))
def test_epoch(model, device, test_loader):
model.eval()
test_loss = 0
correct = 0
with torch.no_grad():
for data, target in test_loader:
data, target = data.to(device), target.to(device)
output = model(data)
pred = output.argmax(dim=1, keepdim=True)
correct += pred.eq(target.view_as(pred)).sum().item()
test_loss /= len(test_loader.dataset)
accuracy = 100. * correct / len(test_loader.dataset)
print('\nTest set: Accuracy: {}/{} ({:.0f}%)\n'.format(
correct, len(test_loader.dataset), accuracy))
return accuracy
def evaluate_model(model):
# By v3.0, the model will be instantiated by default.
device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
model.to(device)
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
transf = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))])
train_loader = DataLoader(MNIST('data/mnist', download=True, transform=transf), batch_size=64, shuffle=True)
test_loader = DataLoader(MNIST('data/mnist', download=True, train=False, transform=transf), batch_size=64)
for epoch in range(3):
# train the model for one epoch
train_epoch(model, device, train_loader, optimizer, epoch)
# test the model for one epoch
accuracy = test_epoch(model, device, test_loader)
# call report intermediate result. Result can be float or dict
nni.report_intermediate_result(accuracy)
# report final test result
nni.report_final_result(accuracy)
# %%
# Create the evaluator
from nni.nas.evaluator import FunctionalEvaluator
evaluator = FunctionalEvaluator(evaluate_model)
# %%
#
# The ``train_epoch`` and ``test_epoch`` here can be any customized function,
# where users can write their own training recipe.
#
# It is recommended that the ``evaluate_model`` here accepts no additional arguments other than ``model``.
# However, in the :doc:`advanced tutorial </nas/evaluator>`, we will show how to use additional arguments in case you actually need those.
# In future, we will support mutation on the arguments of evaluators, which is commonly called "Hyper-parameter tuning".
#
# Launch an Experiment
# --------------------
#
# After all the above are prepared, it is time to start an experiment to do the model search. An example is shown below.
from nni.nas.experiment import NasExperiment
exp = NasExperiment(model_space, evaluator, search_strategy)
# %%
# Different from HPO experiment, NAS experiment will generate an experiment config automatically.
# It should work for most cases. For example, when using multi-trial strategies,
# local training service with concurrency 1 will be used by default.
# Users can customize the config. For example,
exp.config.max_trial_number = 3 # spawn 3 trials at most
exp.config.trial_concurrency = 1 # will run 1 trial concurrently
exp.config.trial_gpu_number = 0 # will not use GPU
# %%
# Remember to set the following config if you want to GPU.
# ``use_active_gpu`` should be set true if you wish to use an occupied GPU (possibly running a GUI)::
#
# exp.config.trial_gpu_number = 1
# exp.config.training_service.use_active_gpu = True
#
# Launch the experiment. The experiment should take several minutes to finish on a workstation with 2 GPUs.
exp.run(port=8081)
# %%
# Users can also run NAS Experiment with :doc:`different training services </experiment/training_service/overview>`
# besides ``local`` training service.
#
# Visualize the Experiment
# ------------------------
#
# Users can visualize their experiment in the same way as visualizing a normal hyper-parameter tuning experiment.
# For example, open ``localhost:8081`` in your browser, 8081 is the port that you set in ``exp.run``.
# Please refer to :doc:`here </experiment/web_portal/web_portal>` for details.
#
# We support visualizing models with 3rd-party visualization engines (like `Netron <https://netron.app/>`__).
# This can be used by clicking ``Visualization`` in detail panel for each trial.
# Note that current visualization is based on `onnx <https://onnx.ai/>`__ ,
# thus visualization is not feasible if the model cannot be exported into onnx.
#
# Built-in evaluators (e.g., Classification) will automatically export the model into a file.
# For your own evaluator, you need to save your file into ``$NNI_OUTPUT_DIR/model.onnx`` to make this work.
# For instance,
import os
from pathlib import Path
def evaluate_model_with_visualization(model):
# dump the model into an onnx
if 'NNI_OUTPUT_DIR' in os.environ:
dummy_input = torch.zeros(1, 3, 32, 32)
torch.onnx.export(model, (dummy_input, ),
Path(os.environ['NNI_OUTPUT_DIR']) / 'model.onnx')
evaluate_model(model)
# %%
# Relaunch the experiment, and a button is shown on Web portal.
#
# .. image:: ../../img/netron_entrance_webui.png
#
# Export Top Models
# -----------------
#
# Users can export top models after the exploration is done using ``export_top_models``.
for model_dict in exp.export_top_models(formatter='dict'):
print(model_dict)
|
import datetime
def today():
now = datetime.datetime.now()
return now.strftime('%Y%m%d')
days = ['20180422', '20180423', '20180424','20180425', '20180426', '20180427', '20180428']
def td(t=0):
day = today()
td = '19700101'
for i,d in enumerate(days):
if d >= day:
td = days[i+t]
break
return td
def test_trade_day():
assert '20180422' == td(-3)
assert '20180426' == td(1)
|
# Core Modules
import datetime
from datetime import date
today=date.today()
#today=datetime.date.today()
print(today)
import time
from time import time
timestamps=time()
#timestamps=time.time()
print(timestamps)
# ------------------------
# -----------------------
##pip module
from camelcase import CamelCase
c=CamelCase()
print(c.hump('hello world'))
# -----------------------
##file module
import validator
from validator import validate_email
email='[email protected]'
if validate_email(email):
print('email is valid.')
else:
print('email is bad.')
#############################################################
from random import randint
x=randint(-100,100)
while x ==0: # make sure x is not zero
x=randint(-100,100)
y=randint(-100,100)
while y==0: # make sure y is not zero
y=randint(-100,100)
if x>0 and y>0:
print('both positive')
elif x<0 and y<0:
print('both negative')
elif x>0 and y<0:
print("x is positive and y is negative")
else:
print('y is positive and y is negative')
###########################################################
# from random import choice,randint
# actually_sick=choice([True,False])
# kinda_sick=choice([True,False])
# hate_your_job=choice([True,False])
# sick_days=randint(0,10)
# calling_in_sick=None
# if actually_sick and sick_days>0:
# calling_in_sick=True
# elif kinda_sick and hate_your_job and sick_days>0:
# calling_in_sick=True
# else:
# calling_in_sick=False |
# A Dictionary is a collection which is unordered, changeable and indexed. No duplicate members.
# Create dict
person1={
'name':'bob smith',
'email':'[email protected]',
'city':'boston',
'age':22
}
print(type(person1),person1)
# Use constructor
person2=dict(name='john doe',email='[email protected]',city='london',age=25)
print(type(person2),person2)
# Get value
print(person1['name'])
print(person1.get('email'))
print(person2['city'])
# Add key/value
person1['job']='developer'
print(person1)
# Get dict keys
print(person1.keys())
# Get dict items
print(person1.items())
# Copy dict
person2=person1.copy()
person2['city']='berlin'
print(person2)
# Remove item
del(person1['job'])
print(person1)
#Remove with pop
person1.pop('email')
print(person1)
# Clear
person1.clear()
print(person1)
# Get length
print(len(person2))
# List of dict
people=[
{
'name':'jack peter',
'hobbies':['hiking','movies','sports'],
'facebook':'www.facebook.com/profile.php?id=6789'
},
{
'name':'jemi jack',
'hobbies':['bass guitar','coding','music'],
'twitter':'www.twitter.com/@jemi34'
}
]
print(type(people),people)
print(people[0]['name'])
print(people[1]['hobbies'][2]) |
#!/usr/bin/env python
def miles(kilometers: float) -> float:
"""
:param kilometers: float
:return: float
"""
return kilometers * 1.6
print(miles(2))
print(miles(3))
print(miles(4))
|
#!/usr/bin/env python
ph = float(input('Enter pH number: '))
if ph < 7.0:
print(ph, 'It is acidic')
if ph > 7.0:
print(ph, 'it is basic')
|
#!/usr/bin/env python
population = input("Please enter population value: ")
print("You have entered: ", population)
|
#!/usr/bin/env python
def average(grade1, grade2, grade3):
"""
Specify the grade between 0 and 100
:param grade1: number
:param grade2: number
:param grade3: number
:return: number
"""
return (grade1 + grade2 + grade3) / 3
print(average(30, 30, 30))
print(average(20,17,38))
|
#!/usr/bin/env python
rat_1 = [111, 112, 113, 114, 115, 116, 117, 118, 119, 120]
rat_2 = [101, 122, 117, 104, 110, 126, 137, 108, 109, 102]
if rat_1[0] > rat_2[0]:
print("Rat 1 weighed more than rat 2 on day 1")
else:
print("Rat 1 weighed less than rat 2 on day 1.")
if rat_1[0] > rat_2[0] and rat_1[9] > rat_2[9]:
print("Rat 1 remained heavier than Rat 2.")
else:
print("Rat 2 became heavier than Rat 1.")
if rat_1[0] > rat_2[0]:
if rat_1[-1] > rat_2[-1]:
print("Rat 1 remained heavier than Rat 2.")
else:
print("Rat 2 became heavier than Rat 1.")
else:
print("Rat 2 became heavier than Rat 1.") |
"""Genetic algorithms methods for the travelling salesman problem."""
import random
import handies as hf
from collections import OrderedDict
cities = OrderedDict()
# cities_names = []
# cities_indices = []
EARTH_RADIUS = 6371
class Salesman(object):
"""salesman travelling around European Union.
Attr.:
city_seq - order in which the salesman visits cities
fitness - 1.0 / <time salesman needs to visit all cities>
(and come back to starting point without visitting any city more than once)
velocity_eu - velocity everywhere in EU except for Poland
velocity_pol - velocity in Poland
diploid - whether we use haploidal or diploidal encoding (boolean)
for diploid:
city_seq2 - second sequence
fitness1 - fitness of city_seq
fitness2 - fitness of city_seq2
fitness - better of the two above
best_seq - better of the two sequences
"""
velocity_eu = 70
velocity_pol = 50
diploid = False
def __init__(self, city_seq, temp=False, city_seq2=None):
"""initialize a salesman.
city_seq - sequence of cities for salesman's journey
city = point in space
temp - temporary salesman, i.e. dont calculate fitness
we dont need fitness being recalculated after crossover for example
we just need it for the selection process, and so we can save some time
"""
self.city_seq = city_seq
if not self.diploid:
if not temp:
self.fitness = self._fitness()
else:
if not city_seq2:
self.city_seq2 = random.sample(
list(cities.values()), len(cities))
else:
self.city_seq2 = city_seq2
if not temp:
self.fitness1, self.fitness2 = self._fitnesses()
self.fitness = max(self.fitness1, self.fitness2)
self.best_seq = self.city_seq if self.fitness == self.fitness1 \
else self.city_seq2
def _fitness(self):
"""return fitness for the salesman."""
t = hf.timelength(self.city_seq, v1=self.velocity_eu,
v2=self.velocity_pol)
if t != 0:
return 1.0 / t
else:
return float('inf')
def _fitnesses(self):
"""return fitnesses for city_seq and city_seq2."""
t1 = hf.timelength(self.city_seq, v1=self.velocity_eu,
v2=self.velocity_pol)
t2 = hf.timelength(self.city_seq2, v1=self.velocity_eu,
v2=self.velocity_pol,)
if t1 != 0:
t1 = 1.0 / t1
else:
t1 = float('inf')
if t2 != 0:
t2 = 1.0 / t2
else:
t2 = float('inf')
return t1, t2
def mfp(n=10):
"""make first population of n salesmen."""
if n % 2 != 0:
n += 1
salesmen = []
sapp = salesmen.append
v = list(cities.values())
for _ in range(n):
nu_v = random.sample(v, len(v))
sapp(Salesman(nu_v))
return salesmen
def crossingover(population=None, pc=0.9):
"""return children of salesmen."""
if population is None:
return None
else:
children = []
children_app = children.append
parents = [random.sample(population, 2)
for _ in range(len(population) // 2)]
for p1, p2 in parents:
r = random.random()
if pc > r:
if Salesman.diploid:
c1, c2 = cxOX(p1.city_seq, p2.city_seq)
c3, c4 = cxOX(p1.city_seq2, p2.city_seq2)
# dont recalc. fitness: temp=True
children_app(Salesman(c1, city_seq2=c3, temp=True))
children_app(Salesman(c2, city_seq2=c4, temp=True))
else:
c1, c2 = cxOX(p1.city_seq, p2.city_seq)
children_app(Salesman(c1, temp=True))
children_app(Salesman(c2, temp=True))
else:
children_app(p1)
children_app(p2)
return children
def mutation(population=None, pm=1e-4):
"""return mutated population."""
if population is None:
return None
else:
mutants = []
mutants_app = mutants.append
for s in population:
city_seq = mutate(s.city_seq, pm)
if Salesman.diploid:
city_seq2 = mutate(s.city_seq2, pm)
mutants_app(Salesman(city_seq, city_seq2=city_seq2))
else:
mutants_app(Salesman(city_seq))
return mutants
def cxOX(sequence1, sequence2):
"""ordered crossover method."""
r1 = random.randint(0, len(sequence1))
# not len()-1 because i'll be slicing
r2 = random.randint(0, len(sequence2))
if r1 > r2:
r1, r2 = r2, r1
elif r1 == r2:
if r2 < len(sequence1):
r2 += 1
else:
r1 -= 1
middle1 = sequence1[r1:r2]
middle2 = sequence2[r1:r2]
# child no. 1
c1 = [city for city in sequence2[:r1]
if city not in middle1 and city not in middle2]
c1 += middle2
c1 += [city for city in sequence2[r2:]
if city not in middle1 and city not in c1]
c1 += [city for city in middle1 if city not in c1]
# child no. 2
c2 = [city for city in sequence1[:r1]
if city not in middle1 and city not in middle2]
c2 += middle1
c2 += [city for city in sequence1[r2:]
if city not in middle1 and city not in c2]
c2 += [city for city in middle2 if city not in c2]
return c1, c2
def mutate(city_sequence, indpm=0.05):
"""mutate sequence, return mutant."""
city_seq = city_sequence
for ii in range(len(city_seq)):
if indpm > random.random():
jj = random.randint(0, len(city_seq) - 1)
if ii == jj:
if jj < len(city_seq) - 1:
jj += 1
else:
jj -= 1
city_seq[ii], city_seq[jj] = city_seq[jj], city_seq[ii]
return city_seq
def selTournament(individuals, k, tournsize):
"""return k new individuals selected via tournament method.
copied from DEAP (Distributed Evolutionary Algorithms in Python)
https://github.com/DEAP/deap
and modified a bit so that it works with my Salesman class
"""
chosen = []
for i in range(k):
aspirants = [random.choice(individuals) for i in range(tournsize)]
chosen.append(max(aspirants, key=lambda x: x.fitness))
return chosen
def evolution(population, pm=1e-4, pc=0.9, tournsize=3):
"""evolve system, return changed population."""
population = selTournament(population, k=len(population),
tournsize=tournsize)
population = crossingover(population, pc=pc)
population = mutation(population, pm=pm)
return population
def findbest(population, k=1):
"""return k best individuals."""
if k == 1:
bf = 0
ind = 0
for ii, x in enumerate(population):
if x.fitness > bf:
bf = x.fitness
ind = ii
return population[ind]
elif k < 1:
return None
else:
return sorted(population, key=lambda s: s.fitness, reverse=True)[:k]
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 14 10:01:23 2019
@author: saurabh
"""
import random
cond=True
count=0
t=(random.randint(1,100))
while(cond):
user=int(input("Enter number : "))
if t>user:
print("enter greater number")
count+=1
elif t<user:
print("enter less number")
count+=1
else:
print("Congratulations!!!!!!!")
count+=1
print("You guessed in",count,"times")
cond=False
|
# Needed modules will be imported and configured.
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
# Output pin declaration for the LEDs.
LED_Red = 2
LED_Green = 3
GPIO.setup(LED_Red, GPIO.OUT, initial= GPIO.LOW)
GPIO.setup(LED_Green, GPIO.OUT, initial= GPIO.LOW)
print("LED-Test [press ctrl+c to end the test]")
# Main program loop
try:
while True:
print("LED Red will be on for 3 seconds")
GPIO.output(LED_Red,GPIO.HIGH) #LED will be switched on
GPIO.output(LED_Green,GPIO.LOW) #LED will be switched off
time.sleep(3) # Waitmode for 3 seconds
print("LED Green will be on for 3 seconds")
GPIO.output(LED_Red,GPIO.LOW) #LED will be switched off
GPIO.output(LED_Green,GPIO.HIGH) #LED will be switched on
time.sleep(3) #Waitmode for another 3 seconds in which the LEDs are shifted
# Scavenging work after the end of the program
except KeyboardInterrupt:
GPIO.cleanup()
|
#!/usr/bin/env python3
import itertools
def example():
data = """1721
979
366
299
675
1456""".splitlines()
a, b = list(
filter(
lambda p: p[0] + p[1] == 2020,
itertools.combinations((int(s) for s in data), 2),
)
)[0]
print(f"example: {a*b == 514579}")
def problem1(input_lines):
a, b = list(
filter(
lambda p: p[0] + p[1] == 2020,
itertools.combinations((int(s) for s in input_lines), 2),
)
)[0]
print(f"problem 1: {a*b}")
def problem2(input_lines):
a, b, c = list(
filter(
lambda p: p[0] + p[1] + p[2] == 2020,
itertools.combinations((int(s) for s in input_lines), 3),
)
)[0]
print(f"problem 2: {a*b*c}")
if __name__ == "__main__":
example()
with open("input.txt", "r") as f:
contents = f.readlines()
problem1(contents)
problem2(contents)
|
# Your team is scrambling to decipher a recent message, worried it's a plot to break into a major European National Cake Vault.
# The message has been mostly deciphered, but all the words are backward! Your colleagues have handed off the last step to you.
# Write a function reverse_words() that takes a message as a list of characters and reverses the order of the words in place. ↴
message = [ 'c', 'a', 'k', 'e', ' ',
'p', 'o', 'u', 'n', 'd', ' ',
's', 't', 'e', 'a', 'l' ]
message2 = [ 't', 'h', 'e', ' ', 'e', 'a', 'g', 'l', 'e', ' ',
'h', 'a', 's', ' ', 'l', 'a', 'n', 'd', 'e', 'd' ]
message3 = [ 'a', ' ', 'b', 'b', ' ', 'c', ' ', 'd', 'd', ' ',
'e', ' ', 'f', 'f', ' ', 'g', ' ', 'h', 'h' ]
# message1 = ['t','h','e', ' ', 'b','r',own dog jumped over the lazy fox]
# Edge Cases:
# If the word at the end doesnt have a space
# question: are one letters consider a word an can you give me an example of that input
# First solution that comes to mind (talk out loud through typing in this case)
# So the first thing that comes in mind is that I can reverse the the list which means reversing everything in the list.
# Reverse all the characters in list
# flip all words when theres a space to the original word and store that in a temp variable
# How would I store it? I would do a temp.insert(0,x) for every letter the loop is going through. This way we get the original word back
# and replace it with flipped wdord
# I would need a start_variable
#
# O(n) solution with O(1) space complexity
# Questions
# the last word would be adjusted for an edgecase?
def reverse_characters(message):
right = len(message) - 1
temp = ''
for i in range(int(len(message)/2)):
temp = message[i]
message[i] = message[right]
message[right] = temp
right -= 1
return message
print(message)
print(reverse_characters(message))
def reverse_list(message):
message = reverse_characters(message)
temp = []
start = 0
for i, x in enumerate(message):
if x == ' ' or i == len(message)-1:
if len(message)-1 == i:
temp.insert(0,x)
message.pop()
message[start:i] = temp
if i != len(message)-1:
start = i+1
temp = []
else:
temp.insert(0,x)
return message
# print(message2)
# print(reverse_list(message2))
# print(message3)
# print(reverse_list(message3)) |
from csp.variables import Variable
class Problem:
"""Class that represents a csp problem."""
def __init__(self):
self.variables = []
self.constraints = []
def add_variable(self, to_add):
"""Adds one or more variables to this problem.
It doesn't check if variables have already been added to this problem.
:param to_add: The variable[s] to add
:type to_add: Variable or list
"""
if isinstance(to_add, Variable):
self.variables.append(to_add)
else:
for x in to_add:
self.add_variable(x)
def add_constraint(self, constr):
"""Adds a constraint to this problem.
It doesn't check if constraint has already been added to this problem.
:param constr: The constraint to add
:type constr: Constraint
"""
self.constraints.append(constr)
def is_solved(self):
"""Checks if this problem is solved.
Partial assignment is not a solution, even if it satisfies all constraints.
"""
for v in self.variables:
if not v.is_instantiated():
return False
for c in self.constraints:
if not c.is_satisfied():
return False
return True
|
from abc import ABC, abstractmethod
class DomainOrderingStrategy(ABC):
"""Abstract class for a variable domain ordering strategy."""
def __init__(self):
self.var = None
def setup(self, problem, propagator):
"""Called to initialize this ordering strategy with problem data.
:param problem: The csp
:param propagator: The solver propagator
:type problem: Problem
:type propagator: Propagator
"""
pass
@abstractmethod
def ordered_domain(self):
"""Returns a copy of var domain ordered using certain strategy.
:return: An ordered copy of var domain
:rtype: list
"""
pass
|
"write a pattern for recognizing a string which must contain at least two of the following words: legal, Trump, policy"
import re
def check_orangeman(text:str)->bool:
# Trump=r"Trump"
# legal=r"Legal"
# policy=r"policy"
words="(Trump|legal|policy).*(?!\1)(Trump|legal|policy)"
if(re.search(words,text)):
return True
else:
return False
text=r"Mister Trump has adopted a new policy where he only allows muricans to have two guns. Of course this policy has made all the rednecks crazy: How are we gonna kill kids in the schools? This is not legal "
if __name__ == "__main__":
print(text)
print(check_orangeman(text))
|
class Node:
"""
Class which represent a tree as a node, it use more or less the same notation as we used in prolog,
the only difference is that here we omit the nil value when there is an empty node.
"""
def __init__(self, value, left=None, right=None):
"""
Constructor for a node, the sub-trees can be omitted if there is no value for these.
:param value: The node payload.
:param left: the left sub-tree (defined as another Node)
:param right: the right sub-tree (defined as another Node)
"""
self.left = left
self.right = right
self.value = value
def number_leaves(tree: Node):
if not tree:
return 0
if tree.value and not tree.right and not tree.left:
return 1
return number_leaves(tree.left) + number_leaves(tree.right)
if __name__ == "__main__":
print(number_leaves(Node(1,Node(1),Node(1,Node(1,Node(1),Node(1)))))) |
#Program 9 Chapter 1
#Name: string rotation
# #Runtime: O(n)
#Date: 4/2/2019
#Notes: Given s1 (the unrotated string) and s2 (the rotated string), s2 will always be a substring of s1s1.
def rotation(str1, str2):
if len(str1) == len(str2):
str1str1 = str1 + str1
if str2 in str1str1:
return True
return False
else:
return False
print(rotation("waterbottle", "erbottlewat")) #true
print(rotation("waterbottle", "elbottlewat")) #false |
#Program 5 Chapter 1
#Name: One Away
#Runtime: O(n)
#Date: 4/1/2019
#Notes: The removed letter may not be duplicated in a row. For example, bye and byee will not work, since you can remove either one of the e's.
#However, it will work if they are separated by at least one other char, like bye and beye.
def oneAway(str1, str2):
if (len(str1) == len(str2)):
return replace(str1, str2)
elif (len(str1)+1 == len(str2)): #str2 is longer by 1
return switchOne(str1, str2)
elif (len(str2)+1 == len(str1)): #str1 is longer by 1
return switchOne(str2, str1)
else:
return False
#return true if there is a one char difference between the two strings
def replace(str1, str2):
diff=0 #keep track of the number of differences
for x in range(len(str1)):
if (str1[x] != str2[x]):
diff+=1
if diff >=2:
return False
else:
return True
#return true if you can take one letter out of str2 and make it equal to str1
#otherwise, return false
def switchOne(str1, str2): #str1 is smaller, str2 is larger
count=0
for x in range(len(str2)):
if str1 == sliceString(str2, x):
count+=1
if count==1:
return True
else:
return False
#returns string with the char at the specified index sliced out
def sliceString(str, index):
newstr=''
for x in range(len(str)):
if x!=index:
newstr+=str[x]
return newstr
print(oneAway("hello", "heeloh")) #false
print(oneAway("bye", "byee")) #false
print(oneAway("bye", "byea")) #true
print(oneAway("bye", "beye")) #true |
# Implement a class to hold room information. This should have name and
# description attributes.
class Room:
"""Room object has a name and text"""
possible_moves = ["n_to", "s_to", "e_to", "w_to"]
def __init__(self, name, text, items=None):
self.name = name
self.text = text
if items is None:
self.items = []
else:
self.items = items[:]
self.n_to = None
self.s_to = None
self.e_to = None
self.w_to = None
def get_possible_moves(self):
"""
uses the static list possible moves to generate a list of directions available from a room
"""
return [mov[:1] for mov in Room.possible_moves if getattr(self, mov) is not None]
def display(self):
print(
f"""{self.name}
\n {self.text}""")
if len(self.items) > 0:
print("\nYou see some items nearby: ")
print(*[item.name for item in self.items], sep=", ")
print("\nPossible Moves: ")
print(*self.get_possible_moves(), sep=", ")
|
# !/user/bin/env python
# _*_ coding: utf-8 _*_
# @Time : 2021/6/8 11:27
# @Author : 王俊
# @File : hashmap.py
# @Software : PyCharm
"""
Entry表示一个Key-value键值对节点,在Python中的dict里面叫做items。
"""
class Entry():
def __init__(self, hash=0, key=0, value=0, next=None):
self.hash = hash
self.key = key
self.value = value
self.next = next
class HashMap():
"""
初始化默认HashMap的容量是16,加载因子是0.75,也就是阈值是16 * 0.75 = 12,就会扩容
"""
def __init__(self, capacity=16, load_factor=0.75):
self.__capacity = capacity # HashMap的容量
self.__load_factor = load_factor # 加载因子,
self.__table = [None for i in range(capacity)] # 创建一个空数组
self.__size = 0 # HashMap中节点总数量
self.__threshold = capacity * load_factor # HashMap的阈值,超过这个阈值需要扩容
"""
重写“toString()”方法,这样可以直接输出HashMap
"""
def __str__(self):
result = "{"
count = 0
for i in range(len(self.__table)):
if (self.__table[i] != None):
result += str(self.__table[i].key)
result += ":"
result += str(self.__table[i].value)
if (count != self.__size - 1):
count += 1
result += ", "
result += "}"
return result
"""
根据hash后的值 和 capacity, 得到下标
Parameters:
hash: 将key进行hash得到的Hash值
capacity: 当前数组的长度
Returns:
index:数组下标,表示该元素应该放到哪个数组中去
"""
def __index_for(self, hash, capacity):
return hash & (self.__capacity - 1)
"""
扩容后,将旧的list中的链表节点转移到新的list中去
Parameters:
new_table: 新创建的Hash表
Retures: None
"""
def __transfer(self, new_talbe):
new_capacity = len(new_talbe)
for e in self.__table:
while (None != e):
next = e.next
i = self.__index_for(e.hash, new_capacity)
e.next = new_talbe[i]
new_talbe[i] = e
e = next
"""
扩容, 创建一个新的hash表,容量是new_capacity
Parameters:
new_capacity: 新Hash表的容量
"""
def __resize(self, new_capacity):
old_table = self.__table
old_capacity = len(old_table)
new_talbe = [Entry() for x in range(new_capacity)]
self.__transfer(new_talbe)
self.__table = new_talbe
self.__threshold = self.__load_factor * self.__capacity
"""
创建一个节点, 并且将节点使用头插法添加到链表中去
"""
def __create_entry(self, hash, key, value, bucketIndex):
e = self.__table[bucketIndex]
self.__table[bucketIndex] = Entry(hash, key, value, e)
self.__size += 1
"""
通过计算key和hash值,将键值对放入到Hash表中去
"""
def __add_entry(self, hash, key, value, bucket_index):
# 如果元素过多,就需要扩容
if ((self.__size >= self.__threshold) and (None != self.__table[bucket_index])):
self.__resize(2 * len(self.__table)) # 将容量扩容成两倍
hash = hash(key)
bucket_index = self.__index_for(hash, len(self.__table))
self.__create_entry(hash, key, value, bucket_index)
"""
将key-value pair放入HashMap中
"""
def put(self, key, value):
h = hash(key)
i = self.__index_for(h, self.__capacity)
e = self.__table[i]
while (e != None):
k = e.key
# 如果key在HashMap中已经存在了
# 那么就把新的value覆盖旧的value,并且把旧的value返回出来
if (e.hash == h and (k == key)):
old_value = e.value
e.value = value
return old_value
e = e.next
self.__add_entry(h, key, value, i)
return None
"""
删除某个节点(Entry)
"""
def __remove_entry_for_key(self, key):
if (self.__size == 0): return None
h = hash(key)
i = self.__index_for(h, len(self.__table))
prev = self.__table[i]
e = prev
while (e != None):
next = e.next
k = e.key
if ((e.hash == h) or k == key):
self.__size -= 1
if (prev == e):
self.__table[i] = next
else:
prev.next = next
return e
prev = e
e = next
return e
def remove(self, key):
e = self.__remove_entry_for_key(key)
if (e == None):
return None
else:
return e.value
"""
get方法,通过key,得到value
"""
def get(self, key):
entry = self.__get_entry(key)
if (entry == None):
return None
else:
return entry.value
"""
通过key,找到那个节点
"""
def __get_entry(self, key):
if (self.__size == 0): return None
h = hash(key)
e = self.__table[self.__index_for(h, len(self.__table))]
while (e != None):
k = e.key
if ((e.hash == h) and e.key == k):
return e
e = e.next
return None
if __name__ == '__main__':
person = HashMap()
person.put('name', 'Jackson')
person.put('sex', 'male')
person.put('age', '19')
print(person) # 输出完整信息
person.remove('age')
print(person)
|
def quicksort(array):
# print(array)
if len(array) < 2:
return array #Base case: arrays with 0 or 1 element are already “sorted.”
else:
pivot = array[0] #Recursive case
less = [i for i in array[1:] if i <= pivot] #Sub-array of all the elements less than the pivot
greater = [i for i in array[1:] if i > pivot] #Sub-array of all the elements greater than the pivot
# print (less)
# print (greater)
result = quicksort(less) + [pivot] + quicksort(greater)
print(result)
return result
print (quicksort([10, 10,5, 2, 3]))
# array = [7,2,5,3]
# print([i for i in array[1:]])
|
class LinkedList:
def __init__(self, list = None):
self.head = None
if list is not None:
self.__create_linked_list_from_list(list)
def __create_linked_list_from_list(self, list):
'''
Creates a linked list from the elements in the list parameter
'''
if not list:
return
self.head = ListNode(list[0])
cur_node = self.head
for i in range(1, len(list)):
cur_node.next = ListNode(list[i])
cur_node = cur_node.next
def __str__(self):
'''
Returns a reader-friendly version of this linked list
@return {String} Entire linked-list as a String with head being the leftmost value and the
tail being the right most value. Arrows (->) are between each node.
'''
cur_node = self.head
list_str = []
arrow = "->"
while cur_node is not None:
list_str.append("%s%s"%(cur_node, arrow))
cur_node = cur_node.next
list_str.append("None")
#print list_str
return ''.join(list_str)
def __eq__(self, other_list):
'''
Returns whether this list and the passed linked list are equivalent. That is, it returns true
if they are of the same length and each node is equivalent to the corresponding node in the
other list.
@param {LinkedList} The other linked list
@param {Boolean} True if the lists are the same, False otherwise
'''
if other_list is None:
return false
fir_node = self.head
sec_node = other_list.head
while fir_node is not None and sec_node is not None:
if fir_node.val != sec_node.val:
return False
fir_node = fir_node.next
sec_node = sec_node.next
if fir_node is None and sec_node is None:
return True
else:
return False
class ListNode:
def __init__(self, val):
self.val = val
self.next = None
def __str__(self):
return '{self.val}'.format(self=self)
def __eq__(self, other):
return self.val == other.val
if __name__ == '__main__':
print "Here be dragons"
|
from collections import deque
from TreeNode import *
class Solution:
# @param {TreeNode} root
# @return {TreeNode}
def invertTree(self,root):
if root is None:
return
self._invert_tree(root)
return root
def _invert_tree(self, node):
if node is None:
return
temp = node.right
node.right = node.left
node.left = temp
self._invert_tree(node.right)
self._invert_tree(node.left)
|
from collections import OrderedDict
from typing import Dict, List, NewType, Optional, Tuple
from random import getrandbits
SquareParity = NewType('SquareParity', int)
SquareColor = NewType('SquareColor', int)
FillStrategy = NewType('FillStrategy', int)
BLACK = SquareParity(0)
WHITE = SquareParity(1)
NO_COLOR = SquareColor(-1)
GRAY = SquareColor(0)
RED = SquareColor(1)
YELLOW = SquareColor(2)
GREEN = SquareColor(4)
BLUE = SquareColor(8)
ALL_GRAY = FillStrategy(0)
HORIZONTAL = FillStrategy(1)
VERTICAL = FillStrategy(2)
COLOR_PAIRS = {
GREEN: BLUE,
BLUE: GREEN,
RED: YELLOW,
YELLOW: RED
}
class Board:
"""
Data representation of an Aztec Diamond board.
The board, stored in the ``data`` field, is as a list of dicts, where each dict represents a row. Only black
squares are stored. The keys represent the absolute X coordinate of their square.
Every square has a parity of either black or white. A square is black if the sum of its X and Y coordinates is even;
in other words, there is a checkerboard pattern starting with a black square at (0, 0).
It's valid to use the coordinates of a white square anywhere that coordinates are expected.
Every square has a color, which it shares with the other part of its domino if it has one.
If the coordinates are outside of the board, the reported color is NO_COLOR.
If a square is not part of a domino, its color is GRAY.
If the domino is vertical and the top square is black, its color is YELLOW; otherwise, it's RED.
If the domino is horizontal and the left square is black, its color is BLUE; otherwise, it's GREEN.
"""
def __init__(self, height, init_data=True):
if height % 2 != 0 or height <= 1:
raise ValueError('The height of an Aztec Diamond board must be an even number greater than 1.')
self.data: Dict[int, Dict[int, SquareColor]]
self.polarity = 1
if init_data:
self.data = self.generate_data(height, fill_strategy=HORIZONTAL)
else:
self.data = OrderedDict()
@staticmethod
def generate_data(height, fill_strategy=ALL_GRAY) -> Dict[int, Dict[int, SquareColor]]:
data = OrderedDict()
colors = {
ALL_GRAY: (GRAY, GRAY),
HORIZONTAL: (GREEN, BLUE) if height % 4 == 0 else (BLUE, GREEN),
VERTICAL: NotImplemented
}[fill_strategy]
offset = -1
for i in range(-height // 2, height // 2):
data[i] = OrderedDict()
for j in range(offset, offset * -1):
if (j + i) % 2 == 0:
data[i][j] = colors[0] if i < 0 else colors[1]
if len(data) < height / 2:
offset -= 1
elif len(data) > height / 2:
offset += 1
return data
@staticmethod
def get_square_parity(x, y) -> SquareParity:
return (x + y) % 2 # 0 = BLACK, 1 = WHITE
def get_square_color(self, x, y) -> SquareColor:
if self.get_square_parity(x, y) == BLACK:
try:
return self.data[y][x]
except KeyError:
return NO_COLOR
elif len(self.data) == 2:
neighbor = self.get_square_neighbor(x, y)
if neighbor:
return self.get_square_color(*neighbor)
return GRAY
else:
orientation = 1 if len(self.data) % 4 == 0 else -1
neighbor = self.get_square_neighbor(x, y)
if neighbor:
return self.get_square_color(*neighbor)
elif (
self.get_square_color(x + orientation, y) != NO_COLOR and self.get_square_color(x, y + 1) != NO_COLOR
) or (
self.get_square_color(x, y - 1) != NO_COLOR and self.get_square_color(x - orientation, y) != NO_COLOR
):
return GRAY
return NO_COLOR
def get_square_neighbor(self, x, y) -> Optional[Tuple[int, int]]:
"""Returns None if the square is gray or invalid. Always returns valid coordinates otherwise."""
parity = self.get_square_parity(x, y)
if parity == BLACK:
color = self.get_square_color(x, y)
if color == RED:
return x, y - self.polarity
elif color == YELLOW:
return x, y + self.polarity
elif color == GREEN:
return x - self.polarity, y
elif color == BLUE:
return x + self.polarity, y
return None
else:
for x2, y2, target_color in (
(x, y - self.polarity, YELLOW),
(x, y + self.polarity, RED),
(x - self.polarity, y, BLUE),
(x + self.polarity, y, GREEN)
):
if self.get_square_color(x2, y2) == target_color:
return x2, y2
return None
def get_holes(self) -> List[Tuple[int, int]]:
"""Returns all 2x2 areas of gray squares as coordinates of their top left corner. Assumes a valid board.
Return values for invalid boards are undefined."""
# In self.data, a hole corresponds to two gray squares that are immediately diagonal of each other.
corners = []
current_row = 0
rows, unvisited = map(list, zip(*(
(i, list(filter(lambda k: self.data[i][k] == GRAY, r.keys()))) for i, r in self.data.items()
)))
while unvisited:
while unvisited[0]:
if unvisited[0][0] - 1 in unvisited[1]:
corners.append((unvisited[0][0] - 1, rows[current_row]))
unvisited[1].remove(unvisited[0][0] - 1)
else:
corners.append((unvisited[0][0], rows[current_row]))
unvisited[1].remove(unvisited[0][0] + 1)
unvisited[0].pop(0)
unvisited.pop(0)
current_row += 1
return corners
def fill_holes(self, holes: List[Tuple[int, int]]):
"""Fills holes at coordinates returned by ``get_holes()`` with a random arrangement of dominoes.
If there are dominoes at given coordinates already, they're overwritten."""
for x, y in holes:
parity = self.get_square_parity(x, y)
squares = ((x, y), (x + 1, y + 1)) if parity == BLACK else ((x + 1, y), (x, y + 1))
arrangement = getrandbits(1)
if arrangement:
if squares[0][1] < squares[1][1]:
self.data[squares[0][1]][squares[0][0]] = BLUE
self.data[squares[1][1]][squares[1][0]] = GREEN
else:
self.data[squares[0][1]][squares[0][0]] = GREEN
self.data[squares[1][1]][squares[1][0]] = BLUE
else:
if squares[0][0] < squares[1][0]:
self.data[squares[0][1]][squares[0][0]] = YELLOW
self.data[squares[1][1]][squares[1][0]] = RED
else:
self.data[squares[0][1]][squares[0][0]] = RED
self.data[squares[1][1]][squares[1][0]] = YELLOW
def advance_magic(self):
"""Performs necessary movement and deletion of dominoes according to current data and changes the board size.
``fill_holes()`` will not be called by this method."""
new_data = self.generate_data(len(self.data) + 2) # O(n2)
color_delta = {
RED: (1, -self.polarity),
YELLOW: (-1, self.polarity),
BLUE: (self.polarity, -1),
GREEN: (-self.polarity, 1),
GRAY: (0, 0)
}
for y, row in self.data.items():
for x, color in row.items(): # O(n2)
new_x = x + color_delta[color][0]
new_y = y + color_delta[color][1]
if color != GRAY and self.data.get(new_y, {}).get(new_x) == COLOR_PAIRS[color]:
new_data[new_y][new_x] = GRAY
self.data[new_y][new_x] = GRAY
else:
new_data[new_y][new_x] = color
self.data = new_data
self.polarity *= -1
|
from Simulation import Simulation # This class contains the major methods required.
# Arguement carries population size
s1 = Simulation(100000) # This initiated the variable for population size.
s1.generatePopulation() # This generates the population as per the desired size.
s1.playSimulation() # This method runs the simulation and populates the arrays with data.
# Exporting Data
# s1.exportAllData() # This Method exports the data as CSV file.
s1.showResults() # This Method shows the plot of entire day wise and sales wise projection.
# s1.showResultsPerDay() # This method only shows the day wise results.
# s1.showResultsPerProduct() # This method only shows the sales wise results.
print("DONE!") # Prints done at the end giving a successful run indication. |
#3-1
names = ['toni', 'john', 'nipsey']
for name in names:
print(name)
#3-2
for name in names:
print(f"Wassup {name.title()} how you doing")
#3-3
cars = ['bmw','benz','audi']
for car in cars:
print(f"I would like to own a {car}")
|
#3-8
locations = ['jozi', 'kapa', 'durban']
print(locations)
print(sorted(locations))
print(locations)
print(sorted(locations, reverse=True))
print(locations)
locations.reverse()
print(locations)
locations.reverse()
print(locations)
locations.sort()
print(locations)
locations.sort(reverse =True)
print(locations)
#3-9
guests = ['mother', 'father', 'brother']
print(len(guests)) |
#8-3
def make_shirt(size,text):
print(f"Shirt size is: {size} \nShirt text is: {text}")
#8-4
def make_shirt(size = 'large',text = 'i love python'):
print(f"Shirt size is: {size} \nShirt text is: {text}")
make_shirt(text = 'life is good')
#8-5
def make_cities(city, country = 'South Africa'):
print(f"{city} is in {country}")
make_cities('kapa')
make_cities('durban')
make_cities('rio', country = 'Brazil') |
from random import choice
questions = ["why do we need nice cars?: ", "why do we need to relieve?: "]
question = choice(questions)
awnser = input(question).strip().lower()
while awnser != "just because":
awnser= input("why?: ")
|
#2-3
name = "Thonipho"
print(f"Hello {name}, would you like to learn today?")
#2-4
print(name.lower())
print(name.upper())
print(name.title())
#2-5
print("Nipsey Hussle once said, im the type to go and go get it")
#2-6
famous_person = "Nipsey Hussle"
message = "im the type to go and go get it"
print(f"{famous_person} once said, {message}")
#2-7
person_name = " Nipsey Hussle "
print = (person_name.lstrip())
print = (person_name.rstrip())
print = (person_name.strip())
|
#!/usr/bin/env python3
# Copyright (c) 2016 Anki, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License in the file LICENSE.txt or at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
'''Make Cozmo drive in a square.
This script combines the two previous examples (02_drive_and_turn.py and
03_count.py) to make Cozmo drive in a square by going forward and turning
left 4 times in a row.
'''
import cozmo
from cozmo.util import degrees, distance_mm, speed_mmps
def cozmo_program(robot: cozmo.robot.Robot):
lookaround = robot.start_behavior(cozmo.behavior.BehaviorTypes.LookAroundInPlace)
cubes = robot.world.wait_until_observe_num_objects(num=2, object_type=cozmo.objects.LightCube, timeout=60)
lookaround.stop()
if len(cubes) < 2:
print("Error: need 2 Cubes but only found", len(cubes), "Cube(s)")
else:
robot.pickup_object(cubes[0]).wait_for_completed()
robot.place_on_object(cubes[1]).wait_for_completed()
# Use a "for loop" to repeat the indented code 4 times
# Note: the _ variable name can be used when you don't need the value
for _ in range(4):
robot.drive_straight(distance_mm(100), speed_mmps(50)).wait_for_completed()
robot.turn_in_place(degrees(90)).wait_for_completed()
anim = robot.play_anim_trigger(cozmo.anim.Triggers.MajorWin)
anim.wait_for_completed()
cozmo.run_program(cozmo_program)
|
import numpy as np
#Start_probability is for if it rain or not today given the last day
#Transition is the probability for rain or sun, given umberella.
rain = [True, False] #different state it can be, in this case it is rain or not rain.
start_prob = np.array([0.5, 0.5]) #Start probability P(X1) = 0.5
transition_prob = np.array([[0.7, 0.3],[0.3, 0.7]]) #Probability matrix for if the day before was rain or not
umbrella = np.array([0.9, 0.2]) #Probability for carrying an umbrella if it is rain or sun
no_umbrella = np.array([0.1, 0.8]) #probability for NOT carrying an umbrella if it is rain or sun
observation = np.array([True,True,False,True,True]) #Observations of carrying umbrella. True = umbrella, False = No umbrella
def forward(observation):
forward_list=np.ones((len(observation)+1,len(rain)))
rain_given_observation=start_prob
forward_list[0]=rain_given_observation
t=0
for i in observation:
t += 1
rain_given_observation = np.dot(np.transpose(transition_prob),rain_given_observation)
if i: #if he carrying an umbrella
rain_given_observation = (rain_given_observation * umbrella)
rain_given_observation = np.divide(rain_given_observation, rain_given_observation.sum()) #Normalization
else: #if he is not carrying an umbrella
rain_given_observation = (rain_given_observation * no_umbrella)
rain_given_observation = np.divide(rain_given_observation, rain_given_observation.sum()) #Normalization
forward_list[t]= rain_given_observation
print("forward_list=",forward_list)
return forward_list
def backward(observation):
backward_list = np.ones((len(observation)+1,len(rain)))
rain_given_observation=np.ones(len(rain))
t=len(observation)
reverse = reversed(observation) #reverse the list of observation, uposit of forward.
for i in reverse:
t -= 1
if i: # if carrying umbrella
rain_given_observation = umbrella * rain_given_observation
else: #if not carrying umbrella
rain_given_observation = no_umbrella * rain_given_observation
rain_given_observation = np.dot(transition_prob, rain_given_observation)
backward_list[t] = rain_given_observation
print("backward_list=",backward_list)
return backward_list
def forward_backward(observation):
forward_list=forward(observation)
backward_list=backward(observation)
forward_backward_list = []
combine = np.multiply(forward_list,backward_list) # this combines both forward and backward list and is an unnormalized list of forward_backward
for i in range(len(forward_list)):
value = combine[i]/combine[i].sum() #Normalize
forward_backward_list.append(value)
print("forward_backward_list=",forward_backward_list)
return forward_backward_list
forward_backward(observation)
|
class Car:
# constructor
def __init__(self, name, year):
self.name = name
self.year = year
def describe(self):
print('The car is a', self.name)
def move(self, direction):
print('The class', self.__class__.__name__, 'is moving towards the', direction)
if __name__ == '__main__':
car = Car('Jaguar', 2020)
car.describe()
car.move('left')
|
higher_order_func = lambda x, func: x + func(x)
if __name__ == '__main__':
sum_func = (lambda x, y: x + y)
_sum = sum_func(7, 3)
print(_sum)
print(higher_order_func(2, lambda x: x**2))
print(higher_order_func(3, lambda x: x + 3)) |
# Problem Set 4C
# Name: Matthew Vogel
# Collaborators:
# Time Spent: x:xx
import string
from ps4a import get_permutations
import re
### HELPER CODE ###
def load_words(file_name):
'''
file_name (string): the name of the file containing
the list of words to load
Returns: a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
'''
#print("Loading word list from file...")
# inFile: file
inFile = open(file_name, 'r')
# wordlist: list of strings
wordlist = []
for line in inFile:
wordlist.extend([word.lower() for word in line.split(' ')])
#print(" ", len(wordlist), "words loaded.")
return wordlist
def is_word(word_list, word):
'''
Determines if word is a valid word, ignoring
capitalization and punctuation
word_list (list): list of words in the dictionary.
word (string): a possible word.
Returns: True if word is in word_list, False otherwise
Example:
>>> is_word(word_list, 'bat') returns
True
>>> is_word(word_list, 'asdf') returns
False
'''
word = word.lower()
word = word.strip(" !@#$%^&*()-_+={}[]|\:;'<>?,./\"")
return word in word_list
### END HELPER CODE ###
WORDLIST_FILENAME = 'words.txt'
# you may find these constants helpful
VOWELS_LOWER = 'aeiou'
VOWELS_UPPER = 'AEIOU'
CONSONANTS_LOWER = 'bcdfghjklmnpqrstvwxyz'
CONSONANTS_UPPER = 'BCDFGHJKLMNPQRSTVWXYZ'
class SubMessage(object):
def __init__(self, text):
'''
Initializes a SubMessage object
text (string): the message's text
A SubMessage object has two attributes:
self.message_text (string, determined by input text)
self.valid_words (list, determined using helper function load_words)
'''
self.message_text = text
self.valid_words = load_words('words.txt')
def get_message_text(self):
'''
Used to safely access self.message_text outside of the class
Returns: self.message_text
'''
return(self.message_text)
def get_valid_words(self):
'''
Used to safely access a copy of self.valid_words outside of the class.
This helps you avoid accidentally mutating class attributes.
Returns: a COPY of self.valid_words
'''
return(self.valid_words.copy())
def build_transpose_dict(self, vowels_permutation):
'''
vowels_permutation (string): a string containing a permutation of vowels (a, e, i, o, u)
Creates a dictionary that can be used to apply a cipher to a letter.
The dictionary maps every uppercase and lowercase letter to an
uppercase and lowercase letter, respectively. Vowels are shuffled
according to vowels_permutation. The first letter in vowels_permutation
corresponds to a, the second to e, and so on in the order a, e, i, o, u.
The consonants remain the same. The dictionary should have 52
keys of all the uppercase letters and all the lowercase letters.
Example: When input "eaiuo":
Mapping is a->e, e->a, i->i, o->u, u->o
and "Hello World!" maps to "Hallu Wurld!"
Returns: a dictionary mapping a letter (string) to
another letter (string).
'''
# create a dictionary of all upper and lowercase letters, mapped to themselves
permuted_dict = {}
all_letters = VOWELS_LOWER + VOWELS_UPPER + CONSONANTS_LOWER + CONSONANTS_UPPER
for l in all_letters:
permuted_dict[l] = l
# itterate over vowels_lower, and map the first vowel (a) to the first item in vowels_permutations
count = 0
for c in VOWELS_LOWER:
permuted_dict[c] = vowels_permutation[count]
count +=1
# do the same thing with an uppercase version of vowels+permutation and vowels_upper
count_u = 0
for c in VOWELS_UPPER:
permuted_dict[c] = vowels_permutation[count_u].upper()
count_u += 1
# retrun this new dictionary
return(permuted_dict)
def apply_transpose(self, transpose_dict):
'''
transpose_dict (dict): a transpose dictionary
Returns: an encrypted version of the message text, based
on the dictionary
'''
# create a variable which contains the message to be encoded
text = self.get_message_text()
# create a new variable for the encoded message, and loop over messages letters, adding their key in transpose dict to the new variable
encoded_text = ''
for c in text:
if c in string.ascii_letters:
encoded_text += transpose_dict[c]
else: encoded_text += c
# return the new variable
return(encoded_text)
class EncryptedSubMessage(SubMessage):
def __init__(self, text):
'''
Initializes an EncryptedSubMessage object
text (string): the encrypted message text
An EncryptedSubMessage object inherits from SubMessage and has two attributes:
self.message_text (string, determined by input text)
self.valid_words (list, determined using helper function load_words)
'''
self.message_text = text
self.valid_words = load_words('words.txt')
def decrypt_message(self):
'''
Attempt to decrypt the encrypted message
Idea is to go through each permutation of the vowels and test it
on the encrypted message. For each permutation, check how many
words in the decrypted text are valid English words, and return
the decrypted message with the most English words.
If no good permutations are found (i.e. no permutations result in
at least 1 valid word), return the original string. If there are
multiple permutations that yield the maximum number of words, return any
one of them.
Returns: the best decrypted message
Hint: use your function from Part 4A
'''
# get the permutations of all vowels
vowels_permuted = get_permutations(VOWELS_LOWER)
# build a transpose dictionary with these permutations
valid_words = self.get_valid_words()
greatest_valid = 0
greatest_permutation = 0
for perm in vowels_permuted:
transpose_dict = self.build_transpose_dict(perm)
# apply transpose on the origional message using these transpose dicts
new_message = self.apply_transpose(transpose_dict)
# test each of these new messages to see how many words are valid
valid_count = 0
new_message_list = re.split('\s+', new_message)
for w in new_message_list:
if is_word(valid_words, w):
valid_count +=1
# if the number of valid words is greater than the p
if valid_count > greatest_valid:
greatest_valid = valid_count
greatest_permutation = perm
# retrun the decrypted message with the best permutation
return(self.apply_transpose(self.build_transpose_dict(greatest_permutation)))
if __name__ == '__main__':
# Example test case
# message = SubMessage("Hello World!")
# permutation = "eaiuo"
# enc_dict = message.build_transpose_dict(permutation)
# print("Original message:", message.get_message_text(), "Permutation:", permutation)
# print("Expected encryption:", "Hallu Wurld!")
# print("Actual encryption:", message.apply_transpose(enc_dict))
# enc_message = EncryptedSubMessage(message.apply_transpose(enc_dict))
# print("Decrypted message:", enc_message.decrypt_message())
#TODO: WRITE YOUR TEST CASES HERE
message = SubMessage('Hello World!')
permutation = 'eaiuo'
enc_dict = message.build_transpose_dict(permutation)
print("Original message:", message.get_message_text(), "Permutation:", permutation)
print("Expected encryption:", "Hallu Wurld!")
print("Actual encryption:", message.apply_transpose(enc_dict))
enc_message = EncryptedSubMessage(message.apply_transpose(enc_dict))
print("Decrypted message:", enc_message.decrypt_message())
message2 = SubMessage('TesTING: CAPitol! $ and. PUNNctuation')
permutation2 = 'ieuoa'
enc_dict2 = message2.build_transpose_dict(permutation2)
print("Original message:", message2.get_message_text(), "Permutation:", permutation2)
print('expected encryption:', 'TesTUNG: CIPutol! $ ind. PANNctaituon')
print("Actual encryption:", message2.apply_transpose(enc_dict2))
enc_message2 = EncryptedSubMessage(message2.apply_transpose(enc_dict2))
print("Decrypted message:", enc_message2.decrypt_message()) |
import math
digit = raw_input('What digit to go to?')
digit = int(digit)
if digit < 40:
print(float(round(math.pi, digit)))
else:
print("Sorry, digit is too large")
|
#!/usr/bin/env python2
# CodeEval Challenge - Reverse Words
# https://www.codeeval.com/open_challenges/8/
import sys
with open(sys.argv[1], 'r') as f:
lines = open(sys.argv[1], 'r').readlines()
for line in lines:
words = line.split()[::-1]
if len(words) == 0: # line is empty
continue
for word in words:
sys.stdout.write(word + " ")
sys.stdout.write("\n")
|
#!/usr/bin/env python2
# CodeEval - Stack Implementation
# https://www.codeeval.com/open_challenges/9/
import sys
def push(list_x, int_y):
'''Append int to list'''
list_x.append(int_y)
def pop(list_x):
'''Remove and return last item in list'''
last_int = list_x[-1]
del(list_x[-1])
return last_int
def print_alternate_ints(list_x):
while True:
try:
sys.stdout.write( str(pop(list_x)) + " " )
pop(list_x)
except:
print("")
return
def main():
with open(sys.argv[1], "rt") as f:
lines = f.readlines()
for line in lines:
ints = line.strip().split()
int_list = []
for int_ in ints:
push(int_list, int_)
print_alternate_ints(int_list)
if __name__ == "__main__":
main()
|
#!/usr/bin/env python2
# CodeEval - Penultimate Word
# https://www.codeeval.com/open_challenges/92/
from sys import argv
with open(argv[1], "rt") as f:
lines = f.readlines()
for line in lines:
words = line.strip().split()
print(words[-2])
|
#!/usr/bin/env python2
# CodeEval - Text Dollar
# https://www.codeeval.com/open_challenges/52/
from sys import argv
single_digits = ("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine")
teens = ("Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen")
double_digits = ("", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety")
def convert_number(number_str):
'''Convert 3 digit numbers to English equivelant'''
number_str = number_str.zfill(3)
number = []
if number_str[0] != "0":
hundreds = int(number_str[0])
string = single_digits[hundreds] + "Hundred"
number.append(string)
if number_str[1] == "0":
string = single_digits[ int(number_str[2]) ]
number.append(string)
elif number_str[1] == "1":
string = teens[ int(number_str[2]) ]
number.append(string)
else:
number.append( double_digits[ int(number_str[1]) ] )
number.append( single_digits[ int(number_str[2]) ] )
return "".join(number)
def text_number(number_str):
number_str = number_str.zfill(9)
number = []
if int(number_str[:3]):
millions = number_str[:3]
millions = convert_number(millions) + "Million"
number.append(millions)
if int(number_str[3:6]):
thousands = number_str[3:6]
thousands = convert_number(thousands) + "Thousand"
number.append(thousands)
if int(number_str[6:]):
hundreds = number_str[6:]
hundreds = convert_number(hundreds)
number.append(hundreds)
return "".join(number)
def main():
f = open(argv[1], "rt")
for line in f:
numbers_str = line.strip()
dollars = text_number(numbers_str)
print(dollars+"Dollars")
f.close()
if __name__ == "__main__":
main()
|
#!/usr/bin/env python2
# Rightmost Char
# https://www.codeeval.com/open_challenges/31/
import sys
with open(sys.argv[1], "r") as f:
file_contents = f.readlines()
for line in file_contents:
string_s, t = line.strip().split(",")
if t in string_s:
print( string_s.index(t) )
else:
print(-1)
|
#!/usr/bin/env python2
"""
- CodeEval: Filename Pattern
- https://www.codeeval.com/open_challenges/169/
"""
from fnmatch import fnmatch
from sys import argv
def match_filenames(pattern, file_names):
match_filenames = []
for i in file_names:
if fnmatch(i, pattern):
match_filenames.append(i)
return match_filenames
def main():
with open(argv[1]) as f:
for line in f:
tokens = line.strip().split(' ')
pattern = tokens[0]
file_names = tokens[1:]
matching_filenames = match_filenames(pattern, file_names)
if matching_filenames:
print( ' '.join(matching_filenames) )
else:
print('-')
if __name__ == "__main__":
main()
|
#!/usr/bin/env python2
# CodeEval - Reverse and Add
# https://www.codeeval.com/open_challenges/45/
from sys import argv
def reverse_add(interger_str):
reverse_str = interger_str[::-1]
sum_ = int(interger_str) + int(reverse_str)
return str(sum_)
def is_palindrome(interger_str):
if interger_str == interger_str[::-1]:
return True
else:
return False
def main():
f = open(argv[1], "rt")
for line in f:
interger_str = line.strip()
iterations = 0
while True:
interger_str = reverse_add(interger_str)
iterations += 1
if is_palindrome(interger_str):
print("%d %s" % (iterations, interger_str))
break
f.close()
if __name__ == "__main__":
main()
|
#!/usr/bin/python3
import sys
nombre_marches = int( sys.argv[1] )
print(nombre_marches)
for i in range(nombre_marches):
string = ' ' * (nombre_marches + 1 - i) + '#' * (i + 1)
print (string)
|
from math import *
import random
class matrix:
def __init__(self, value):
self.value = value
self.dimx = len(value)
self.dimy = len(value[0])
if value == [[]]:
self.dimx = 0
def zero(self, dimx, dimy):
# verificar dimensiones
if dimx < 1 or dimy < 1:
raise ValueError, "Tamaño de matriz no válido"
else:
self.dimx = dimx
self.dimy = dimy
self.value = [[0 for row in range(dimy)] for col in range(dimx)]
def identity(self, dim):
# Verificar dimensiones
if dim < 1:
raise ValueError, "Tamaño de matriz no válido"
else:
self.dimx = dim
self.dimy = dim
self.value = [[0 for row in range(dim)] for col in range(dim)]
for i in range(dim):
self.value[i][i] = 1
def show(self):
for i in range(self.dimx):
print self.value[i]
print ' '
def __sum__(self, other):
if self.dimx != other.dimx or self.dimx != other.dimx:
raise ValueError, "Las matrices deben ser de igual dimensión para sumar"
else:
# suma si las dimeniones son correctas
res = matrix([[]])
res.zero(self.dimx, self.dimy)
for i in range(self.dimx):
for j in range(self.dimy):
res.value[i][j] = self.value[i][j] + other.value[i][j]
return res
def __res__(self, other):
# verifica el tamaño correcto
if self.dimx != other.dimx or self.dimx != other.dimx:
raise ValueError, "Las matrices deben ser de igual dimensión para restarse"
else:
# res si la dimension es correcta
res = matrix([[]])
res.zero(self.dimx, self.dimy)
for i in range(self.dimx):
for j in range(self.dimy):
res.value[i][j] = self.value[i][j] - other.value[i][j]
return res
def __mul__(self, other):
# verificar dimensiones
if self.dimy != other.dimx:
raise ValueError, "m*n o n*p para multiplicar"
else:
# multiplicar si las dimensiones son correctas
res = matrix([[]])
res.zero(self.dimx, other.dimy)
for i in range(self.dimx):
for j in range(other.dimy):
for k in range(self.dimy):
res.value[i][j] += self.value[i][k] * other.value[k][j]
return res
def transpose(self):
# traspuesta de toda la vida xd
res = matrix([[]])
res.zero(self.dimy, self.dimx)
for i in range(self.dimx):
for j in range(self.dimy):
res.value[j][i] = self.value[i][j]
return res
def __repr__(self):
return repr(self.value)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Author: Chris Berardi
Solution to Week 2 Assignment for Stat656 Spring 2018
Uses Python to preprocess and clean data
"""
import pandas as pd
import numpy as np
from sklearn import preprocessing
file_path = 'C:/Users/Saistout/Desktop/656 Applied Analytics/Data/'
credit = pd.read_excel(file_path+"credithistory_HW2.xlsx")
# Place the number of observations in 'n_obs'
n_obs = credit.shape[0]
# Identify Outliers and Set to Missing
# Age should be between 1 and 120
# Amount should be between 0 and 20,000
# The categorical attributes should only contain the values in the dictionary
# Check: 'savings', 'employed' and 'marital'
# Recode: Nominal and Ordinal values
# Scale: Interval values
# Print the mean of all interval variables and the mode frequency for
# each nominal or ordinal variable
initial_missing = credit.isnull().sum()
feature_names = np.array(credit.columns.values)
for feature in feature_names:
if initial_missing[feature]>(n_obs/2):
print(feature+":\n\t%i missing: Drop this attribute." \
%initial_missing[feature])
# Category Values for Nominal and Binary Attributes
n_interval = 3
n_binary = 4
n_nominal = 20-n_interval-n_binary
n_cat = n_binary+n_nominal
# Attribute Map: the key is the name in the DataFrame
# The first number of 0=Interval, 1=Binary, 2=Nominal
# The 1st tuple for interval attributes is their lower and upper bounds
# The 1st tuple for categorical attributes is their allowed categories
# The 2nd tuple contains the number missing and number of outliers
attribute_map = {
'age' :[0,(1, 120),[0,0]],
'amount' :[0,(0, 20000),[0,0]],
'duration':[0,(0,240),[0,0]],
'checking':[2,(1, 2, 3, 4),[0,0]],
'coapp' :[2,(1,2,3),[0,0]],
'depends' :[1,(1,2),[0,0]],
'employed':[2,(1,2,3,4,5),[0,0]],
'existcr' :[2,(1,2,3,4),[0,0]],
'foreign' :[1,(1,2),[0,0]],
'good_bad':[1,('good','bad'),[0,0]],
'history' :[2,(0,1,2,3,4),[0,0]],
'housing' :[2,(1,2,3),[0,0]],
'installp':[2,(1,2,3,4),[0,0]],
'job' :[2,(1,2,3,4),[0,0]],
'marital' :[2,(1,2,3,4),[0,0]],
'other' :[2,(1,2,3),[0,0]],
'property':[2,(1,2,3,4),[0,0]],
'resident':[2,(1,2,3,4),[0,0]],
'savings' :[2,(1,2,3,4,5),[0,0]],
'telephon':[1,(1,2),[0,0]]
}
# Initialize number missing in attribute_map
for k,v in attribute_map.items():
for feature in feature_names:
if feature==k:
v[2][0] = initial_missing[feature]
break
# Scan for outliers among interval attributes
nan_map = credit.isnull()
print(nan_map.shape)
for i in range(n_obs):
# Check for outliers in interval attributes
for k, v in attribute_map.items():
if nan_map.loc[i,k]==True:
continue
if v[0]==0: # Interval Attribute
l_limit = v[1][0]
u_limit = v[1][1]
if credit.loc[i, k]>u_limit or credit.loc[i,k]<l_limit:
v[2][1] += 1
credit.loc[i,k] = None
else: # Categorical Attribute
in_cat = False
for cat in v[1]:
if credit.loc[i,k]==cat:
in_cat=True
if in_cat==False:
credit.loc[i,k] = None
v[2][1] += 1
print("\nNumber of missing values and outliers by attribute:")
feature_names = np.array(credit.columns.values)
for k,v in attribute_map.items():
print(k+":\t%i missing" %v[2][0]+ " %i outlier(s)" %v[2][1])
interval_attributes = []
nominal_attributes = []
binary_attributes = []
onehot_attributes = []
for k,v in attribute_map.items():
if v[0]==0:
interval_attributes.append(k)
else:
if v[0]==1:
binary_attributes.append(k)
else:
nominal_attributes.append(k)
for i in range(len(v[1])):
str = k+("%i" %i)
onehot_attributes.append(str)
n_interval = len(interval_attributes)
n_binary = len(binary_attributes)
n_nominal = len(nominal_attributes)
n_onehot = len(onehot_attributes)
print("\nFound %i Interval Attributes, " %n_interval, \
"%i Binary," %n_binary, \
"and %i Nominal Attribute\n" %n_nominal)
# Put the interval data from the dataframe into a numpy array
interval_data = credit.as_matrix(columns=interval_attributes)
# Create the Imputer for the Interval Data
interval_imputer = preprocessing.Imputer(strategy='mean')
# Impute the missing values in the Interval data
imputed_interval_data = interval_imputer.fit_transform(interval_data)
# Convert String Categorical Attribute to Numbers
# Create a dictionary with mapping of categories to numbers for attribute 'good_bad'
cat_map = {'good':1, 'bad':2}
# Change the string categories of 'B' to numbers
credit['good_bad'] = credit['good_bad'].map(cat_map)
# Put the nominal and binary data from the dataframe into a numpy array
nominal_data = credit.as_matrix(columns=nominal_attributes)
binary_data = credit.as_matrix(columns=binary_attributes)
# Create Imputer for Categorical Data
cat_imputer = preprocessing.Imputer(strategy='most_frequent')
# Impute the missing values in the Categorical Data
imputed_nominal_data = cat_imputer.fit_transform(nominal_data)
imputed_binary_data = cat_imputer.fit_transform(binary_data)
# Encoding Interval Data by Scaling
scaler = preprocessing.StandardScaler() # Create an instance of StandardScaler()
scaler.fit(imputed_interval_data)
scaled_interval_data = scaler.transform(imputed_interval_data)
# Create an instance of the OneHotEncoder & Selecting Attributes
onehot = preprocessing.OneHotEncoder()
hot_array = onehot.fit_transform(imputed_nominal_data).toarray()
# Bring Interval and Categorial Data Together
# The Imputed Data
data_array= np.hstack((imputed_interval_data, imputed_binary_data, \
imputed_nominal_data))
col = []
for i in range(n_interval):
col.append(interval_attributes[i])
for i in range(n_binary):
col.append(binary_attributes[i])
for i in range(n_nominal):
col.append(nominal_attributes[i])
credit_imputed = pd.DataFrame(data_array,columns=col)
print("\nImputed DataFrame:\n", credit_imputed[0:15])
# The Imputed and Encoded Data
data_array = np.hstack((scaled_interval_data, imputed_binary_data, hot_array))
#col = (interval_attributes, cat_attributes)
col = []
for i in range(n_interval):
col.append(interval_attributes[i])
for i in range(n_binary):
col.append(binary_attributes[i])
for i in range(n_onehot):
col.append(onehot_attributes[i])
credit_imputed_scaled = pd.DataFrame(data_array,columns=col)
print("\nImputed & Scaled DataFrame:\n", credit_imputed_scaled[0:15])
|
#we will represent a sudoku grid with a list of lists
# the first list represents the first row and so forth
# any empty places are represented with a 0
# a sudoku puzzle is usually 9 x 9
# valid returns true if the current puzzle is in a valid state, and false otherwise
# we consider a state valid if there are no repeating elements in rows columns or squares
def valid(puzzle):
map_row = [{} for _ in range(9)]
map_col = [{} for _ in range(9)]
map_cell = [[{} for _ in range(3)] for __ in range(3)]
for i in range(9):
for j in range(9):
char = puzzle[i][j]
if char == 0: continue
if char in map_row[i]:
return False
else:
map_row[i][char] = [i, j]
if char in map_col[j]:
return False
else:
map_col[j][char] = [i, j]
if char in map_cell[i // 3][j // 3]:
return False
else:
map_cell[i // 3][j // 3][char] = [i, j]
return True
# solved returns true if the puzzle is solved and false otherwise
def solved(puzzle):
blanks = sum([i.count(0) for i in puzzle])
return blanks==0 and valid(puzzle)
def findNext(grid, i, j):
for x in range(i, 9):
for y in range(j, 9):
if grid[x][y] == 0:
return x, y
for x in range(0, 9):
for y in range(0, 9):
if grid[x][y] == 0:
return x, y
return -1, -1
def solveSudoku(grid, i=0, j=0):
i, j = findNext(grid, i, j)
if i == -1:
return True
for e in range(1, 10):
if isValid(grid, i, j, e):
grid[i][j] = e
if solveSudoku(grid, i, j):
return True
grid[i][j] = 0
return False
def isValid(grid, i, j, e):
if all([e != grid[i][x] for x in range(9)]) and all([e != grid[x][j] for x in range(9)]):
mx, my = 3 * (i // 3), 3 * (j // 3)
for x in range(mx, mx + 3):
for y in range(my, my + 3):
if grid[x][y] == e:
return False
return True
return False
'''
testing = [[5,1,7,6,0,0,0,3,4],[2,8,9,0,0,4,0,0,0],[3,4,6,2,0,5,0,9,0],[6,0,2,0,0,0,0,1,0],[0,3,8,0,0,6,0,4,7],[0,0,0,0,0,0,0,0,0],[0,9,0,0,0,0,0,7,8],[7,0,3,4,0,0,5,6,0],[0,0,0,0,0,0,0,0,0]]
solveSudoku(testing) -> solves puzzle
print(testing) -> outputs solved puzzle
print(solved(testing)) -> True
''' |
n1 = int(input('Digite o primeiro numero '))
n2 = int(input('Digite o segundo numero '))
n3 = int(input('Digite o terceiro numero '))
if n1 > n2 and n1 > n3:
maior = n1
elif n2 > n3:
maior = n2
else:
maior = n3
if n1 < n2 and n1 < n3:
menor = n1
elif n2 < n3:
menor = n2
else:
menor = n3
print(f'O maior numero digitado foi {maior}')
print(f'O menor numero digitado foi {menor}') |
n1 = float(input('Digite a primeira nota: '))
n2 = float(input('Digite a segunda nota: '))
media = (n1 + n2) / 2
if media >= 7.0:
print(f'Sua media foi {media} e você esta aprovado')
elif media >= 5.0:
print(f'Sua media foi {media} e você esta de recuperação')
else:
print(f'Sua media foi {media} e você esta reprovado')
|
import random
pc = random.randint(1, 5)
jogador = int(input('Digite um numero: '))
if pc == jogador:
print(f'Parabens você ganhou, eu tambem pensei no numero {pc}')
else:
print(f'Eu ganhei, pensei no numero {pc}')
|
numero = int(input('Digite um numero '))
u = numero // 1 % 10
d = numero // 10 % 10
c = numero // 100 % 10
m = numero // 1000 % 10
print(f'Unidade {u}')
print(f'Dezena {d}')
print(f'Centena {c}')
print(f'Milhar {m}')
|
nome = str(input('Digite seu nome completo ')).strip()
maisculas = nome.upper()
minusculas = nome.lower()
letras = len(nome) - nome.count(' ')
primeiro = nome.find(' ')
print(f'Seu nome em maiusculas é {maisculas}')
print(f'Seu nome em minusculas é {minusculas}')
print(f'Seu nome tem ao todo {letras} letras')
print(f'Seu primeiro nome tem {primeiro} letras') |
# -*- coding: utf-8 -*-
"""
Created on Sat May 5 20:36:03 2018
8 二叉树的下一个结点
给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。
注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。
@author: situ
"""
tin = {8,6,10,5,7,9,11}
pNode = 8
#对应输出应该为:9
class TreeLinkNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
self.next = None #指向父结点,不是指向子节点!!不是指向下一个!!!
def GetNext(pNode):
if pNode.right is not None:#右子树不为空,则下一个结点为其右子树的最左子节点
temp_right = pNode.right
while temp_right.left is not None:
temp_right = temp_right.left
return temp_right
else:
temp_next = pNode
while temp_next.next is not None:
if temp_next.next.left==temp_next:#右子树为空,该结点为父节点的左结点,则下一个结点为其父节点
return temp_next.next
else:#右子树为空,该结点为父节点的右结点,则下一个结点为:从该结点一直向上追溯父节点,直到有一个父结点为这个父结点的父结点的左子树为止
temp_next = temp_next.next
return None
|
# -*- coding: utf-8 -*-
"""
Created on Wed May 9 22:50:00 2018
17 打印从1到最大的n位数
@author: situ
"""
def Print1ToMaxOfNDigits_1(n):
Max = int("9"*n)
for i in range(1,Max+1):
print(i) |
# -*- coding: utf-8 -*-
"""
Created on Sun May 6 16:59:50 2018
12 矩阵中的路径
请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。
路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。
如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。
例如 a b c e s f c s a d e e 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,
因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
@author: situ
"""
class Solution:
def hasPath(self, matrix, rows, cols, path):
visited = [0]*rows*cols
pathLength = 0
for row in range(rows):
for col in range(cols):
if self.hasPathCore(matrix,rows,cols,row,col,path,visited,pathLength):
return True
return False
def hasPathCore(self,matrix,rows,cols,row,col,path,visited,pathLength):
if pathLength==len(path):
return True
haspath=0
# print(row,col,pathLength)
if row<rows and col<cols and row>=0 and col>=0 \
and matrix[row*cols+col]==path[pathLength] and visited[row*cols+col]==0:
pathLength +=1
visited[row*cols+col] = 1
haspath = self.hasPathCore(matrix,rows,cols,row+1,col,path,visited,pathLength) \
or self.hasPathCore(matrix,rows,cols,row-1,col,path,visited,pathLength)\
or self.hasPathCore(matrix,rows,cols,row,col+1,path,visited,pathLength)\
or self.hasPathCore(matrix,rows,cols,row,col-1,path,visited,pathLength)
if haspath==0:
pathLength -=1
visited[row*cols+col] = 0
return haspath
def main():
matrix, rows, cols, path = "ABCESFCSADEE",3,4,"ABCCED"
a = Solution()
print(a.hasPath(matrix, rows, cols, path))
if __name__=="__main__":
main()
|
import math
import numpy
#PARAMS:
# seen: list of 2 dictionaries, corresponding to female and male respectively
# Each dict of the form {word:count},
# where all of the words are associated
# with their respective counts of appearence
# aggregated over all of that gender's blog posts
#
# n: number of significant "male heavy" or "female heavy"
# words to print
#Normalizes word frequencies for male and female labeled blog posts
#Computing the z-score for each, then determines "significance"
#to be the ratio of male z-score : female z-score
#ADDITIONALLY
#This writes the largest and smallest male:female z-scores
#to the file "significant_words.txt" in the data folder
def term_stats(seen,n):
#Normalizing words
##################
#get total number of words by males and females
f_vals = seen[0].values()
m_vals = seen[1].values()
tot_f = sum(f_vals)
tot_m = sum(m_vals)
mean_f = numpy.mean(f_vals)
std_f = numpy.std(f_vals)
mean_m = numpy.mean(m_vals)
std_m = numpy.std(m_vals)
print("Female Mean word frequency: %.2f"%mean_f)
print("Male Mean word frequency: %.2f"%mean_m)
print("Female Standard Deviation: %.2f"%std_f)
print("Male Standard Deviation: %.2f"%std_m)
print("")
#Divide word counts by number of words males/females used
seen[1] = {key:(val-mean_m)/std_m for key,val in seen[1].items()}
seen[0] = {key:(val-mean_f)/std_f for key,val in seen[0].items()}
##################
#Seen words now normalized as % frequency that they appear
top_male = sorted(seen[1].items(),key=lambda x:x[1],reverse=True)
top_female = sorted(seen[0].items(),key=lambda x:x[1],reverse=True)
top_diffs = []
for key,val in top_male:
if key in seen[0]:
diff = term_diff(val,seen[0][key])
top_diffs.append((key,diff))
top_diffs = sorted(top_diffs,key=lambda x:x[1])
#column width spacer for words
col_width = max(len(word[0]) for word in top_diffs)-12
#Column width spacer for numbers
w=23
#output = open("../data/significant_words.txt","w")
print("Male Dominant Words")
print("High Male:Female Z-Score Ratio")
print("___________________")
print("Words: ".ljust(col_width)+"(Male:Female)".ljust(w)+"Z-Male".ljust(w)+"Z-Female")
for word in sorted(top_diffs[-n:],key=lambda x:x[1],reverse=True):
label = word[0].ljust(col_width)
diff = ("%.3f"%word[1]).ljust(w)
male = ("%.3f"%seen[1][word[0]]).ljust(w)
female = ("%.3f"%seen[0][word[0]])
print(label+diff+male+female)
#output.write(word[0]+"\n")
print("")
print("Female Dominant Words")
print("Low Male:Female Z-Score Ratio")
print("___________________")
print("Words: ".ljust(col_width)+"(Male:Female)".ljust(w)+"Z-Male".ljust(w)+"Z-Female")
for word in sorted(top_diffs[0:n],key=lambda x:x[1]):
label = word[0].ljust(col_width)
diff = ("%.3f"%word[1]).ljust(w)
male = ("%.3f"%seen[1][word[0]]).ljust(w)
female = ("%.3f"%seen[0][word[0]])
print(label+diff+male+female)
#output.write(word[0]+"\n")
#output.close()
count1 = 0
count2 = 0
count3 = 0
for item,count in seen[0].items():
if count < 0:
count1+=1
if count > 0:
count2+=1
count3 += 1
print(count1/float(count3))
print(count2/float(count3))
return top_diffs
#TRY CHANGING ME
#try changing to differences in z-score, ratio, transformations, etc. etc.
#PARAMS male z-score of word frequencies
# female """""
#RETURNS ratio/difference/comparison between the two
def term_diff(male_val,female_val):
#if both are negative, these
#are too uncommon to be significant
if male_val < 0:
male_val = .01
if female_val < 0:
female_val = .01
return round(male_val/female_val,3)
|
string = list(input())
up = 0
lo = 0
for i in string:
if i.isupper():
up += 1
#print("IN upper")
else:
lo += 1
# print("In lower")
if up > lo:
string = ''.join(string)
string = string.upper()
else:
string = ''.join(string)
string = string.lower()
print(string) |
#Let's assume that a song consists of some number of words.
# To make the dubstep remix of this song, Vasya inserts a certain number of words "WUB"
# before the first word of the song (the number may be zero), after the last word (the number may be zero),
# and between words (at least one between any pair of neighbouring words), and then the boy glues together all the words,
# including "WUB", in one string and plays the song at the club.
string = input()
string2 = string.replace('WUB', ' ')
string2 = string2.strip()
print(string2) |
#Chef has a number D containing only digits 0's and 1's.
# He wants to make the number to have all the digits same.
# For that, he will change exactly one digit, i.e. from 0 to 1 or from 1 to 0.
# If it is possible to make all digits equal (either all 0's or all 1's) by flipping exactly 1 digit then output "Yes", else print "No"
for i in range(int(input())):
num = list(input())
if num.count('1') == 1 or num.count('0') == 1:
print("Yes")
else:
print("No") |
#You are given a string.
# Your task is to determine whether number of occurrences of some character in the string is equal to the sum of the numbers of
# occurrences of other characters in the string.
for i in range(int(input())):
s = input()
c = []
flag = 1
st = list(set(s))
for j in st:
c.append(s.count(j))
for j in range(len(c)):
if c[j] == sum(c)-c[j]:
flag = 0
print("YES")
break
if flag == 1:
print("NO") |
print("Enter the elements")
li = [int(x) for x in input().split()]
unique = set(li)
print("Maximum element in the set:",max(unique))
print("Minimum element in the set:",min(unique)) |
for i in range(int(input())):
salary = int(input())
if salary < 1500:
gross = salary + ((10 * salary) + (90 * salary))/100
else:
gross = salary + 500 + (98*salary)/100
print('%.2f'%gross) |
#Program to obtain a number and print how many digits number is it
def digitCount(number):
digits = 0
while(number > 0):
digits += 1
number //= 10
return digits
number = int(input())
print("the number of digits in the number are:",digitCount(number)) |
def split_and_join(line):
line = line.split(" ")
newline = '-'.join(line)
return newline
line = input()
result = split_and_join(line)
print(result) |
import gym
import numpy as np
env = gym.make("MountainCar-v0")
LEARNING_RATE = 0.1
DISCOUNT = 0.95
# how important future rewards are, compared to current rewards
EPISODES = 25000
# measure of how often to do a 'random' action and explore
epsilon = 0.5
# we dont want to always do a random action. decay lowers the amount over time
START_EPSILON_DECAYING = 1
# end decay halfway through
END_EPSILON_DECAYING = EPISODES//2
# amount to decrement by
epsilon_decay_value = epsilon/(END_EPSILON_DECAYING-START_EPSILON_DECAYING)
RENDER_FREQ = 1000
"""
Q Learning is like a table, where you look up the state variables and get an action.
However, the observations are very accurate numbers, and getting a action for every one would be inefficient
We can group the variables to make them smaller and 'discrete'.
DISCRETE_OS_SIZE is the 'chunks' to round the observations to
length of observation_space.high is the number of observations
"""
DISCRETE_OS_SIZE = [20]*len(env.observation_space.high)
discrete_os_win_size = (env.observation_space.high - env.observation_space.low) / DISCRETE_OS_SIZE
print(
f"""
Highest Observations: {env.observation_space.high}
Lowest Observations: {env.observation_space.low}
Observations in chunks: {discrete_os_win_size}
"""
)
q_table = np.random.uniform(low=-2, high=0, size=(DISCRETE_OS_SIZE + [env.action_space.n]))
"""
creates a 20x20x3 table (DISCRETE_OS_SIZE is 20x20 list, there are 3 actions for this environment)
20x20 is every combination of every observation from the environment
x3 is what action to take for each combination of observations
Q values are random to start with
Refer to notes for 2D table
"""
def get_discrete_state(state):
"""
:param state: observations of current state as np array
:return: the state as discrete values (rounded to the nearest chunk) as tuple
"""
discrete_state = (state - env.observation_space.low) / discrete_os_win_size
return tuple(discrete_state.astype(np.int))
for ep in range(EPISODES):
if ep % RENDER_FREQ == 0:
render = True
else:
render = False
# env.reset returns the starting state
discrete_state = get_discrete_state(env.reset())
done = False
while not done:
action = np.argmax(q_table[discrete_state])
# get the action for the current state
if render:
env.render()
new_state, reward, done, _ = env.step(action)
new_discrete_state = get_discrete_state(new_state)
if not done:
max_future_q = np.max(q_table[new_discrete_state])
# get highest Q value
current_q = q_table[discrete_state + (action, )]
# get q value of action
new_q = (1-LEARNING_RATE) * current_q + LEARNING_RATE * (reward + DISCOUNT * max_future_q)
# new q value to update with using the q learning formula
q_table[discrete_state + (action, )] = new_q
# update the action that we took previously to the new q value. this isn't the new discrete state
elif new_state[0] >= env.goal_position:
q_table[discrete_state + (action, )] = 0
print('Finished')
# if we have finished, update q value to 0 (a reward)
discrete_state = new_discrete_state
if END_EPSILON_DECAYING >= ep >= START_EPSILON_DECAYING:
epsilon -= epsilon_decay_value
env.close()
|
class HTNode(object):
def __init__(self, item, next):
self.item = item
self.next = next
class hash_table(object):
def __init__(self, table_size):
self.size = 0
self.table = [None] * table_size
# hash function using the first letter in each word to place words
def hash_func(self, word, letter):
return (word ** letter) % len(self.table)
# average number of comparisons
def avg_comps(self):
total_nodes = 0
compd_nodes = 0
for i in range(len(self.table)):
temp = self.table[i]
# increase compared nodes for each extra node in a index
if temp is not None:
compd_nodes += 1
# increase total nodes and increment temp
while temp is not None:
total_nodes += 1
temp = temp.next
# calculate average comparisons
avg = total_nodes / compd_nodes
print(avg)
# calculate load factor
def load_factor(self):
lf = self.size / len(self.table)
print(lf)
# find the ascii value of words
def ascii(self, word):
ascii_value = 0
# loop through each character in word
for char in word:
# use ord() to get the ascii value of each char and then add chars together
ascii_value += ord(char)
return ascii_value
def insert(self, item):
self.size += 1
ascii_word = self.ascii(item)
# set first letter of the word
letter = self.ascii(item[:1])
i = self.hash_func(ascii_word, letter)
self.table[i] = HTNode(item, self.table[i])
class hash_table2(object):
def __init__(self, table_size):
self.size = 0
self.table = [None] * table_size
# hash function using the first letter in each word to place words
def hash_func(self, word, length):
return (word ** length) % len(self.table)
# average number of comparisons
def avg_comps(self):
total_nodes = 0
compd_nodes = 0
for i in range(len(self.table)):
temp = self.table[i]
# increase compared nodes for each extra node in a index
if temp is not None:
compd_nodes += 1
# increase total nodes and increment temp
while temp is not None:
total_nodes += 1
temp = temp.next
# calculate average comparisons
avg = total_nodes / compd_nodes
print(avg)
# calculate load factor
def load_factor(self):
lf = self.size / len(self.table)
print(lf)
# find the ascii value of words
def ascii(self, word):
ascii_value = 0
# loop through each character in word
for char in word:
# use ord() to get the ascii value of each char and then add chars together
ascii_value += ord(char)
return ascii_value
def insert(self, item):
self.size += 1
ascii_word = self.ascii(item)
# set length of the word
length = len(item)
i = self.hash_func(ascii_word, length)
self.table[i] = HTNode(item, self.table[i])
# set table size to 26
hashtable = hash_table(26)
hashtable2 = hash_table2(10)
#open word file and insert into hash table
with open("words.txt", "r") as file:
for line in file:
hashtable.insert(line)
hashtable2.insert(line)
# print avg comparisons and load factor
print("")
print("Average comparisons:")
hashtable.avg_comps()
hashtable2.avg_comps()
print("Load factor: ")
hashtable.load_factor()
hashtable2.load_factor() |
"""
Basic console application that allows the user to guess
the outcome of a random coin flip or dice roll
"""
import time, random
def coin_flip():
global correct
global total
global start
print(f"Your score is {correct} out of {total}")
guess_coin = input("Heads or tails? >>> ").lower().replace(" ", "")
print("Let's flip it...")
time.sleep(1)
flip_res_n = random.randint(1, 2)
if flip_res_n == 1:
flip_res = "tails"
else:
flip_res = "heads"
print(f"It lands on... {flip_res}")
time.sleep(1)
if guess_coin == flip_res:
print ("Good job! You guessed right")
correct += 1
else:
print ("You guessed wrong. Try again!")
total += 1
start = input("Another game? yes/no >>> ").replace(" ", "")
def roll_dice():
global correct
global total
global start
print(f"Your score is {correct} out of {total}")
guess_dice = input("Your guess for dice? 1-6 >>> ").lower().replace(" ", "")
print("Let's roll it...")
time.sleep(1)
dice_res = random.randint(1, 6)
print(f"The result is... {dice_res}")
time.sleep(1)
if int(guess_dice) == dice_res:
print ("Good job! You guessed right")
correct += 1
else:
print ("You guessed wrong. Try again!")
total += 1
start = input("Another game? yes/no >>> ").replace(" ", "")
start = input("Ready to start? yes/no >>> ").lower().replace(" ", "")
total = 0
correct = 0
while start == "yes":
game = input("Choose a game: Coin flip or dice roll? >>> ").lower().replace(" ", "")
#print(game)
if game == "coinflip":
coin_flip()
elif game == "diceroll":
roll_dice()
else:
print("Something wrong. Try again")
start = input("Ready to start? yes/no >>> ").lower().replace(" ", "")
|
#!/usr/bin/env python3
import sys
import math
from collections import namedtuple as t
######################Helping definitions##########################
Planet = t('Planet', [
'name',
'parent',
'child'
])
Orbit = t('Orbit', [
'center',
'child'
])
Traversal = t('Traversal', [
'seen',
'depth'
])
#######################Helping functions###########################
def data_parser(filepath):
"""
Parse the data by splitting the line by commas, and making input
to ints
"""
orbit_list = []
with open(filepath, 'r') as f:
for line in f:
center,orbit = line.split(")")
orbit_list.append(Orbit(center.rstrip(),orbit.rstrip()))
return orbit_list
def generate_orbit_graph(orbit_list):
"""
Generates an acrylic graph based on the orbits from input
"""
# Return a dict with planet name as key, and
orbit_graph = dict()
for orbit in orbit_list:
if orbit.center not in orbit_graph:
orbit_graph[orbit.center] = Planet(orbit.center,[],[])
if orbit.child not in orbit_graph:
orbit_graph[orbit.child] = Planet(orbit.child,[],[])
orbit_graph[orbit.center].child.append(orbit.child)
orbit_graph[orbit.child].parent.append(orbit.center)
return orbit_graph
def distance_between(planet_a,planet_b,orbit_graph,traversed = []):
"""
Find the distance between two planets by orbital graph.
"""
# If the planet has already been traversed, we terminate
if planet_a.name in traversed or planet_b.name in traversed:
return Traversal(False,0)
# If the planet hits, we got a possible travel
if planet_a.name == planet_b.name:
return Traversal(True,0)
# Find child
for child in planet_a.child:
t = traversed.copy()
t.append(planet_a.name)
travel = distance_between(orbit_graph[child],planet_b,orbit_graph,t)
if travel.seen:
return Traversal(True,travel.depth + 1)
# Find parent
for parent in planet_a.parent:
t = traversed.copy()
t.append(planet_a.name)
travel = distance_between(orbit_graph[parent],planet_b,orbit_graph,t)
if travel.seen:
return Traversal(True,travel.depth + 1)
return Traversal(False,0)
def total_orbits(orbit_graph):
"""
Traverse the graph recursively, and save if the note has been seen,
and the depth. Sum over all this for all planets
"""
def travel(from_planet,to_planet):
#print("-------------",(from_planet,to_planet))
if from_planet.name == to_planet.name:
return Traversal(True,0)
if len(orbit_graph[from_planet.name]) == 0:
return Traversal(False,0)
temp = [travel(orbit_graph[x],to_planet) for x in orbit_graph[from_planet.name].child]
result = list(filter(lambda x: x.seen, temp))
result.sort(key = lambda x: x.depth)
if result == []:
return Traversal(False,0)
return Traversal(True,result[0].depth + 1)
return sum([travel(orbit_graph["COM"],orbit_graph[planet]).depth for planet in orbit_graph])
#########################Main functions############################
def solver_1star(d):
"""
Generate the orbit graph, and count the orbits
"""
orbit_graph = generate_orbit_graph(d)
return total_orbits(orbit_graph)
def solver_2star(d):
"""
Use the orbit graph, and traverse between the planets
"""
orbit_graph = generate_orbit_graph(d)
travel = distance_between(orbit_graph["YOU"],orbit_graph["SAN"],orbit_graph)
return travel.depth - 2
##############################MAIN#################################
def main():
"""
Run the program by itself, return a tuple of star1 and star2
"""
input_source = "../input1.txt"
# Make list, since the generator has to be used multiple times
d = list(data_parser(input_source))
return (solver_1star(d),solver_2star(d))
if __name__ == "__main__":
star1,star2 = main()
if len(sys.argv) == 2:
arg = sys.argv[1]
if arg == '1':
print(star1)
elif arg == '2':
print(star2)
else:
print("Day 1 first star:")
print(star1)
print("Day 1 second star:")
print(star2) |
#Write a program which will: Ask for two numbers. Then offers a menu to the user giving them a choice of operator e.g. – Enter “a” if you want to add “b” if you want to subtract Etc. Include +, -, /, *, **(to the power of) and square.
#define my function
def calculator():
#cast inputs to floats to get two float inputs
num1 = float(input("Please enter your first number:\n"))
num2 = float(input("Now please enter your second number:\n"))
#next input is choice
choice = input("Would you like to:\na - add your numbers.\nb - subtract your numbers.\nc - multiply your numbers.\nd - divide your numbers.\ne - multiply by the power of.\nf - square.\n")
#open if and elif statements for choice
if choice == "a":
print (num1, "plus", num2, "is", num1+num2)
elif choice == "b":
print (num1, "take away", num2, "is", num1-num2)
elif choice == "c":
print (num1, "multiplied by", num2, "is", num1*num2)
elif choice == "d":
print (num1, "divided by", num2, "is", num1/num2)
elif choice == "e":
print (num1, "muliplied by the power of", num2, "is", num1**num2)
elif choice == "f":
print (num1, "squared is", num1**2, "and", num2, "squared is", num2**2)
# and else in case of invalid entry
else:
print("Invalid entry")
#run funcation
calculator()
|
#Define method which takes number and returns depending if even or odd a return value
def collatz(number):
calculatedNumber = 0
if number%2 == 0:
calculatedNumber = number//2
else:
calculatedNumber = number * 3 + 1
print(calculatedNumber)
return calculatedNumber
#User input
try:
print("Input as number:")
userInput = int(input())
while userInput!= 1:
userInput = collatz(userInput)
except ValueError:
print("Please type in a number")
|
'''
https://open.kattis.com/problems/icpcteamselection
'''
import sys
def test():
assert(solve([9, 8, 10, 9, 6, 8], 2) == 17)
assert(solve([1, 2, 3, 4, 5, 6, 7, 8, 9], 3) == 18)
assert(solve([1, 100, 51], 1) == 51)
assert(solve([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3], 4) == 21)
print("All Tests Passed...")
def solve(scores, numOfTeams):
scores.sort(reverse=True)
total = 0
for i in range(numOfTeams):
total += scores[i*2+1]
# # wrong solution...
# team = []
# for member in range(3):
# score = scores.pop(0)
# team.append(score)
# team.sort()
# total += team[1]
return(total)
if __name__ == "__main__":
if len(sys.argv) > 1 and sys.argv[1] == 'test':
test()
else:
for i in range(int(input())):
numOfTeams = int(input())
scores = [int(num) for num in input().split()]
print(solve(scores, numOfTeams))
'''
for i in range(int(input())):
numOfTeams = int(input())
scores = [int(num) for num in input().split()]
scores.sort(reverse = True)
# print(scores)
total = 0
for i in range(numOfTeams):
total += scores[i*2+1]
# team = []
# for member in range(3):
# score = scores.pop(0)
# team.append(score)
# team.sort()
# total += team[1]
print(total)
'''
|
# Задача-1:
# Дан список, заполненный произвольными целыми числами, получите новый список,
# элементами которого будут квадратные корни элементов исходного списка,
# но только если результаты извлечения корня не имеют десятичной части и
# если такой корень вообще можно извлечь
# Пример: Дано: [2, -5, 8, 9, -25, 25, 4] Результат: [3, 5, 2]
import math
a=[2, -5, 8, 9, -25, 25, 4]
b=[]
for i in a:
if i > 0:
x = math.sqrt(i)
if x - int(x) == 0:
b.append(int(x))
print(b)
# Задача-2: Дана дата в формате dd.mm.yyyy, например: 02.11.2013.
# Ваша задача вывести дату в текстовом виде, например: второе ноября 2013 года.
# Склонением пренебречь (2000 года, 2010 года)
import datetime
import locale
loc=locale.getlocale()
locale.setlocale(locale.LC_ALL, ('RU','UTF8'))
days = [
"undefined",
"первое",
"второе",
"третье",
"четвертое",
"пятое",
"шестое",
"седьмое",
"восьмое",
"девятое",
"десятое",
"одиннадцатое",
"двенадцатое",
"тринадцатое",
"четырнадцатое",
"пятнадцатое",
"шестнадцатое",
"и т.п."
]
today = "02.11.2013"
b = today.split('.')
day = int(b[0])
month = int(b[1])
year = b[2]
print(days[day], datetime.date(1900, month, 1).strftime('%B'), year, "года")
# Задача-3: Напишите алгоритм, заполняющий список произвольными целыми числами
# в диапазоне от -100 до 100. В списке должно быть n - элементов.
# Подсказка:
# для получения случайного числа используйте функцию randint() модуля random
import random
a=[]
while len(a) <= 100:
a.append(random.randint(-100,100))
print(a)
# Задача-4: Дан список, заполненный произвольными целыми числами.
# Получите новый список, элементами которого будут:
# а) неповторяющиеся элементы исходного списка:
# например, lst = [1, 2, 4, 5, 6, 2, 5, 2], нужно получить lst2 = [1, 2, 4, 5, 6]
# б) элементы исходного списка, которые не имеют повторений:
# например, lst = [1 , 2, 4, 5, 6, 2, 5, 2], нужно получить lst2 = [1, 4, 6]
a=[1, 2, 4, 5, 6, 2, 5, 2]
b=[]
c=[]
for i in a:
if a.count(i) > 1:
b.append(i)
else:
c.append(i)
print(a)
print(b)
print(c)
|
# Задача-2:
# Даны два произвольные списка.
# Удалите из первого списка элементы, присутствующие во втором списке.
a=[1,2,3,3,4,4,5,6,10,12]
b=[3,4,5,6,7,8]
a = list(set(a) - set(b))
print(a)
|
class Program:
def __init__(self, name, weight, sub):
self.name = name
self.weight = weight
self.cum_weight = weight
# A leaf is balanced
self.balanced = True
# Construct the sub nodes
self.sub = []
for i in sub:
self.sub.append(Program(*tuples[i]))
# Am I balanced?
if len(self.sub):
weights = [ x.cum_weight for x in self.sub ]
if max(weights) != min(weights):
self.balanced = False
self.cum_weight += sum(weights)
def find_wrong(self, diff):
if self.balanced:
return self.weight + diff
weights = [ x.cum_weight for x in self.sub ]
possible_wrong = [ i for i in range(len(self.sub)) if weights.count(self.sub[i].cum_weight) == 1 ]
# Check the understanding of the problem, and the tree's construction
if len(self.sub) == 2:
raise Exception("In {}, two unbalanced: {}".format(self.name, weights))
if len(possible_wrong) > 1:
raise Exception("In {}, more than one wrong: {}".format(self.name, possible_wrong))
if not len(possible_wrong):
raise Exception("In {} but there's no wrong son...".format(self.name))
wrong = possible_wrong[0]
if diff == 0:
diff = self.sub[wrong-1].cum_weight - self.sub[wrong].cum_weight
return self.sub[wrong].find_wrong(diff)
def __str__(self):
return self.print(0, recur=True)
def print(self, depth, recur=False):
string = "{}{}: weight {}, cum_weight {}, {} sons, balanced: {}, sons: {}\n".format(depth*'\t', self.name, self.weight, self.cum_weight, len(self.sub), self.balanced, [ s.name for s in self.sub ])
if recur:
for i in self.sub:
string += i.print(depth+1, recur=recur)
return string
# Construct a dict with all nodes as tuples: (name, weight, list of sub-nodes)
#f = open("test7", "r")
f = open("input7", "r")
tuples={}
for i in f.readlines():
words = i.split()
name = words[0]
weight = int(words[1].replace(')', '').replace('(',''))
subs=[]
if len(words) > 2:
subs = [ x.replace(',', '') for x in words[3:] ]
tuples[name] = (name, weight, subs)
possible_roots = list(tuples.keys())
for i in tuples.keys():
for son in tuples[i][2]:
possible_roots.remove(son)
# Now that we have the root, construct the tree
root = possible_roots[0]
print(root)
a = Program(*tuples[root])
#print(a)
# Answer step 2
print(a.find_wrong(0))
|
from __future__ import print_function, unicode_literals
"""
1a. Create an ssh_conn function. This function should have three parameters: ip_addr, username,
and password. The function should print out each of these three variables and clearly indicate which
variable it is printing out.
Call this ssh_conn function using entirely positional arguments.
Call this ssh_conn function using entirely named arguments.
Call this ssh_conn function using a mix of positional and named arguments.
1b. Expand on the ssh_conn function from exercise1 except add a fourth parameter 'device_type'
with a default value of 'cisco_ios'. Print all four of the function variables out as part of the
function's execution.
Call the 'ssh_conn2' function both with and without specifying the device_type
Create a dictionary that maps to the function's parameters. Call this ssh_conn2 function using
the **kwargs technique.
"""
# Create an ssh_conn function. This function should have three parameters: ip_addr, username,
# and password. The function should print out each of these three variables and clearly indicate which
# variable it is printing out.
def ssh_conn(ip_addr, username, password):
print()
print('IP ADDRESS: {}'.format(ip_addr))
print('USERNAME: {}'.format(username))
print('PASSWORD: {}'.format(password))
print()
# Call this ssh_conn function using entirely positional arguments.
ssh_conn('10.1.1.1', 'roberto', 'P@ssw0rd')
# Call this ssh_conn function using entirely named arguments.
ssh_conn(ip_addr='172.21.10.1', username='roberto', password='myP@ssw0rd')
# Call this ssh_conn function using a mix of positional and named arguments.
ssh_conn('192.168.0.1', 'User', password='MyPass')
# Expand on the ssh_conn function from exercise1 except add a fourth parameter 'device_type'
# with a default value of 'cisco_ios'. Print all four of the function variables out as part of the
# function's execution.
def ssh_conn2(ip_addr, username, password, device_type='cisco_ios'):
print()
print('IP ADDRESS: {}'.format(ip_addr))
print('USERNAME: {}'.format(username))
print('PASSWORD: {}'.format(password))
print('DEVICE TYPE: {}'.format(device_type))
print()
# Call the 'ssh_conn2' function both with and without specifying the device_type
ssh_conn2('5.5.5.5', 'roberto', 'MyP@ss')
ssh_conn2('5.5.5.5', 'roberto', 'MyP@ss', 'junos')
# Create a dictionary that maps to the function's parameters. Call this ssh_conn2 function using
# the **kwargs technique.
dev_dict = {
'ip_addr': '9.9.9.9',
'username': 'roberto',
'password': 'myP@ss3',
'device_type': 'eos'
}
ssh_conn2(**dev_dict)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.