text
stringlengths 37
1.41M
|
---|
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 12 00:09:36 2020
@author: jayada1
"""
def find_order(words):
cols = max([len(w) for w in words])
rows = len(words)
matrix = list()
for word in words:
word_col = list(word)
word_col.extend([None]*(cols-len(word)))
matrix.append(word_col)
letter_list = list()
for j in range(0, rows):
if matrix[j][0] not in letter_list:
letter_list.append(matrix[j][0])
print(letter_list)
words = ["baa", "abcd", "abca", "cab", "cad"]
find_order(words)
|
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 18 13:06:57 2019
@author: jayada1
create heap from an unsorted array
"""
class BinaryHeap():
def __init__(self):
self.heap = []
def insert(self, val):
i = self.size()
self.heap.append(val)
while i != 0:
p = self.parent(i)
if self.get(i) > self.get(p):
self.swap(i, p)
i = p
def insert_simple(self, arr):
for i in arr:
self.heap.append(i)
return self.heap
def delete(self):
self.heap.pop(0)
# The method size returns the number of elements in the heap.
def size(self):
return len(self.heap)
# The method parent takes an index as argument and returns the index of the parent.
def parent(self, index):
return (index - 1) // 2
# The method left takes an index as argument and returns the index of its left child.
def left(self, index):
return 2 * index + 1
# The method right takes an index as argument and returns the index of its right child.
def right(self, index):
return 2 * index + 2
# The method get takes an index as argument and returns the key at the index.
def get(self, index):
return self.heap[index]
# The method get_max returns the maximum element in the heap by returning the first element in the list items.
def get_max(self):
if self.size == 0:
return None
return self.heap[0]
# The method extract_max returns the the maximum element in the heap and removes it.
def extract_max(self):
pop = self.heap.index(self.get_max())
return self.heap.pop(pop)
# The method max_heapify takes an index as argument and modifies
# the heap structure at and below the node at this index to make it
# satisfy the heap property.
def max_heapify(self, index):
pass
def swap(self, index, maxval_i):
self.heap[index], self.heap[maxval_i] = self.heap[maxval_i], self.heap[index]
def heapify(self, index):
heap = self.heap
ri = self.right(index)
li = self.left(index)
size = self.size()
print(ri, li, sep=' ')
if li < size and heap[li] > heap[index]:
maxval_i = li
if ri < size and heap[ri] > heap[maxval_i]:
maxval_i = ri
elif maxval_i != index:
self.swap(index, maxval_i)
self.heapify(index)
bheap = BinaryHeap()
print('Menu')
print('insert <data>')
print('max get')
print('max extract')
print('print')
print('heapify')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'insert':
data = int(do[1])
bheap.insert(data)
elif operation == 'max':
suboperation = do[1].strip().lower()
if suboperation == 'get':
print('Maximum value: {}'.format(bheap.get_max()))
elif suboperation == 'extract':
print('Maximum value removed: {}'.format(bheap.extract_max()))
elif operation == 'print':
print(bheap.heap)
elif operation == 'heapify':
heap = bheap.insert_simple([7, 10, 4, 3, 20, 15])
for i in range(len(heap), 0, -1):
bheap.heapify(i)
elif operation == 'quit':
break
|
"""
Implement the RandomizedSet class:
RandomizedSet() Initializes the RandomizedSet object.
bool insert(int val) Inserts an item val into the set if not present. Returns true if the item was not present, false otherwise.
bool remove(int val) Removes an item val from the set if present. Returns true if the item was present, false otherwise.
int getRandom() Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the same probability of being returned.
You must implement the functions of the class such that each function works in average O(1) time complexity.
"""
import random
class RandomizedSet:
def __init__(self):
self.num_hash = {}
self.num_list = []
def insert(self, val):
if val in self.num_hash: # O(1)
return False
else:
self.num_list.append(val) # O(1)
self.num_hash[val] = len(self.num_list) - 1 # O(1)
return True
def remove(self, val):
if val in self.num_hash:
pos = self.num_hash[val]
self.num_list[pos] = self.num_list[-1]
self.num_hash[self.num_list[-1]] = pos
self.num_list.pop() # O(1)
self.num_hash.pop(val) # O(1)
return True
else:
return False
def getRandom(self):
return random.choice(self.num_list)
# Your RandomizedSet object will be instantiated and called as such:
# obj = RandomizedSet()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom()
"""
1. Can we use builtin random functions?
2. What happens if only 1 element is present in the map and list
"""
|
from collections import Counter
candidates = [2,3,6,7]
target = 7
Counter
def find_combination(nums, target, path, res):
if target < 0:
return
if target == 0:
res.append(path)
return
for i in range(len(nums)):
find_combination(nums[i:], target-nums[i], path+[nums[i]], res)
def combination_sum(candidates, target):
res = []
find_combination(candidates, target, [], res)
return res
print(combination_sum(candidates, target))
|
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 3 11:34:10 2019
@author: jayada1
"""
arr = [1,2,3,4,5,6,7]
d = 2
n = 7
def rotate(arr, d, n):
new_arr = arr[d:]
new_arr.extend(arr[0:d])
return new_arr
print(rotate(arr, d, n))
"""
num = 123
output : 231, 312
num = 1445
output: 4451, 4514, 5144
"""
def find_num_digits(num):
count = 0
while num>0 :
num = int(num /10)
count += 1
return count
def generate_all_left_rotations(num):
n = find_num_digits(num) - 1
for i in range (0,n):
first_digit = int(num / (10**n))
remain_digits = num % (10**n)
num = remain_digits * 10 + first_digit
print(num)
generate_all_left_rotations(1445)
arr = [2,3,4,1,5]
arr2 = [2,31,1,38,29,5,44,6,12,18,39,9,48,49,13,11,7,27,14,33,50,21,46,23,15,26,8,47,40,3,32,22,34,42,16,41,24,10,4,28,36,30,37,35,20,17,45,43,25,19]
arr3 = [8,45,35,84,79,12,74,92,81,82,61,32,36,1,65,44,89,40,28,20,97,90,22,87,48,26,56,18,49,71,23,34,59,54,14,16,19,76,83,95,31,30,69,7,9,60,66,25,52,5,37,27,63,80,24,42,3,50,6,11,64,10,96,47,38,57,2,88,100,4,78,85,21,29,75,94,43,77,33,86,98,68,73,72,13,91,70,41,17,15,67,93,62,39,53,51,55,58,99,46]
def minimumSwaps(arr):
sorted_arr = arr.copy()
arr.sort()
n = len(arr)
err = 0
for i in range(0,n):
if arr[i]==sorted_arr[i]:
err += 1
if err!=0:
return n - err - 1
err = minimumSwaps(arr3)
print(err)
'Array' == 'array'
"""
Rearrange an array such that arr[i] = i
Input : arr = {-1, -1, 6, 1, 9, 3, 2, -1, 4, -1}
Output : [-1, 1, 2, 3, 4, -1, 6, -1, -1, 9]
Input : arr = {19, 7, 0, 3, 18, 15, 12, 6, 1, 8,
11, 10, 9, 5, 13, 16, 2, 14, 17, 4}
Output : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17, 18, 19]
"""
def array_rearrange(arr):
l = len(arr)
new_arr = [None] * l
for i in range(0, l):
if i in arr:
new_arr[i] = i
else:
new_arr[i] = -1
print(new_arr)
array_rearrange([-1, -1, 6, 1, 9, 3, 2, -1, 4, -1])
array_rearrange([19, 7, 0, 3, 18, 15, 12, 6, 1, 8,
11, 10, 9, 5, 13, 16, 2, 14, 17, 4])
l = [-1, -1, 6, 1, 9, 3, 2, -1, 4, -1]
"""
Move all zeroes to end of array
Input : arr[] = {1, 2, 0, 4, 3, 0, 5, 0};
Output : arr[] = {1, 2, 4, 3, 5, 0, 0};
Input : arr[] = {1, 2, 0, 0, 0, 3, 6};
Output : arr[] = {1, 2, 3, 6, 0, 0, 0};
"""
def move_zeroes_to_end_while(arr):
n = len(arr)-1
i = 0
j = 0
while j <= n:
if arr[i] == 0:
arr.pop(i)
arr.append(0)
else:
i = i + 1
j += 1
print(arr)
#test cases
move_zeroes_to_end_while([1, 2, 0, 4, 3, 0, 5, 0])
move_zeroes_to_end_while([1, 2, 0, 0, 0, 3, 6])
move_zeroes_to_end_while([0, 1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9])
"""
Rearrange positive and negative numbers using inbuilt sort function
Given an array of positive and negative numbers, arrange them such that all negative integers appear before all the positive integers in the array without using any additional data structure like hash table, arrays, etc. The order of appearance should be maintained.
Examples:
Input : arr[] = [12, 11, -13, -5, 6, -7, 5, -3, -6]
Output : arr[] = [-13, -5, -7, -3, -6, 12, 11, 6, 5]
Input : arr[] = [-12, 11, 0, -5, 6, -7, 5, -3, -6]
Output : arr[] = [-12, -5, -7, -3, -6, 0, 11, 6, 5]
"""
def Rearrange(arr):
# First lambda expression returns list of negative numbers
# in arr.
# Second lambda expression returns list of positive numbers
# in arr.
return [x for x in arr if x < 0] + [x for x in arr if x >= 0]
arr = [12, 11, -13, -5, 6, -7, 5, -3, -6]
print(Rearrange(arr) )
"""
Rearrange an array in order – smallest, largest, 2nd smallest, 2nd largest, ..
Given an array of integers, task is to print the array in the order – smallest number, Largest number, 2nd smallest number, 2nd largest number, 3rd smallest number, 3rd largest number and so on…..
Examples:
Input : arr[] = [5, 8, 1, 4, 2, 9, 3, 7, 6]
Output :arr[] = {1, 9, 2, 8, 3, 7, 4, 6, 5}
Input : arr[] = [1, 2, 3, 4]
Output :arr[] = {1, 4, 2, 3}
"""
def rearrange_s_l(arr):
n = int(len(arr)/2)
arr.sort()
new_arr = [None]*len(arr)
j = 0
for i in range(n):
new_arr[j]=arr[i]
new_arr[j+1]=arr[-i-1]
j += 2
new_arr[len(arr)-1] = arr[n]
print(new_arr)
rearrange_s_l([5, 8, 1, 4, 2, 9, 3, 7, 6])
rearrange_s_l([1, 2, 3, 4])
"""
Double the first element and move zero to end
Given an array of integers of size n. Assume ‘0’ as invalid number and all other as valid number. Convert the array in such a way that if next valid number is same as current number, double its value and replace the next number with 0. After the modification, rearrange the array such that all 0’s are shifted to the end.
Examples:
Input : arr[] = {2, 2, 0, 4, 0, 8}
Output : 4 4 8 0 0 0
Input : arr[] = {0, 2, 2, 2, 0, 6, 6, 0, 0, 8}
Output : 4 2 12 8 0 0 0 0 0 0
"""
def make_new_arr(arr):
n= len(arr)-1
count = 0
for i in range(n):
if arr[i]==0:
count += 1
arr.pop(i)
if arr[i] == arr[i+1]:
arr[i] *= 2
arr.pop(i+1)
count += 1
for j in range(count):
arr.append(0)
print(arr)
make_new_arr([2, 2, 0, 4, 0, 8])
with open('C:/Users/jayada1/Desktop/backup/study/portalscv.txt','r') as f:
for line in f:
print(line)
def minimumSwaps(arr):
count = 0
n = len(arr)
sorted_arr = [i for i in range(1,n+1)]
diff_arr = [i1-i2 for i1,i2 in zip(sorted_arr,arr)]
for item in diff_arr:
if item != 0:
count+=1
return count-1
#arr = [2,31,1,38,29,5,44,6,12,18,39,9,48,49,13,11,7,27,14,33,50,21,46,23,15,26,8,47,40,3,32,22,34,42,16,41,24,10,4,28,36,30,37,35,20,17,45,43,25,19]
arr = [1,3,5,2,4,6,7]
minimumSwaps(arr)
|
# https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/
def remove_duplicates_str(s):
stack = []
for c in s:
if stack and stack[-1] == c:
stack.pop()
else:
stack.append(c)
return "".join(stack)
# print(remove_duplicates_str("abbaca"))
# print(remove_duplicates_str("azxxzy"))
# https://leetcode.com/problems/removing-stars-from-a-string/
def remove_stars(s):
stack = []
for c in s:
if c == '*' and stack:
stack.pop()
else:
stack.append(c)
print("".join(stack))
# remove_stars("leet**cod*e")
# remove_stars("erase*****")
# https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string-ii/
def remove_adjacent_duplicate_with_k(s, k):
stack = []
for elem in s:
if stack and stack[-1][0] == elem:
stack[-1][1] += 1
else:
stack.append([elem, 1])
if stack[-1][1] == k:
stack.pop()
print(stack)
res = ""
for elem, count in stack:
res += elem*count
print(res)
remove_adjacent_duplicate_with_k("deeedbbcccbdaa", 3)
|
# https://leetcode.com/discuss/interview-question/364618/
def count_min_steps_equalize(arr):
arr.sort(reverse=True) # O(nlogn)
steps = 0
n = len(arr)
i = 0
while i in range(n-1): # O(n)
if arr[i] > arr[i+1]:
# for k in range(0,i+1): # O(n)
# arr[k] = arr[i+1]
# steps += 1
steps += i+1
i += 1
return steps
# piles = [5, 2, 1]
# piles = [1,1,2,2,2,3,3,3,4,4]
# piles = [2,1]
# piles = [10, 10]
# piles = []
# piles = [4,5,5,4,2]
# piles = [4,8,8]
piles = [5,2,1,6]
print(count_min_steps_equalize(piles))
|
envelopes = [[5, 4], [6, 4], [6, 7], [2, 3]]
def merge_sorted_arrays(left, right, m, n):
sorted_array = []
i = 0
j = 0
while i < m and j < n:
if left[i] <= right[j]:
sorted_array.append(left[i])
i += 1
else:
sorted_array.append(right[j])
j += 1
if i < m:
sorted_array.extend(left[i:])
if j < n:
sorted_array.extend(right[j:])
return sorted_array
def merge_sort(envelopes, sorted_array):
if len(envelopes) > 1:
mid = len(envelopes) // 2
left = merge_sort(envelopes[:mid], sorted_list)
right = merge_sort(envelopes[mid:], sorted_list)
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
sorted_array.append(left[i])
i += 1
else:
sorted_array.append(right[j])
j += 1
if i < len(left):
sorted_array.extend(left[i:])
if j < len(right):
sorted_array.extend(right[j:])
return sorted_array
def sort_envelopes(envelopes):
sorted_envelopes = []
# left = [1, 5, 7, 13, 15]
# right = [2, 4, 10]
# merge_sorted_arrays(left, right, len(left), len(right))
arr = [1, 13, 14, 2, 6, 5, 9, 10, 2]
sorted_list = []
e = merge_sort(arr, sorted_list)
print(e)
|
def sort_array_recursive(arr, sorted_array):
if not arr:
return sorted_array
min_num = arr[0]
min_idx = 0
for i, n in enumerate(arr):
if n < min_num:
min_num = n
min_idx = i
sorted_array.append(min_num)
return sort_array_recursive(arr[:min_idx] + arr[min_idx + 1:], sorted_array)
sorted_arr = []
sort_array_recursive([7, 2, 3, 6, 6, 5, 4, -1], sorted_arr)
print(sorted_arr)
def find_min_in_array(arr, n, min_num, idx):
if n == 0:
return min_num, idx
idx = n
min_num = min(min_num, find_min_in_array(arr, n-1, min_num, idx))
return min_num, idx
|
# original = [5, 2, 4, 3, 1, 6] #works
# original = [1,2,3,4] #works
# original = [3, 6, 4, 2, 1] #works
original = [4,3,2,1]
temp_stack = []
sorted_stack = []
while original:
if not sorted_stack:
sorted_stack.append(original.pop())
while sorted_stack:
if original[-1] > sorted_stack[-1]:
temp_stack.append(sorted_stack.pop())
else:
break
sorted_stack.append(original.pop())
while temp_stack:
sorted_stack.append(temp_stack.pop())
print(sorted_stack)
print(original)
|
def solve(arr, start, n, k):
if n == 1:
return arr[0]
start = (start + k) % n
if arr:
arr.pop(start)
print(arr)
return solve(arr, start, n - 1, k)
# n = 7
# k = 3
#
n = 5
k = 2
def main(n, k):
arr = [i for i in range(1, n + 1)]
print(solve(arr, 0, n, k))
# main(n, k)
def josephus2(arr, n, k, curr):
if n == 1:
print(arr[0])
return
elif n > 1:
curr = (curr + k - 1) % n
arr.pop(curr)
josephus2(arr, n - 1, k, curr)
def josephus_iter(n, k, curr):
arr = [i for i in range(1, n + 1)]
while n > 1:
curr = (curr + k - 1) % n
arr.pop(curr)
n -= 1
return arr[0]
def main2(n, k):
arr = [i for i in range(1, n + 1)]
josephus2(arr, n, k, 0)
print(josephus_iter(n, k, 0))
main2(40, 7)
|
# n = 3
#
#
# def solve(n, output, stack):
# if n == 0:
# if not stack:
# output = output + '()'
# else:
# while stack:
# output = output + ')'
# stack.pop()
# print(output)
# elif n >= 1:
# solve(n - 1, output + ")", stack)
# for i in range(2):
# stack.append('(')
# solve(n - 1, output + "(", stack)
stack = ['(']
# solve(3, "(", stack)
def solve2(output, open, close):
if open == 0 and close == 0:
print(output)
return
if open > 0:
solve2(output + "(", open - 1, close)
if close > 0 and close > open:
solve2(output + ")", open, close - 1)
open = 2
close = 3
# solve2("(", open, close)
def generate(o, c, path, ret, n):
if len(path) == n*2:
ret.append(path)
return
if o < n:
generate(o + 1, c, path + "(", ret, n)
if c < n and c < o:
generate(o, c + 1, path + ")", ret, n)
ret = []
generate(0,0,"", ret, 3)
print(ret)
|
# https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/
def is_palindrome(word):
return word == word[::-1]
def longest_palindrome(words):
palindromes = []
for word in words:
if is_palindrome(word):
palindromes.append(word)
elif word[::-1] in words:
palindromes.append(word + word[::-1])
for word in words:
for pal in palindromes:
if word not in pal and word[::-1] in words and not is_palindrome(word):
palindromes.append(word+pal+word[::-1])
print(palindromes)
# words = ["ab", "ty", "yt", "lc", "cl", "ab"]
# words = ["lc","cl","gg"]
words = ["cc","ll","xx"]
longest_palindrome(words)
|
import re
def snack_checker(choice, options):
for var_list in options:
if choice in var_list:
chosen = var_list[0].title()
is_valid = "yes"
break
else:
is_valid = "no"
if is_valid == "yes":
return chosen
else:
return "invalid choice"
def get_snack():
# regular expression to find if item starts with a number
number_regex = "^[1-9]"
# valid snacks holds list of all snacks
# Each item in valid snacks is a list with
# valid options for each snack <full name, letter code (a - e)
# , and possible abbreviations etc>
valid_snacks = [
["popcorn", "p", "corn", "a"],
["M&M's", "m&m's", "mms", "m", "b"],
["pita chips", "chips", "pc", "pita", "c"],
["water", "w", "d"],
["orange juice", "oj", "o", "juice", "e"]
]
# holds snack order for a single user
snack_order = []
desired_snack = ""
while desired_snack != "xxx":
snack_row = []
# Ask the user for desired snack
desired_snack = input("Snack: ").lower()
if desired_snack == "xxx":
return snack_order
# if item has a number, seperate it into two (numbers / items)
if re.match(number_regex, desired_snack):
amount = int(desired_snack[0])
desired_snack = desired_snack[1:]
else:
amount = 1
desired_snack = desired_snack
# remove white space around snack
desired_snack = desired_snack.strip()
# check if snack is valid
snack_choice = snack_checker(desired_snack, valid_snacks)
if snack_choice == "invalid choice":
print("Please enter a valid option")
print()
# check snack amount is valid (less than 5)
if amount >= 5:
print("Sorry - we have a four snack maximum")
snack_choice = "invalid choice"
# add snack AND amount to list
snack_row.append(amount)
snack_row.append(snack_choice)
if snack_choice != "xxx" and snack_choice != "invalid choice":
snack_order.append(snack_row)
# valid options for yes / no questions
yes_no = [
["yes", "y"],
["no", "n"]
]
# ask the user if they want a snack
check_snack = "invalid choice"
while check_snack == "invalid choice":
want_snack = input("Do you want to order snacks?: ").lower()
check_snack = snack_checker(want_snack, yes_no)
# If user doesnt enter a valid option (yes/y or no/n), generate an error and ask the question again
if check_snack == "invalid choice":
print("Please enter a valid option")
print()
# If they want snacks, ask what snacks they want
if check_snack == "Yes":
get_order = get_snack()
else:
get_order =[]
# show snack orders
print()
if len(get_order) == 0:
print("Snack ordered: None")
else:
print("Snacks ordered: ")
for item in get_order:
print(item)
|
class myclass:
#__a,__b=0,0;
__var1 = 99;
def __init__(self):
self.a = 10;
self.b = 20;
print("instantiating");
#swaps a number without using a temporary variables...
def swap_values(self):
temp = 99; print ("temp is 20", 20);
print("before swaping",self.a,self.b);
self.a = self.a + self.b
self.b = self.a - self.b
self.a = self.a -self.b; print ("After swapping", self.a,self.b);
return
#isprime is used to see if the number is prime or not.
def isprime(n):
if n == 1:
print ("1 is special")
return False
for x in range(2,n):
if n%x == 0:
print("number is not prime")
return False
else:
print("number is prime")
#calculate factorial of a number
def cal_factorial(f):
t = 1;result = 1;
if f == 1:
print ("the factorial is one");
else:
while (f>0):
result = result*f;
f=f-1;
print ("the factorial is", result)
def main():
print("In main")
temp = myclass();
temp.swap_values();
#temp.print_private()
#call isprime to see if the number is prime or not.
isprime(3)
cal_factorial(4)
#call main
main()
|
# bike OOP
class Bike(object):
def __init__(self, name, price, max_speed, miles=0):
self.name = name
self.price = price
self.max_speed = max_speed
self.miles = miles
def displayInfo(self):
print "\n{}".format(self.name)
print "Price: {} dollars".format(self.price)
print "Maximum Speed: {} mph".format(self.max_speed)
print "Total Miles:", self.miles, "\n"
return self
def ride(self):
print "Riding {}!".format(self.name)
self.miles += 10
return self
def reverse(self):
print "Reversing {}!".format(self.name)
if (self.miles-5) < 0:
self.miles = 0
else:
self.miles -= 5
return self
# bike 1
bike1 = Bike("bike one", 200, 25)
bike1.ride().ride().ride().reverse().displayInfo()
# bike 2
bike2 = Bike("bike two", 1000, 40)
bike2.ride().ride().reverse().reverse().displayInfo()
# bike 3
bike3 = Bike("bike three", 800, 35)
bike3.reverse().reverse().reverse().displayInfo()
|
# bike OOP
class Bike(object):
def __init__(self, name, price, max_speed, miles=0):
self.name = name
self.price = price
self.max_speed = max_speed
self.miles = miles
def displayInfo(self):
print "\n{}".format(self.name)
print "Price: {} dollars".format(self.price)
print "Maximum Speed: {} mph".format(self.max_speed)
print "Total Miles:", self.miles, "\n"
def ride(self):
print "Riding {}!".format(self.name)
self.miles += 10
def reverse(self):
print "Reversing {}!".format(self.name)
if (self.miles-5) < 0:
self.miles = 0
else:
self.miles -= 5
# bike 1
bike1 = Bike("bike one", 200, 25)
bike1.ride()
bike1.ride()
bike1.ride()
bike1.reverse()
bike1.displayInfo()
# bike 2
bike2 = Bike("bike two", 1000, 40)
bike2.ride()
bike2.ride()
bike2.reverse()
bike2.reverse()
bike2.displayInfo()
# bike 3
bike3 = Bike("bike three", 800, 35)
bike3.reverse()
bike3.reverse()
bike3.reverse()
bike3.displayInfo()
|
reais = float(input('quanto dinheiro tem na carteira: '))
dol = 3.27
cambio = reais/dol
print(f'voce pode comprar {cambio:.2f} dólares')
|
import random, time
print('=-'*50)
print('Vou pensar em um numero entre 0 e 5. Tente adivinhar...')
print('=-'*50)
x = random.randrange(0, 5, 1)
y = int(input('Em qual numero eu pensei? '))
print('PROCESSANDO...')
time.sleep(1)
if x == y:
print('PARABENS!! Você conseguiu me vencer.')
else:
print(f'GANHEI!! Eu pensei no numero {x} e não {y}')
|
import datetime
contmaior = 0
contmenor = 0
hoje = datetime.date.today().year
for c in range(1, 8, 1):
n = int(input(f'ano de nascimento da {c}ª pessoa: '))
idade = hoje - n
if idade >= 18:
contmaior += 1
else:
contmenor += 1
print(f'{contmaior} pessoas maiores de 18\n'
f'{contmenor} pessoas menores de 18')
|
print('GERADOR DE PA')
print('=-'*20)
termo = int(input('digite o primeiro termo '))
razao = int(input('digite a razao '))
cont = 1
while cont <= 10:
print(f'{termo} - ', end='')
termo += razao
cont += 1
print('FIM')
|
n1 = int(input('digite um numero: '))
n2 = int(input('digite outro numero: '))
if n1 > n2:
print(f'o primeiro nr é maior: {n1}')
elif n2 > n1:
print(f'o segundo nr é maior: {n2}')
else:
print(f'os dois são iguais {n1} e {n2}')
|
n = 0
cont = 0
soma = 0
while n != 999:
soma += n
n = int(input('digite um nr (999 para parar): '))
if n == 999:
break
cont += 1
print(f'a soma dos {cont} valores é {soma}')
|
celcius = float(input('digite a temperatura em celcius: '))
fahren = ((9*celcius)/5)+32
print (f'a temperatura de {celcius} celcius é de {fahren} FH')
|
# IMPORTAÇÕES
# FUNÇÕES
def multa(velocidade):
if velocidade > 80:
print(f'VOCE FOI MULTADO! o limite é de 80 km/h\n'
f'Voce excedeu o limite em {(velocidade-80):.2f} km/h\n'
f'Valor da multa R$ {((velocidade - 80)*7):.2f}')
else:
print('velocidade dentro dos limites')
# PROGRAMA PRINCIPAL
vel = float(input('digite a velocidade: '))
multa(vel)
|
frase = str(input('digite a frase ')).strip().upper()
palavras = frase.split()
junto = ''.join(palavras)
inverso = ''
for c in range(len(junto)-1, -1, -1):
inverso += junto[c]
if junto == inverso:
print(f'{junto} é palindromo \n'
f'{junto} = {inverso}')
else:
print(f'{junto} não é palindromo\n'
f'{junto} != {inverso}')
|
matriz = [[], [], []]
num = 0
for l in range(0, 3):
for c in range(0, 3):
num = int(input(f'digite a posição {[l, c]}: '))
matriz[l].append(num)
for l in range(0, 3):
for c in range(0, 3):
print(f'[{(matriz[l][c]):^3}]', end='')
print()
|
with open("input.txt") as f:
buses_str = [x for x in f.readline().strip().split(",")]
buses = []
for (index, bus) in enumerate(buses_str):
if bus != "x":
bus = int(bus)
buses.append((bus, (bus - index) % bus))
buses = sorted(buses, key=lambda x: -x[0])
def closest_divisable(number, divident):
return number + (divident - number % divident) % divident
def closest_divisable_rem(number, divident, add, rem):
while number % divident != rem:
number += add
return number
def check(n, buses):
n = closest_divisable_rem(n, buses[1][0], buses[0][0], buses[1][1])
assert n % buses[0][0] == buses[0][1]
assert n % buses[1][0] == buses[1][1]
for (bus, index) in buses[2:]:
if n % bus != index:
return n
print(n)
exit()
# index = closest_divisable_rem(100000000000000, buses[0][0], 1, buses[0][1])
# while True:
# index = check(index, buses)
# index += buses[0][0]
def check2(base, multiplier, divident, rem):
while True:
if base % divident == rem:
return base
base += multiplier
number = closest_divisable_rem(100000000000000, buses[0][0], 1, buses[0][1])
bus_index = 1
multiplier = buses[0][0]
while bus_index < len(buses):
number = check2(number, multiplier, buses[bus_index][0], buses[bus_index][1])
multiplier *= buses[bus_index][0]
bus_index += 1
print(number)
|
active = set()
with open("input.txt") as f:
for (row, line) in enumerate(f):
line = line.strip()
for (col, point) in enumerate(line):
if point == "#":
active.add((row, col, 0, 0))
def iterate_neighbors(pos):
x, y, z, w = pos
for x1 in range(-1, 2):
for y1 in range(-1, 2):
for z1 in range(-1, 2):
for w1 in range(-1, 2):
position = (x + x1, y + y1, z + z1, w + w1)
if pos == position:
continue
yield position
def count_alive_neighbors(active, pos):
alive = 0
for neighbor in iterate_neighbors(pos):
if neighbor in active:
alive += 1
return alive
def check_item(pos, active, next):
neighbors = count_alive_neighbors(active, pos)
alive = pos in active
# print(f"Checking {pos}, was {alive}, has {neighbors} alive neighbors")
if alive and neighbors in (2, 3):
next.add(pos)
elif not alive and neighbors == 3:
next.add(pos)
def move(active):
next = set()
for pos in active:
check_item(pos, active, next)
for neighbor in iterate_neighbors(pos):
if neighbor not in active:
check_item(neighbor, active, next)
return next
for _ in range(6):
active = move(active)
print(len(active))
|
from collections import defaultdict
tile_commands = []
def iterate_commands(path):
index = 0
while index < len(path):
c = path[index]
if c in ("n", "s"):
yield path[index:index+2]
index += 2
else:
yield path[index:index+1]
index += 1
with open("input.txt") as f:
for line in f:
line = line.strip()
tile_commands.append(list(iterate_commands(line)))
def get_location(commands):
pos = [0, 0]
for command in commands:
if "n" in command:
pos[0] -= 1
if "s" in command:
pos[0] += 1
if "e" in command:
pos[1] += 2 if command == "e" else 1
if "w" in command:
pos[1] -= 2 if command == "w" else 1
return tuple(pos)
def get_neighbours(pos):
for command in ("w", "e", "ne", "se", "nw", "sw"):
location = get_location([command])
yield (pos[0] + location[0], pos[1] + location[1])
def get_alive_neighbours(state, pos):
alive = 0
for neighbour in get_neighbours(pos):
if state.get(neighbour, False):
alive += 1
return alive
def check(pos, state, next_state):
alive = get_alive_neighbours(state, pos)
if state.get(pos, False):
if alive == 0 or alive > 2:
pass # set to white
else:
next_state[pos] = True
elif alive == 2:
next_state[pos] = True
def move(state):
next_state = {}
for pos in state:
check(pos, state, next_state)
for neighbour in get_neighbours(pos):
if neighbour not in state:
check(neighbour, state, next_state)
return next_state
state = defaultdict(lambda: False)
for command in tile_commands:
location = get_location(command)
state[location] = not state[location]
state = dict(state)
for i in range(100):
state = move(state)
print(len([v for v in state.values() if v]))
|
from abc import abstractmethod, ABC
class Band():
members = []
bands = []
def __init__(self,name):
self.name=name
Band.bands.append(self)
def add_members(self,mname):
self.mname=mname
Band.members.append(mname)
def play_solos(self):
result =''
for i in Band.members:
result+= f'{i.play_solo()}\n'
return result
@classmethod
def to_list(cls):
return cls.members
def __str__(self):
return f"Band <{self.name}>"
def __repr__(self):
return f" '{self.name}' "
class Musician():
def __init__(self,name):
self.name = name
@abstractmethod
def __str__(self):
return f"Musician <{self.name}>"
@abstractmethod
def __repr__(self):
return f" '{self.name}' "
def play_solo(self):
return f'{self.name} Play solo'
class Guitarist(Musician):
def __init__(self,name):
super().__init__(name)
def __str__(self):
return f"Guitarist <{self.name}>"
def __repr__(self):
return f" '{self.name}' "
def get_instrument(self):
return 'Guitarist'
class Bassist(Musician):
def __init__(self,name):
super().__init__(name)
def __str__(self):
return f"Bassist <{self.name}>"
def __repr__(self):
return f" '{self.name}' "
def get_instrument(self):
return 'Bassist'
class Drummer(Musician):
def __init__(self,name):
super().__init__(name)
def __str__(self):
return f"Drummer <{self.name}>"
def __repr__(self):
return f" '{self.name}' "
def get_instrument(self):
return 'Drummer'
if __name__ == "__main__":
aziz = Guitarist('Aziz')
saleh=Drummer('Saleh')
emad = Bassist('Emad')
print(aziz)
print(aziz.get_instrument())
print(saleh)
print(saleh.get_instrument())
print(emad)
print(emad.get_instrument())
print(aziz.play_solo())
print(saleh.play_solo())
print(emad.play_solo())
habail = Band('habail')
habail.add_members(aziz)
habail.add_members(saleh)
habail.add_members(emad)
print(habail.bands)
print(habail.__str__())
print(habail.to_list())
print(habail.play_solos())
|
import random
from hangman.lives import LIVES
with open('hangman/words.txt') as f:
lines = f.read().splitlines()
action_list = []
first_time = True
word = ""
letters = []
hearts = 10
used_letters = []
def random_word():
return lines[random.randint(0, len(lines))].lower()
def display_letters(letters):
dashes = ""
for w in word:
if w in letters:
dashes += w
else:
dashes += "-"
return dashes
def display_used_letters(used_letters):
used_letter = ""
print(used_letters)
for letter in used_letters:
if letter not in used_letter:
used_letter += letter + ", "
else:
pass
return used_letter
def hanging_man(hearts):
i = 10 - hearts
return LIVES[i]
def first_message(word):
return "Welcome to hangman. Your word is " + str(
len(word)) + " letters long. \nYou currently have 10 lives left. \n" + LIVES[0] + "Enter your first letter! \n"
def first_run():
global first_time
global word
word = random_word()
print(word)
message = first_message(word)
first_time = False
return message
def run_game(letter):
global hearts
if first_time:
return first_run()
elif letter == "/reset":
reset()
return "/reset"
else:
if letter in word:
letters.append(letter)
if "-" not in display_letters(letters):
reset()
return "Well Done! You beat hangman"
else:
return hanging_man(hearts) + "You have " + str(hearts) + " lives left \n" + display_letters(
letters) + "\nIncorrect Letters: " + display_used_letters(used_letters)
else:
used_letters.append(letter)
hearts -= 1
if hearts == 0:
reset()
return "You failed. Try again next time"
else:
return hanging_man(hearts) + "You have " + str(hearts) + " lives left \n" + display_letters(
letters) + "\nIncorrect letters: " + display_used_letters(used_letters)
def reset():
global first_time
global hearts
global word
global letters
global used_letters
first_time = True
hearts = 10
word = ""
letters = []
used_letters = []
|
x=10 #int
y=10.5 # float
print(type(x))
print(type(y))
#Type Conversion
print(x) #10
print(float(x)) #10.0 #convert int to float
print(type(float(x)))
y=10.0
print(y)
print(type(y))
print(int(y)) #convert float to int
large=max(10,2,3)
small=min(11,41,6,7,3,4)
print("max number : ",large)
print("min number : ",small)
|
#swapping
x=10
y=5
print("Before swapping : ",x,y)
x,y=y,x
print("After swapping : ",x,y)
|
#Type Casting
num1=int(input("Enter First Number:")) #10
num2=float(input("Enter Second Number:")) #10.5
print(num1+num2) #20.5
num1=input("Enter First Number:") #10
num2=input("Enter Second Number:") #10.5
print(int(num1)+float(num2)) #20.5
num1=input("Enter First Number:") #10.5
num2=input("Enter Second Number:") #10.5
print(float(num1)+float(num2)) #21
num1=input("Enter First Number:") #10.5
num2=input("Enter Second Number:") #10
print(float(num1)+float(num2)) #20.5
num1=input("Enter First Number:") #10.5
num2=input("Enter Second Number:") #10.5
print(int(num1)+float(num2)) #ValueError: invalid literal for int() with base 10: '10.5'
#Float can hold int value
#Int cannot hold float value
|
#Number - int , float
x=100 #int type
y=100.5 #float type
s='welcome' #string/char type
a=True # Boolean Type
# to Know the type of variable
print(type(x))
print(type(y))
print(type(s))
print(type(a))
|
# Python list
'''list1=[10,11,12,13,14,15]
list2=list1
print(list2)
list1[0]='apple'
print(list1)'''
# Range function
for x in range(1,11):
print(x)
|
from datetime import datetime
import pandas as pd
import settings
from receipt_roll import money, common
import numpy as np
import matplotlib.pyplot as plot
import seaborn as sn
def terms_for_index():
""" Basic structure for holding data with terms as the index. """
return {'Michaelmas': [], 'Hilary': [], 'Easter': [], 'Trinity': []}
def terms_for_column():
""" So we can use terms as column headings. """
return ['Michaelmas', 'Hilary', 'Easter', 'Trinity']
# ---------- Methods used in apply()
def date_to_period(row, freq='D'):
""" 'Date' is a string. Create a Period. Default is year, month and day. """
date = row[common.DATE_COL]
period = pd.Period(date, freq=freq)
return period
def date_to_month_year_period(row):
return date_to_period(row, 'M')
def date_to_year_period(row):
return date_to_period(row, 'Y')
def date_to_week_freq(row):
return date_to_period(row, 'W-MON')
def roll_as_df():
""" Return the CSV file as a pandas data frame"""
return pd.read_csv(settings.ROLL_CSV)
def daily_sums_df():
""" Return the CSV file with the daily sums """
return pd.read_csv(settings.DAILY_SUMS_CSV)
def daily_sum_from_roll_df(df):
""" Create a new data frame of daily sums in pence and the equivalent £.s.d. from the roll data """
data = []
columns = [common.DATE_COL, common.PENCE_COL, common.PSD_COL]
date_group = df.groupby(common.DATE_COL)
for date, group in date_group:
pence = group[common.PENCE_COL].sum()
row = [date, pence, money.pence_to_psd(pence)]
data.append(row)
return pd.DataFrame(data, columns=columns)
def roll_with_entities_df():
""" Return the CSV file of the roll with entities as a pandas data frame"""
return pd.read_csv(settings.ROLL_WITH_ENTITIES_CSV)
def compare_daily_sums_df():
""" Return the comparison files as a Pandas data frame. """
return pd.read_csv(settings.DAILY_SUMS_COMPARE_CSV)
def terms_overview_df():
""" A data frame that holds summary data about each of the terms_for_index. """
# columns for this overview
columns = ['Total Days', 'Days with payments', 'Days with no payments', 'Term total', 'Total entries']
# data structure to hold calculations
terms_data = terms_for_index()
df = roll_with_entities_df()
# group by terms
for name, group in df.groupby(common.TERM_COL):
# number of days in term payments were recorded
term_days = group[common.DATE_COL].unique().size
# total amount collected for the term
term_total = group[common.PENCE_COL].sum()
# days with no payments
days_no_payment = group[group[common.DETAILS_COL] == 'NOTHING'][common.DATE_COL].unique().size
# days with payments
days_with_payment = term_days - days_no_payment
# no of entries
term_entries_no = group[common.DETAILS_COL].count()
# add the raw data
terms_data[name].append(term_days)
terms_data[name].append(days_with_payment)
terms_data[name].append(days_no_payment)
terms_data[name].append(term_total)
terms_data[name].append(term_entries_no)
return pd.DataFrame.from_dict(terms_data, orient='index', columns=columns)
def payments_overview_df():
df = roll_with_entities_df()
# shorten the label
df = df.replace(['ENGLISH DEBTS BY THE MERCHANTS OF LUCCA'], 'MERCHANTS OF LUCCA')
data = []
group_by = df.groupby(common.SOURCE_COL)
columns = [common.SOURCE_COL, common.PENCE_COL]
for name, group in group_by:
if name != 'NOTHING':
data.append([name.title(), group[common.PENCE_COL].sum()])
return pd.DataFrame(data=data, columns=columns)
def source_term_payments_matrix_df():
# get the data
df = roll_with_entities_df()
# shorten the label
df = df.replace(['ENGLISH DEBTS BY THE MERCHANTS OF LUCCA'], 'MERCHANTS OF LUCCA')
# columns
terms_names = terms_for_column()
# indexes (sources)
sources_names = df[common.SOURCE_COL].unique()
# create a matrix with values set to zero
matrix = pd.DataFrame(np.zeros(shape=(len(sources_names), len(terms_names))), columns=terms_names,
index=sources_names)
# group by term
group_by_term = df.groupby(common.TERM_COL)
# iterate over the terms
for term, term_group in group_by_term:
# for each term, group by source of income, and iterate over each source
for source, source_group in term_group.groupby(common.SOURCE_COL):
# get the total for that source
total = source_group[common.PENCE_COL].sum()
# update the matrix
matrix.at[source, term] = total
# remove 'NOTHING' as a source
matrix = matrix.drop(index='NOTHING').sort_index()
# change the source name (index) to title case
matrix.index = matrix.index.map(str.title)
return matrix
def source_term_payments_pc_matrix_df():
# get the data
df = roll_with_entities_df()
# shorten the label
df = df.replace(['ENGLISH DEBTS BY THE MERCHANTS OF LUCCA'], 'MERCHANTS OF LUCCA')
# columns
terms_names = terms_for_column()
# indexes (sources)
sources_names = df[common.SOURCE_COL].unique()
# create a matrix with values set to zero
matrix = pd.DataFrame(np.zeros(shape=(len(sources_names), len(terms_names))), columns=terms_names,
index=sources_names)
year_total = df['Pence'].sum()
# group by term
group_by_term = df.groupby(common.TERM_COL)
# iterate over the terms
for term, term_group in group_by_term:
# for each term, group by source of income, and iterate over each source
for source, source_group in term_group.groupby(common.SOURCE_COL):
# get the total for that source
total = source_group[common.PENCE_COL].sum()
# update the matrix
matrix.at[source, term] = total / year_total * 100
# remove 'NOTHING' as a source
matrix = matrix.drop(index='NOTHING').sort_index()
# change the source name (index) to title case
matrix.index = matrix.index.map(str.title)
return matrix
def days_of_week_total_by_term():
# get the data
df = roll_with_entities_df()
df = df[df[common.SOURCE_COL] != 'NOTHING']
term_names = terms_for_column()
# create a matrix with values set to zero
matrix = pd.DataFrame(np.zeros(shape=(len(term_names), len(common.DAYS_OF_WEEK))), columns=common.DAYS_OF_WEEK,
index=term_names)
for term, term_group in df.groupby(common.TERM_COL):
for day, day_group in term_group.groupby(common.DAY_COL):
total = day_group[common.PENCE_COL].sum()
matrix.at[term, day] = total
return matrix
|
from typing import List, Tuple
SeatingPlan = List[List[int]]
def solve():
seating_plan = get_seating_plan('input.txt')
settled_seating_plan = get_settled_seating_plan(seating_plan)
occupied_seats = count_occupied_seats(settled_seating_plan)
print(occupied_seats)
def get_seating_plan(input_file: str) -> SeatingPlan:
"""
0 = floor
1 = empty
2 = occupied
"""
str_to_piece = {
'.': 0,
'L': 1,
'#': 2,
}
seating_plan = []
with open(input_file) as f:
for line in f:
line = line.strip()
seating_plan.append([str_to_piece[c] for c in line])
return seating_plan
def print_seating_plan(seating_plan: SeatingPlan):
int_to_str = {
0: '.',
1: 'L',
2: '#',
}
for seating_row in seating_plan:
print(''.join([int_to_str[x] for x in seating_row]))
print()
def get_settled_seating_plan(seating_plan: SeatingPlan) -> SeatingPlan:
old_seating_plan = None
while not is_same_seating_plan(seating_plan, old_seating_plan):
print_seating_plan(seating_plan)
old_seating_plan = seating_plan
seating_plan = run_round(old_seating_plan)
return seating_plan
def is_same_seating_plan(seating_plan1: SeatingPlan, seating_plan2: SeatingPlan) -> bool:
if seating_plan2 is None:
return False
for i, _ in enumerate(seating_plan1):
for j, _ in enumerate(seating_plan1[i]):
if seating_plan1[i][j] != seating_plan2[i][j]:
return False
return True
def run_round(seating_plan: SeatingPlan) -> SeatingPlan:
new_seating_plan = []
for i, seating_row in enumerate(seating_plan):
new_seating_row = []
new_seating_plan.append(new_seating_row)
for j, seat in enumerate(seating_row):
adjacent_occupied_seats = get_adjacent_occupied_seats(seating_plan, i, j)
if seat == 1 and adjacent_occupied_seats == 0:
new_seating_row.append(2)
elif seat == 2 and adjacent_occupied_seats >= 5:
new_seating_row.append(1)
else:
new_seating_row.append(seat)
return new_seating_plan
def get_adjacent_occupied_seats(seating_plan: SeatingPlan, i: int, j: int) -> int:
total = 0
directions = [
(-1, -1),
(-1, 0),
(-1, 1),
(0, -1),
(0, 1),
(1, -1),
(1, 0),
(1, 1),
]
for direction in directions:
first_seat = get_first_adjacent_seat(seating_plan, i, j, direction)
if first_seat == 2:
total += 1
return total
def get_first_adjacent_seat(seating_plan: SeatingPlan, i: int, j: int, direction: Tuple[int, int]):
distance = 1
i_direction, j_direction = direction
while True:
_i = i_direction * distance
_j = j_direction * distance
if i + _i < 0:
return 0
if j + _j < 0:
return 0
try:
seat = seating_plan[i + _i][j + _j]
if seat > 0:
return seat
except IndexError:
return 0
distance += 1
def count_occupied_seats(seating_plan: SeatingPlan) -> int:
total = 0
for seating_row in seating_plan:
for seat in seating_row:
if seat == 2:
total += 1
return total
if __name__ == "__main__":
solve()
|
from queue import deque
def solve():
player_1, player_2 = parse_input('input.txt')
while player_1 and player_2:
run_round(player_1, player_2)
winner = player_1 or player_2
score = calculate_score(winner)
print(score)
def parse_input(input_file):
players = {}
players[0] = deque([])
players[1] = deque([])
with open(input_file) as f:
lines = [line.strip() for line in f]
player = 0
for line in lines[1:]:
if not line:
continue
if line.startswith('Player'):
player = 1
else:
players[player].append(int(line))
return players[0], players[1]
def run_round(player_1, player_2):
p1 = player_1.popleft()
p2 = player_2.popleft()
if p1 > p2:
player_1.append(p1)
player_1.append(p2)
else:
player_2.append(p2)
player_2.append(p1)
def calculate_score(winner):
total_score = 0
for i, card in enumerate(reversed(winner)):
total_score += (i + 1) * card
return total_score
if __name__ == "__main__":
solve()
|
import re
def solve():
all_entries = {}
valid_entries = 0
with open('input.txt') as f:
for line in f.readlines():
if line.strip() == "":
if len(all_entries) > 7 or len(all_entries) == 7 and "cid" not in all_entries:
if all_keys_valid(all_entries):
valid_entries += 1
print(f"valid: {all_entries}")
else:
print(f"Not valid: {all_entries}")
all_entries = {}
else:
for pair in line.split():
k, v = pair.split(':')
all_entries[k] = v
print(valid_entries)
def all_keys_valid(all_keys: dict) -> bool:
for k, v in all_keys.items():
if not is_valid(k, v):
print(f"Not valid {k} = {v}")
# print("False")
return False
return True
def is_valid(key, value):
# print(f"Checking {key} = {value}")
if key == "byr":
value = int(value)
return 1920 <= value and value <= 2002
elif key == "iyr":
value = int(value)
return 2010 <= value and value <= 2020
elif key == "eyr":
value = int(value)
return 2020 <= value and value <= 2030
elif key == "hgt":
if not re.match(r"^[0-9]+cm$", value) and not re.match(r"^[0-9]+in$", value):
return False
if value[-2:] == "cm":
value = int(value[:-2])
return 150 <= value and value <= 193
elif value[-2:] == "in":
value = int(value[:-2])
return 59 <= value and value <= 76
elif key == "hcl":
return re.match(r"^#[0-9a-f]{6}$", value)
elif key == "ecl":
return value in ["amb", "blu", "brn", "gry", "grn", "hzl", "oth"]
elif key == "pid":
return re.match(r"^[0-9]{9}$", value)
elif key == "cid":
return True
return False
if __name__ == "__main__":
solve()
|
import numpy as np
def rot_n(string: str, n: int) -> str:
ord_list = [ord(c) for c in string]
translated_list = []
for c in ord_list:
# ord('A') == 65, ord('Z') == 90
# ord('a') == 97, ord('z') == 122
if c >= 65 and c <= 90:
c -= 65
c = (c - n + 26) % 26
c += 65
elif c >= 97 and c <= 122:
c -= 97
c = (c - n + 26) % 26
c += 97
translated_list.append(c)
chr_list = [chr(c) for c in translated_list]
return "".join(chr_list)
def rot_all(string: str) -> list:
string_list = []
for i in range(1, 26):
string_list.append(rot_n(string, i))
return string_list
def print_rot_n(string: str, n: int):
translated_string = rot_n(string, n)
print("ROT{}: {}".format(n, translated_string))
return
def print_rot_all(string: str):
for i in range(1, 26):
print_rot_n(string, i)
return
|
#Leer tres numeros entereos de un digito y almacenarlos en una sola variable
#Que contenga a esos tres digitos por ejemplo si A=5 y B=6 y C=2 entomces X=562
print("Bienvedido al Programa".center(50,"-"))
a = ""
b = ""
c = ""
x = ""
a = input("Ingrese primer numero: ")
b = input("Ingrese segundo numero: ")
c = input("Ingrese tercer numero: ")
x = a + b + c
print("X= {}".format(x))
|
#Calcula el preio de unboleto de viaje, tomando en cuenta el numero de kilometros
#que se van a ecorrer, siend el precio BS/.10,50 por km.
print("bienvenidos al programa".center(50,"-"))
Precio_km = 10.50
kms = 0
total = 0
kms = float(input("Ingrese kilometros a recorrer:."))
total = Precio_km * kms
print("Precio del boleto: Bs.",total)
|
#Ejercicio4
#realizar el promedio de n notas utilizando el for
print ("BIENVENIDO")
suma = 0
valor = int(input("Ingresar su nota")
for i in range (valor):
nota = int(input("ingrese su nota"))
suma = suma + int(nota)
promedio = suma / nota
print ("El promedio es :. {}".format (promedio))
|
"""
Real-time stream of audio from your microphone
==============================================
This is an example of using your own Microphone to continuously transcribe what is being uttered,
**while it is being uttered**. Whenever the recognizer detects a silence in the audio stream
from your microphone, the generator will return is_last=True, and the full transcription from the secondary model.
"""
from danspeech import Recognizer
from danspeech.pretrained_models import CPUStreamingRNN, TestModel
from danspeech.audio.resources import Microphone
from danspeech.language_models import DSL3gram
print("Loading model...")
model = CPUStreamingRNN()
mic_list = Microphone.list_microphone_names()
mic_list_with_numbers = list(zip(range(len(mic_list)), mic_list))
print("Available microphones: {0}".format(mic_list_with_numbers))
mic_number = input("Pick the number of the microphone you would like to use: ")
m = Microphone(sampling_rate=16000, device_index=int(mic_number))
r = Recognizer()
print("Adjusting energy level...")
with m as source:
r.adjust_for_ambient_noise(source, duration=1)
seconday_model = TestModel()
r = Recognizer(model=model)
try:
lm = DSL3gram()
r.update_decoder(lm=lm)
except ImportError:
print("ctcdecode not installed. Using greedy decoding.")
r.enable_real_time_streaming(streaming_model=model, string_parts=False, secondary_model=seconday_model)
generator = r.real_time_streaming(source=m)
iterating_transcript = ""
print("Speak!")
while True:
is_last, trans = next(generator)
# If the transcription is empty, it means that the energy level required for data
# was passed, but nothing was predicted.
if is_last and trans:
print("Final: " + trans)
iterating_transcript = ""
continue
if trans:
iterating_transcript += trans
print(iterating_transcript)
continue
|
"""
Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).
Example :
Given binary tree
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
"""
class Solution:
# @param A : root node of tree
# @return a list of list of integers
def levelOrder(self, A):
l = {}
def dist(x, level):
if level in l:
l[level].append(x.val)
else:
l[level] = [x.val]
if x.left is not None:
dist(x.left, level+1)
if x.right is not None:
dist(x.right, level+1)
dist(A, 0)
return l.values()
|
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import random
import numpy as np
from numpy.random import randint
from matplotlib import pyplot as plt
#Question 1
plt.figure(1)
x_coord = [1,2,3,4]
y_coord = [1,2,3,4]
plt.plot(x_coord, y_coord, marker = '', linestyle = ':', color = 'r')
plt.show()
plt.figure(2)
x_coord1 = [1,2,3,4]
y_coord1 = [1,2,3,4]
plt.plot(x_coord1, y_coord1, marker = '^', linestyle = '-', color = 'b')
plt.show()
#Question 2
#original function
def dieRoll():
y_series = randint(1,7,(1,10000))
y_series = y_series[0]
plt.figure(1)
plt.hist(y_series, bins = 6, rwidth = .7, align = 'mid',\
weights = np.zeros_like(y_series) + 1. / y_series.size)
plt.xlim(1,6)
plt.title("Rolling a Die")
plt.xlabel("Value")
plt.ylabel("Probability")
plt.show()
#my function
def dieroll(m):
sum_list = [0 for x in range(10000)]
for i in range(10000):
roll_sum = 0
for j in range(m):
roll = random.choice(range(1,7))
roll_sum += roll
sum_list[i] = roll_sum
plt.figure(1)
plt.hist(sum_list, bins = 6*m, rwidth = .7, align = 'mid',\
weights = np.zeros_like(sum_list) + 1. / len(sum_list))
plt.xlim(1,6*m)
plt.title("Rolling a Die " + str(m) + " Time(s)")
plt.xlabel("Value")
plt.ylabel("Probability")
plt.show()
dieroll(100)
#Question 3
def draw_point():
x = random.uniform(-1.0, 1.0)
y = random.uniform(-1.0, 1.0)
if ((x**2) + (y**2)) <= 1.0:
return True
else:
return False
def pi_Estimate(n):
T = 0.0
C = 0.0
for i in range(n):
if draw_point() == True:
C += 1
T += 1
estimate = 4*(C/T)
print(C, 'points in the circle out of', T, 'total so pi is estimated to be', estimate)
print estimate
pi_Estimate(100000)
#Question 4
def expt(p):
count = 0
while True:
choice = random.random()
if choice > p:
count+=1
else:
count+=1
break
return count
def Coin_flip_test(n,p):
count_list = []
for x in range(n):
count_list += [expt(p)]
return count_list
def plot_cft_pmf(n,p):
count_list = Coin_flip_test(n,p)
plt.figure(1)
plt.hist(count_list, bins = max(count_list), rwidth = .7, align = 'mid',\
weights = np.zeros_like(count_list) + 1. / len(count_list))
plt.xlim(1,max(count_list))
plt.title("Flipping a p-biased coin with p = " + str(p) + " Probability")
plt.xlabel("Number of Flips")
plt.ylabel("Probability")
x = np.linspace(0, max(count_list), 10000)
y = p*((1-p)**(x-1))
plt.plot(x, y, linestyle = '-', color = 'r', linewidth = 4)
plt.show()
plot_cft_pmf(10000, .8)
|
import sqlite3
'''
This file contains necessary functions for modifying
and querying the sqlite3 'professors' database.
'''
######################################################
## FUNCTIONS FOR PROFS TABLE ##
######################################################
def insert(samID, firstName, lastName, email, cv, docYear, docType, mastYear, mastType, experience, profType, onlineCert):
# Clean the inputs. If the string is "None" or "", must change to the python None type before updating.
if (samID == "") or (samID == "None"):
return
if (firstName == "") or (firstName == "None"):
firstName = ""
if (lastName == "") or (lastName == "None"):
lastName = ""
if (email == "") or (email == "None"):
email = ""
if (cv == "") or (cv == "None"):
cv = ""
if (docYear == "") or (docYear == "None"):
docYear = ""
if (mastYear == "") or (mastYear == "None"):
mastYear = ""
if (mastType == "") or (mastType == "None"):
mastType = ""
if (experience == "") or (experience == "None"):
experience = ""
if (profType == "") or (profType == "None"):
profType = ""
if (onlineCert == "") or (onlineCert == "None"):
onlineCert = ""
conn = sqlite3.connect("professors.db")
cur = conn.cursor()
cur.execute("INSERT INTO profs VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
(samID, firstName, lastName, email, cv, docYear, docType, mastYear, mastType, experience, profType, onlineCert))
conn.commit()
conn.close()
def view():
conn = sqlite3.connect("professors.db")
cur = conn.cursor()
cur.execute("SELECT * FROM profs")
#rows is a tuple containing all rows from db
rows = cur.fetchall()
conn.close()
return rows
def search(samID="", firstName="", lastName="", email="", cv="", docYear="", docType="", mastYear="", mastType="", experience="", profType="", onlineCert=""):
# Need the if statements because searching while fields were empty was pulling
# up all records that had at least one empty field.
if (samID=="") or (samID=="None"):
samID = -1
if (firstName=="") or (firstName=="None"):
firstName = "-1"
if (lastName=="") or (lastName=="None"):
lastName="-1"
if (email=="") or (email=="None"):
email="-1"
if (cv=="") or (cv=="None"):
cv="-1"
if (docYear=="") or (docYear=="None"):
docYear=-1
if (docType=="") or (docType=="None"):
docType="-1"
if (mastYear=="") or (mastYear=="None"):
mastYear=-1
if (mastType=="") or (mastType=="None"):
mastType="-1"
if (experience=="") or (experience=="None"):
experience="-1"
if (profType == "") or (profType=="None"):
profType=-1
if (onlineCert=="") or (onlineCert=="None"):
onlineCert=-1
conn = sqlite3.connect("professors.db")
cur = conn.cursor()
cur.execute("""SELECT * FROM profs WHERE samID=? OR firstName=? COLLATE NOCASE OR lastName=? COLLATE NOCASE OR email=? COLLATE NOCASE OR cv=? COLLATE NOCASE
OR doctorate_year=? OR doctorate_type=? OR masters_year=? OR masters_type=? OR experience=? OR profType=? OR onlineCert=?""",
(samID, firstName, lastName, email, cv, docYear, docType, mastYear, mastType, experience, profType, onlineCert))
#rows is a tuple containing all rows from db
rows = cur.fetchall()
conn.close()
return rows
def delete(samID):
conn = sqlite3.connect("professors.db")
cur = conn.cursor()
cur.execute("DELETE FROM profs WHERE samID=?", (samID,))
conn.commit()
conn.close()
# Update assumes that the samID is correct and will only change the other fields.
def update(samID, firstName, lastName, email, cv, docYear, docType, mastYear, mastType, experience, profType, onlineCert):
# Clean the inputs. If the string is "None" or "", must change to the python None type before updating.
if (firstName == "") or (firstName == "None"):
firstName = ""
if (lastName == "") or (lastName == "None"):
lastName = ""
if (email == "") or (email == "None"):
email = ""
if (cv == "") or (cv == "None"):
cv = ""
if (docYear == "") or (docYear == "None"):
docYear = ""
if (mastYear == "") or (mastYear == "None"):
mastYear = ""
if (mastType == "") or (mastType == "None"):
mastType = ""
if (experience == "") or (experience == "None"):
experience = ""
if (profType == "") or (profType == "None"):
profType = ""
if (onlineCert == "") or (onlineCert == "None"):
onlineCert = ""
conn = sqlite3.connect("professors.db")
cur = conn.cursor()
cur.execute("""UPDATE profs SET firstName=?, lastName=?, email=?, cv=?, doctorate_year=?,
doctorate_type=?, masters_year=?, masters_type=?, experience=?, profType=?, onlineCert=? WHERE samID=?""",
(firstName, lastName, email, cv, docYear, docType, mastYear, mastType, experience, profType, onlineCert, samID))
conn.commit()
conn.close()
def getDoctoralOnly():
conn = sqlite3.connect("professors.db")
cur = conn.cursor()
cur.execute("SELECT * FROM profs WHERE doctorate_year IS NOT NULL AND doctorate_year!=\'\' AND doctorate_year != \'None\'")
rows = cur.fetchall()
conn.close()
return rows
def getMastersOnly():
conn = sqlite3.connect("professors.db")
cur = conn.cursor()
cur.execute("SELECT * FROM profs WHERE doctorate_year IS NULL OR doctorate_year=\'\' OR doctorate_year=\'None\'")
rows = cur.fetchall()
conn.close()
return rows
###############################################################
# FUNCTIONS FOR COURSES TABLE
###############################################################
def view_courses():
conn = sqlite3.connect("professors.db")
cur = conn.cursor()
cur.execute("SELECT * FROM courses")
#rows is a tuple containing all rows from db
rows = cur.fetchall()
conn.close()
return rows
def insert_courses(semester, year, courseNum, sectionNum, instructorID, instructorLastName, instructionMethod, ideaScore):
if instructorID == "None":
instructorID = ""
if instructorLastName == "None":
instructorLastName = ""
if instructionMethod == "None":
instructionMethod = ""
if ideaScore == "None":
ideaScore = ""
conn = sqlite3.connect("professors.db")
cur = conn.cursor()
cur.execute("INSERT INTO courses VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
(semester, year, courseNum, sectionNum, instructorID, instructorLastName, instructionMethod, ideaScore))
conn.commit()
conn.close()
def search_courses(semester='', year='', courseNum='', sectionNum='', instructorID='', instructorLastName='', instructionMethod='', ideaScore=''):
searchString = "SELECT * FROM courses WHERE"
count = 0
if (semester=="") or (semester=="None"):
semester = "-1"
else:
searchString += " semester= \'" + str(semester) + "\'"
count += 1
if (year=="") or (year=="None"):
year = -1
else:
if (count==0):
searchString += " year=\'" + str(year) + "\'"
count +=1
else:
searchString += " AND year=\'" + str(year) + "\'"
count +=1
if (courseNum=="") or (courseNum=="None"):
courseNum=-1
else:
if (count==0):
searchString += " courseNum=\'" + str(courseNum) + "\'"
count += 1
else:
searchString += " AND courseNum=\'" + str(courseNum) + "\'"
count +=1
if (sectionNum=="") or (sectionNum=="None"):
sectionNum=-1
else:
if (count==0):
searchString += " sectionNum=\'" + str(sectionNum) + "\'"
count += 1
else:
searchString += " AND sectionNum=\'" + str(sectionNum) + "\'"
count +=1
if (instructorID=="") or (instructorID=="None"):
instructorID=-1
else:
if (count==0):
searchString += " instructorID=\'" + str(instructorID) + "\'"
count += 1
else:
searchString += " AND instructorID=\'" + str(instructorID) + "\'"
count +=1
if (instructorLastName=="") or (instructorLastName=="None"):
instructorLastName="-1"
else:
if (count==0):
searchString += " instructorLastName=\'" + str(instructorLastName) + "\'"
count += 1
else:
searchString += " AND instructorLastName=\'" + str(instructorLastName) + "\'"
count +=1
if (instructionMethod=="") or (instructionMethod=="None"):
instructionMethod=-1
else:
if (count==0):
searchString += " instructionMethod=\'" + str(instructionMethod) + "\'"
count += 1
else:
searchString += " AND instructionMethod=\'" + str(instructionMethod) + "\'"
count +=1
if (ideaScore=="") or (ideaScore=="None"):
ideaScore=-1.1
else:
if (count==0):
searchString += " ideaScore=\'" + str(ideaScore) + "\'"
count += 1
else:
searchString += " AND ideaScore=\'" + str(ideaScore) + "\'"
count +=1
if (count != 0):
#print(searchString)
conn = sqlite3.connect("professors.db")
cur = conn.cursor()
cur.execute(searchString)
#rows is a tuple containing all rows from db
rows = cur.fetchall()
conn.close()
return rows
def delete_courses(semester, year, courseNum, sectionNum):
conn = sqlite3.connect("professors.db")
cur = conn.cursor()
cur.execute("DELETE FROM courses WHERE semester=? AND year=? AND courseNum=? AND sectionNum=?",
(semester, year, courseNum, sectionNum))
conn.commit()
conn.close()
# Update assumes that the samID is correct and will only change the other fields.
def update_courses(semester='', year='', courseNum='', sectionNum='', instructorID='', instructorLastName='', instructionMethod='', ideaScore=''):
if instructorID == "None":
instructorID = ""
if instructorLastName == "None":
instructorLastName = ""
if instructionMethod == "None":
instructionMethod = ""
if ideaScore == "None":
ideaScore = ""
conn = sqlite3.connect("professors.db")
cur = conn.cursor()
cur.execute("""UPDATE courses SET instructorID=?, instructorLastName=?, instructionMethod=?, ideaScore=?
WHERE semester=? AND year=? AND courseNum=? AND sectionNum=?""",
(instructorID, instructorLastName, instructionMethod, ideaScore, semester, year, courseNum, sectionNum))
conn.commit()
conn.close()
######################################################################
# FUNCTIONS FOR REPORT GENERATION
######################################################################
def prof_report (samID):
conn = sqlite3.connect("professors.db")
cur = conn.cursor()
cur.execute("""SELECT * FROM courses WHERE instructorID=?""", (samID,))
rows=cur.fetchall()
conn.close()
return rows
def course_report (semester, year, courseNum):
conn = sqlite3.connect("professors.db")
cur = conn.cursor()
cur.execute("""SELECT * FROM courses WHERE semester=? AND year=? AND courseNum=?""",
(semester, year, courseNum))
rows=cur.fetchall()
conn.close()
return rows
def get_prof_info(samID):
conn = sqlite3.connect("professors.db")
cur = conn.cursor()
cur.execute("""SELECT * FROM profs WHERE samID=?""",(samID,))
rows=cur.fetchall()
conn.close()
return rows
|
from Common.state import State, Game_Phase
from Common.player import Player
from copy import deepcopy
"""
Data representation for a game tree representing the tree of all possible states from a starting state.
Each node in the game tree contains a State, a list indicating the order of the players, a reference
to the parent GameTreeNode, and a list of all direct children, or successor states given the current state.
A tree can be generated using a GameTreeNode using the generate_tree method, which will generate the tree up to the depth
you specify.
The game tree node can represent two of nodes:
- game-is-over
- current-player-can-move
The last state, current-player-is-stuck, cannot be represented by our state because our state automatically updates the
turn index to the next player that has any valid moves remaining, therefore eliminating that possibility.
"""
class GameTreeNode():
# TODO: Refactor GameTree to be more... functional
"""
__init__ - Creates a GameTreeNode given either the players, tiles, and parent, or given a State and parent.
Parameters:
Mandatory
Either:
players - List of Player objects, in order of turn.
tiles - List of tiles representing the full structure of the board. Tile should be represented in a MxN list of list of ints, where
each int represents the number of fish on the tile.
Or:
state - A complete State. This state will be used as the starting state for this node.
"""
class GameTreeNode:
"""
Data representation for a game tree representing the tree of all possible states from a starting state.
Each node in the game tree contains a State, a list indicating the order of the players, a reference
to the parent GameTreeNode, and a list of all direct children, or successor states given the current state.
A tree can be generated using a GameTreeNode using the generate_tree method, which will generate the tree up to the depth
you specify.
The game tree node can represent two of nodes:
- game-is-over
- current-player-can-move
The last state, current-player-is-stuck, cannot be represented by our state because our state automatically updates the
turn index to the next player that has any valid moves remaining, therefore eliminating that possibility.
"""
def __init__(self, state: State, moves = []):
"""
__init__ - Creates a GameTreeNode given either the players, tiles, and parent, or given a State and parent.
Parameters:
Mandatory
Either:
players - List of Player objects, in order of turn.
tiles - List of tiles representing the full structure of the board. Tile should be represented in a MxN list of list of ints, where
each int represents the number of fish on the tile.
Or:
state - A complete State. This state will be used as the starting state for this node.
Optional:
parent - The parent node of this GameTreeNode.
Output -> A Tree_node object with the provided players, tiles, and parent.
"""
self.state = State.from_state(state)
self.previous_moves = moves
# TODO: children should be a dict to make finding pregenerated children easier
self.children = []
def check_valid_move(self, penguin_posn: tuple, destination: int):
"""
check_valid_move - Checks whether the given move is legal. Returns a boolean.
Parameters:
player_color - color of player
penguin_posn - position (in tuple) of penguin to be moved
destination - position (in tuple) of destination coordinates
Output -> True if the move is valid, else False
"""
return self.state.valid_move(penguin_posn, destination)
def check_available_actions(self):
"""
check_available_moves - Gets game states of all possible moves from the current state and player penguin.
Parameters:
player_color - color of player
penguin_posn - position (in tuple) of penguin to be moved
Output -> List of valid successor states given the current state, current player's turn, and penguin that will be moved.
"""
return self.state.get_valid_moves()
def generate_tree(self, depth=1):
"""
def generate_tree - Generates a tree of nodes to the depth that is given. The default depth of the tree is 1. Successors are stored in this nodes
list of children.
Parameters:
depth - an integer representing the depth of the tree to be created. A depth of 1 generates direct successors of this node.
"""
if depth > 0 and not self.state.game_over():
states = self.check_available_moves()
for state in states:
child = GameTreeNode(state=state, parent=self)
self.children.append(child)
for child in self.children:
child.generate_tree(depth=depth-1)
def generate_successor(self, action: list):
"""
generate_successor - Query function that takes in a GameTreeNode, penguin position, and destination coordinates
and either signals that the action is illegal by returning None or returns the resulting state from the action.
Parameters:
action: list - An action is one of:
- A list containing one tuple [(row, col)]. This represents a placement.
- A list containing 2 tuples [(origin-row, origin-col), (dest-row, dest-col)], representing a
movement.
"""
state = State.from_state(self.state)
try:
if len(action) == 0:
return state
if self.state.get_game_phase() == Game_Phase.PLACEMENT:
state.place_penguin(action[0])
elif self.state.get_game_phase() == Game_Phase.PLAYING:
state.move_penguin(action[0], action[1])
else:
raise ValueError("")
return state
except (ValueError, IndexError):
return None
def get_game_state(self):
return {"Board" : self.state.get_board(),
"Scores" : self.state.get_scores(),
"Players" : self.state.get_players(),
"Turns" : self.state.turn_order()}
def get_state(self):
return State.from_state(self.state)
def map_game_states(self, node, function):
"""
map_game_states - Static query method that takes a GameTreeNode and applies the given function over all game states that are
directly reachable from the state in the provided GameTreeNode in 1 action.
"""
player = self.state.get_current_player()
states = []
for penguin_posn in player.get_penguin_locations():
states.extend(self.check_available_moves(player.get_color(), penguin_posn))
result = []
for state in states:
result.append(function(state))
return result
|
import unittest
import sys
sys.path.insert(1, '../../')
from Common.board import Board
# from Common.utils import parse_json
class TestBoard(unittest.TestCase):
def __init__(self, *args, **kwargs):
unittest.TestCase.__init__(self, *args, **kwargs)
"""
Tests that make_board_from_tiles properly constructs a board from the given tiles.
"""
def test_make_board_from_tiles(self):
tiles = [
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]
]
board = Board.make_board_from_tiles(tiles)
self.assertEqual(tiles, board.get_board())
"""
Tests that make_random_board constructs a random board.
"""
def test_make_random_board(self):
board = Board.make_random_board(5, 4)
tiles = board.get_board()
self.assertEqual(5, len(tiles))
self.assertEqual(4, len(tiles[0]))
for i in range(len(tiles)):
for j in range(len(tiles[i])):
self.assertTrue(tiles[i][j] >= 1 and tiles[i][j] <= 5)
"""
Tests that make_random_board constructs a random board with holes.
"""
def test_make_random_board_with_holes(self):
holes = [(0, 0), (1, 1), (2, 2), (3, 3)]
board = Board.make_random_board(4, 4, holes=holes)
tiles = board.get_board()
self.assertEqual(4, len(tiles))
self.assertEqual(4, len(tiles[0]))
for i in range(len(tiles)):
for j in range(len(tiles[i])):
if (i, j) not in holes:
self.assertTrue(tiles[i][j] >= 1 and tiles[i][j] <= 5)
else:
self.assertTrue(tiles[i][j] == 0)
"""
Tests that make_random_board constructs a random board with a minimum number of tiles that contain 1 fish.
"""
def test_make_random_board_with_min_ones(self):
min_ones = 10
board = Board.make_random_board(4, 4, min_ones=min_ones)
tiles = board.get_board()
self.assertEqual(4, len(tiles))
self.assertEqual(4, len(tiles[0]))
count = 0
for i in range(len(tiles)):
for j in range(len(tiles[i])):
self.assertTrue(tiles[i][j] >= 1 and tiles[i][j] <= 5)
if tiles[i][j] == 1:
count = count + 1
self.assertTrue(count >= min_ones)
"""
Tests that make_uniform_board constructs a uniform board.
"""
def test_make_uniform_board(self):
board = Board.make_uniform_board(5, 4, 3)
tiles = board.get_board()
self.assertEqual(5, len(tiles))
self.assertEqual(4, len(tiles[0]))
for i in range(len(tiles)):
for j in range(len(tiles[i])):
self.assertTrue(tiles[i][j] == 3)
"""
Tests that remove_tile correctly creates a hole at the specified x and y coordinate in the board, and that the method
is idempotent.
"""
def test_remove_tile(self):
board = Board.make_uniform_board(5, 4, 3)
tiles = board.get_board()
self.assertEqual(5, len(tiles))
self.assertEqual(4, len(tiles[0]))
for i in range(len(tiles)):
for j in range(len(tiles[i])):
self.assertTrue(tiles[i][j] == 3)
board.remove_tile(0, 0)
board.remove_tile(1, 1)
tiles = board.get_board()
for i in range(len(tiles)):
for j in range(len(tiles[i])):
if (i, j) == (0, 0) or (i, j) == (1, 1):
self.assertTrue(tiles[i][j] == 0)
else:
self.assertTrue(tiles[i][j] == 3)
board.remove_tile(0, 0)
tiles = board.get_board()
for i in range(len(tiles)):
for j in range(len(tiles[i])):
if (i, j) == (0, 0) or (i, j) == (1, 1):
self.assertTrue(tiles[i][j] == 0)
else:
self.assertTrue(tiles[i][j] == 3)
"""
Tests that check_valid_tile returns true when provided the coordinates of a valid tile and returns false when
provided the coordinates of a hole.
"""
def test_check_valid_tile(self):
holes = [(0, 0), (1, 1), (2, 2), (3, 3)]
board = Board.make_random_board(4, 4, holes=holes)
tiles = board.get_board()
self.assertEqual(4, len(tiles))
self.assertEqual(4, len(tiles[0]))
for i in range(len(tiles)):
for j in range(len(tiles[i])):
if (i, j) in holes:
self.assertFalse(board.check_valid_tile(i, j))
else:
self.assertTrue(board.check_valid_tile(i, j))
def test_reachable_spaces_north(self):
board = Board.make_uniform_board(5, 5, 1)
spaces = board.reachable_spaces_north(0, 0)
self.assertTrue(len(spaces) == 0)
spaces = board.reachable_spaces_north(1, 0)
self.assertTrue(len(spaces) == 0)
spaces = board.reachable_spaces_north(2, 0)
self.assertTrue(spaces == [(0, 0)])
spaces = board.reachable_spaces_north(3, 0)
self.assertTrue(spaces == [(1, 0)])
spaces = board.reachable_spaces_north(4, 0)
self.assertTrue(spaces == [(2, 0), (0, 0)])
spaces = board.reachable_spaces_north(4, 0, depth=1)
self.assertTrue(spaces == [(2, 0)])
spaces = board.reachable_spaces_north(4, 0, depth=2)
self.assertTrue(spaces == [(2, 0), (0, 0)])
spaces = board.reachable_spaces_north(4, 0, depth=3)
self.assertTrue(spaces == [(2, 0), (0, 0)])
board.remove_tile(2, 0)
spaces = board.reachable_spaces_north(4, 0)
self.assertTrue(len(spaces) == 0)
def test_reachable_spaces_northeast(self):
board = Board.make_uniform_board(5, 5, 1)
spaces = board.reachable_spaces_northeast(0, 0)
self.assertTrue(len(spaces) == 0)
spaces = board.reachable_spaces_northeast(1, 0)
self.assertTrue(spaces == [(0, 1)])
spaces = board.reachable_spaces_northeast(2, 0)
self.assertTrue(spaces == [(1, 0), (0, 1)])
spaces = board.reachable_spaces_northeast(3, 0)
self.assertTrue(spaces == [(2, 1), (1, 1), (0, 2)])
spaces = board.reachable_spaces_northeast(4, 0)
self.assertTrue(spaces == [(3, 0), (2, 1), (1, 1), (0, 2)])
spaces = board.reachable_spaces_northeast(4, 0, depth=1)
self.assertTrue(spaces == [(3, 0)])
spaces = board.reachable_spaces_northeast(4, 0, depth=2)
self.assertTrue(spaces == [(3, 0), (2, 1)])
spaces = board.reachable_spaces_northeast(4, 0, depth=4)
self.assertTrue(spaces == [(3, 0), (2, 1), (1, 1), (0, 2)])
spaces = board.reachable_spaces_northeast(4, 0, depth=5)
self.assertTrue(spaces == [(3, 0), (2, 1), (1, 1), (0, 2)])
board.remove_tile(1, 1)
spaces = board.reachable_spaces_northeast(4, 0)
self.assertTrue(spaces == [(3, 0), (2, 1)])
def test_reachable_spaces_southeast(self):
board = Board.make_uniform_board(5, 5, 1)
spaces = board.reachable_spaces_southeast(0, 0)
self.assertTrue(spaces == [(1, 0), (2, 1), (3, 1), (4, 2)])
spaces = board.reachable_spaces_southeast(1, 0)
self.assertTrue(spaces == [(2, 1), (3, 1), (4, 2)])
spaces = board.reachable_spaces_southeast(0, 1)
self.assertTrue(spaces == [(1, 1), (2, 2), (3, 2), (4, 3)])
spaces = board.reachable_spaces_southeast(0, 2)
self.assertTrue(spaces == [(1, 2), (2, 3), (3, 3), (4, 4)])
spaces = board.reachable_spaces_southeast(0, 2, depth=1)
self.assertTrue(spaces == [(1, 2)])
spaces = board.reachable_spaces_southeast(0, 2, depth=2)
self.assertTrue(spaces == [(1, 2), (2, 3)])
spaces = board.reachable_spaces_southeast(0, 2, depth=4)
self.assertTrue(spaces == [(1, 2), (2, 3), (3, 3), (4, 4)])
spaces = board.reachable_spaces_southeast(0, 2, depth=5)
self.assertTrue(spaces == [(1, 2), (2, 3), (3, 3), (4, 4)])
board.remove_tile(3, 1)
spaces = board.reachable_spaces_southeast(0, 0)
self.assertTrue(spaces == [(1, 0), (2, 1)])
def test_reachable_spaces_south(self):
board = Board.make_uniform_board(5, 5, 1)
spaces = board.reachable_spaces_south(0, 0)
self.assertTrue(spaces == [(2, 0), (4, 0)])
spaces = board.reachable_spaces_south(1, 0)
self.assertTrue(spaces == [(3, 0)])
spaces = board.reachable_spaces_south(2, 0)
self.assertTrue(spaces == [(4, 0)])
spaces = board.reachable_spaces_south(3, 0)
self.assertTrue(len(spaces) == 0)
spaces = board.reachable_spaces_south(0, 0, depth=1)
self.assertTrue(spaces == [(2, 0)])
spaces = board.reachable_spaces_south(0, 0, depth=2)
self.assertTrue(spaces == [(2, 0), (4, 0)])
spaces = board.reachable_spaces_south(0, 0, depth=10)
self.assertTrue(spaces == [(2, 0), (4, 0)])
board.remove_tile(4, 0)
spaces = board.reachable_spaces_south(0, 0)
self.assertTrue(spaces == [(2, 0)])
def test_reachable_spaces_southwest(self):
board = Board.make_uniform_board(5, 5, 1)
spaces = board.reachable_spaces_southwest(0, 0)
self.assertTrue(len(spaces) == 0)
spaces = board.reachable_spaces_southwest(1, 0)
self.assertTrue(spaces == [(2, 0)])
spaces = board.reachable_spaces_southwest(0, 1)
self.assertTrue(spaces == [(1, 0), (2, 0)])
spaces = board.reachable_spaces_southwest(0, 2)
self.assertTrue(spaces == [(1, 1), (2, 1), (3, 0), (4, 0)])
spaces = board.reachable_spaces_southwest(4, 4)
self.assertTrue(len(spaces) == 0)
spaces = board.reachable_spaces_southwest(0, 2, depth=1)
self.assertTrue(spaces == [(1, 1)])
spaces = board.reachable_spaces_southwest(0, 2, depth=2)
self.assertTrue(spaces == [(1, 1), (2, 1)])
spaces = board.reachable_spaces_southwest(0, 2, depth=10)
self.assertTrue(spaces == [(1, 1), (2, 1), (3, 0), (4, 0)])
board.remove_tile(2, 1)
spaces = board.reachable_spaces_southwest(0, 2)
self.assertTrue(spaces == [(1, 1)])
def test_reachable_spaces_northwest(self):
board = Board.make_uniform_board(5, 5, 1)
spaces = board.reachable_spaces_northwest(0, 0)
self.assertTrue(len(spaces) == 0)
spaces = board.reachable_spaces_northwest(1, 0)
self.assertTrue(spaces == [(0, 0)])
spaces = board.reachable_spaces_northwest(2, 0)
self.assertTrue(len(spaces) == 0)
spaces = board.reachable_spaces_northwest(4, 4)
self.assertTrue(spaces == [(3, 3), (2, 3), (1, 2), (0, 2)])
spaces = board.reachable_spaces_northwest(4, 4, depth=1)
self.assertTrue(spaces == [(3, 3)])
spaces = board.reachable_spaces_northwest(4, 4, depth=2)
self.assertTrue(spaces == [(3, 3), (2, 3)])
spaces = board.reachable_spaces_northwest(4, 4, depth=float("inf"))
self.assertTrue(spaces == [(3, 3), (2, 3), (1, 2), (0, 2)])
board.remove_tile(1, 2)
spaces = board.reachable_spaces_northwest(4, 4)
self.assertTrue(spaces == [(3, 3), (2, 3)])
def test_reachable_spaces(self):
board = Board.make_uniform_board(5, 5, 1)
spaces = board.reachable_spaces(0, 0)
self.assertTrue(spaces == [(1, 0), (2, 1), (3, 1), (4, 2), (2, 0), (4, 0)])
spaces = board.reachable_spaces(0, 0, depth=1)
self.assertTrue(spaces == [(1, 0), (2, 0)])
spaces = board.reachable_spaces(0, 0, depth=2)
self.assertTrue(spaces == [(1, 0), (2, 1), (2, 0), (4, 0)])
spaces = board.reachable_spaces(0, 0, depth=float("inf"))
self.assertTrue(spaces == [(1, 0), (2, 1), (3, 1), (4, 2), (2, 0), (4, 0)])
board.remove_tile(3, 1)
board.remove_tile(2, 0)
spaces = board.reachable_spaces(0, 0)
self.assertTrue(spaces == [(1, 0), (2, 1)])
if __name__ == '__main__':
unittest.main()
|
import data
import pickle
class Nearest(object):
""" =========================================================
It's a very important module that can determine performance
and correctness of this algorithm.
CURRENT STRATEGY : To find nearest user, we look at users
set's intersection, and we only calculate elements number of
this intersection to determine their similarity.
============================================================="""
def __init__(self,data):
super(Nearest, self).__init__()
self.users = data.getUser()
self.items = data.getItem()
self.user_item = data.getUserItem()
self.nearest = {}
self.outfilename = "/home/grzhan/Workspace/ali_bigdata/data/nearest_serialize"
self.simi_total = 0
self.simi_avg = 0
self.simi_n = 0
self.len_t = 0
self.len_a = 0
self.len_n = 0
self.len_threshold = 0.0677358214499078
def main(self):
K = 4
user_item = self.user_item
nearest = self.nearest
for active_user in self.users:
self.nearest_set_init(active_user)
for dest_user in self.users:
self.nearest_set_init(dest_user)
if active_user == dest_user:
continue
if active_user in nearest[dest_user]:
continue
intersection = user_item[active_user].intersection(user_item[dest_user])
if not intersection :
continue
# Important
simi = self.strategyLen(intersection, user_item[active_user], user_item[dest_user])
if simi :
nearest[active_user].add(dest_user)
nearest[dest_user].add(active_user)
def strategyLen(self,inter,active_set,dest_set):
# Important function !
self.simi_n += 1
self.len_n += 1
len_inter = len(inter)
len_activ = len(active_set)
len_ = len_inter * 1.0 / len_activ
self.len_t += len_
if len_ >= 0.4: # What threshold is better ?
return True
else:
return False
# if len_inter >= 4:
# return True
# else:
# return False
def nearest_set_init(self,index):
nearest = self.nearest
if not nearest.has_key(index):
nearest[index] = set()
def export(self):
filename = self.outfilename
serialize_s = pickle.dumps(self.nearest)
with open(self.outfilename, "w") as filehandle:
filehandle.write(serialize_s)
def getNearest(self):
return self.nearest
if __name__ == '__main__':
data_model = data.Data("/home/grzhan/Workspace/ali_bigdata/data/pre-g2.txt")
data_model.createRawData()
data_model.processRaw()
nearest = Nearest(data_model)
nearest.main()
nearest.export()
# Threshold:
# In [3]: nearest.len_t / nearest.len_n
# Out[3]: 0.0667062763561931
|
name = 'Ali'
if name == 'Alice':
print('Hi Alice.')
else:
print(name)
|
import numpy as np
# Some vector calculus functions
def unit_vector(a):
"""
Vector function: Given a vector a, return the unit vector
"""
return a / np.linalg.norm(a)
def d_unit_vector(a, ndim=3):
term1 = np.eye(ndim)/np.linalg.norm(a)
term2 = np.outer(a, a)/(np.linalg.norm(a)**3)
answer = term1-term2
return answer
def d_cross(a, b):
"""
Given two vectors a and b, return the gradient of the
cross product axb w/r.t. a.
(Note that the answer is independent of a.)
Derivative is on the first axis.
"""
d_cross = np.zeros((3, 3), dtype=float)
for i in range(3):
ei = np.zeros(3, dtype=float)
ei[i] = 1.0
d_cross[i] = np.cross(ei, b)
return d_cross
def d_cross_ab(a, b, da, db):
"""
Given two vectors a, b and their derivatives w/r.t.
a parameter, return the derivative
of the cross product
"""
answer = np.zeros((da.shape[0], 3), dtype=float)
for i in range(da.shape[0]):
answer[i] = np.cross(a, db[i]) + np.cross(da[i], b)
return answer
def ncross(a, b):
"""
Scalar function: Given vectors a and b, return the
norm of the cross product
"""
cross = np.cross(a, b)
return np.linalg.norm(cross)
def d_ncross(a, b):
"""
Return the gradient of the norm of the cross product w/r.t. a
"""
ncross = np.linalg.norm(np.cross(a, b))
term1 = a * np.dot(b, b)
term2 = -b * np.dot(a, b)
answer = (term1+term2)/ncross
return answer
def nudot(a, b):
r"""
Given two vectors a and b, return the dot product (\hat{a}).b.
"""
ev = a / np.linalg.norm(a)
return np.dot(ev, b)
def d_nudot(a, b):
r"""
Given two vectors a and b, return the gradient of
the norm of the dot product (\hat{a}).b w/r.t. a.
"""
return np.dot(d_unit_vector(a), b)
def ucross(a, b):
r"""
Given two vectors a and b, return the cross product (\hat{a})xb.
"""
ev = a / np.linalg.norm(a)
return np.cross(ev, b)
def d_ucross(a, b):
r"""
Given two vectors a and b, return the gradient of
the cross product (\hat{a})xb w/r.t. a.
"""
ev = a / np.linalg.norm(a)
return np.dot(d_unit_vector(a), d_cross(ev, b))
def nucross(a, b):
r"""
Given two vectors a and b, return the norm of the
cross product (\hat{a})xb.
"""
ev = a / np.linalg.norm(a)
return np.linalg.norm(np.cross(ev, b))
def d_nucross(a, b):
r"""
Given two vectors a and b, return the gradient of
the norm of the cross product (\hat{a})xb w/r.t. a.
"""
ev = a / np.linalg.norm(a)
return np.dot(d_unit_vector(a), d_ncross(ev, b))
# End vector calculus functions
# 8/10/2019
# LPW wrote a way to perform conjugate orthogonalization
# here is my own implementation which is similar to the orthogonalize
# GS algorithm. Also different is that LPW algorithm does not
# normalize the basis vectors -- they are simply the
# orthogonalized projection on the G surface.
# Here I think the DLC vectors are orthonormalized
# on the G surface.
def conjugate_orthogonalize(vecs, G, numCvecs=0):
"""
vecs contains some set of vectors
we want to orthogonalize them on the surface G
numCvecs is the number of vectors that should be
linearly dependent
after the gram-schmidt process is applied
"""
rows = vecs.shape[0]
cols = vecs.shape[1]
Expect = cols - numCvecs
# basis holds the Gram-schmidt orthogonalized DLCs
basis = np.zeros((rows, Expect))
norms = np.zeros(Expect, dtype=float)
def ov(vi, vj):
return np.linalg.multi_dot([vi, G, vj])
# first orthogonalize the Cvecs
for ic in range(numCvecs): # orthogonalize with respect to these
basis[:, ic] = vecs[:, ic].copy()
ui = basis[:, ic]
norms[ic] = np.sqrt(ov(ui, ui))
# Project out newest basis column from all remaining vecs columns.
for jc in range(ic+1, cols):
vj = vecs[:, jc]
vj -= ui * ov(ui, vj)/norms[ic]**2
count = numCvecs
for v in vecs[:, numCvecs:].T:
# w = v - np.sum( np.dot(v,b)*b for b in basis.T)
w = v - np.sum(ov(v, b)*b/ov(b, b) for b in basis[:, :count].T)
# A =np.linalg.multi_dot([w[:,np.newaxis].T,G,w[:,np.newaxis]])
# wnorm = np.sqrt(ov(w[:,np.newaxis],w[:,np.newaxis]))
wnorm = np.sqrt(ov(w, w))
if wnorm > 1e-5 and (abs(w) > 1e-6).any():
try:
basis[:, count] = w/wnorm
count += 1
except:
print("this vector should be vanishing, exiting")
print("norm=", wnorm)
print(w)
exit(1)
dots = np.linalg.multi_dot([basis.T, G, basis])
if not (np.allclose(dots, np.eye(dots.shape[0], dtype=float))):
print("np.dot(b.T,b)")
print(dots)
raise RuntimeError("error in orthonormality")
return basis
# TODO cVecs can be orthonormalized first to make it less confusing
# since they are being added to basis before being technically orthonormal
def orthogonalize(vecs, numCvecs=0):
"""
"""
# print("in orthogonalize")
rows = vecs.shape[0]
cols = vecs.shape[1]
basis = np.zeros((rows, cols-numCvecs))
# for i in range(numCvecs): # orthogonalize with respect to these
# basis[:,i]= vecs[:,i]
# count=numCvecs-1
count = 0
for v in vecs.T:
w = v - np.sum(np.dot(v, b)*b for b in basis.T)
wnorm = np.linalg.norm(w)
# print("wnorm {} count {}".format(wnorm,count))
if wnorm > 1e-3 and (abs(w) > 1e-6).any():
try:
basis[:, count] = w/wnorm
count += 1
except:
print("this vector should be vanishing, exiting")
print("norm=", wnorm)
# print(w)
exit(1)
dots = np.matmul(basis.T, basis)
if not (np.allclose(dots, np.eye(dots.shape[0], dtype=float), atol=1e-4)):
print("np.dot(b.T,b)")
# print(dots)
print(dots - np.eye(dots.shape[0], dtype=float))
raise RuntimeError("error in orthonormality")
return basis
|
from Tkinter import *
top=Tk()
main_frame=Frame(top)
main_frame.pack()
top_frame=Frame(top)
top_frame.pack(side=TOP)
c=Canvas(main_frame, bg="blue",height=300,width=200)
x=0
def printButton():
print("button\n")
def drawCircle(x):#probably could get more desired behavior using actual classes
c.create_polygon(x+10,x+10,x+20,x+20,x+30,x+20,x+10,x+10,fill='red')
x+=10
b=Button(top_frame,text="Button",command=lambda:drawCircle(x))
b.pack()
c.pack()
top.mainloop()
|
from tkinter import *
def setUpCanvas(root):
root.title("Wolfram's cellular automata: A Tk/Python Graphics Program")
canvas = Canvas(root, width = 1270, height = 780, bg = 'black')
canvas.pack(expand = YES, fill = BOTH)
return canvas
def printList(rule):
#1. print title
canvas.create_text(170, 20, text = "Rule " + str(rule), fill = 'gold', font = ('Helvetica', 20, 'bold'))
#2. set up list and print top row
L = [1,]
canvas.create_text(650, 10, text =chr(9607), fill = 'RED', font = ('Helvetica', FSIZE, 'bold'))
#3. write the rest
for row in range(90):
L = ['0','0']+L+['0','0']
num = []
for n in range(len(L)-2):
num.append(int(str(L[n])+str(L[n+1])+str(L[n+2]),2))
L = []
for a in num:
L += str(rule[a])
kolor = 'RED'
c=0
for n in L:
if n == '0':
kolor = 'BLACK'
canvas.create_text(650-row*FSIZE + FSIZE*c, 10+row*FSIZE, text =chr(9607), fill = kolor, font = ('Helvetica', FSIZE, 'bold'))
c += 1
kolor = 'RED'
root = Tk()
canvas = setUpCanvas(root)
FSIZE = 8
def main():
rule = [0,1,0,1,1,0,1,0,]
# rule = [1,0,1,1,0,1,0,1,]
# rule = [0,1,1,0,1,1,1,0,]
# rule = [1,1,0,0,1,1,1,0,]
# rule = [1,1,1,1,1,1,1,1,]
printList(rule)
root.mainloop()
if __name__ == '__main__':
main()
|
# Send one player around the board for a specified number of turns.
import matplotlib.pyplot as pyplot # For drawing bar chart.
import numpy as np
import sys # For parsing parms.
import game
# Convert the parm list of numbers to a list of percentages of the sum of the list.
# For example list_to_percentages([0.5, 0.5, ,2,3,4]) returns [5, 5, 20, 30, 40].
def list_to_percentages(this_list):
percentage = lambda x: 100 * x / sum(this_list)
return list(map(percentage, this_list))
print("""Decisions & Assumptions.
1. The program sends one player around the board for a specified number of turns.
2. There is no buying or selling of properties.
2. Whenever the player goes to Jail, if he holds a Get Out Of Jail card, he will use it to leave Jail immediately.
Otherwise, he will attempt to throw doubles in order to try to leave Jail.
After 3 unsuccessful attempts to throw doubles, he will leave Jail on his next turn.""")
assert(len(sys.argv) == 3) # There should be 3 parms passed to this program.
parm_turns = int(sys.argv[1])
parm_verbose = sys.argv[2] == 'True'
test_game = game.Game(num_players=1, verbose=parm_verbose)
# Take a number of turns for this player.
for turns in range(parm_turns):
test_game.take_a_turn(test_game.players[0])
land_on_percent = list_to_percentages(test_game.land_on_count) # Work out frequency percentages.
end_on_percent = list_to_percentages(test_game.turn_end_count) # Work out frequency percentages.
# Make a label list of square names for the graph, and print out table of results.
label = []
sq = 0
print('\nLand On Turn End On Square')
for i in test_game.board.squares:
label.append(i.name)
print(' {0:.2f}%'.format(land_on_percent[sq]), ' {0:.2f}%'.format(end_on_percent[sq]), ' ', i.name)
sq += 1
index = np.arange(len(label))
width = 0.27 # The width of the bars.
fig, ax = pyplot.subplots(nrows=1, ncols=1, figsize=(10, 5))
pyplot.bar(index - width/2, land_on_percent, width=width, align='center', color='blue', label='Land On')
pyplot.bar(index + width/2, end_on_percent, width=width, align='center', color='orange', label='End Turn On')
pyplot.legend(loc='upper left')
pyplot.ylabel('Frequency (percentage)', fontsize=10)
pyplot.xticks(index, label, fontsize=8, rotation=90)
pyplot.title('Square Frequencies (after ' + '{:,}'.format(parm_turns) + ' turns)')
pyplot.tight_layout() # Ensure that the property names fit on the plot area.
pyplot.show()
|
i=1
sum=0
n=int(input("enter the number"))
while(i<=n):
sum=sum+i
i=i+1
print(sum)
|
mytuple=("ram",343,"regal",3,45,"jalal",7.9)
print(mytuple)
print(mytuple[2])
print(mytuple*2)
print(mytuple[1:3])
second=("yui",9999,"ddd",99)
print(mytuple+second)
|
def pallindrome(x):
g=x
rev=0
while(x!=0):
s=x%10
rev=rev*10+s
x=x//10
if (g==rev):
return"pallindrome number"
else:
return"not a pallindrome nujmber"
n=int(input("enter the number"))
result=pallindrome(n)
print(result)
|
from datetime import datetime
from typing import Union
class Parser:
@staticmethod
def parse_data(date: str, formats: list) -> Union[datetime, None]:
"""Parse string with given formats
:param date: (str) - string with date
:param formats: (list) - all possible formats, that date may look like
:return:
"""
parsed_date = None
for fmt in formats:
try:
parsed_date = datetime.strptime(date, fmt)
break
except ValueError as _:
continue
return parsed_date
|
#Exercise 177: Roman Numerals
'''(25 Lines)
As the name implies, Roman numerals were developed in ancient Rome. Even after
the Roman empire fell, its numerals continued to be widely used in Europe until the
late middle ages, and its numerals are still used in limited circumstances today.
Roman numerals are constructed from the letters M, D, C, L, X, V and I which
represent 1000, 500, 100, 50, 10, 5 and 1 respectively. The numerals are generally
written from largest value to smallest value. When this occurs the value of the number
is the sum of the values of all of its numerals. If a smaller value precedes a larger
value then the smaller value is subtracted from the larger value that it immediately
precedes, and that difference is added to the value of the number.
Create a recursive function that converts a Roman numeral to an integer. Your
function should process one or two characters at the beginning of the string, and
then call itself recursively on all of the unprocessed characters. Use an empty string,
which has the value 0, for the base case. In addition, write a main program that reads
a Roman numeral from the user and displays its value. You can assume that the value
entered by the user is valid. Your program does not need to do any error checking.'''
print('Exercício 177: Vamos converter um número em romano para decimal.')
def romano(n, fin=0):
dic = {"M":1000, 'D':500, 'C':100, 'L':50, 'X':10, 'V':5, 'I':1}
if len(n) == 1:
fin += dic[n]
else:
if dic[n[0]] < dic[n[1]]:
fin = fin - dic[n[0]] + romano(n[1:len(n)], fin)
else:
fin += dic[n[0]] + romano(n[1:len(n)], fin)
return fin
def main():
num = str(input("Digite o número em romano a ser convertido: "))
num = num.upper()
num = num.replace(' ', '')
res = romano(num)
print("o número romano", num, "corresponde a", res, "em decimal.\n")
main()
|
"""
Q U E U E S I N P Y T H O N
"""
"""
- Using the FIFO approach, three names will be added into a queue.
- Then an element is removed using this approach.
- Think of a queue outside a retail store, the first one to arrive is Marc. When able to enter, Marc leaves the queue first.
"""
from collections import deque
q = deque()
q.append("Marc")
q.append("Steve")
q.append("Sarah")
# Output: deque(['Marc', 'Steve', 'Sarah'])
q.popleft()
# Output: deque(['Steve', 'Sarah'])
"""
I M P L E M E N T A Q U E U E
- This is great knowledge for coding interviews and understanding data structures.
"""
class Queue:
def __init__(self):
self.elements = []
self.length = 0
self.first = None
def __repr__(self):
q = []
for e in self.elements:
q.append(str(e))
return "[" + ", ".join(q) + "]"
def add(self, element):
self.elements.append(element) # Append new element to the queue
self.length += 1
self.first = self.elements[0]
def remove(self):
if not self.first:
raise Exception("Array is empty.")
self.length -= 1
# Select the first element in the queue
firstElement = self.elements[0]
# Remove the first element in the queue
self.elements = self.elements[1:]
self.first = self.elements[0]
return firstElement
queue = Queue() # Output: []
queue.add(2)
queue.add(5)
queue.add(12)
queue.add(3)
queue # Output: [2, 5, 12, 3]
queue.remove()
queue # Output: [5, 12, 3]
|
import itertools
def get_data():
with open("data/data_09.txt") as data_file:
data_string = data_file.read()
data_array = data_string.split("\n")
data_array = list(map(lambda x: int(x), data_array))
return data_array
def fetch_preamble(start, length):
with open("data/data_09.txt") as f:
iteration = itertools.islice(f, start, start + length)
list_output = list(map(lambda x: str.rstrip(x), [item for item in iteration]))
return list_output
def check_sums(preamble, number):
solution = []
for i, value1 in enumerate(preamble):
for value2 in preamble[i:]:
total = int(value1) + int(value2)
if total == number:
solution.append(number)
if len(solution) == 0:
return False
else:
return True
def find_contiguous(data, number):
start = 0
while start < len(data):
contig = []
for value in data[start::]:
contig.append(value)
if sum(contig) == number:
return contig
start += 1
return []
def calculate_answer(data):
data.sort()
return data[0] + data[-1]
data_set = get_data()
total = len(data_set)
preamble_length = 25
remaining_data = data_set[preamble_length:]
for counter, value in enumerate(remaining_data):
preamble = fetch_preamble(counter, preamble_length)
result = check_sums(preamble, value)
if not result:
invalid_number = value
print(f"Value {value} has failed")
weak_set = find_contiguous(data_set, invalid_number)
answer = calculate_answer(weak_set)
print(answer)
|
class LL:
def __init__(self, data):
self.data = data
self.next = None
def insrt_or_append(self, data, pos = None):
if pos != None:
c = 1
while c != pos-1:
c+=1
self = self.next
r = self.next
f = LL(data)
self.next = f
f.next = r
else:
while self.next != None:
self = self.next
self.next = LL(data)
def trav(self):
while self != None:
print(self.data)
self = self.next
def reverse(self):
prev = fwd = None
while self != None:
fwd = self.next
self.next = prev
prev = self
self = fwd
self = prev
while self != None:
print(self.data)
self = self.next
s = LL(1)
s.insrt_or_append(2)
s.insrt_or_append(3)
s.insrt_or_append(4)
s.insrt_or_append(5,4)
s.insrt_or_append(6)
s.insrt_or_append(8)
s.insrt_or_append(10, 2)
s.trav()
print("While reversing the order:")
s.reverse()
"""
O/P :
1
10
2
3
5
4
6
8
While reversing the order:
8
6
4
5
3
2
10
1
"""
|
def primeNative(n):
if n < 2:
return False
for x in range(2, n):
if (n % x) == 0:
return False
return True
print(primeNative(15))
|
from trie import *
# Create the tree
mytrie = Trie()
# Get the input ready
s = "The quick brown fox jumps over the lazy dog"
toks = s.strip().split()
for tok in toks:
# Insert key:value {word: meaning} in to tree
mytrie.addWord(mytrie.rootNode, tok, "blabla")
# If search is successful, you will get meaning in
# a list
result = False
meaning = []
result = mytrie.search(mytrie.rootNode, "lazy", meaning)
# Output
print meaning
|
"""# Exercise: GCDRecr
# Write a Python function, gcdRecur(a, b),
that takes in two numbers and returns the GCD(a,b) of given a and b.
# This function takes in two numbers and returns one number."""
def gcd_recursion(a_val, b_val):
'''a, b: positive integers
returns: a positive integer,
the greatest common divisor of a & b.
'''
if b_val == 0:
return a_val
return gcd_recursion(b_val, a_val%b_val)
def main():
"""Main Function"""
data = input()
data = data.split()
print(gcd_recursion(int(data[0]), int(data[1])))
main()
|
"""#Guess My Number Exercise"""
LOW_NUM = 0
HIGH_NUM = 100
print("Please think of a number between 0 and 100!")
print("Enter 'y' if guess done, or 'h' if that (number > your guess ) else 'l' ")
USER_GUESS = 'LOW_NUM'
while USER_GUESS != 'y':
print("Is your secret number ", int((LOW_NUM+HIGH_NUM)//2), "?")
USER_GUESS = input()
if USER_GUESS == 'l':
LOW_NUM = ((LOW_NUM+HIGH_NUM)//2)
elif USER_GUESS == 'h':
HIGH_NUM = ((LOW_NUM+HIGH_NUM)//2)
print(USER_GUESS)
|
from numpy import exp, array, random, dot
class neural_network:
def __init__(self):
random.seed(1)
# We model a single neuron, with 3 inputs and 1 output and assign random weight.
self.weights = 2 * random.random((3, 1)) - 1
def __sigmoid(self, x):
return 1 / (1 + exp(-x))
def train(self, inputs, outputs, num):
for iteration in range(num):
output = self.think(inputs)
error = outputs - output
adjustment = dot(inputs.T, error * output*(1-output))
self.weights += adjustment
def think(self, inputs):
result = self.__sigmoid(dot(inputs, self.weights))
return result
network = neural_network()
# The training set
inputs = array([[1, 1, 1], [1, 0, 1], [0, 1, 1]])
outputs = array([[1, 1, 0]]).T
# Training the neural network using the training set.
network.train(inputs, outputs, 10000)
# Ask the neural network the output
print(network.think(array([1, 0, 0])))
|
"""Constants related to visualization methods."""
from typing import Tuple, Union
LEN_RGB = 3 # number of elements in an RGB color
LEN_RGBA = 4 # number of elements in an RGBA color
RGB = Tuple[(float,) * LEN_RGB] # typing of an RGB color
RGBA = Tuple[(float,) * LEN_RGBA] # typing of an RGBA color
RGB_RGBA = Union[RGB, RGBA] # typing of an RGB or RGBA color
RGBA_MIN = 0 # min value for an RGBA element
RGBA_MAX = 1 # max value for an RGBA element
RGBA_ALPHA = 3 # zero-indexed fourth element in RGBA
RGBA_WHITE = (RGBA_MAX, RGBA_MAX, RGBA_MAX, RGBA_MAX) # white as an RGBA color
RGBA_BLACK = (RGBA_MIN, RGBA_MIN, RGBA_MIN, RGBA_MAX) # black as an RGBA color
|
from functools import reduce
"""
A small expressions language, with variables and assignment
as a result we have 3 additions to the AST nodes menagerie
* Expressions to build a program block
* Assignment to store a result in a variable name
* Variable to reference a variable (use latest stored value)
"""
# https://docs.python.org/3/library/operator.html
# typically neg looks like
# neg = lambda x: -x
# and add is like
# add = lambda x, y: x + y
from operator import neg, add, sub, mul, truediv
class Expression:
"""
for compatibility with v1
we need our expressions to be able to do eval()
with possibly no argument
so our child classes will implement _eval(env) (mandatory arg)
and this layer deals with creating an empty env when needed
"""
def eval(self, env=None):
if env is None:
env = {}
return self._eval(env)
def _eval(self, env):
print(f"{type(self).__name__} needs to implement _eval(env)")
class Atom(Expression):
"""
a class to implement an atomic value,
like an int, a float, a str, ...
in order to be able to use this,
child classes need to provide self.type
that should be a class like int or float
or similar whose constructor expects one arg
"""
def __init__(self, value):
self.value = self.type(value)
def _eval(self, env):
return self.value
class Unary(Expression):
"""
the mother of all unary operators
in order to be able to use this,
child classes need to provide self.function
which is expected to be a 1-parameter function
"""
def __init__(self, operand):
self.operand = operand
def _eval(self, env):
"""
"""
try:
return self.function(self.operand.eval(env))
except AttributeError:
print(f"WARNING - class {self.__class__.__name__} lacks a function")
class Binary(Expression):
"""
the mother of all binary operators
in order to be able to use this,
child classes need to provide self.function
which is expected to be a 2-parameter function
"""
def __init__(self, left, right):
self.left = left
self.right = right
def _eval(self, env):
try:
return self.function(self.left.eval(env),
self.right.eval(env))
except AttributeError:
print(f"WARNING - class {self.__class__.__name__} lacks a function")
class Nary(Expression):
"""
the mother of all n-ary operators
self.function is expected to be a 2-ary associative function
and evaluation is performed through a call to reduce()
"""
# 2 parameters are required
def __init__(self, left, right, *more):
self.children = [left, right, *more]
def _eval(self, env):
try:
return reduce(self.function, (x.eval(env) for x in self.children))
except AttributeError:
print(f"WARNING - class {self.__class__.__name__} lacks a function")
######
class Integer(Atom):
type = int
class Float(Atom):
type = float
class Negative(Unary):
function = neg
class Minus(Binary):
function = sub
class Divide(Binary):
function = truediv
class Plus(Nary):
function = add
class Multiply(Nary):
function = mul
class Expressions(Expression):
"""
a sequence of expressions
its result is the result of the last expression
"""
def __init__(self, mandatory, *optional):
# optional is bound to a tuple
self.children = [mandatory] + list(optional)
def _eval(self, env):
last_result = None
for child in self.children:
last_result = child.eval(env)
return last_result
class Assignment(Expression):
"""
Assignment(varname, expression) evaluates the expression,
assigns the result to varname, and returns that result
"""
def __init__(self, varname, expression):
self.varname = varname
self.expression = expression
def _eval(self, env):
result = self.expression.eval(env)
env[self.varname] = result
return result
class Variable(Expression):
"""
returns the value of that variable
"""
def __init__(self, varname):
self.varname = varname
def _eval(self, env):
# keep it simple for now
# our language does not support exceptions, so
# let us return None on undefined variables
return env.get(self.varname, None)
|
# https: // leetcode.com/problems/reverse-words-in-a-string-iii/
# Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
def reverseWords(s):
new_words = []
split = s.split()
for word in split:
new_words.append(reverse(word))
return " ".join(new_words)
def reverse(string):
i = 0
j = len(string) - 1
split = list(string)
while (i < j):
temp = split[i]
split[i] = split[j]
split[j] = temp
i += 1
j -= 1
return "".join(split)
input = "Let's take LeetCode contest"
# Output: "s'teL ekat edoCteeL tsetnoc"
word = 'cat dog'
print(reverseWords(input))
|
def addNum(seq, num):
seq = list(seq)
for i in range(len(seq)):
seq[i] += num
return seq
origin = (3, 6, 2, 6)
changed = addNum(origin, 3)
print(origin)
print(changed)
l = [(10, 20, 40), (40, 50, 60), (70, 80, 90)]
print([t[:-1] + (100,) for t in l])
a = {0, 1, 2, 3}
b = {4, 3, 2, 1}
c = a.intersection(b)
print(c)
x = {1, 2, 3}
y = {4, 3, 6}
z = y.clear()
print(y)
l1 = [10, 20, 30, 40, 50]
l2 = [50, 75, 30, 20, 40, 69]
res = [x for x in l1 + l2 if x not in a or l1 not in l2]
print(res)
a.difference(l2)
|
"""This file contains all the classes you must complete for this project.
You can use the test cases in agent_test.py to help during development, and
augment the test suite with your own test cases to further test your code.
You must test your agent's strength against a set of agents with known
relative strength using tournament.py and include the results in your report.
"""
import random
infinity = float('inf')
class Timeout(Exception):
"""Subclass base exception for code clarity."""
pass
def custom_score_basic(game, player):
"""Calculate the heuristic value of a game state from the point of view
of the given player.
Parameters
----------
game : `isolation.Board`
An instance of `isolation.Board` encoding the current state of the
game (e.g., player locations and blocked cells).
player : object
A player instance in the current game (i.e., an object corresponding to
one of the player objects `game.__player_1__` or `game.__player_2__`.)
Returns
----------
float
The heuristic value of the current game state to the specified player.
"""
if game.is_loser(player):
return float("-inf")
if game.is_winner(player):
return float("inf")
own_moves = game.get_legal_moves(player)
score = len(own_moves)
return float(score)
def custom_score_improved(game, player):
"""Calculate the heuristic value of a game state from the point of view
of the given player. This score function returns the difference
between the number of moves available for self and the opponent player.
A mixing factor is used to compute weighted sum of the two instead of
plain addition.
Parameters
----------
game : `isolation.Board`
An instance of `isolation.Board` encoding the current state of the
game (e.g., player locations and blocked cells).
player : object
A player instance in the current game (i.e., an object corresponding to
one of the player objects `game.__player_1__` or `game.__player_2__`.)
Returns
----------
float
The heuristic value of the current game state to the specified player.
"""
if game.is_loser(player):
return float("-inf")
if game.is_winner(player):
return float("inf")
mixing_factor = 0.4
own_moves = len(game.get_legal_moves(player))
opp_moves = len(game.get_legal_moves(game.get_opponent(player)))
return float(mixing_factor * own_moves + (1 - mixing_factor) * (-opp_moves))
def custom_score_opponent_moves(game, player):
"""Calculate the heuristic value of a game state from the point of view
of the given player. This score function only returns the number of
moves available for opponent player.
Parameters
----------
game : `isolation.Board`
An instance of `isolation.Board` encoding the current state of the
game (e.g., player locations and blocked cells).
player : object
A player instance in the current game (i.e., an object corresponding to
one of the player objects `game.__player_1__` or `game.__player_2__`.)
Returns
----------
float
The heuristic value of the current game state to the specified player.
"""
if game.is_loser(player):
return float("-inf")
if game.is_winner(player):
return float("inf")
own_moves = 0 # len(game.get_legal_moves(player))
opp_moves = len(game.get_legal_moves(game.get_opponent(player)))
return float(own_moves - opp_moves)
def custom_score_own_moves(game, player):
"""Calculate the heuristic value of a game state from the point of view
of the given player. This score function only returns the number of
moves available for the player.
Parameters
----------
game : `isolation.Board`
An instance of `isolation.Board` encoding the current state of the
game (e.g., player locations and blocked cells).
player : object
A player instance in the current game (i.e., an object corresponding to
one of the player objects `game.__player_1__` or `game.__player_2__`.)
Returns
----------
float
The heuristic value of the current game state to the specified player.
"""
if game.is_loser(player):
return float("-inf")
if game.is_winner(player):
return float("inf")
own_moves = len(game.get_legal_moves(player))
return float(own_moves)
def custom_score_center_deviation(game, player):
"""Calculate the heuristic value of a game state from the point of view
of the given player. This score function discourages the player to go to
the boundaries of the board by discounting the distance to centre of the
board from the returned score.
Parameters
----------
game : `isolation.Board`
An instance of `isolation.Board` encoding the current state of the
game (e.g., player locations and blocked cells).
player : object
A player instance in the current game (i.e., an object corresponding to
one of the player objects `game.__player_1__` or `game.__player_2__`.)
Returns
----------
float
The heuristic value of the current game state to the specified player.
"""
if game.is_loser(player):
return float("-inf")
if game.is_winner(player):
return float("inf")
mixing_factor = 0.8
board_center = (game.width / 2.0, game.height / 2.0)
current_location = game.get_player_location(player)
distance_to_center = (current_location[0] - board_center[0]) ** 2 + (current_location[1] - board_center[1]) ** 2
distance_to_center_normilized = distance_to_center / ( (board_center[0]) ** 2 + (board_center[1]) ** 2 )
#print("distance to center = " + str(-distance_to_center))
nrof_own_moves = len(game.get_legal_moves(player))
nrof_own_moves_normilized = nrof_own_moves / 8.0
score = mixing_factor * nrof_own_moves_normilized + (1 - mixing_factor) * (- distance_to_center_normilized)
#print('score = ' + str(score))
return float(score)
def custom_score_lookahead_opponent(game, player):
"""Calculate the heuristic value of a game state from the point of view
of the given player. This score function looks at the number of available
moves for its own player subtracted by the average number of moves available
for the opponent in the next round.
Parameters
----------
game : `isolation.Board`
An instance of `isolation.Board` encoding the current state of the
game (e.g., player locations and blocked cells).
player : object
A player instance in the current game (i.e., an object corresponding to
one of the player objects `game.__player_1__` or `game.__player_2__`.)
Returns
----------
float
The heuristic value of the current game state to the specified player.
"""
if game.is_loser(player):
return float("-inf")
if game.is_winner(player):
return float("inf")
own_moves = game.get_legal_moves(player)
if len(own_moves) == 0:
return float("-inf")
opp_moves = 0.0
for move in own_moves:
new_game = game.forecast_move(move)
opp_moves += len(new_game.get_legal_moves(game.get_opponent(player)))
# get the average moves that the opponent have
avg_opp_moves = opp_moves / len(own_moves)
return float(len(own_moves) - avg_opp_moves)
def custom_score_lookahead_own(game, player):
"""Calculate the heuristic value of a game state from the point of view
of the given player. This score function looks ahead one level deeper and
returns the number of legal moves at the current step and the average of
number of moves available due to each of the moves in previous step.
Parameters
----------
game : `isolation.Board`
An instance of `isolation.Board` encoding the current state of the
game (e.g., player locations and blocked cells).
player : object
A player instance in the current game (i.e., an object corresponding to
one of the player objects `game.__player_1__` or `game.__player_2__`.)
Returns
----------
float
The heuristic value of the current game state to the specified player.
"""
# TODO: finish this function!
#raise NotImplementedError
if game.is_loser(player):
return float("-inf")
if game.is_winner(player):
return float("inf")
own_moves = game.get_legal_moves(player)
if len(own_moves) == 0:
return float("-inf")
mixing_factor = 0.4
lookahead_moves = 0.0
for move in own_moves:
lookahead_game = game.forecast_move(move)
lookahead_moves += len(lookahead_game.get_legal_moves(player))
lookahead_moves /= len(own_moves)
if lookahead_moves == 0:
# loosing game in the future
return float("-inf")
score = mixing_factor * len(own_moves) + (1 - mixing_factor) * lookahead_moves
return float(score)
def custom_score_lookahead_both(game, player):
"""Calculate the heuristic value of a game state from the point of view
of the given player. This score function looks ahead one level deeper and
returns the number of legal moves at the current step and the average of
number of moves available due to each of the moves in previous step.
This look ahead is performed for both players.
Parameters
----------
game : `isolation.Board`
An instance of `isolation.Board` encoding the current state of the
game (e.g., player locations and blocked cells).
player : object
A player instance in the current game (i.e., an object corresponding to
one of the player objects `game.__player_1__` or `game.__player_2__`.)
Returns
----------
float
The heuristic value of the current game state to the specified player.
"""
# TODO: finish this function!
#raise NotImplementedError
if game.is_loser(player):
return float("-inf")
if game.is_winner(player):
return float("inf")
own_moves = game.get_legal_moves(player)
opp_moves = len(game.get_legal_moves(game.get_opponent(player)))
mixing_factor = 0.5
if len(own_moves) == 0:
return float("-inf")
lookahead_moves = 0.0
opp_moves_next_level = 0.0
for move in own_moves:
lookahead_game = game.forecast_move(move)
lookahead_moves += len(lookahead_game.get_legal_moves(player))
# opponent moves
opp_moves_next_level += len(lookahead_game.get_legal_moves(game.get_opponent(player)))
lookahead_moves /= len(own_moves)
# get the average moves that the opponent have
opp_moves_next_level /= len(own_moves)
if lookahead_moves == 0:
# loosing game in the future
#return float("-inf")
pass
score = mixing_factor * (len(own_moves) - opp_moves) + (1 - mixing_factor) * (lookahead_moves - opp_moves_next_level)
return float(score)
def custom_score(game, player):
"""Calculate the heuristic value of a game state from the point of view
of the given player.
Parameters
----------
game : `isolation.Board`
An instance of `isolation.Board` encoding the current state of the
game (e.g., player locations and blocked cells).
player : object
A player instance in the current game (i.e., an object corresponding to
one of the player objects `game.__player_1__` or `game.__player_2__`.)
Returns
----------
float
The heuristic value of the current game state to the specified player.
"""
#return custom_score_basic(game, player)
#return custom_score_improved(game, player)
#return custom_score_opponent_moves(game, player)
#return custom_score_own_moves(game, player)
#return custom_score_lookahead_opponent(game, player)
#return custom_score_center_deviation(game, player)
#return custom_score_lookahead_own(game, player)
return custom_score_lookahead_both(game, player)
class CustomPlayer:
"""Game-playing agent that chooses a move using your evaluation function
and a depth-limited minimax algorithm with alpha-beta pruning. You must
finish and test this player to make sure it properly uses minimax and
alpha-beta to return a good move before the search time limit expires.
Parameters
----------
search_depth : int (optional)
A strictly positive integer (i.e., 1, 2, 3,...) for the number of
layers in the game tree to explore for fixed-depth search. (i.e., a
depth of one (1) would only explore the immediate sucessors of the
current state.)
score_fn : callable (optional)
A function to use for heuristic evaluation of game states.
iterative : boolean (optional)
Flag indicating whether to perform fixed-depth search (False) or
iterative deepening search (True).
method : {'minimax', 'alphabeta'} (optional)
The name of the search method to use in get_move().
timeout : float (optional)
Time remaining (in milliseconds) when search is aborted. Should be a
positive value large enough to allow the function to return before the
timer expires.
"""
def __init__(self, search_depth=3, score_fn=custom_score,
iterative=True, method='minimax', timeout=10.):
self.search_depth = search_depth
self.iterative = iterative
self.score = score_fn
self.method = method
self.time_left = None
self.TIMER_THRESHOLD = timeout
def get_move(self, game, legal_moves, time_left):
"""Search for the best move from the available legal moves and return a
result before the time limit expires.
This function must perform iterative deepening if self.iterative=True,
and it must use the search method (minimax or alphabeta) corresponding
to the self.method value.
**********************************************************************
NOTE: If time_left < 0 when this function returns, the agent will
forfeit the game due to timeout. You must return _before_ the
timer reaches 0.
**********************************************************************
Parameters
----------
game : `isolation.Board`
An instance of `isolation.Board` encoding the current state of the
game (e.g., player locations and blocked cells).
legal_moves : list<(int, int)>
A list containing legal moves. Moves are encoded as tuples of pairs
of ints defining the next (row, col) for the agent to occupy.
time_left : callable
A function that returns the number of milliseconds left in the
current turn. Returning with any less than 0 ms remaining forfeits
the game.
Returns
----------
(int, int)
Board coordinates corresponding to a legal move; may return
(-1, -1) if there are no available legal moves.
"""
self.time_left = time_left
# TODO: finish this function!
# Perform any required initializations, including selecting an initial
# move from the game board (i.e., an opening book), or returning
# immediately if there are no legal moves
if len(legal_moves) == 0:
return (-1, -1)
# initialize next move
move = legal_moves[0]
TERMINAL_MOVE = [(-1, -1)]
try:
# The search method call (alpha beta or minimax) should happen in
# here in order to avoid timeout. The try/except block will
# automatically catch the exception raised by the search method
# when the timer gets close to expiring
if self.method == 'minimax':
search_alg = self.minimax
elif self.method == 'alphabeta':
search_alg = self.alphabeta
else:
raise Exception
if self.iterative:
# if iterative deepening is activated, it starts from depth zero
# and work it's way toward deeper levels of the decision tree
depth = 0
else:
# if iterative deepening is not activated, it only does the
# search once for the maximum depth of the tree
depth = self.search_depth
while self.iterative or depth <= self.search_depth and move not in TERMINAL_MOVE:
# go one level deeper in the search tree
_, move = search_alg(game, depth)
depth += 1
except Timeout:
# Handle any actions required at timeout, if necessary
pass
# Return the best move from the last completed search iteration
return move
def minimax(self, game, depth, maximizing_player=True):
"""Implement the minimax search algorithm as described in the lectures.
Parameters
----------
game : isolation.Board
An instance of the Isolation game `Board` class representing the
current game state
depth : int
Depth is an integer representing the maximum number of plies to
search in the game tree before aborting
maximizing_player : bool
Flag indicating whether the current search depth corresponds to a
maximizing layer (True) or a minimizing layer (False)
Returns
----------
float
The score for the current search branch
tuple(int, int)
The best move for the current branch; (-1, -1) for no legal moves
"""
player = game.active_player
def min_value(game, depth):
if self.time_left() < self.TIMER_THRESHOLD:
raise Timeout()
# depth zero means we are at the leaf
next_move = (-1, -1)
if depth == 0 or len(game.get_legal_moves()) == 0:
return self.score(game, player), next_move
score = infinity
for move in game.get_legal_moves():
v, _ = max_value(game.forecast_move(move), depth - 1)
# find the min(score, v) and the corresponding move
if score > v:
score = v
next_move = move
return score, next_move
def max_value(game, depth):
if self.time_left() < self.TIMER_THRESHOLD:
raise Timeout()
# depth zero means we are at the leaf
next_move = (-1, -1)
if depth == 0 or len(game.get_legal_moves()) == 0:
return self.score(game, player), next_move
score = -infinity
for move in game.get_legal_moves():
v, _ = min_value(game.forecast_move(move), depth - 1)
# find the max(score, v) and the corresponding move
if score < v:
score = v
next_move = move
return score, next_move
if self.time_left() < self.TIMER_THRESHOLD:
raise Timeout()
# Do a search with a bounded depth
if maximizing_player:
score, next_move = max_value(game, depth)
else:
raise NotImplemented
return score, next_move
def alphabeta(self, game, depth, alpha=float("-inf"), beta=float("inf"), maximizing_player=True):
"""Implement minimax search with alpha-beta pruning as described in the
lectures.
Parameters
----------
game : isolation.Board
An instance of the Isolation game `Board` class representing the
current game state
depth : int
Depth is an integer representing the maximum number of plies to
search in the game tree before aborting
alpha : float
Alpha limits the lower bound of search on minimizing layers
beta : float
Beta limits the upper bound of search on maximizing layers
maximizing_player : bool
Flag indicating whether the current search depth corresponds to a
maximizing layer (True) or a minimizing layer (False)
Returns
----------
float
The score for the current search branch
tuple(int, int)
The best move for the current branch; (-1, -1) for no legal moves
"""
def min_value(game, depth, alpha = -infinity, beta = infinity):
if self.time_left() < self.TIMER_THRESHOLD:
raise Timeout()
# initialize the next move
next_move = (-1, -1)
# depth zero means we are at the leaf
if depth == 0 or len(game.get_legal_moves()) == 0:
return self.score(game, player), next_move
score = infinity
for move in game.get_legal_moves():
v, _ = max_value(game.forecast_move(move), depth - 1, alpha, beta)
# compare and find hte maximium score and the corresponding move
if score > v:
score = v
next_move = move
# pruning
if score <= alpha:
break
# update the value for alpha
beta = min(beta, score)
return score, next_move
def max_value(game, depth, alpha = -infinity, beta = infinity):
if self.time_left() < self.TIMER_THRESHOLD:
raise Timeout()
# initialize the next move
next_move = (-1, -1)
# depth zero means we are at the leaf
if depth == 0 or len(game.get_legal_moves()) == 0:
return self.score(game, player), next_move
score = -infinity
for move in game.get_legal_moves():
v, _ = min_value(game.forecast_move(move), depth - 1, alpha, beta)
# compare and find hte maximium score and the corresponding move
if score < v:
score = v
next_move = move
# pruning
if score >= beta:
break
# update the value for alpha
alpha = max(alpha, score)
return score, next_move
if self.time_left() < self.TIMER_THRESHOLD:
raise Timeout()
player = game.active_player
if maximizing_player:
score, next_move = max_value(game, depth, alpha, beta)
else:
raise NotImplemented
return score, next_move
|
"""
* Sample input:
*
* 1
* / \
* 3 5
* / / \
* 2 4 7
* / \ \
* 9 6 8
*
* Expected output:
* 1
* 3 5
* 2 4 7
* 9 6 8
"""
class TreeNode:
def __init__(self,data):
self.data = data
self.left = None
self.right = None
def LevelOrderPrint(root):
stack = [root]
while stack:
level, result = list(), list()
for node in stack:
result.append(str(node.data))
if node.left:
level.append(node.left)
if node.right:
level.append(node.right)
stack = level
print(' '.join(result))
if __name__ == '__main__':
root = TreeNode(1)
root.left = TreeNode(3)
root.right = TreeNode(5)
root.left.left = TreeNode(2)
root.right.left = TreeNode(4)
root.right.right = TreeNode(7)
root.left.left.left = TreeNode(9)
root.left.left.right = TreeNode(6)
root.right.left.right = TreeNode(8)
LevelOrderPrint(root)
|
nomes = ('Ana','Bia','Gui','Ana')
#Identificar tipo da classe e valor booleano
print(type(nomes))
print('Bia' in nomes)
#Formas de pesquisas nas listas
print(nomes[2])
print(nomes[0:2])
print(nomes[1:-1])
print(nomes)
|
lista = ["abacate","bola","cachorro"]
for i in range(len(lista)): # RENGE cria um vetor e LEN mede o tamanho da lista
print(i, lista[i])
#Enumerate:
lista = ["abacate","bola","cachorro"]
for i, nome in enumerate(lista): # Melhor forma de se fazer
print(i, nome)
|
a = "Brasil"
b = "China"
concatenar = a + " " + b + "\n" #"\n" pula uma linha, para remover tem que usar print(concatenar.STRIP()).
print(concatenar)
print(concatenar.lower()) #Método para deixar os caracteres em minúsculo sem alterar a variável
print(concatenar.upper()) #Método para deixar os caracteres em maiúsculo sem alterar a variável
concatenar = concatenar.upper #Método para deixar os caracteres em maiúsculo alterando a variável
#Usando SPLIT
minha_string = "O rato roeu a roupa do rei de Roma"
Minha_lista = minha_string.split()
print(Minha_lista)
#Remover letra com a letra desejada
minha_string = "O rato roeu a roupa do rei de Roma"
Minha_lista = minha_string.split("r") # "r" é a letra a ser removida
print(Minha_lista)
#Busca de String FIND
minha_string = "O rato roeu a roupa do rei de Roma"
busca = minha_string.find("rei") #Buscou onde começa da palavra "rei"
print(busca)
print(minha_string[busca:]) #Para imprimir a frase até o final
minha_string2 = "O rato roeu a roupa do rei de Roma"
minha_string2 = minha_string2.replace("o rei","a rainha")#Subistituir a palavra
print(minha_string2)
|
import random
# Sorteia um numero aleatorio de 0 a 10
numero = random.randint(0,10)
print(numero)
# Sorteia um numero pré definido
random.seed(1)
numero = random.randint(0,10)
print(numero)
# Sorteia um numero da lista aleatoriamente (esse comando só funciona sozinho)
lista = [6,45,9,66]
numero = random.choice(lista)
print(numero)
|
#### To group records based on a field ####
#### The records are stored in a list of dictionaries ####
#### Using itertools.groupy() ####
from itertools import groupby
from operator import itemgetter
rows = [
{'address': '5412 N CLARK', 'date': '07/01/2012'},
{'address': '5148 N CLARK', 'date': '07/04/2012'},
{'address': '5800 E 58TH', 'date': '07/02/2012'},
{'address': '2122 N CLARK', 'date': '07/03/2012'},
{'address': '5645 N RAVENSWOOD', 'date': '07/02/2012'},
{'address': '1060 W ADDISON', 'date': '07/02/2012'},
{'address': '4801 N BROADWAY', 'date': '07/01/2012'},
{'address': '1039 W GRANVILLE', 'date': '07/04/2012'},
]
# Sort by the desired field first, which is a required process due to groupby() can only scan consequtive sequences
rows.sort(key=itemgetter('date'))
# Group the records based on date
grouped_records = {}
for date, items in groupby(rows, key=itemgetter('date')):
grouped_records[date] = []
for item in items:
grouped_records[date].append(item)
|
#### to perform useful calculations on dictionary contents, it is often useful to convert the keys and values of the dictionary using zip() ####
#### zip() creates an iterator, which can only be consumed once ####
numbers = {
'Bryrant': 24,
'Gasol': 16,
'Bynum': 17,
'Odom': 7,
'Fisher': 2
}
# find min/max value with its key
min_number = min(zip(numbers.values(), numbers.keys()))
max_number = max(zip(numbers.values(), numbers.keys()))
# sort the dictionary
numbers_sorted = sorted(zip(numbers.values(), numbers.keys())) # sort by values
numbers_sorted = sorted(zip(numbers.keys(), numbers.values())) # sort by keys
|
#!/usr/bin/env python
from __future__ import print_function, unicode_literals
'''
1. Create a directory called mytest. In ./mytest create three Python modules world.py,
simple.py, whatever.py.
a. These three files should each have a function that prints a statement when
called (func1, func2, func3).
b. In each of the three modules use the __name__ technique to separate executable
code from importable code. Each module should contain executable code.
c. Verify that you are NOT able to 'import mytest' (try this from the directory
that contains ./mytest).
Note, recent versions of Python3 will allow you to import the package even though
no __init__.py exists in the directory. In other words, recent versions of Python3
(Python3.3 or greater) will allow packages without __init__.py files in certain contexts.
'''
def simple_func1():
print('This is func1 from simple.py!')
print('The name of the __name__ variable is {}!'.format(__name__))
def simple_func2():
print('This is func2 from simple.py!')
print('The name of the __name__ variable is {}!'.format(__name__))
def simple_func3():
print('This is func3 from wsimple.py!')
print('The name of the __name__ variable is {}!'.format(__name__))
def main():
print('\nYou just ran simple.py directly as a main script.')
print('The name of the __name__ variable is {}!'.format(__name__))
if __name__ == "__main__":
main()
print("Just a simple hello")
|
#Dado n, inteiro maior que zero imprimir tabela com os valores de x * y para x e y = 1, 2, ..., n.
#Imprimir apenas o triângulo inferior
def main ():
# ler n inteiro >= 0
n = int(input("Entre com o valor de n inteiro > a zero: "))
#imprimir o cabeçalho
print (" ", end = '')
for i in range (1, n + 1):
print ("%5d" %i, end = '')
print ()
# Variar i de 1 até n. Para cada i, variar j de 1 até i.
# Para cada para (i, j) imprimir i * j
for i in range (1, n + 1):
print ("%5d" %i, end = '')
for j in range (1, i + 1): print ("%5d" %(i*j), end = '')
print ()
print ()
while True:
main ()
|
# Calcular o valor da função x^3 + x^2+ x + 1 para x = 1, -1, 2, -2, 3, -3
def main ():
for k in [1,-1,2,-2,3,-3]:
print ("O valor de x quando vale %d é =" %k, k*k*k + k*k + k + 1)
main ()
|
# Função maior(x,y) que calcula e devolve o maior entre dois valores.
def maior(x, y):
if x > y: return x
return y
print (maior (3,5))
|
# Dado N > 0 e uma sequência de N números, determinar o maior elemento da sequência.
def main():
# ler a quantidade de números N
N = int(input("Digite a quantidade de números da sequência: "))
# Consistência dos dados de entrada
if N == 0:
print("A sequência possui zero elementos")
else:
maior = float(input("Digite o primeiro valor da sequência: "))
# inicia o contador e define o maior número inicial
contador = 1
# repete a comparação dos valores imputados N vezes
while N - 1 >= contador:
#ler o próximo
x = float(input("Digite o próximo valor da sequência: "))
#faz a comparação
if x > maior: maior = x
contador = contador + 1
#imprime o resultado
print ("O maior valor da sequência é:", maior)
main()
|
# Dado N > 0, inteiro, calcular a soma N + N/2 + N/4 + ... + 1
# solução abaixo considera a divisão inteira. Por exemplo, para N = 15 (15 + 7 + 3 + 1), para N = 10
# (10 + 5 + 2 + 1).
def main():
N = int(input("Entre com N > 0 e inteiro:"))
soma = 0
while N > 0:
soma = soma + N
N = N // 2
print("Valor da soma = ", soma)
main()
|
#Dada uma sequência de números terminada por zero, determinar o menor elemento da sequência.
def main():
#lê o primeiro elemento
x = float(input("Digite o primeiro elemento da sequência: "))
#consistência dos dados
if x == 0:
print("Esta sequência possui apenas o número zero como elemento.")
#determina que o x até então é o menor
else:
menor = x
#inicia o loop
while x != 0:
x = float(input("Digite o próximo elemento da sequência: "))
if x != 0 and x < menor: menor = x
#saiu do loop
print("O maior elemento da sequência é:", menor)
main()
|
# Função simetrica(a, n) que verifica se a matriz a de n linhas e n colunas é uma matriz simétrica,
# isto é, se a[i][j] é igual a a[j][i], devolvendo True (sim) ou False (não). percorrendo apenas o triângulo inferior
a = [[2,4,4], [4,6,6], [4,6,9]]
def simetrica(a,n):
for i in range(n):
print("i = ", i)
for j in range(i):
print("i =", i,"j = ",j)
if a[i][j] != a[j][i]:
return False
return True
print(simetrica(a, 3))
for i in range(len(a)):
print()
for j in range(len(a)):
print("%8.2f"%a[i][j], end = "")
|
# Dados 2 números imprimi-los em ordem crescente.
# Considere ordem crescente quando o primeiro é menor ou igual ao segundo.
a = int(input("Digite o primeiro número: "))
b = int(input("Digite o segundo número: "))
if a>b: print(b,a)
elif b>a: print(a,b)
else: print("Os números são iguais")
|
#Função verifica_linhas(a, n) que verifica se a matriz a n x n, possui 2 linhas iguais, devolvendo True ou False.
a = [[1,1,0,1], [1,2,0,1],[3,3,0,0], [3,3,0,0]]
def verifica_linhas(a):
for j in range (len(a)):
if a[j] not in a[j+1:]:
linhas_iguais = False
else:
linhas_iguais = True
break
return linhas_iguais
print(verifica_linhas(a))
|
#Dado N > 0 e uma sequência de N números, determinar o menor elemento da sequência.
def main():
#ler o número de elementos da sequência
N = int(input("Digite a quantidade de números da sequência: "))
#consistência dos dados de entrada de N
if N == 0:
print ("O número de elementos da sequência é zero.")
else:
menor = float(input("Digite o primeiro valor da sequência: "))
#inicia o contador
contador = 1
#repete a operação
while N -1 >= contador:
x = float(input("Digite o próximo valor da sequência: "))
#compara os valores
if x < menor: menor = x
contador = contador + 1
#imprime o resultado
print ("O menor valor da sequência é", menor)
main ()
|
#dado n > 1, inteiro, verificar se n é primo
#não precisa testar para todos os possíveis divisores de 1 em 1. Basta testar para 2 e depois só os ímpares
def main ():
#leia n
n = int(input("Type a number you'd like to check if is prime or not: "))
div = 2
cont = 3
if n % 2 == 0:
print (n, "is not prime number.")
return
while cont <= n // 2:
if n % cont == 0:
print (n, "is not prime number.")
return
cont = cont + 2
print(n, "is a prime number.")
main ()
|
# Dado um valor em reais V (com duas casas decimais, os centavos), determinar a quantidade máxima de
# notas de 100, 50, 20, 10, 5 2 e 1, moedas de 0,50, 0,25, 0,10, 0,05 e 0,01 necessárias para compor V.
def main ():
V = float(input("Digite o total em R$ com até duas casas decimais: "))
x = int(V * 100)
n_100 = x // 10000
n_50 = x % 10000 // 5000
n_20 = x % 10000 % 5000 // 2000
n_10 = x % 10000 % 5000 % 2000 // 1000
n_5 = x % 10000 % 5000 % 2000 % 1000 // 500
n_2 = x % 10000 % 5000 % 2000 % 1000 % 500 // 200
n_1 = x % 10000 % 5000 % 2000 % 1000 % 500 % 200 // 100
m_05 = x % 10000 % 5000 % 2000 % 1000 % 500 % 200 % 100 // 50
m_025 = x % 10000 % 5000 % 2000 % 1000 % 500 % 200 % 100 % 50 // 25
m_010 = x % 10000 % 5000 % 2000 % 1000 % 500 % 200 % 100 % 50 % 25 // 10
m_005 = x % 10000 % 5000 % 2000 % 1000 % 500 % 200 % 100 % 50 % 25 % 10 // 5
m_001 = x % 10000 % 5000 % 2000 % 1000 % 500 % 200 % 100 % 50 % 25 % 10 % 5 // 1
print("O valor inserido pode ser composto por", n_100, "nota(s) de R$100,", n_50, "nota(s) de R$50,", n_20, "nota(s) de R$20,", n_10, "nota(s) de R$10,", n_5, "nota(s) de R$5,", n_2, "nota(s) de R$2,", n_1, "nota(s) de R$1 e", m_05, "moeda(s) de R$0,50,", m_025, "moeda(s) de R$0,25,", m_010, "moeda(s) de R$0,10,", m_005, "moeda(s) de R$0,05 e", m_001, "moeda(s) de R$0,01.")
main ()
|
#Escreva a função void LCZero(mat) que devolve uma dupla de listas.
# A primeira com todas as linhas zeradas e a segunda com todas as colunas zeradas da matriz mat.
# Exemplo – se mat for a matriz abaixo, devolve: ([2, 3, 5], [0, 4])
mat =[[0,2,0,6], [0,3,5,0], [0,0,0,0], [0,0,0,0], [0,1,2,0], [0,0,0,0]]
def LCZero(mat):
a,b = [],[] #cria duas listas vazias
tupla = (a,b) #cria a tupla com as listas vazias
for i in range(len(mat)): #varre as linhas
if LinhaZero(mat,i): #verifica se as linhas estão zeradas
a.append(i) #se sim, adiciona na lista das linhas
for k in range(len(mat[0])): #varre as colunas
if ColunaZero(mat,k): #verifica se as colunas estão zeradas
b.append(k) #se sim, adiciona na lista das colunas
return tupla
def ColunaZero(mat,col):
for i in range (len(mat)): #varre as colunas
if mat[i][col] != 0: #compara os elementos da coluna com o zero
return False
return True
def LinhaZero(mat, lin):
linha_aux = len(mat[lin]) * [0] # cria uma lista com zeros do tamanho da linha
if mat[lin] == linha_aux: # compara a linha com a lista com zeros
return True
return False
print (LCZero(mat))
|
'''
Dados a e b float (a < b), n e k inteiros e maiores que 0, uma sequência de n valores float no intervalor [a, b),
ou seja maiores ou iguais a a e menores que b. Dividir o intervalo [a, b) em k subintervalos iguais e determinar quantos
estão em cada intervalo. Note que serão k contadores e o tamanho do intervalor é t = (b – a) / k:
f[0] = elementos ≥ a e < a + t * 1
f[1] = elementos ≥ a + t * 1 e < a + t * 2
...
f[k-1] = elementos ≥ a + t * (k-1) e < a + t * k = b
'''
import math
def main ():
a = float(input("digite o valor de a: "))
b = float(input("digite o valor de b: "))
n = int(input("digite o valor de n: "))
k = int(input("digite o valor de subintervalos: "))
f = k * [0]
t = (b - a) / k
for i in range (n):
x = float(input("digite o valor da sequência: "))
ind = math.trunc((x-a)//t)
f[ind] = f[ind] + 1
for i in range (k):
print("Há ", f[i], "elementos >=", a+(t*i), "e <", a+(t*(i+1)))
main()
|
# Dado N, simule a jogada de um dado (faces 1 a 6) N vezes e calcule quantas vezes cada face ocorreu
import random
def main ():
n = int(input("Digite o valor de n: "))
a = 1
soma_1 = 0
soma_2 = 0
soma_3 = 0
soma_4 = 0
soma_5 = 0
soma_6 = 0
while a <= n:
k = random.randrange(1,7)
if k == 1: soma_1 += 1
elif k == 2: soma_2 += 1
elif k == 3: soma_3 += 1
elif k == 4: soma_4 += 1
elif k == 5: soma_5 += 1
elif k == 6: soma_6 += 1
a += 1
print("Face Nº de vezes")
print("%3d%12d\n%3d%12d\n%3d%12d\n%3d%12d\n%3d%12d\n%3d%12d" % (1,soma_1, 2, soma_2, 3, soma_3, 4, soma_4, 5, soma_5, 6, soma_6))
main ()
|
'''Dado um valor inteiro em reais (R$), determinar quantas notas de R$100, R$50, R$20, R$10, R$5, R$2 e R$1
são necessárias para compor esse valor. A solução procurada é aquela com o máximo de notas de cada tipo.'''
N = int(input("Digite o valor total em R$: "))
total_100 = N // 100
total_50 = N % 100 // 50
total_20 = N % 100 % 50 // 20
total_10 = N % 100 % 50 % 20 // 10
total_5 = N % 100 % 50 % 20 % 10 // 5
total_2 = 100 % 50 % 20 % 10 % 5 // 2
total_1 = 100 % 50 % 20 % 10 % 5 % 2 // 1
print ("Serão necessárias", total_100, "nota(s) de R$100", total_50, "nota(s) de R$50", total_20, "nota(s) de R$20", total_10, "nota(s) de R$10", total_5, "nota(s) de R$5", total_2, "nota(s) de R$2 e", total_1, "nota(s) de R$1")
|
#Função procura_elemento(a, x), que procura elemento igual a x na lista a,
# devolvendo como o índice do primeiro elemento que é igual a x ou -1 caso não encontre.
# É quase a mesma coisa que a função index(x) já usada anteriormente. Assim, suponha que não exista a index(x)
a = [0,0,0,0,1,1,1,1,2,2,2]
def procura_elemento(a,x):
for k in range (len(a)):
if a[k] == x:
return k
else: return -1
print (procura_elemento(a,3))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.