text stringlengths 37 1.41M |
|---|
"""
给定一个字符串 s 和一个整数 k,你需要对从字符串开头算起的每隔 2k 个字符的前 k 个字符进行反转。
如果剩余字符少于 k 个,则将剩余字符全部反转。
如果剩余字符小于 2k 但大于或等于 k 个,则反转前 k 个字符,其余字符保持原样。
示例:
输入: s = "abcdefg", k = 2
输出: "bacdfeg"
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-string-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
class Solution:
def reverseStr(self, s: str, k: int) -> str:
# sliding window with 2k
if not s: return s
i = 0
res = ""
while i < len(s):
if len(s) - i < k:
res += s[i::][::-1]
break
elif k <= len(s) - i < 2*k:
res += s[i:i+k][::-1] + s[i+k:]
break
else:
res += s[i:i+k][::-1] + s[i+k:i+2*k]
i += 2*k
return res |
from random import uniform, gauss, choice, randint
from math import pow, sin
import numpy as np
class DataGenerator():
func = ("uniform", "linear", "power", "sin")
def __init__(self, len, count):
self.len = len
self.count = count
def noise(self):
noise_avg = 0
noise_std = 1
return gauss(noise_avg, noise_std)
def uniform_function(self, x, noise_factor, K):
y = K * (1 + self.noise() * noise_factor)
if y < 0:
y = 0
return y
def linear_function(self, x, noise_factor, K, bias, phase):
y = K * (1 + self.noise() * noise_factor) * (x - phase) + bias
if y < 0:
y = 0
return y
def power_function(self, x, noise_factor, K, bias, phase, exp):
y = K * (1 + self.noise() * noise_factor) * pow(x - phase, exp) + bias
if y < 0:
y = 0
return y
def sin_function(self, x, noise_factor, K, bias, phase):
y = K * (sin(x - phase) + self.noise() * noise_factor) + bias
if y < 0:
y = 0
return y
def signal_iterator(self, func_id):
signal = []
# The proportion of noise could not over 30% of signal.
noise_factor = uniform(0, 0.3)
# Factor of any kind of function, used to amplify or minify the signal.
K = uniform(-2, 2)
# Bias of any kind of function, used to shift the signal to up(increase) or down(decrease).
# The proportion of absolute value of bias could not over 100% of signal.
bias = randint(0, 10)
# Phase of any kind of function(Except uniform function), used to shift the signal to left(backward) or right(forward).
phase = uniform(-10, 10)
# Exponent of power funtion
exp = randint(-2, 2)
for x in range(0, self.len):
if func_id == 0:
y = self.uniform_function(x, noise_factor, abs(K))
elif func_id == 1:
y = self.linear_function(x, noise_factor, K, bias, phase)
elif func_id == 2:
y = self.power_function(x, noise_factor, K, bias, phase, exp)
elif func_id == 3:
y = self.sin_function(x, noise_factor, K, bias, phase)
else:
y = -1
signal.append(int(y))
return signal
def generate(self):
dataset = []
func_info = []
for i in range(0, self.count):
func_id = choice(range(0, 4))
func_info.append(self.func[func_id])
dataset.append(self.signal_iterator(func_id))
return dataset, func_info
def generate_one_node_dataset(T, c_num):
dg = DataGenerator(T, c_num)
dataset, func = dg.generate()
return np.array(dataset).T
def generate_multi_nodes_dataset(n_num, T, c_num):
dataset = []
for i in range(n_num):
dataset.append(generate_one_node_dataset(T, c_num))
return np.array(dataset)
def binomial_function(mean):
return float(np.random.binomial(1, mean))
def generate_multi_nodes_binomial(n_num, T, c_num, mean):
dataset = []
for i in range(n_num):
t_seq = []
for j in range(T):
c_set = []
for k in range(c_num):
c_set.append(binomial_function(mean))
t_seq.append(c_set)
dataset.append(t_seq)
return np.array(dataset)
if __name__ == "__main__":
# dg = DataGenerator(10, 10)
# ds1, funcs1 = dg.generate()
# print funcs1
# for d in ds1:
# print d
print generate_multi_nodes_binomial(2, 4, 88, 0.5)
|
N, H, x = list(map(int, input().split()))
T = list(map(int, input().split()))
time_zone = max(T)
if (time_zone + x) >= H:
print("YES")
else:
print("NO")
|
# Assignment Operators
# 1. = -> It will assign the value to the rhs to the variable on left
a = 10
b = 30
c = b
print(a, b, c)
# 2. += -> It will act same as a = a + 1
a += 1 # Instead of writing a = a + 1, we write this
b += a # Instead of writing a = a + b, we write this
print(a, b)
# 3. -= -> It will act same as a = a - 1
a -= 1 # Instead of writing a = a - 1, we write this
b -= a # Instead of writing a = a - b, we write this
print(a, b)
# 4. *= -> It will act same as a = a * 2
a *= 2
# 5. %= -> It will act same as a = a % 7
a %= 7
# 6. /= -> It will act same as a = a / 2
a /= 2
# 7. //= -> It will act same as a = a // 2
a //= 2
# 8. **= -> It will act same as a = a ** 2
a **= 2
# a++ or ++a for a = a + 1 does not exist in python
# ---------------------------------------------------------
# Bitwise operator -> these will work on bit by bit level
# 1. & -> a&b -> It will do bitwise and on binary of a, b
z = 5 & 4 # 5 -> 101 , 4 -> 100, 101&100 -> 100(4)
print(z)
# 2. | -> a|b -> It will do bitwise or on binary of a, b
z = 5 | 4 # 5 -> 101 , 4 -> 100, 101|100 -> 101(5)
print(z)
# 3. ^ -> a^b -> It will do bitwise xor on binary of a, b
z = 5 ^ 4 # 5 -> 101 , 4 -> 100, 101^100 -> 001(1)
print(z)
# 4. ~ -> ~a -> It will do bitwise not on binary of a
z = ~5 # 5 -> 101 , ~101 -> -6 (in complement of 2)
print(z)
# 5. << -> Left shift operator
z = 1 << 3 # it will append 3 zeroes to the right of 1 -> 1 -> 1000 , 6 << 2 -> 110 -> 11000
print(z)
# 6. >> -> Right shift operator
z = 5 >> 2 # It will prepend 2 zeroes to the left of 5 and remove last 2 bits
print(z)
# (101) >> 2
# 101 -> 010 -> 001
# 5 >> 3 -> (101) -> 010 -> 001 -> 000
# ------------------------------------------------------
# Membership operator
# 1. in operator
arr = [1,2,3,'shiraz']
print(3 in arr) # is there value of 3 in arr? True
print('shirazmangat' in arr) # is shirazmangat in arr? -> False
# 2. not in operator
print( 3 not in arr) # is 3 not in arr? False
print("for string", 'a' in 'astrology' )
# 3. Identity operator
# It will check if the two values are of same type and having same value
print( 3 is 4) # -> False
print(2 == 2 is True) # -> False
print(4 is True) # -> False
print(6 is 6) # -> True
print(7 is not 7) # -> False
# 2**3**2 will be read from right side onwards
# ([1,2] == [1,2]) -> True
print(2**3**2) # -> 2**(9) -> 512
print([1,2] == [1,2])
|
n = int(input())
sum = 1
for i in range(2, int(n**0.5) + 1):
if (n % i == 0):
sum += i
sum += n//i
if n**0.5 is int:
sum -= n**0.5
if sum == n:
print("YES")
else:
print("NO")
|
"""
Example =>
n = 36
factors:-
1,36
2,18
3,12
4,9
6,6
9,4
12,3
18,2
36,1
"""
from math import floor
def check_prime(n):
if n == 2:
return True
for i in range(2, floor(n**0.5) + 1):
if (n % i) == 0:
return False
return True
n = int(input())
result = check_prime(n)
if (result == True):
print("Yes it is a prime")
else:
print("No it is not a prime")
# Time Complexity => O(n)
|
def prime_factorization(n):
i = 2
factors = {}
while i * i <= n:
if n % i != 0:
i += 1
else:
n //= i
if i not in factors.keys():
factors[i] = 1
else:
factors[i] += 1
if n > 1:
if n not in factors.keys():
factors[n] = 1
else:
factors[n] += 1
return sorted(zip(factors.keys(), factors.values()), key=lambda x: x[0])
if __name__ == '__main__':
print(prime_factorization(356))
|
def count_consonants(str):
consonants = "bcdfghjklmnpqrstvwxz"
consonants_count = 0
for ch in str.lower():
if ch in consonants:
consonants_count += 1
return consonants_count
if __name__ == '__main__':
print(count_consonants("Github is the second best thing that happend to programmers, after the keyboard!"))
|
import sqlite3
from client import Client
class Database:
def __init__(self):
self._conn = sqlite3.connect("bank.db")
self._cursor = self._conn.cursor()
@property
def conn(self):
return self._conn
@property
def cursor(self):
return self._cursor
def create_clients_table(self):
create_query = '''CREATE TABLE IF NOT EXISTS
clients(id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT,
email TEXT,
password TEXT,
balance REAL DEFAULT 0,
message TEXT,
reset_password_hash TEXT)'''
self._cursor.execute(create_query)
def change_message(self, new_message, logged_user):
update_sql = "UPDATE clients SET message = ? WHERE id = ?"
self._cursor.execute(update_sql, (new_message, logged_user.get_id()))
self._conn.commit()
logged_user.set_message(new_message)
def change_pass(self, new_pass, logged_user):
update_sql = "UPDATE clients SET password = ? WHERE id = ?"
self._cursor.execute(update_sql, (new_pass, logged_user.get_id()))
self._conn.commit()
def register(self, username, email, password):
insert_sql = "INSERT INTO clients (username, email, password) VALUES (?, ?, ?)"
self._cursor.execute(insert_sql, (username, email, password))
self._conn.commit()
def login(self, username, password):
select_query = "SELECT id, username, balance, message, email FROM clients WHERE username = ? AND password = ? LIMIT 1"
self._cursor.execute(select_query, (username, password))
user = self._cursor.fetchone()
if user:
return Client(user[0], user[1], user[2], user[3], user[4])
else:
return False
def get_user_email(self, username):
get_email = "SELECT email FROM clients WHERE username = ? LIMIT 1"
self._cursor.execute(get_email, (username, ))
user = self._cursor.fetchone()
if user:
return user[0]
return False
def update_reset_pass(self, reset_pass_hash, username):
update_reset_pass_hash = "UPDATE clients SET reset_password_hash = ? WHERE username = ?"
self._cursor.execute(update_reset_pass_hash, (reset_pass_hash, username))
self._conn.commit()
def get_reset_pass_hash(self, username):
get_reset_pass = "SELECT reset_password_hash FROM clients WHERE username = ? LIMIT 1"
self._cursor.execute(get_reset_pass, (username, ))
user = self._cursor.fetchone()
if user:
return user[0]
return False
def clear_reset_hash(self, username):
clear_reset_hash = "UPDATE clients SET reset_password_hash = ? WHERE username = ?"
self._cursor.execute(clear_reset_hash, (None, username))
self._conn.commit()
def close(self):
self._cursor.close()
self._conn.close()
|
def to_digits(n):
result = []
while n > 0:
result.append(n % 10)
n //= 10
return result[::-1]
if __name__ == '__main__':
print(to_digits(123))
print(to_digits(99999))
print(to_digits(123023))
|
def fibonacci(n):
result = []
fib1 = 1
fib2 = 1
fib = fib1 + fib2
if n == 1:
return [1]
elif n == 2:
return [1, 1]
else:
result.append(fib1)
result.append(fib2)
result.append(fib)
while n > 3:
fib1 = fib2
fib2 = fib
fib = fib1 + fib2
result.append(fib)
n -= 1
return result
if __name__ == '__main__':
print(fibonacci(10))
|
import unittest
from song import Song
class TestSong(unittest.TestCase):
def setUp(self):
self._song = Song(title="Odin", artist="Manowar",
album="The Sons of Odin", length="3:44")
def test_init(self):
self.assertTrue(isinstance(self._song, Song))
with self.assertRaises(ValueError):
Song(title="Odin", artist="Manowar",
album="The Sons of Odin", length=":44")
with self.assertRaises(TypeError):
Song(title=0, artist="Manowar",
album="The Sons of Odin", length="3:44")
with self.assertRaises(TypeError):
Song(title="Odin", artist=0,
album="The Sons of Odin", length="3:44")
with self.assertRaises(TypeError):
Song(title="Odin", artist="Manowar",
album=0, length="3:44")
with self.assertRaises(TypeError):
Song(title="Odin", artist="Manowar",
album="The Sons of Odin", length=0)
def test_str(self):
valid_str = "Manowar - Odin from The Sons of Odin - 3:44"
self.assertEqual(str(self._song), valid_str)
def test_eq(self):
same_song = Song(title="Odin", artist="Manowar",
album="The Sons of Odin", length="3:44")
self.assertEqual(self._song, same_song)
def test_hash(self):
self.assertEqual(hash(self._song), hash(str(self._song)))
def test_length(self):
self.assertEqual(self._song.length(), "3:44")
def test_length_seconds(self):
self.assertEqual(self._song.length(seconds=True), 224)
def test_length_minutes(self):
self.assertEqual(self._song.length(minutes=True), 3)
def test_length_hours(self):
self.assertEqual(self._song.length(hours=True), 0)
if __name__ == '__main__':
unittest.main()
|
hrs = input("""Enter number of working hours""")
rate = input("Enter rate per hour")
wages = float(hrs*rate*52)
print("Your gross pay is ", wages) |
# https://leetcode.com/problems/remove-duplicates-from-sorted-array/
# It's mention - we don't need to use the Extra memory
# Also, we need to remove / replace the elements IN_PPLACE.
# Approach:
# take a Two pointers i & j (i at 0 and j at 1)
# one is slow pointer and other is fast pointer (we can say)
# So we will compare nums[i] with nums[j]
# if it's equal - menas duplicate, we increment J pointer (keeping I at same position)
# and also decrease count value (because we need to return number of non-duplicates or unique elements)
# if nums[i] == nums[j] - means no more duplicates,
# So we will shift nums[j] at next position of nums[i] i.e. at nums[i+1] (in this way, we are bringing all unique elements together)
# and then increment i and j both
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
i = 0
j = 1
count = len(nums)
while j < len(nums):
if nums[i] == nums[j]:
j = j + 1
count = count - 1
elif nums[i] != nums[j]:
nums[i+1] = nums[j]
i = i + 1
j = j + 1
return count |
# https://leetcode.com/problems/longest-common-prefix/
# Method-1
# Find Longest common prefix of first 2 string
# Then find longest common prefix between output of 1st and 3rd string
# Then find longest common prefix between output of 2nd and 4th string and so on...
# in this way - at the end - we have Longest common prefix.
# Example ["leets", "leetcode", "leet", "leeds"]
# compare "leets" & leetcode ==> leet
# Now compare leet and leet ==> leet
# now compare leet and leeds ==> lee
class Solution:
def longest(self, string1: str, string2: str) -> str:
largest_string_prefix = ""
length = min(len(string1), len(string2))
for i in range(length):
if string1[i] == string2[i]:
largest_string_prefix = largest_string_prefix + string1[i]
else:
break
return largest_string_prefix
def longestCommonPrefix(self, strs: List[str]) -> str:
t = strs[0]
for s in range(len(strs)):
t = self.longest(t, strs[s])
return t
# Method-2
# Let's sort the string array(list)
# So it will get sorted on basis of prefix
# So, now we can only compare 1st and last string
# Because all string gets sorted, if first string starts with 'a' and last string starts with 'a'
# then definately all strings in middle starts with 'a'
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
strs.sort()
out = ""
for x, y in zip(strs[0], strs[-1]):
if x == y:
out = out + x
else:
break
return out |
import unittest
def divide(x, y):
if x and y:
return (x / y)
else:
return -1
class TestMath(unittest.TestCase):
def test_divide_returns_correct_result(self):
# Arranage - setup the environment
test_x = 20
test_y = 10
# Act
result = divide(test_x, test_y)
# Assert
self.assertEqual(result, 2, "Should be 2")
def test_divide_fails_when_dividing_by_zero(self):
# Arranage - setup the environment
test_x = 20
test_y = 0
# Act
result = divide(test_x, test_y)
# Assert
self.assertEqual(result, -1, "Should fail")
#self.assertRaises(ZeroDivisionError, divide, test_x, test_y)
if __name__ == "__main__":
unittest.main()
|
# First thing we'll do is import the requests library
import requests
# Define a variable with the URL of the API
api_url = "http://shibe.online/api/shibes?count=1"
# Call the root of the api with GET, store the answer in a response variable
# This call will return a list of URLs that represent dog pictures
response = requests.get(api_url)
# Get the status code for the response. Should be 200 OK
# Which means everything worked as expected
print(f"Response status code is: {response.status_code}")
# Get the result as JSON
response_json = response.json()
# Print it. We should see a list with one image URL.
print(response_json)
# Passing in a non-existant URL will result in a 404 (not found)
bad_response = requests.get("http://shibe.online/api/german-shepards")
print(f"Bad Response Status Code is: {bad_response.status_code}") # Status code is 404, meaning that resource doesn’t exist.
|
T = int(input())
data={}
for i in range(0,T):
string = str(input()).split(" ")
data[string[0]] = string[1]
for j in range(0,T):
name = str(input())
if name in data:
print(name + "=" + data[name])
else:
print("Not found") |
#--# Python Calculator ENGLISH: By TheRealCodeGamer #--#
import sys
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x / y
#opties
print("Choose an option:")
print("---------------")
print("1. +")
print("2. -")
print("3. x")
print("4. :")
print("5. Stop")
choice = input("Choice (1/2/3/4/5): ")
if choice == '1':
num1 = int(input("Number 1: "))
num2 = int(input("Number 2: "))
print(num1, " + ", num2, " = ", add(num1, num2))
print("-----------------------")
elif choice == '2':
num1 = int(input("Number 1: "))
num2 = int(input("Number 2: "))
print(num1, " - ", num2, " = ", subtract(num1, num2))
print("-----------------------")
elif choice == '3':
num1 = int(input("Number 1: "))
num2 = int(input("Number 2: "))
print(num1, " x ", num2, " = ", multiply(num1, num2))
print("-----------------------")
elif choice == '4':
num1 = int(input("Number 1: "))
num2 = int(input("Number 2: "))
print(num1, " : ", num2, " = ", divide(num1, num2))
print("-----------------------")
elif choice == '5':
sys.exit("Thank you for using the MathMax!")
else:
print("Invalid Option.")
print("-----------------------")
|
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
current = head
if(!current):
return current
while current.next:
if current.next.val == current.val:
current.next = current.next.next
else:
current = current.next
return head
head = ListNode()
s = Solution()
s.deleteDuplicates(head)
|
import fisika
def main():
#membuat judul program
print("program mencari BERAT BENDA")
#memninta user memasukkan bilangan
w=float(input("Masukkan w: "))
g=float(input("Masukkan g: "))
massa = fisika.massaBenda(w, g)
#menampilkan hasil
print("MASSA BENDA")
print("berat benda\t:", w)
print("percepatan gravitasi\t:", g)
print("hasil massa\t=", massa)
if __name__=="__main__":
main()
|
def rotated_array_search(input_list, number):
"""
Find the index by searching in a rotated sorted array
Args:
input_list(array), number(int): Input array to search and the target
Returns:
int: Index or -1
"""
start_idx = 0
end_idx = len(input_list) - 1
while start_idx <= end_idx:
mid_idx = (end_idx - start_idx) // 2 + start_idx
if number == input_list[mid_idx]:
return mid_idx
if input_list[start_idx] <= input_list[mid_idx]: # pivot point on the right side
if input_list[start_idx] <= number < input_list[mid_idx]:
end_idx = mid_idx - 1 # left side
else:
start_idx = mid_idx + 1 # right side
else: # pivot point left
if input_list[mid_idx] < number <= input_list[end_idx]:
start_idx = mid_idx + 1 # right side
else:
end_idx = mid_idx - 1 # left side
return -1
def linear_search(input_list, number):
for index, element in enumerate(input_list):
if element == number:
return index
return -1
def test_function(test_case):
input_list = test_case[0]
number = test_case[1]
if linear_search(input_list, number) == rotated_array_search(input_list, number):
print("Pass")
else:
print("Fail")
arr = [3,4,6,15,625,13468,0,1,2]
arr1 = [13468,4,6,15,625,626,627,628,630]
arr2 = [4,6,15,625,626,627,628,1,2,3]
arr3 = [3,5,37,41,80,85, 91,1]
test_function([arr, 13468]) # pass
test_function([arr1, 13468]) # pass
test_function([arr, 6]) # pass
test_function([arr1, 6]) # pass
test_function([arr, 4]) # pass
test_function([arr1, 4]) # pass
test_function([arr, 10]) # pass
test_function([arr1, 10]) # pass
test_function([arr, 630]) # pass
test_function([arr1, 630]) # pass
test_function([arr, 0]) # pass
test_function([arr1, 0]) # pass
for i in range(100):
result = rotated_array_search(arr3, i)
if result != -1:
print(f"Wert {i} in Array an Index :{result}")
|
import matplotlib.pyplot as plt
plt.plot([1,2,3],[5,7,4])
plt.show()
import matplotlib.pyplot as plt
plt.bar([1,3,5,7,9],[5,2,7,8,2], label="Example one")
plt.bar([2,4,6,8,10],[8,6,2,5,6], label="Example two", color='g')
plt.legend()
plt.xlabel('bar number')
plt.ylabel('bar height')
plt.title('Epic Graph\nAnother Line! Whoa')
plt.show
import matplotlib.pyplot as plt
population_ages = [22,55,62,45,21,22,34,42,42,4,99,102,110,120,121,122,130,111,115,112,80,75,65,54,44,43,42,48]
bins = [0,10,20,30,40,50,60,70,80,90,100,110,120,130]
plt.hist(population_ages, bins, histtype='bar', rwidth=0.8)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Interesting Graph\nCheck it out')
plt.legend()
plt.show()
import matplotlib.pyplot as plt
import numpy as np
import urllib
import matplotlib.dates as mdates
def graph_data(stock):
stock_price_url = 'http://chartapi.finance.yahoo.com/instrument/1.0/GOOG/chartdata;type=quote;range=10y/csv'
source_code = urllib.request.urlopen(stock_price_url).read().decode()
stock_data = []
split_source = source_code.split('\n')
for line in split_source:
split_line = line.split(',')
if len(split_line) == 6:
if 'values' not in line:
stock_data.append(line)
date, closep, highp, lowp, openp, volume = np.loadtxt(stock_data,
delimiter=',',
unpack=True,
# %Y = full year. 2015
# %y = partial year 15
# %m = number month
# %d = number day
# %H = hours
# %M = minutes
# %S = seconds
# 12-06-2014
# %m-%d-%Y
converters={0: bytespdate2num('%Y%m%d')})
plt.xlabel('x')
plt.ylabel('y')
plt.title('Interesting Graph\nCheck it out')
plt.legend()
plt.show()
graph_data('GOOG')
|
# Project Euler
# Problem 12
# Solution by Ewen Bramble
# How many distinct terms are in the sequence generated by a**b for 2 ≤ a ≤ 100 and 2 ≤ b ≤ 100?
terms = set()
for a in range(2,101):
for b in range(2,101):
terms.add(a**b)
print("Number of distinct terms: {}".format(len(terms))) |
# Project Euler
# Problem 28
# Solution by Ewen Bramble
# What is the sum of the numbers on the diagonals in a 1001 by 1001 spiral?
# Idea: write function to populate grid from middle outward. Function takes dimension(s)
# Grid full of zeros initially
# Turn right if zero in grid, else go straight
# While loop with total number of 'moves' being num squares in grid
# Keep track of index at end of each iteration, direction also
def make_zero_grid(size):
'''Returns a square grid, size x size populated with zeros as a list of lists'''
out_list = []
for x in range(size):
out_list.append([0 for x in range(size)])
return out_list
grid_size = 1001
num_squares = (grid_size*grid_size) # size of grid
starting_square_index = int((grid_size-1)/2) # index of starting square, both outer/inner lists
index_row = starting_square_index # initialise row index
index_col = starting_square_index # initialise column index
grid = make_zero_grid(grid_size) # make grid of zeros
grid[starting_square_index][starting_square_index] = 1 # start with 1 in centre of grid
grid[starting_square_index][starting_square_index+1] = 2
index_col += 1 # first move to the right
n = 3 # keep track of moves
direction = 1 # keep track of direction, initially 'heading right'. 1 = R, 2 = Down, 3 = L, 4 = Up
while n <= num_squares:
while direction == 1: # right
if grid[index_row + 1][index_col] == 0: # checking if below square is 0 (can turn right)
grid[index_row + 1][index_col] = n # write next number to square
n += 1
index_row += 1 # we are now one row lower
direction = 2 # now heading down
else: # can't turn right, so move straight and write to square
try:
grid[index_row][index_col + 1] = n
except: # if out of range error
break
else:
n += 1
index_col += 1
while direction == 2: # down
if grid[index_row][index_col-1] == 0: # checking if left square is 0 (can turn right)
grid[index_row][index_col-1] = n # write next number to square
n += 1
index_col -= 1 # we are now one column left
direction = 3 # now heading left
else: # can't turn right, so move straight and write to square
try:
grid[index_row+1][index_col] = n
except:
break
else:
n += 1
index_row += 1
while direction == 3: # left
if grid[index_row-1][index_col] == 0: # checking if above square is 0 (can turn right)
grid[index_row-1][index_col] = n # write next number to square
n += 1
index_row -= 1 # we are now one row higher
direction = 4 # now heading up
else: # can't turn right, so move straight and write to square
try:
grid[index_row][index_col-1] = n
except:
break
else:
n += 1
index_col -= 1
while direction == 4: # up
if grid[index_row][index_col+1] == 0: # checking if right square is 0 (can turn right)
grid[index_row][index_col+1] = n # write next number to square
n += 1
index_col += 1 # we are now one column right
direction = 1 # now heading right
else: # can't turn right, so move straight and write to square
try:
grid[index_row-1][index_col] = n
except:
break
else:
n += 1
index_row -= 1
# SUM DIAGONALS
# Plan: work inward from top to row above middle row, then work bottom up similarly. Add these to 1 (middle num)
def sum_diagonals(grid):
'''Function returns sum of diagonal numbers in grid (list of lists)
excluding centre square (1 in spiral grid)'''
half_list_size = int((len(grid)-1)/2) # Need the number of rows in half the grid minus the middle row
total = 0
# Top half of grid
# Indexes for each row to work inward from each side
left_index = 0
right_index = -1
for i in range(half_list_size): # iterate row by row downward
total += grid[i][left_index]
total += grid[i][right_index]
left_index += 1 # move inward for following row
right_index -= 1
# Bottom half of grid
left_index = 0 # Reset indexes
right_index = -1
for i in range((len(grid)-1),(len(grid)-1)-half_list_size,-1): # iterate backward from bottom
total += grid[i][left_index]
total += grid[i][right_index]
left_index += 1 # move inward for following row
right_index -= 1
total += 1 # add 1 for centre square
return total
print("The sum of diagonals in 1001x1001 spiral grid is: {}".format(sum_diagonals(grid))) |
from sys import argv
script, user_name = argv
prompt = ">"
print "Hi %s, I am the %s script. Excuse the silliness of this set-up" % (
user_name, script
)
print "I need to ask you a few questions."
print "Are you comfortable with me, %s?" % user_name
likes = raw_input(prompt)
print "Please tell me where you live, %s" % user_name
lives = raw_input(prompt)
print "Do you use a Windows PC or a Mac, %s" % user_name
pc = raw_input(prompt)
print '''
So you want us to believe that
someone who lives in %r and
says '%r' to a dumb terminal
owns a %r? Are you nuts?
''' % (lives, likes, pc)
|
import numpy as np
import sys
from gym.envs.toy_text import discrete
from lib.utils import *
actions = ['NW','N','NE','W','X','E','SW','S','SE']
def categorical_sample(prob_n, np_random = None):
"""
Sample from categorical distribution
Each row specifies class probabilities
"""
prob_n = np.asarray(prob_n)
csprob_n = np.cumsum(prob_n)
return (csprob_n > np.random.rand()).argmax()
class CatMouseEnv_binary_reward(discrete.DiscreteEnv):
"""
An implementation of the pursuer-evader (cat-and-mouse) reinforcement
learning task.
Adapted from code provided on applenob's Github https://github.com/applenob
and Javen Chen's blog https://applenob.github.io/cliff_walking.html
(In turn this was adapted from Example 6.6 (page 106) from
Reinforcement Learning: An Introduction by Sutton and Barto:
http://incompleteideas.net/book/bookdraft2018jan1.pdf
With inspiration from:
https://github.com/dennybritz/reinforcement-learning/blob/master/lib/envs/cliff_walking.py)
The board is a matrix with dimensions specified when the environment is initialised.
In the binary_reward environment, a reward of 1 is received when the cat catches
the mouse (and this terminates the episode). All other moves incur 0 reward.
"""
metadata = {'render.modes': ['human', 'ansi']}
def __init__(self, board_height, board_width, walls = None):
self.board_height = board_height
self.board_width = board_width
self.walls = walls
self.reward_type = 'bin'
nS = self.board_height * self.board_width * self.board_height * self.board_width
nA = len(actions)
P = {}
for state_index in range(nS):
(cat_vert_pos, cat_horz_pos), (mouse_vert_pos, mouse_horz_pos) = state_index_to_positions(state_index, self.board_height, self.board_width)
# state_index = self._positions_to_state_index((cat_vert_pos, cat_horz_pos), (mouse_vert_pos, mouse_horz_pos))
P[state_index] = {}
for action in actions:
cat_vert_move, cat_horz_move = action_to_moves(action)
cat_move_stays_on_board = move_is_legal((cat_vert_pos, cat_horz_pos), cat_vert_move, cat_horz_move, self.board_height, self.board_width, walls = walls)
# cat_move_stays_on_board = ((cat_vert_pos + cat_vert_move) in range(self.board_height)) and ((cat_horz_pos + cat_horz_move) in range(self.board_width))
new_cat_vert_pos = cat_vert_pos + cat_vert_move * cat_move_stays_on_board
new_cat_horz_pos = cat_horz_pos + cat_horz_move * cat_move_stays_on_board
new_state_instances = {}
mouse_vert_moves, mouse_horz_moves = [-1,0,1], [-1,0,1]
for mouse_vert_move in mouse_vert_moves:
for mouse_horz_move in mouse_horz_moves:
# mouse_action = self._moves_to_action(mouse_vert_move, mouse_horz_move)
mouse_move_stays_on_board = move_is_legal((mouse_vert_pos, mouse_horz_pos), mouse_vert_move, mouse_horz_move, self.board_height, self.board_width, walls = walls)
new_mouse_vert_pos = mouse_vert_pos + mouse_vert_move * mouse_move_stays_on_board
new_mouse_horz_pos = mouse_horz_pos + mouse_horz_move * mouse_move_stays_on_board
new_state = positions_to_state_index((new_cat_vert_pos, new_cat_horz_pos), (new_mouse_vert_pos, new_mouse_horz_pos), self.board_height, self.board_width)
if not new_state in new_state_instances.keys():
game_over = ((new_cat_vert_pos == new_mouse_vert_pos) and (new_cat_horz_pos == new_mouse_horz_pos))
new_state_instances[new_state] = [1, game_over]
else:
new_state_instances[new_state][0] += 1
possible_next_states_list = []
for new_state, (no_instances, game_over) in new_state_instances.items():
reward = 1 * game_over
possible_next_state_tuple = (no_instances/(len(mouse_vert_moves) * len(mouse_horz_moves)), new_state, reward, game_over)
possible_next_states_list.append(possible_next_state_tuple)
P[state_index][action_to_action_index(action)] = possible_next_states_list
# Calculate initial state distribution
isd = np.ones(nS)
for state_index in range(nS):
(cat_vert_pos, cat_horz_pos), (mouse_vert_pos, mouse_horz_pos) = state_index_to_positions(state_index, self.board_height, self.board_width)
if ((cat_vert_pos == mouse_vert_pos) and (cat_horz_pos == mouse_horz_pos)):
isd[state_index] = 0
isd = isd/sum(isd)
super(CatMouseEnv_binary_reward, self).__init__(nS, nA, P, isd)
def render(self, mode='human'):
outfile = sys.stdout
for row in range(self.board_height):
for col in range(self.board_width):
(cat_vert_pos, cat_horz_pos), (mouse_vert_pos, mouse_horz_pos) = state_index_to_positions(self.s, self.board_height, self.board_width)
if (cat_vert_pos == row and cat_horz_pos == col and mouse_vert_pos == row and mouse_horz_pos == col):
output = " @ "
elif (cat_vert_pos == row and cat_horz_pos == col):
output = " C "
elif (mouse_vert_pos == row and mouse_horz_pos == col):
output = " M "
else:
output = " o "
if col == 0:
output = output.lstrip()
if col == (self.board_width - 1):
output = output.rstrip()
output += '\n'
outfile.write(output)
outfile.write('\n')
# def _state_index_to_positions(self, state_index):
# if not state_index in range(self.board_height**2 * self.board_width**2):
# raise ValueError('state_index must be between 0 and %d' % (self.board_height**2 * self.board_width**2 - 1))
#
# cat_vert_pos = float(np.mod(state_index,self.board_height))
# cat_horz_pos = np.mod(state_index - cat_vert_pos, self.board_height * self.board_width) / self.board_height
# mouse_vert_pos = np.mod(state_index - cat_horz_pos * self.board_height - cat_vert_pos, self.board_height * self.board_width * self.board_height) / (self.board_height * self.board_width)
# mouse_horz_pos = (state_index - mouse_vert_pos * self.board_height * self.board_width - cat_horz_pos * self.board_height - cat_vert_pos) / (self.board_height * self.board_width * self.board_height)
# return (int(cat_vert_pos), int(cat_horz_pos)), (int(mouse_vert_pos), int(mouse_horz_pos))
#
#
# def _positions_to_state_index(self, cat_pos, mouse_pos):
# if not np.prod([ \
# cat_pos[0] in range(self.board_height), \
# cat_pos[1] in range(self.board_width), \
# ]):
# raise ValueError('Cat position (%d,%d) is outside the board' % (cat_pos[0], cat_pos[1]))
#
# if not np.prod([ \
# mouse_pos[0] in range(self.board_height), \
# mouse_pos[1] in range(self.board_width) \
# ]):
# raise ValueError('Mouse position (%d,%d) is outside the board' % (mouse_pos[0], mouse_pos[1]))
#
# return int( \
# cat_pos[0] + \
# cat_pos[1] * self.board_height + \
# mouse_pos[0] * self.board_height * self.board_width + \
# mouse_pos[1] * self.board_height * self.board_width * self.board_height \
# )
#
#
# def _action_to_action_index(self, action):
# # note that action X means the agent remains where it is
# valid_actions = ['NW','N','NE','W','X','E','SW','S','SE']
# if not action in valid_actions:
# raise Exception('Invalid action')
# return int(valid_actions.index(action))
#
#
# def _action_index_to_action(self, action_index):
# if not action_index in range(9):
# raise Exception('action_index must be between 0 and 9')
# valid_actions = ['NW','N','NE','W','X','E','SW','S','SE']
# return valid_actions[action_index]
#
#
# def _action_to_moves(self, action):
# # takes action from ['NW','N','NE','W','X','E','SW','S','SE'] as input
# # returns vert_move, horz_move
# valid_actions = ['NW','N','NE','W','X','E','SW','S','SE']
# if not action in valid_actions:
# raise Exception('Invalid action')
# action_index = valid_actions.index(action)
# horz_move = float(np.mod(action_index, 3) - 1)
# vert_move = np.mod((action_index - horz_move - 1)/3, 3) - 1
# return int(vert_move), int(horz_move)
#
#
# def _moves_to_action(self, vert_move, horz_move):
# # takes vert_move, horz_move
# # returns action from ['NW','N','NE','W','X','E','SW','S','SE'] as input
# if not (vert_move in [-1, 0, 1] and horz_move in [-1, 0, 1]):
# raise Exception('Invalid move. Vertical and horizontal components must be in [-1. 0. 1]')
# valid_actions = ['NW','N','NE','W','X','E','SW','S','SE']
# return valid_actions[(vert_move + 1 ) * 3 + (horz_move + 1)]
#
#
# def _action_index_to_moves(self, action_index):
# if not action_index in range(9):
# raise Exception('action_index must be between 0 and 9')
# horz_move = float(np.mod(action_index, 3) - 1)
# vert_move = np.mod((action_index - horz_move - 1)/3, 3) - 1
# return int(vert_move), int(horz_move)
#
#
# def _moves_to_action_index(vert_move, horz_move):
# if not (vert_move in [-1, 0, 1] and horz_move in [-1, 0, 1]):
# raise Exception('Invalid move. Vertical and horizontal components must be in [-1. 0. 1]')
# return int((vert_move + 1 ) * 3 + (horz_move + 1))
class CatMouseEnv_proximity_reward(discrete.DiscreteEnv):
"""
An implementation of the pursuer-evader (cat-and-mouse)
reinforcement learning task.
Adapted from code provided on applenob's Github https://github.com/applenob
and Javen Chen's blog https://applenob.github.io/cliff_walking.html
(In turn this was adapted from Example 6.6 (page 106) from
Reinforcement Learning: An Introduction by Sutton and Barto:
http://incompleteideas.net/book/bookdraft2018jan1.pdf
With inspiration from:
https://github.com/dennybritz/reinforcement-learning/blob/master/lib/envs/cliff_walking.py)
The board is a matrix with dimensions specified when the environment is initialised.
In the proximity_reward environment, a reward of board_height * board_width is received
when the cat catches the mouse (and this terminates the episode). All other moves incur
reward equal to the distance between the cat and the mouse (defined to be the min
number of moves it could take for the cat to catch the mouse if the mouse didn't move).
"""
metadata = {'render.modes': ['human', 'ansi']}
def __init__(self, board_height, board_width, walls = None):
self.board_height = board_height
self.board_width = board_width
self.walls = walls
self.reward_type = 'prox'
nS = self.board_height * self.board_width * self.board_height * self.board_width
nA = len(actions)
P = {}
for state_index in range(nS):
(cat_vert_pos, cat_horz_pos), (mouse_vert_pos, mouse_horz_pos) = state_index_to_positions(state_index, self.board_height, self.board_width)
# state_index = self._positions_to_state_index((cat_vert_pos, cat_horz_pos), (mouse_vert_pos, mouse_horz_pos))
P[state_index] = {}
for action in actions:
cat_vert_move, cat_horz_move = action_to_moves(action)
cat_move_stays_on_board = move_is_legal((cat_vert_pos, cat_horz_pos), cat_vert_move, cat_horz_move, self.board_height, self.board_width, walls = walls)
# ((cat_vert_pos + cat_vert_move) in range(self.board_height)) and ((cat_horz_pos + cat_horz_move) in range(self.board_width))
new_cat_vert_pos = cat_vert_pos + cat_vert_move * cat_move_stays_on_board
new_cat_horz_pos = cat_horz_pos + cat_horz_move * cat_move_stays_on_board
new_state_instances = {}
mouse_vert_moves, mouse_horz_moves = [-1,0,1], [-1,0,1]
for mouse_vert_move in mouse_vert_moves:
for mouse_horz_move in mouse_horz_moves:
# mouse_action = self._moves_to_action(mouse_vert_move, mouse_horz_move)
mouse_move_stays_on_board = move_is_legal((mouse_vert_pos, mouse_horz_pos), mouse_vert_move, mouse_horz_move, self.board_height, self.board_width, walls = walls)
new_mouse_vert_pos = mouse_vert_pos + mouse_vert_move * mouse_move_stays_on_board
new_mouse_horz_pos = mouse_horz_pos + mouse_horz_move * mouse_move_stays_on_board
new_state = positions_to_state_index((new_cat_vert_pos, new_cat_horz_pos), (new_mouse_vert_pos, new_mouse_horz_pos), self.board_height, self.board_width)
if not new_state in new_state_instances.keys():
game_over = ((new_cat_vert_pos == new_mouse_vert_pos) and (new_cat_horz_pos == new_mouse_horz_pos))
new_state_instances[new_state] = [1, game_over, new_cat_vert_pos, new_cat_horz_pos, new_mouse_vert_pos, new_mouse_horz_pos]
else:
new_state_instances[new_state][0] += 1
possible_next_states_list = []
for new_state, (no_instances, game_over, new_cat_vert_pos, new_cat_horz_pos, new_mouse_vert_pos, new_mouse_horz_pos) in new_state_instances.items():
if game_over:
reward = self.board_height * self.board_width
else:
cat_mouse_separation = max(abs(new_cat_vert_pos - new_mouse_vert_pos), abs(new_cat_horz_pos - new_mouse_horz_pos))
reward = 0 - cat_mouse_separation
possible_next_state_tuple = (no_instances/(len(mouse_vert_moves) * len(mouse_horz_moves)), new_state, int(reward), game_over)
possible_next_states_list.append(possible_next_state_tuple)
P[state_index][action_to_action_index(action)] = possible_next_states_list
isd = np.ones(nS)
for state_index in range(nS):
(cat_vert_pos, cat_horz_pos), (mouse_vert_pos, mouse_horz_pos) = state_index_to_positions(state_index, self.board_height, self.board_width)
if ((cat_vert_pos == mouse_vert_pos) and (cat_horz_pos == mouse_horz_pos)):
isd[state_index] = 0
isd = isd/sum(isd)
super(CatMouseEnv_proximity_reward, self).__init__(nS, nA, P, isd)
def render(self, mode='human'):
outfile = sys.stdout
for row in range(self.board_height):
for col in range(self.board_width):
(cat_vert_pos, cat_horz_pos), (mouse_vert_pos, mouse_horz_pos) = state_index_to_positions(self.s, self.board_height, self.board_width)
if (cat_vert_pos == row and cat_horz_pos == col and mouse_vert_pos == row and mouse_horz_pos == col):
output = " @ "
elif (cat_vert_pos == row and cat_horz_pos == col):
output = " C "
elif (mouse_vert_pos == row and mouse_horz_pos == col):
output = " M "
else:
output = " o "
if col == 0:
output = output.lstrip()
if col == (self.board_width - 1):
output = output.rstrip()
output += '\n'
outfile.write(output)
outfile.write('\n')
# def _state_index_to_positions(self, state_index):
# if not state_index in range(self.board_height**2 * self.board_width**2):
# raise ValueError('state_index must be between 0 and %d' % (self.board_height**2 * self.board_width**2 - 1))
#
# cat_vert_pos = float(np.mod(state_index,self.board_height))
# cat_horz_pos = np.mod(state_index - cat_vert_pos, self.board_height * self.board_width) / self.board_height
# mouse_vert_pos = np.mod(state_index - cat_horz_pos * self.board_height - cat_vert_pos, self.board_height * self.board_width * self.board_height) / (self.board_height * self.board_width)
# mouse_horz_pos = (state_index - mouse_vert_pos * self.board_height * self.board_width - cat_horz_pos * self.board_height - cat_vert_pos) / (self.board_height * self.board_width * self.board_height)
# return (int(cat_vert_pos), int(cat_horz_pos)), (int(mouse_vert_pos), int(mouse_horz_pos))
#
#
# def _positions_to_state_index(self, cat_pos, mouse_pos):
# if not np.prod([ \
# cat_pos[0] in range(self.board_height), \
# cat_pos[1] in range(self.board_width), \
# ]):
# raise ValueError('Cat position (%d,%d) is outside the board' % (cat_pos[0], cat_pos[1]))
#
# if not np.prod([ \
# mouse_pos[0] in range(self.board_height), \
# mouse_pos[1] in range(self.board_width) \
# ]):
# raise ValueError('Mouse position (%d,%d) is outside the board' % (mouse_pos[0], mouse_pos[1]))
#
# return int( \
# cat_pos[0] + \
# cat_pos[1] * self.board_height + \
# mouse_pos[0] * self.board_height * self.board_width + \
# mouse_pos[1] * self.board_height * self.board_width * self.board_height \
# )
#
#
# def _action_to_action_index(self, action):
# # note that action X means the agent remains where it is
# valid_actions = ['NW','N','NE','W','X','E','SW','S','SE']
# if not action in valid_actions:
# raise Exception('Invalid action')
# return int(valid_actions.index(action))
#
#
# def _action_index_to_action(self, action_index):
# if not action_index in range(9):
# raise Exception('action_index must be between 0 and 9')
# valid_actions = ['NW','N','NE','W','X','E','SW','S','SE']
# return valid_actions[action_index]
#
#
# def _action_to_moves(self, action):
# # takes action from ['NW','N','NE','W','X','E','SW','S','SE'] as input
# # returns vert_move, horz_move
# valid_actions = ['NW','N','NE','W','X','E','SW','S','SE']
# if not action in valid_actions:
# raise Exception('Invalid action')
# action_index = valid_actions.index(action)
# horz_move = float(np.mod(action_index, 3) - 1)
# vert_move = np.mod((action_index - horz_move - 1)/3, 3) - 1
# return int(vert_move), int(horz_move)
#
#
# def _moves_to_action(self, vert_move, horz_move):
# # takes vert_move, horz_move
# # returns action from ['NW','N','NE','W','X','E','SW','S','SE'] as input
# if not (vert_move in [-1, 0, 1] and horz_move in [-1, 0, 1]):
# raise Exception('Invalid move. Vertical and horizontal components must be in [-1. 0. 1]')
# valid_actions = ['NW','N','NE','W','X','E','SW','S','SE']
# return valid_actions[(vert_move + 1 ) * 3 + (horz_move + 1)]
#
#
# def _action_index_to_moves(self, action_index):
# if not action_index in range(9):
# raise Exception('action_index must be between 0 and 9')
# horz_move = float(np.mod(action_index, 3) - 1)
# vert_move = np.mod((action_index - horz_move - 1)/3, 3) - 1
# return int(vert_move), int(horz_move)
#
#
# def _moves_to_action_index(vert_move, horz_move):
# if not (vert_move in [-1, 0, 1] and horz_move in [-1, 0, 1]):
# raise Exception('Invalid move. Vertical and horizontal components must be in [-1. 0. 1]')
# return int((vert_move + 1 ) * 3 + (horz_move + 1))
# vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv new versions using different spaces vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
# from gym.envs.toy_text import discrete
#
# class CatMouseEnv_proximity_reward_box(discrete.DiscreteEnv):
# """
# An implementation of the pursuer-evader (cat-and-mouse)
# reinforcement learning task.
#
# Adapted from code provided on applenob's Github https://github.com/applenob
# and Javen Chen's blog https://applenob.github.io/cliff_walking.html
#
# (In turn this was adapted from Example 6.6 (page 106) from
# Reinforcement Learning: An Introduction by Sutton and Barto:
# http://incompleteideas.net/book/bookdraft2018jan1.pdf
#
# With inspiration from:
# https://github.com/dennybritz/reinforcement-learning/blob/master/lib/envs/cliff_walking.py)
#
# The board is a matrix with dimensions specified when the environment is initialised.
#
# In the proximity_reward environment, a reward of board_height * board_width is received
# when the cat catches the mouse (and this terminates the episode). All other moves incur
# reward equal to the distance between the cat and the mouse (defined to be the min
# number of moves it could take for the cat to catch the mouse if the mouse didn't move).
#
# Note that everything in this class descibes exactly the environment. If the agent does
# not have perfect information (i.e. there is partial obervability), it may only 'know'
# a subset of the current state.
# """
# metadata = {'render.modes': ['human', 'ansi']}
#
#
# def __init__(self, board_height, board_width):
# self.board_height = board_height
# self.board_width = board_width
# self.reward_type = 'prox'
#
# nS = self.board_height * self.board_width * self.board_height * self.board_width
# nA = len(actions)
#
# P = {}
# for state_index in range(nS):
# (cat_vert_pos, cat_horz_pos), (mouse_vert_pos, mouse_horz_pos) = self._state_index_to_positions(s)
# # state_index = self._positions_to_state_index((cat_vert_pos, cat_horz_pos), (mouse_vert_pos, mouse_horz_pos))
# P[state_index] = {}
# for action in actions:
# cat_vert_move, cat_horz_move = self._action_to_moves(action)
# cat_move_stays_on_board = ((cat_vert_pos + cat_vert_move) in range(self.board_height)) and ((cat_horz_pos + cat_horz_move) in range(self.board_width))
# new_cat_vert_pos = cat_vert_pos + cat_vert_move * cat_move_stays_on_board
# new_cat_horz_pos = cat_horz_pos + cat_horz_move * cat_move_stays_on_board
# new_state_instances = {}
# mouse_vert_moves, mouse_horz_moves = [-1,0,1], [-1,0,1]
# for mouse_vert_move in mouse_vert_moves:
# for mouse_horz_move in mouse_horz_moves:
# # mouse_action = self._moves_to_action(mouse_vert_move, mouse_horz_move)
# mouse_move_stays_on_board = move_stays_on_board((mouse_vert_pos, mouse_horz_pos), mouse_vert_move, mouse_horz_move, self.board_height, self.board_width)
# new_mouse_vert_pos = mouse_vert_pos + mouse_vert_move * mouse_move_stays_on_board
# new_mouse_horz_pos = mouse_horz_pos + mouse_horz_move * mouse_move_stays_on_board
# new_state = self._positions_to_state_index((new_cat_vert_pos, new_cat_horz_pos), (new_mouse_vert_pos, new_mouse_horz_pos))
# if not new_state in new_state_instances.keys():
# game_over = ((new_cat_vert_pos == new_mouse_vert_pos) and (new_cat_horz_pos == new_mouse_horz_pos))
# new_state_instances[new_state] = [1, game_over, new_cat_vert_pos, new_cat_horz_pos, new_mouse_vert_pos, new_mouse_horz_pos]
# else:
# new_state_instances[new_state][0] += 1
# possible_next_states_list = []
# for new_state, (no_instances, game_over, new_cat_vert_pos, new_cat_horz_pos, new_mouse_vert_pos, new_mouse_horz_pos) in new_state_instances.items():
# if game_over:
# reward = self.board_height * self.board_width
# else:
# cat_mouse_separation = max(abs(new_cat_vert_pos - new_mouse_vert_pos), abs(new_cat_horz_pos - new_mouse_horz_pos))
# reward = 0 - cat_mouse_separation
# possible_next_state_tuple = (no_instances/(len(mouse_vert_moves) * len(mouse_horz_moves)), new_state, int(reward), game_over)
# possible_next_states_list.append(possible_next_state_tuple)
# P[state_index][self._action_to_action_index(action)] = possible_next_states_list
#
# isd = np.ones(nS)
# for state_index in range(nS):
# (cat_vert_pos, cat_horz_pos), (mouse_vert_pos, mouse_horz_pos) = self._state_index_to_positions(state_index)
# if ((cat_vert_pos == mouse_vert_pos) and (cat_horz_pos == mouse_horz_pos)):
# isd[state_index] = 0
# isd = isd/sum(isd)
#
# super(CatMouseEnv_proximity_reward, self).__init__(nS, nA, P, isd)
#
#
# def render(self, mode='human'):
# outfile = sys.stdout
#
# for row in range(self.board_height):
# for col in range(self.board_width):
# (cat_vert_pos, cat_horz_pos), (mouse_vert_pos, mouse_horz_pos) = self._state_index_to_positions(self.s)
# if (cat_vert_pos == row and cat_horz_pos == col and mouse_vert_pos == row and mouse_horz_pos == col):
# output = " @ "
# elif (cat_vert_pos == row and cat_horz_pos == col):
# output = " C "
# elif (mouse_vert_pos == row and mouse_horz_pos == col):
# output = " M "
# else:
# output = " o "
# if col == 0:
# output = output.lstrip()
# if col == (self.board_width - 1):
# output = output.rstrip()
# output += '\n'
# outfile.write(output)
# outfile.write('\n')
#
#
# def _state_index_to_positions(self, state_index):
# if not state_index in range(self.board_height**2 * self.board_width**2):
# raise ValueError('state_index must be between 0 and %d' % (self.board_height**2 * self.board_width**2 - 1))
#
# cat_vert_pos = float(np.mod(state_index,self.board_height))
# cat_horz_pos = np.mod(state_index - cat_vert_pos, self.board_height * self.board_width) / self.board_height
# mouse_vert_pos = np.mod(state_index - cat_horz_pos * self.board_height - cat_vert_pos, self.board_height * self.board_width * self.board_height) / (self.board_height * self.board_width)
# mouse_horz_pos = (state_index - mouse_vert_pos * self.board_height * self.board_width - cat_horz_pos * self.board_height - cat_vert_pos) / (self.board_height * self.board_width * self.board_height)
# return (int(cat_vert_pos), int(cat_horz_pos)), (int(mouse_vert_pos), int(mouse_horz_pos))
#
#
# def _positions_to_state_index(self, cat_pos, mouse_pos):
# if not np.prod([ \
# cat_pos[0] in range(self.board_height), \
# cat_pos[1] in range(self.board_width), \
# ]):
# raise ValueError('Cat position (%d,%d) is outside the board' % (cat_pos[0], cat_pos[1]))
#
# if not np.prod([ \
# mouse_pos[0] in range(self.board_height), \
# mouse_pos[1] in range(self.board_width) \
# ]):
# raise ValueError('Mouse position (%d,%d) is outside the board' % (mouse_pos[0], mouse_pos[1]))
#
# return int( \
# cat_pos[0] + \
# cat_pos[1] * self.board_height + \
# mouse_pos[0] * self.board_height * self.board_width + \
# mouse_pos[1] * self.board_height * self.board_width * self.board_height \
# )
#
#
# def _action_to_action_index(self, action):
# # note that action X means the agent remains where it is
# valid_actions = ['NW','N','NE','W','X','E','SW','S','SE']
# if not action in valid_actions:
# raise Exception('Invalid action')
# return int(valid_actions.index(action))
#
#
# def _action_index_to_action(self, action_index):
# if not action_index in range(9):
# raise Exception('action_index must be between 0 and 9')
# valid_actions = ['NW','N','NE','W','X','E','SW','S','SE']
# return valid_actions[action_index]
#
#
# def _action_to_moves(self, action):
# # takes action from ['NW','N','NE','W','X','E','SW','S','SE'] as input
# # returns vert_move, horz_move
# valid_actions = ['NW','N','NE','W','X','E','SW','S','SE']
# if not action in valid_actions:
# raise Exception('Invalid action')
# action_index = valid_actions.index(action)
# horz_move = float(np.mod(action_index, 3) - 1)
# vert_move = np.mod((action_index - horz_move - 1)/3, 3) - 1
# return int(vert_move), int(horz_move)
#
#
# def _moves_to_action(self, vert_move, horz_move):
# # takes vert_move, horz_move
# # returns action from ['NW','N','NE','W','X','E','SW','S','SE'] as input
# if not (vert_move in [-1, 0, 1] and horz_move in [-1, 0, 1]):
# raise Exception('Invalid move. Vertical and horizontal components must be in [-1. 0. 1]')
# valid_actions = ['NW','N','NE','W','X','E','SW','S','SE']
# return valid_actions[(vert_move + 1 ) * 3 + (horz_move + 1)]
#
#
# def _action_index_to_moves(self, action_index):
# if not action_index in range(9):
# raise Exception('action_index must be between 0 and 9')
# horz_move = float(np.mod(action_index, 3) - 1)
# vert_move = np.mod((action_index - horz_move - 1)/3, 3) - 1
# return int(vert_move), int(horz_move)
#
#
# def _moves_to_action_index(vert_move, horz_move):
# if not (vert_move in [-1, 0, 1] and horz_move in [-1, 0, 1]):
# raise Exception('Invalid move. Vertical and horizontal components must be in [-1. 0. 1]')
# return int((vert_move + 1 ) * 3 + (horz_move + 1))
|
"""
questions to ask:
- will we have empty arrays? yes
- all are numbers? yes
"""
"""
naive approach: put all of the numbers into a single array
Time O(n) when construct
Space O(n)
104 ms, faster than 17.66%
"""
class Vector2D(object):
def __init__(self, v):
self.nums = []
for arr in v:
for num in arr:
self.nums.append(num)
def next(self):
return self.nums.pop(0)
def hasNext(self):
return len(self.nums) > 0
"""
1st approach: 2pointers
- row starts from 0
- col starts from -1
Time O(n)
Space O(n)
80 ms, faster than 34.20%
"""
class Vector2D(object):
def __init__(self, v):
"""
:type v: List[List[int]]
"""
self.v = v
self.row = 0
# very important
self.col = -1
def next(self):
"""
:rtype: int
"""
nextRow = self.row + 1
nextCol = self.col + 1
if self.row < len(self.v):
if nextCol < len(self.v[self.row]):
self.col = nextCol
return self.v[self.row][nextCol]
else:
while nextRow < len(self.v):
if len(self.v[nextRow]) > 0:
self.row = nextRow
self.col = 0
return self.v[nextRow][0]
nextRow += 1
return -1
return -1
def hasNext(self):
"""
:rtype: bool
"""
nextRow = self.row + 1
nextCol = self.col + 1
if self.row < len(self.v):
if nextCol < len(self.v[self.row]):
return True
else:
while nextRow < len(self.v):
if len(self.v[nextRow]) > 0:
return True
nextRow += 1
return False
return False
# Your Vector2D object will be instantiated and called as such:
# obj = Vector2D(v)
# param_1 = obj.next()
# param_2 = obj.hasNext()
|
import numpy as np
"""
Used Alpha-Beta Pruning to optimize Minimax algorithm.
The algorithm checks the maximizers and minimizers and when it isn't possible to beat a better option,
it stops searching and moves onto the next options.
"""
BOARD_COLS = BOARD_ROWS = 3
AI = 1
PLAYER = -1
state = [['1', '2', '3'],
['4', '5', '6'],
['7', '8', '9']]
#AI is 1, Human is -1
class State:
"""
Represents the state of the board we're in
"""
def __init__(self, p1, p2):
self.board = np.zeros((BOARD_ROWS, BOARD_COLS))
self.p1 = p1
self.p2 = p2
self.isEnd = False
self.playerSymbol = 1
def showBoard(self):
"""
Objective: Print the board for the user
"""
for i in range(BOARD_ROWS):
print('-------------')
row_symbol = '| '
for j in range(BOARD_COLS):
if self.board[i][j] == 1:
row_symbol += ('X')
elif self.board[i][j] == -1:
row_symbol += ('O')
else:
row_symbol += ''
row_symbol += ' | '
print(row_symbol)
print('-------------')
def play(self):
"""
Objective: Play game against Computer
"""
while not self.isEnd:
p1_action = self.p1.bestMove(self.board)
self.board[p1_action] = self.playerSymbol
self.playerSymbol *= -1
result, self.isEnd = checkWinner(self.board)
self.showBoard()
if result is not None:
if result == 1:
print('Computer Wins')
elif result == -1:
print('You have defied logic!')
else:
print('Draw')
self.isEnd = True
return
p2_action = self.p2.move(self.board, self.playerSymbol)
self.board[p2_action] = self.playerSymbol
self.playerSymbol *= -1
self.showBoard()
result, self.isEnd = checkWinner(self.board)
if result is not None:
if result == 1:
print(self.p1.name, 'wins!')
elif result == -1:
print(self.p2.name, 'wins!')
else:
print('Draw')
self.isEnd = True
return
class Player:
"""
Represents us, the human player
"""
def __init__(self, name):
"""
Initialize class for human player
"""
self.name = name
def move(self, board, playerSymbol):
"""
Inputs: the state of the board, and whose turn it is
Returns: coordinates of the cell player moves to
Objective: Make human move on board. Replaces valid cell with marker
"""
while True:
cell = int(input('Choose cell: '))
i = (cell-1) // 3
j = (cell-1)%3
if board[i][j]== 0:
board[i][j] == playerSymbol
return (i, j)
else:
print('Invalid Move')
#Represents the rewards that will influence the bot's decisions
scores = {
-1: -10,
1: 10,
0: 0
}
class Computer:
"""
Represents the computer we will be playing against
"""
def __init__(self, name):
"""
Inputs: name
Objective: Initialize Computer with a name
"""
self.name = name
def bestMove(self, board):
"""
Inputs: state of given board
Return: tuple representing the cell the computer should move
Objective: Decides computer's best move, using minimax algo
"""
best_score = -float('inf')
for i in range(BOARD_ROWS):
for j in range(BOARD_COLS):
#Check if spot available
if board[i][j] == 0:
board[i][j] = AI
score = minimax(board, 0, False, -float('inf'), float('inf'))
board[i][j] = 0
if score > best_score:
best_score = score
best_move = (i,j)
board[best_move] = 1
return best_move
def checkWinner(board):
"""
Input: state of board
Returns: 1 or -1, depending on if X or O won, respectively
0 if draw
None if game is still in progress
Objective: check the result of the board, see the outcome
"""
vert = 0
hori = 0
draw = True
#Horizontal, Vertical, or Draw check
for i in range(BOARD_ROWS):
for j in range(BOARD_COLS):
vert += board[j][i]
hori += board[i][j]
if board[i][j] == 0:
draw = False
if vert == 3 or hori == 3:
return 1, True
if vert == -3 or hori == -3:
return -1, True
vert = hori = 0
#Two diagonals to check
diag_sum1 = sum([board[i, i] for i in range(BOARD_COLS)])
diag_sum2 = sum([board[i, BOARD_COLS - i - 1] for i in range(BOARD_COLS)])
check_diag = max(abs(diag_sum1), abs(diag_sum2))
if check_diag == 3:
if diag_sum1 == 3 or diag_sum2 == 3:
return 1, True
else:
return -1, True
if draw:
return 0, True
return None, False
def minimax(board, depth, isMaximizing, alpha, beta):
"""
Inputs: state of board,
depth indicating level of tree,
isMaximizing to denote if minimizing or maximizing player,
alpha represents the minimum score that the maximizing player is guaranteed
beta represents the maximum score that the minimizing player is guaranteed
Returns: best score from after running minimax on the given board
Objective: Runs minimax with alpha beta pruning to check best move for computer
"""
current_result, _ = checkWinner(board)
if current_result is not None: #If game done, return score
return scores[current_result]
if isMaximizing: #Finds best move if AI is next, maximize score
best_score = -float('inf')
for i in range(3):
for j in range(3):
#Check if spot available, AI turn
if board[i][j] == 0:
board[i][j] = AI
score = minimax(board, depth+1, False, alpha, beta)
board[i][j] = 0
best_score = max(score - depth , best_score) #We want the AI to win ASAP
alpha = max(alpha, best_score) #Maximize score, best explored option for maximizer from the current state
if beta <= alpha: #A better option exists so prune
return best_score
return best_score
else:
best_score = float('inf')
for i in range(3):
for j in range(3):
#Check if spot available, player turn
if board[i][j] == 0:
board[i][j] = PLAYER
score = minimax(board, depth+1, True, alpha, beta)
board[i][j] = 0
best_score = min(depth + score, best_score) #We want the AI to lose as slowly as possible
beta = min(beta, best_score) #Minimize score, best explored option for minimizer from the current state
if beta <= alpha:
return best_score
return best_score
def print_board(game_state):
"""
Used to print template board
"""
print('-------------')
print('| ' + str(game_state[0][0]) + ' | ' + str(game_state[0][1]) + ' | ' + str(game_state[0][2]) + ' |')
print('-------------')
print('| ' + str(game_state[1][0]) + ' | ' + str(game_state[1][1]) + ' | ' + str(game_state[1][2]) + ' |')
print('-------------')
print('| ' + str(game_state[2][0]) + ' | ' + str(game_state[2][1]) + ' | ' + str(game_state[2][2]) + ' |')
print('-------------')
print('Please follow this cell notation for movemaking: ')
print_board(state)
print('Computer goes first :P ')
p1 = Computer('p1')
p2 = Player('p2')
st = State(p1, p2)
st.play() |
#database.py
#use python 3.4
import sys, shelve
def store_person(db):
"""
Query user for data and store it in the shelf object
"""
pid = input('Enter unique ID number: ')
person = {}
person['name'] = input('Enter name: ')
person['age'] = input('Enter age: ')
person['phone'] = input('Enter phone number: ')
db[pid] = person
def lookup_person(db):
"""
Query user for ID and desired field, and fetch the corresponding data from the shelf object
"""
pid = input('Enter ID number: ')
field = input('What would you like to konw? (name, age, phone) ')
field = field.strip().lower()
field = field.split(',')
for ele in field:
try:
print(ele)
print(ele.capitalize()+':'+db[pid][ele])
except KeyError:
continue
def print_help():
print('The available commands are: ')
print('store : Stores information about a person')
print('lookup : Look up a person from ID number')
print('quit : Save changes and exit')
print('? : Prints this message')
def enter_command():
cmd = input('Enter command (? for help): ')
cmd = cmd.strip().lower()
return cmd
def main():
database = shelve.open('database.dat')
try:
while True:
cmd =enter_command()
if cmd == 'store':
store_person(database)
elif cmd == 'lookup':
lookup_person(database)
elif cmd == '?':
print_help()
elif cmd == 'quit':
return
finally:
database.close()
if __name__ =='__main__': main()
|
# a simple markup program
# aim:
# 1. print some beginning markup
# 2. for each block, print the block enclosed in paragraph tags.
# 3. print some ending markup
#
# python simple_markup.py <test_input.txt> test_output.html
import sys, re
from util import *
print('<html><head><title>...</title><body>')
title = True
for block in blocks(sys.stdin):
block = re.sub(r'\*(.+?)\*',r'<em>\1</em>',block)
if title:
print('<h1>')
print(block)
print('</h1>')
title = False
else:
print('<p>')
print(block)
print('</p>')
print('</body></html>')
|
import curses
from curses import KEY_RIGHT, KEY_LEFT, KEY_UP, KEY_DOWN
from random import randint
curses.initscr()
window = curses.newwin(30, 60, 0, 0)
window.keypad(True)
curses.noecho()
curses.curs_set(0)
window.nodelay(True)
key = KEY_RIGHT
score = 0
snake = [[5, 8], [5, 7], [5, 6]]
food = [10, 25]
window.addch(food[0], food[1], 'O')
while key != 27:
window.border(0)
window.addstr(0, 2, 'Score: ' + str(score) + ' ')
window.addstr(0, 27, ' SNAKE! ')
window.timeout(140 - (len(snake) / 5 + len(snake) / 10) % 120)
event = window.getch()
key = key if event == -1 else event
snake.insert(0, [snake[0][0] + (key == KEY_DOWN and 1) + (key == KEY_UP and -1),
snake[0][1] + (key == KEY_LEFT and -1) + (key == KEY_RIGHT and 1)])
if snake[0][0] == 0 or snake[0][0] == 29 or snake[0][1] == 0 or snake[0][1] == 59: break
if snake[0] in snake[1:]: break
if snake[0] == food:
food = []
score += 1
while food == []:
food = [randint(1, 28), randint(1, 58)]
if food in snake: food = []
window.addch(food[0], food[1], 'O')
else:
last = snake.pop()
window.addch(last[0], last[1], ' ')
window.addch(snake[0][0], snake[0][1], '#')
curses.endwin()
print("\nScore: " + str(score))
|
from karel.stanfordkarel import *
"""
File: TripleKarel.py
--------------------
When you finish writing this file, TripleKarel should be
able to paint the exterior of three buildings in a given
world, as described in the Assignment 1 handout. You
should make sure that your program works for all of the
Triple sample worlds supplied in the starter folder.
"""
"""
Karel paints 3 exterior sides of each in a world of three buildings
"""
def main():
for i in range(3): # Paints 3 buildings in a given world
for j in range(2): # Paints 2 sides of a building
paint()
move()
paint() # Paints 3rd side of a building
turn_left()
turn_left()
turn_left()
# pre : Karel will be facing left
# post : Karel need to turn right from the the current position
def turn_right():
turn_left()
turn_left()
turn_left()
# pre : Karel is in the top right corner of the building (external)
# post : Karel paints one side of the building
def paint():
turn_left()
while front_is_blocked():
put_beeper()
turn_right()
move()
turn_left()
# There is no need to edit code beyond this point
if __name__ == "__main__":
run_karel_program()
|
x = 3
password = 'a123456'
while x > 0:
code = input('type your password: ')
if code == password:
print('accessed')
break
else:
x = x - 1
if x == 0:
break
print('u still have', x, 'chance')
|
# Problem: A car dealer earns a base wage of $36.25 per hour up to their normal work week of 37 hours.
# Only whole hours are counted. If he works more hours than that (overtime) he gets paid at 1.5 times his normal rate for the overtime.
# If he sells more than 5 cars in a week, he gets a bonus of $200 per car from the 6th car sold.
# Write program to calculate the wages plus bonus for the car dealer in a week.
hours = int(input("How many hours were worked? "))
cars = int(input("Total number of cars sold for the week? "))
baseRate = 36.25
baseSalary = 37 * baseRate
commission = (cars - 5) * 200
extraHours = hours-37
penaltyRate = baseRate*1.5
overTime = extraHours*penaltyRate
if hours > 37:
salary = baseSalary + overTime
if cars > 5:
salary = salary + commission
else:
salary = hours * baseRate
print(f'The salary is {salary}')
# print("base salary: ", baseSalary) # temporary
# print("commission: ", commission) # temporary
# print("extra hours: ", extraHours) # temporary
# print("over time: ",overTime) # temporary |
#program converts kilometres to Miles
km = float(input("Enter kilometres: "))
miles = 0.621771 * km
print(f'{km} kilometres is equal to {miles} miles') |
'''
class newlist(list):
def __init__(self,aname):
list.__init__([])
self.name=aname
a=newlist(333)
print(a)
print(a.name)
class bird():
def __init__(self):
self.hurgy=True
def eat(self):
if self.hurgy:
print('hahahahah')
self.hurgy=False
else:
print('no,thanks!')
class songbird(bird):
def __init__(self):
bird.__init__(self)
self.sound="nononnonon"
def song(self):
print(self.sound)
b=songbird()
b.eat()
'''
def decorator_a(func):
print ('Get in decorator_a')
def inner_a(*args, **kwargs):
print ('Get in inner_a')
return func(*args, **kwargs)
return inner_a
def decorator_b(func):
print ('Get in decorator_b')
def inner_b(*args, **kwargs):
print ('Get in inner_b')
return func(*args, **kwargs)
return inner_b
@decorator_b
@decorator_a
def f(x):
print ('Get in f')
return x * 2
#f=decorator_a(f)
#f=decorator_b(f)
#f(1)
|
"""Test Vector identities using numpy"""
import numpy as np
import random
def main():
#create three random arrays called v_1, v_2, v_3 whose entries are random real numbers in range (-100,100)
v_1=np.array([random.uniform(-100,100) for i in range(3)])
v_2=np.array([random.uniform(-100,100) for i in range(3)])
v_3=np.array([random.uniform(-100,100) for i in range(3)])
#print the vectors to the terminal:
print("the first vector is:"+str(v_1))
print("the first second is:"+str(v_2))
print("the first third is:"+str(v_3))
#print the norms of each vector to the terminal
print("the norm of the first vector is:"+str(np.linalg.norm(v_1)))
print("the norm of the second vector is:"+str(np.linalg.norm(v_2)))
print("the norm of the third vector is:"+str(np.linalg.norm(v_3)))
#print the sum of the first two vectors using the operator overloading of numpy
sum=v_1+v_2
print("the sum of the first two vectors is:"+str(sum))
#print the dot product of the first two vectors using np.inner()
dot_prod=np.inner(v_1,v_2)
print("the dot product of the first and second vectors is:"+str(dot_prod))
#calculate cross product of first and second vectors using np.cross
cross_prod=np.cross(v_1,v_2)
print("the cross product of the first and second vectors is:"+str(cross_prod))
#git
main()
|
# coding 1 neuron
# count these as outputs from previous neuron layer
inputs = [1, 2, 3, 2.5]
weights = [0.2, 0.8, -0.5, 1.0]
# this is for neuron that we are currently coding. Bias - зміщення
bias = 2
# output of our neuron
output = inputs[0] * weights[0] + inputs[1] * weights[1] + inputs[2] * weights[2] + inputs[3] * weights[3] + bias
print(output)
# output = [inputs[0] * weights1[0] + inputs[1] * weights1[1] + inputs[2] * weights1[2] + inputs[3] * weights1[3] + bias1,
# inputs[0] * weights2[0] + inputs[1] * weights2[1] + inputs[2] * weights2[2] + inputs[3] * weights2[3] + bias2,
# inputs[0] * weights3[0] + inputs[1] * weights3[1] + inputs[2] * weights3[2] + inputs[3] * weights3[3] + bias3]
# print(output)
# layer_outputs = []
#
# for neuron_weights, neuron_bias in zip(weights, biases):
# neuron_output = 0
# for n_input, weight in zip(inputs, neuron_weights):
# neuron_output += n_input * weight
# neuron_output += neuron_bias
# layer_outputs.append(neuron_output)
#
# print(layer_outputs)
|
#!C:Users\Vaibhavi Raut\AppData\Local\Programs\Python\Python37
'''
3-2-19
WAP to accept a string from user and print count of consonants in it.
'''
def count(s):
l = len(s)
cnt = 0
v = 0
for x in s:
if x in "aeiouAEIOU":#x=='a' or x=='e' or x=='i' or x=='o' or x=='u':
v +=1#continue
else:
cnt+=1
print("Vowels: ",v)
return cnt
def main():
s = input("Enter a String: ")
y = count(s)
print("Count of Consonants in String: ",y)
if __name__=='__main__':
main()
|
#!C:Users\Vaibhavi Raut\AppData\Local\Programs\Python\Python37
'''
3-2-19
"Foundation"
WAP to accept a number for user and a bit position to turn off from the given
number. Print number in decimal after turning off the bit. If already off then let
it be
Example: 16 bit=5 answer:0
Note: turn off always lsb to msb
the no. and create no. with inverse of that binary no. ex: 0001000 and
inverse: 1110111
'''
def bit_change(n,b):
t = n
x = 1
x = x<<(b-1)
x = ~x
r = t & x
return r
def main():
n = eval(input("Enter a number: "))
b = eval(input("Enter the bit position: "))
print("Binary of n: ",bin(n))
print("Number: ",n,"Bit Position: ",b)
r = bit_change(n,b)
print("Answer: ",r)
print("Binary of answer: ",bin(r))
if __name__=='__main__':
main()
'''
OUTPUT:
Enter a number: 16
Enter the bit position: 5
Number: 16 Bit Position: 5
Answer: 0
bin():
Enter a number: 16
Enter the bit position: 5
Binary of n: 0b10000
Number: 16 Bit Position: 5
Answer: 0
Binary of answer: 0b0
'''
|
#!C:Users\Vaibhavi Raut\AppData\Local\Programs\Python\Python37
'''
WAP to count the number of 0's in the given number.
Example:
i/p: 64 o/p:7
i/p: 63 o/p:3
'''
def count0(n):
cnt = 0
while n!=0:
cnt+=1
n = n&(n-1)
return cnt
def main():
n = eval(input("Enter a number: "))
tot = 8 #as in 8 bits
a = count0(n)
print("Number of 0's are ",(tot-a))
if __name__=='__main__':
main()
|
#!C:Users\Vaibhavi Raut\AppData\Local\Programs\Python\Python37
'''
WAP to add two numbers using bitwise operators.
'''
def bit_add(a,b):
while b!=0:
t = a & b
a = a ^ b
b = t << 1
return a
def main():
a,b = eval(input("Enter two numbers: "))
ans = bit_add(a,b)
print("Addition: ",ans)
if __name__=='__main__':
main()
'''
OUTPUT:
Enter two numbers: 7,5
Addition: 12
'''
|
numero = int(input('Digite um número: '))
if numero > 8:
print('O número digitado divido por 2 é: ', (numero/2))
else:
print('O número ao cubo é: ', (numero**2))
input()
|
import math
numero = float(input('Digite um número: '))
if numero > 0:
print('O número é positivo e sua raiz quadrada é: ', round(math.sqrt(numero)))
else:
print('O número é negativo ')
input()
|
lista1 = [0,0,0,0,0,0,0,0,0,0]
lista2 = [0,0,0,0,0,0,0,0,0,0]
lista3 = [0,0,0,0,0,0,0,0,0,0]
n = 0
while n < 10:
lista1[n] = int(input('Digite os números da primeira lista: '))
lista2[n] = int(input('Digite os números da segunda lista: '))
lista3[n] = lista1[n] * lista2[n]
n = n + 1
print('\n')
print('Primeira lista digitada: \n ',lista1,'\n')
print('Segunda lista digitada: \n ',lista2,'\n')
print('Multiplicação das duas lista: \n',lista3)
input()
|
class Customer:
def __init__(self,x,y,rd,id):
self.coordinate = (x,y)
self.release = rd
self.id = id
def getData(self):
return [self.coordinate[0], self.coordinate[1], self.release]
def __str__(self):
return 'CustomerRD ' + str(self.release)
def __repr__(self):
return "C " +str(self.id)
def __eq__(self, other):
return self.id == other.id
class Depot:
def __init__(self,x,y):
self.coordinate = (x,y)
self.release = 0
self.id = 0
|
#Write your code below this row 👇
total = 0
for number in range(2, 101):
if number % 2 == 0:
total += number
print(total)
jumlah = 0
for nomor in range(2, 101, 2):
jumlah += nomor
print(jumlah) |
#Look for #IMPLEMENT tags in this file. These tags indicate what has
#to be implemented.
import random
import itertools
'''
This file will contain different variable ordering heuristics to be used within
bt_search.
var_ordering == a function with the following template
ord_type(csp)
==> returns Variable
csp is a CSP object---the heuristic can use this to get access to the
variables and constraints of the problem. The assigned variables can be
accessed via methods, the values assigned can also be accessed.
ord_type returns the next Variable to be assigned, as per the definition
of the heuristic it implements.
val_ordering == a function with the following template
val_ordering(csp,var)
==> returns [Value, Value, Value...]
csp is a CSP object, var is a Variable object; the heuristic can use csp to access the constraints of the problem, and use var to access var's potential values.
val_ordering returns a list of all var's potential values, ordered from best value choice to worst value choice according to the heuristic.
'''
def ord_random(csp):
'''
ord_random(csp):
A var_ordering function that takes a CSP object csp and returns a Variable object var at random. var must be an unassigned variable.
'''
var = random.choice(csp.get_all_unasgn_vars())
return var
def val_arbitrary(csp,var):
'''
val_arbitrary(csp,var):
A val_ordering function that takes CSP object csp and Variable object var,
and returns a value in var's current domain arbitrarily.
'''
return var.cur_domain()
def ord_mrv(csp):
'''
ord_mrv(csp):
A var_ordering function that takes CSP object csp and returns Variable object var,
according to the Minimum Remaining Values (MRV) heuristic as covered in lecture.
MRV returns the variable with the most constrained current domain
(i.e., the variable with the fewest legal values).
'''
#IMPLEMENT
min = None
for v in csp.get_all_unasgn_vars():
if v.cur_domain_size() == 1:
return v
if not min or v.cur_domain_size() < min.cur_domain_size():
min = v
return min
def ord_dh(csp):
'''
ord_dh(csp):
A var_ordering function that takes CSP object csp and returns Variable object var,
according to the Degree Heuristic (DH), as covered in lecture.
Given the constraint graph for the CSP, where each variable is a node,
and there exists an edge from two variable nodes v1, v2 iff there exists
at least one constraint that includes both v1 and v2,
DH returns the variable whose node has highest degree.
'''
#IMPLEMENT
cons = csp.get_all_cons()
degrees = {}
for c in cons:
unassigned_vars = c.get_unasgn_vars()
for v in c.get_scope():
# check if a variable is within a constraint's scope
if unassigned_vars.count(v) > 0:
# update degree for node v
if v not in degrees:
degrees[v] = 0
degrees[v] = degrees[v] + len(unassigned_vars)
var = max(degrees, key=degrees.get)
return var
def val_lcv(csp,var):
'''
val_lcv(csp,var):
A val_ordering function that takes CSP object csp and Variable object var,
and returns a list of Values [val1,val2,val3,...]
from var's current domain, ordered from best to worst, evaluated according to the
Least Constraining Value (LCV) heuristic.
(In other words, the list will go from least constraining value in the 0th index,
to most constraining value in the $j-1$th index, if the variable has $j$ current domain values.)
The best value, according to LCV, is the one that rules out the fewest domain values in other
variables that share at least one constraint with var.
'''
#IMPLEMENT
domain = var.cur_domain()
cons = csp.get_cons_with_var(var)
sums = {}
# look at values in domain of var
for value in domain:
# assign value to variable
var.assign(value)
accounted_for = {} # neighbours with values that have been ruled out
total = 0
# look at constraints with var
for c in cons:
# look at unassigned neighbours in each constraint
for n in c.get_unasgn_vars():
# look at the domains of each neighbour and count invalid values
for val in n.cur_domain():
if not c.has_support(n, val):
# keep track of which neighbour has already been ruled out
if n not in accounted_for:
accounted_for[n] = [val]
else:
# avoid double counting
if val not in accounted_for[n]:
accounted_for[n].append(val)
# count how many were ruled out
for lst in accounted_for.values():
total += len(lst)
sums[value] = total
var.unassign()
return sorted(sums, key=sums.get)
def ord_custom(csp):
'''
ord_custom(csp):
A var_ordering function that takes CSP object csp and returns Variable object var,
according to a Heuristic of your design. This can be a combination of the ordering heuristics
that you have defined above.
'''
#IMPLEMENT
# run MRV and find min ties
mins = []
for v in csp.get_all_unasgn_vars():
if len(mins) == 0:
mins = [v]
elif v.cur_domain_size() == mins[0].cur_domain_size():
mins.append(v)
elif v.cur_domain_size() < mins[0].cur_domain_size():
mins = [v]
if len(mins) == 1:
return mins[0]
else:
# use DH as tiebreaker
cons = csp.get_all_cons()
degrees = {}
for c in cons:
unassigned_vars = c.get_unasgn_vars()
# loop over minimum variables found instead of entire scope
for v in mins:
# check if a variable is within a constraint's scope
if unassigned_vars.count(v) > 0:
# update degree for node v
if v not in degrees:
degrees[v] = 0
degrees[v] = degrees[v] + len(unassigned_vars)
var = max(degrees, key=degrees.get)
return var
|
'''
Suraj Kumar Saini
www.linkedin.com/in/suraj-saini-8a1027143/
https://github.com/surya3217
'''
# my generic solution to update dictionary
def recurse_dict(dd, d2):
for key in d2.keys(): # finding the key from d2 dict to update
print(key)
if type(d2[key])==dict: # checking the data type of dict val
dd[key]= recurse_dict(dd[key], d2[key]) # moving to next inside key of dict using recursion
else:
dd[key]= d2[key] # if dict val is normal than just updating the val
return dd
###### input 1
# d1= {'address': {"city": "Delhi", "pincode": "11111", "country": "India"},
# 'personal_info': {'first_name': "Suraj", 'last_name': "Saini"}
# }
# d2= {'address': {"pincode": "10001"}}
d1= {
'personal_info': {'first_name': "Suraj", 'last_name': "Saini"},'address': {"city": "Delhi", "pincode": "11111", "country": "India"}
}
d2= {'address': {"pincode": "10001"},'personal_info':{'first_name': "Sai"}}
###### input 2
d3= {'patient_info': {'contact': {'email': "abc@gmail.com", 'phone': 9824627820},
'name': "Jonny", "DOB": "19-09-1999"}}
d4= {'patient_info': {'contact': {'email': "xyz@yahoo.com"},
}}
update_dic= recurse_dict(d1, d2)
print(update_dic)
''' Pincode has changed
output 1
{'address': {'city': 'Delhi', 'pincode': '10001', 'country': 'India'},
'personal_info': {'first_name': 'Suraj', 'last_name': 'Saini'}}
'''
update_dic= recurse_dict(d3, d4)
print(update_dic)
''' Email has changed
output 2
{'patient_info': {'contact': {'email': 'xyz@yahoo.com', 'phone': 9824627820},
'name': 'Jonny', 'DOB': '19-09-1999'}}
'''
#################################
# print first n prime no., update the function
def prime(num):
for i in range(2,num//2+1):
if num% i==0:
return False
return True
n= int(input('enter num.:'))
count= 0
num= 2
while count!=n:
if prime(num):
print('prime', num)
count+=1
num+=1
|
"""
Name:
Height Calculator
Problem Statement:
Lets assume your height is 5 Foot and 11 inches
Convert 5 Foot into meters and Convert 11 inch into meters and
print your total height in meters and print your total heigjt in centimetres also
Extension:
Take the height of the user from input
Hint:
1 Foot = 0.3048 meters
1 inch = 0.0254 meters
1 m = 100 cm
"""
foot= float(input('Enter your height in foot: '))
inch= float(input('Enter your height in inches: '))
meter= (foot*0.3048)+(inch*0.0254)
print('Height in meters: ',meter,'m')
print('Height in centimetres: ',meter*100,'cm' ) |
import csv
import string
unfiltered = []
filtered = []
valid = 0
with open('input.csv') as csvfile:
reader = csv.reader(csvfile, delimiter = ",")
for x in reader:
unfiltered.append(x)
unfiltered.pop(0)
for x in range(len(unfiltered)):
filtered.append(unfiltered[x][0].split(":"))
for x in filtered:
policy = x[0]
password = x[1]
letter = policy.split(' ')[1]
window = policy.split(' ')[0]
minimum = int(window.split('-')[0])
maximum = int(window.split('-')[1])
count = 0
for element in password:
if element == letter:
count += 1
if count <= maximum and count >= minimum:
valid += 1
print(valid)
|
import math
def bus_time(bus, time):
bus = int(bus)
time = int(time)
if time % bus == 0:
return time
else:
return bus_time(bus, time + 1)
def check_time(bus, time):
if bus == 'x':
return True
else:
bus = int(bus)
time = int(time)
if time % bus == 0:
return True
else:
return False
with open('input13.txt', 'r') as inputfile:
lines = inputfile.readlines()
time = lines[0].rstrip('\n')
schedule = lines[1].split(',')
busses = []
for bus in schedule:
if bus != 'x':
busses.append(bus)
shortest = (busses[0], bus_time(busses[0], time))
for bus in busses:
prev_bus, prev_time = shortest
curr_time = bus_time(bus, time)
if curr_time < prev_time:
shortest = (bus, curr_time)
print(shortest)
x, y = shortest
print('part 1:', int(x) * (y - int(time)))
num = 0
mult = 1
offset = 0
for bus in schedule:
if bus == 'x':
offset += 1
continue
else:
print(num, mult, bus, offset)
bus = int(bus)
count = 0
while ((num + offset + count) % bus != 0):
count = count + mult
num = num + count
mult = math.lcm(mult, bus)
offset += 1
print('part 2:', num)
|
# initialise list
assignments = []
# read input file
with open('adventofcode2022/day4/day4input.txt', 'r') as input:
for line in input:
line = line.strip()
assignments.append(line.split(','))
# calculate number of pairs with overlapping ranges
contains = 0
for pair in assignments:
elf1,elf2 = pair[0],pair[-1]
start1,end1 = elf1.split('-')
start2,end2 = elf2.split('-')
# cast to integer
start1 = int(start1)
start2 = int(start2)
end1 = int(end1)
end2 = int(end2)
# check if elf 1's range contains elf 2's range
if(start1 <= start2 and end1 >= end2):
contains = contains + 1
# check if elf 2's range contains elf 1's range
elif(start2 <= start1 and end2 >= end1):
contains = contains + 1
# print answer
print(contains) |
with open('adventofcode2020\day3\day3input.txt', 'r') as input:
hilltop = [line.rstrip() for line in input]
def treeCounter(right_slope, down_slope):
x,y,trees = 0,0,0
while y < len(hilltop):
if(x >= len(hilltop[0])):
x -= len(hilltop[0])
if(hilltop[y][x] == '#'):
trees += 1
x += right_slope
y += down_slope
return(trees)
print(treeCounter(1,1) * treeCounter(3,1) * treeCounter(5,1) * treeCounter(7,1) * treeCounter(1,2)) |
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
for row in board:
if not self.isValid(row):
return False
for col in zip(*board):
if not self.isValid(col):
return False
for i in (0,3,6):
for j in (0,3,6):
unit = [board[x][y] for x in range(i,i+3) for y in range(j,j+3)]
if not self.isValid(unit):
return False
return True
def isValid(self,unit) -> bool:
s = [x for x in unit if x.isdigit()]
return len(s) != len(set(s)):
|
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def traverse(self, root, num):
for i in range(num):
root = root.next
return root
def count(self,root):
cnt = 0
while root:
root = root.next
cnt = cnt+1
return cnt
def getIntersectionNode(self, headA, headB):
n = self.count(headA)
m = self.count(headB)
diff = abs(n-m)
if m>n:
headB = self.traverse(headB, diff)
else:
headA = self.traverse(headA, diff)
while True:
if headA == headB:
return headA
else:
headA = headA.next
headB = headB.next
|
import random
class Rulet:
def __init__(self):
self.money = 100
self.limit = 5000
def display_title_bar(self):
print("\t~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("\t~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ RULET ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("\t~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
def get_user_choice(self):
print("\n[1] Igraj Rulet")
print("[x] Izlaz.")
return input("Odaberite što želite napraviti? ")
def start_game(self):
while self.money <= self.limit:
print("Imate: {} kn.".format(self.money))
if self.money <= 0:
print("Završili ste s igrom")
break
bet_amount = int(input("Ulog: "))
while bet_amount > self.money:
print("Nemate dovoljno novaca za takav ulog.")
bet_amount = int(input("Ulog: "))
self.money = self.money - bet_amount
bet = input("Na što želite uložiti? [1] Broj ili [2] Boja. ")
if bet == '1':
final_bet = int(input("Odaberite na koji broj stavljate ulog (1-36): "))
if 1 <= final_bet <= 36:
print("Rulet se okreće ...")
k = random.randint (1, 37)
print("\nKuglica na ruletu je na broju: {}".format(k))
if k == final_bet:
print("Čestitamo! Vaš ulog se povećao za 20 puta!")
self.money = self.money + bet_amount*20
else:
print("Izgubili ste! Više sreće drugi put!")
else:
self.money = self.money + bet_amount
print("HVATANJE IZUZETAKA")
elif bet == '2':
final_bet = input("Na koju boju stavljate ulog? Upišite crna ili crvena: ")
if final_bet.lower() == "crna" or final_bet.lower() == "crvena":
print("Rulet se okreće ...")
k = random.choice(["crvena", "crna"])
print("\nKuglica na ruletu je na boji: {}".format(k))
if k == final_bet:
print("Čestitamo! Vaš ulog se povećao za 2 puta!")
self.money = self.money + bet_amount*2
else:
print("Izgubili ste! Više sreće drugi put!")
else:
self.money = self.money + bet_amount
print("HVATANJE IZUZETAKA")
else:
self.money = self.money + bet_amount
print("HVATANJE IZUZETAKA")
def play(self):
choice = ''
while choice != 'x':
self.display_title_bar()
choice = self.get_user_choice()
if choice == '1':
self.start_game()
elif choice == 'x':
print("Hvala na igranju! Pozdrav!")
else:
print("HVATANJE IZUZETAKA")
if __name__ == '__main__':
game = Rulet ()
game.play () |
from datetime import datetime
def pad_zero(n):
if len(n) == 2:
return n
if len(n) == 1:
return '0' + n
raise Exception('Received a value with too many digits')
class Clock(object):
def get(self):
now = datetime.now()
hour = pad_zero(str(now.hour))
minute = pad_zero(str(now.minute))
return hour + minute
def stop(self):
return
|
class Complex:
def __init__(self, numb):
self.numb = numb
def __add__(self, other):
if self.numb.count('+'):
num_1 = self.numb.split('+')
else:
num_1 = self.numb.split('-')
if len(num_1) > 2:
num_1.remove('')
num_1[0] = '-' + num_1[0]
num_1[1] = '-' + num_1[1]
if other.numb.count('+'):
num_2 = other.numb.split('+')
else:
num_2 = other.numb.split('-')
if len(num_2) > 2:
num_2.remove('')
num_2[0] = '-' + num_2[0]
print(num_2[0])
num_2[1] = '-' + num_2[1]
num_1[1] = num_1[1].removesuffix('j')
num_2[1] = num_2[1].removesuffix('j')
result_real = int(num_1[0]) + int(num_2[0])
result_img = int(num_1[1]) + int(num_2[1])
if result_img < 0:
result = f'{result_real}{result_img}j'
else:
result = f'{result_real}+{result_img}j'
return result
def __mul__(self, other):
if self.numb.count('+'):
num_1 = self.numb.split('+')
else:
num_1 = self.numb.split('-')
if len(num_1) > 2:
num_1.remove('')
num_1[0] = '-' + num_1[0]
num_1[1] = '-' + num_1[1]
if other.numb.count('+'):
num_2 = other.numb.split('+')
else:
num_2 = other.numb.split('-')
if len(num_2) > 2:
num_2.remove('')
num_2[0] = '-' + num_2[0]
print(num_2[0])
num_2[1] = '-' + num_2[1]
num_1[1] = num_1[1].removesuffix('j')
num_2[1] = num_2[1].removesuffix('j')
result_real = (int(num_1[0]) * int(num_2[0])) - (int(num_1[1]) * int(num_2[1]))
result_img = (int(num_1[0]) * int(num_2[1])) + (int(num_2[0]) * int(num_1[1]))
if result_img < 0:
result = f'{result_real}{result_img}j'
else:
result = f'{result_real}+{result_img}j'
return result
my_num_1 = Complex('5-6j')
my_num_2 = Complex('-3+2j')
print(my_num_1 + my_num_2)
print(my_num_1 * my_num_2)
|
class Car:
def __init__(self, speed, color, name, is_police=False):
self.speed = speed
self.color = color
self.name = name
self.is_police = is_police
def go(self):
print('Машина поехала')
def stop(self):
print('Машина остановилась')
def turn(self, direction):
print(f'Машина повернула на{direction}')
def show_speed(self):
print(self.speed)
class TownCar(Car):
def show_speed(self):
if self.speed > 60:
print(f'{self.speed} > 60: Превышение скорости')
else:
print(self.speed)
def car_type(self):
print('Городская машина')
class WorkCar(Car):
def show_speed(self):
if self.speed > 40:
print(f'{self.speed} > 40: Превышение скорости')
else:
print(self.speed)
def car_type(self):
print('Рабочая машина')
class SportCar(Car):
def car_type(self):
print('Спортивная машина')
class PoliceCar(Car):
def car_type(self):
print('Полицейская машина')
rand_car = Car(60, 'Green', 'Lexus')
town = TownCar(80, 'Red', 'Mazda')
work = WorkCar(45, 'Blue', 'КАМАЗ')
police = PoliceCar(90, 'Black', 'BMW', True)
sport = SportCar(120, 'White', 'Porsche')
print(vars(rand_car))
rand_car.go()
rand_car.turn('право')
rand_car.stop()
rand_car.show_speed()
print()
print(vars(town))
town.car_type()
town.go()
town.turn('лево')
town.stop()
town.show_speed()
print()
print(vars(work))
work.car_type()
work.go()
work.turn('право')
work.stop()
work.show_speed()
print()
print(vars(police))
police.car_type()
police.go()
police.turn('лево')
police.stop()
police.show_speed()
print()
print(vars(sport))
sport.car_type()
sport.go()
sport.turn('право')
sport.stop()
sport.show_speed()
|
# For loops allow you to iterate over a sequence of values
# by default, the value in range starts with x = 0
# the range number is not inclusive
for x in range(5):
print(x)
# you can loop through strings in an array
friends = ['Taylor', 'Alex', 'Pat', 'Eli']
for friend in friends:
print("Hi "+ friend)
# when you want to start to iterate in a number different than zero,
# add more parameters to range(start, end). Note that end is not inclusive
product = 1
for n in range(1,10):
product = product * n
print(product)
# the default step is 1
# to change the step, type range(start, end, step)
def to_celsius(x):
return (x-32)*5/9
for x in range(0,101,10):
print(x, to_celsius(x))
# NESTED LOOPS
# printing domino tiles
for left in range(7):
for right in range(left,7):
print("[" + str(left) + "|" + str(right) + "]", end=" ")
print()
# note that end= parameter in print changes the default newline character to what you define
# print all possible combinations of teams
# not that a team cannot play itself
teams = [ 'Dragons', 'Wolves', 'Pandas', 'Unicorns']
for home_team in teams:
for away_team in teams:
if home_team != away_team:
print(home_team + " vs " + away_team)
# another way to iterate over a list
for x in [25, 26, 27]:
print(x)
# another example and what would happen if instead of passing a list, you pass a single value outside a list
def greet_friends(friends):
for friend in friends:
print("Hi " + friend)
#call with a list
greet_friends(['Taylor', 'Pat', 'Ana'])
# call with single element in list
greet_friends(['Ana'])
# call with single variable outside list
greet_friends("Ana")
# strings are iterable, so it'll print each character in the string
# this won't work for a number, for example
|
"""
Minimal req:
Publisher tracks list of subscribers (adds/removes).
Subscriber implement update method.
"""
class Subscriber:
def __init__(self, name):
self.name = name
def update(self, article, publisher):
print(f'{self.name} received article from publisher: {publisher.name}.')
class Publisher:
def __init__(self, name):
self.name = name
self.__subscribers = []
self.__articles = []
def add_article(self, article):
self.__articles.append(article)
self.notify_subscribers(article)
def subscribe(self, subscriber):
self.__subscribers.append(subscriber)
def unsubscribe(self, subscriber):
self.__subscribers.remove(subscriber)
def notify_subscribers(self, article):
for subscriber in self.__subscribers:
subscriber.update(article, self)
if __name__ == '__main__':
publisher = Publisher('BigPublisher')
subscriber = Subscriber('Mark Suboptimal')
publisher.subscribe(subscriber)
publisher.add_article('Clickbait title')
|
#lists
array = [1,2,3,4]
print(array)
print(array[0])
print(array[-1])
print(array[3:])
print(array[:3])
print(array[:-2])
print(array[-2:])
|
#comparison operators
#
'''
print(1==1)
print(1==2)
print(2>1)
print(1>2)
print(2>2)
print(2<=2)
'''
#combining comparison and boolean expressions
'''
print(1==1 and 2==1)
print(2>1 and 5<10)
'''
|
class Persona:
def __init__(self, nombre, edad, apellido):
self.name = nombre
self.age = edad
self.last_name = apellido
def __str__(self):
return "Nombre: " + self.name + ", edad: " + str(self.age)
class Empleado(Persona):
def __init__(self, nombre, edad, sueldo):
super().__init__(nombre,edad)
self.salary = sueldo
def __str__(self):
return super().__str__() + ", Sueldo: "+ str(self.salary)
persona = Persona('Alexs',24)
print(persona) |
import math
def func(m,s,p):
return 0.5*(1+math.erf((p-m)/(s*2**0.5)))
m=20
s=2
p1=19.5
p2=20
p3=22
res1=func(m,s,p1)
res2=func(m,s,p3)-func(m,s,p2)
print('%.3f\n%.3f'%(res1,res2))
|
def median(l):
n=len(l)
if n%2==0:
return (l[n//2-1]+l[n//2])//2
else:
return(l[n//2])
n=int(input())
l=sorted(list(map(int,input().split())))
a=[]
b=[]
c=[]
if n%2==0:
b.append(l[n//2-1])
b.append(l[n//2])
a=l[:n//2]
c=l[n//2:]
else:
b.append(l[n//2])
a=l[:n//2]
c=l[n//2+1:]
print(median(a))
print(median(b))
print(median(c)) |
#-*- coding: utf-8 -*-
import numpy as np
import random
names = np.array(['Bob', 'joe', 'will','Bob', 'will', 'joe', 'joe'])
data = np.random.randn(7, 4)
print names
print data
print names == 'Bob'
arr = np.empty((8, 4))
print 'arr is \n ', arr
for i in range(8):
arr[i]=i
print arr
|
# Generate a formatted full name including a middle name
def get_full_name(first_name: str, last_name: str, middle_name='', greeting='Hello Master: ') -> str:
if len(middle_name) > 0:
full_name = first_name + ' ' + middle_name + ' ' + last_name
else:
full_name = first_name + ' ' + last_name
return f'{greeting} {full_name}'
|
print('Поддерживаемые операторы: +, -, *, /, %, **')
print('Вводи через пробел')
while True:
inp = input(">> ")
inp.split(' ')
ar_len = len(inp)
print(inp)
if ar_len == 1 and inp.isdigit() is True:
first_num = inp
elif ar_len == 2 and inp[0].isdigit() is False:
operator = inp[0]
sec_num = inp[1]
if inp[0] != '+' :
print('Введи нормальное выражение')
elif inp[0] != '-':
print('Введи нормальное выражение')
elif inp[0] != '*':
print('Введи нормальное выражение')
elif inp[0] != '/':
print('Введи нормальное выражение')
elif inp[0] != '%':
print('Введи нормальное выражение')
elif inp[0] != '**':
print('Введи нормальное выражение')
elif inp == "=":
res = first_num + operator + sec_num
res_n = eval(res)
print(res_n)
break
else:
print('Введи нормальное выражение')
|
print "Programa para Calcular el Area de un Triangulo"
base = float(raw_input("Medida de la Base: "))
altura = float(raw_input("Medida de la Altura: "))
area = (base * altura) / 2.0
print "La base es %6.2f, y el Area es %6.2f" %(base,area)
#Salida Con Formato |
opcion = "z"
while opcion < "a" or opcion > "c":
print "a) Adoro Python"
print "b) Detesto Python"
print "c) No se lo que es Python"
opcion = raw_input("Elija una Opcion: ")
if opcion == "a":
print "Me Alegro."
elif opcion == "b":
print "Que Mal."
elif opcion == "c":
print "Ya Deberias Conocerlo."
else:
print "Tu Opcion no es Valida"
|
import string
def change(chararray):
intarray = [int(index) for index in chararray]
return intarray
lawer_case = string.ascii_uppercase
charlist = list(lawer_case)
countlist = []
try:
while(True):
val = input()
# Enter values separated by comma: x,y,z
if val:
inputlist = list(val)
else:
break
except EOFError:
pass
for char in charlist:
countlist.append(inputlist.count(char))
downtoplist = sorted(countlist, reverse=True)
maisu = downtoplist[0]
if("*" in inputlist):
maisu+=1
twocount = downtoplist.count(2)
if(maisu == 4):
print("FourCard")
elif(maisu == 3):
print("ThreeCard")
elif(twocount == 2):
print("TwoPair")
elif(maisu == 2):
print("OnePair")
else:
print("NoPair")
|
""" Módulo de contas """
class ContaCorrente:
""" Cria classe de conta corrente """
def __init__(self, numero, nome_correntista, saldo=0.0):
""" Inicializa atributos da classe """
self.numero = numero
self.alterar_nome(nome_correntista)
self.saldo = saldo
def alterar_nome(self, nome_correntista):
""" Altera o nome do titular """
self.nome_correntista = nome_correntista
def deposito(self, valor):
""" Realiza depósito na conta """
self.saldo += valor
def saque(self, valor):
""" Realiza saque na conta """
self.saldo -= valor
|
# 3. Реализовать функцию my_func(), которая принимает три позиционных аргумента,
# и возвращает сумму наибольших двух аргументов.
def my_func(arg_a, arg_b, arg_c):
try:
arg_a = float(arg_a)
arg_b = float(arg_b)
arg_c = float(arg_c)
except ValueError:
return 'Invalid value detected!'
return (arg_a + arg_b + arg_c) - min(arg_a, arg_b, arg_c)
args = []
for i in range(3):
args.append(input(f'Type argument {i+1}: '))
print(f'Result: {my_func(args[0], args[1], args[2])}')
|
# 5. Реализовать формирование списка,
# используя функцию range() и возможности генератора.
# В список должны войти четные числа от 100 до 1000 (включая границы).
# Необходимо получить результат вычисления произведения всех элементов списка.
# Подсказка: использовать функцию reduce().
from functools import reduce
def mul_everything(ex, wy): return ex * wy
print(reduce(mul_everything, [i for i in range(100, 1001) if not (i%2)])) |
# 6. Реализовать функцию int_func(), принимающую слово из маленьких латинских букв и возвращающую его же,
# но с прописной первой буквой. Например, print(int_func(‘text’)) -> Text.
# Продолжить работу над заданием. В программу должна попадать строка из слов, разделенных пробелом.
# Каждое слово состоит из латинских букв в нижнем регистре.
# Сделать вывод исходной строки, но каждое слово должно начинаться с заглавной буквы.
# Необходимо использовать написанную ранее функцию int_func().
# ============================================== SIMPLE =============================================
# def int_func(text='No text'):
# return text.lower().capitalize()
#
#
# print(f"{' '.join(i for i in map(int_func, input('Type a few words with space: ').split()))}")
# ============================================== ord() =============================================
def int_func(text='No text'):
char = ord(text[0])
return chr(char - 32) + text[1:] if char in range(97, 123) else text
print(f"{' '.join(i for i in map(int_func, input('Type a few words with space: ').split()))}")
|
# 2. Создайте собственный класс-исключение, обрабатывающий ситуацию деления на нуль.
# Проверьте его работу на данных, вводимых пользователем.
# При вводе пользователем нуля в качестве делителя
# программа должна корректно обработать эту ситуацию и не завершиться с ошибкой.
import time
class NUL_DIVISION(Exception):
@staticmethod
def err():
print("Всё ок, вы поделили на ноль.")
time.sleep(1)
print("Для точного подсчета потребуется немного вечности.")
time.sleep(3)
print("Ваше железо не справляется. Хотите продолжить деление?")
something = " "
while something != "666":
something = input("Делим 10 на: ")
try:
if int(something) == 0:
raise NUL_DIVISION
print(f'Вышло: {10 / int(something)}')
except NUL_DIVISION as n:
n.err()
except:
print(f'Вы ввели {something}. Пожалуйста, опрерируйте целыми числами. Для выхода: 666')
print(f'Вышло: на совсем') |
d={}
print('Welcome#')
print('Using this system you will becom a english pro')
while True:
print('=>')
print('1.Choose words')
print('2.list out all thw words')
print('3.English translate to Chinese')
print('4.Chinese tranlate to English')
print('5.Test skills that you learn')
print('6.leave system')
sel=input('please choose one sysem to use')
if sel=='1':
while True:
voc=input('please enter new word(press0 to go out')
if voc=='0':
break
if voc not in d:
m=input('please enter chinses translation')
d[voc]=m
else:
print('word already exist')
elif sel=='2':
lk=sorted(d)
for item in lk:
print(item,"is:",d[item])
elif sel=='3':
voc=input('search english word(press0 to go out):')
if voc=='0':
break
if voc in d:
print(d[voc])
else:
print('My dictionary does not have this word')
elif sel=='4':
got=False
ch=input('please enter chinses word')
if ch=='0':
break
for k,v in d.items():
if ch==v:
print(ch,'in english is',k)
got=True
if not got:
print("sorry we can't find it")
elif sel=='5':
score=0
print('the total scoreis',len(d),'points')
for k,v in d.items():
print(v,':')
ans=input()
if ans==k:
score+=1
print('correct! you got',score,'points now')
else:
print('wrong! you got',score,'points now')
elif sel=='6':
break
else:
print('enter wrongly , please retry!')
|
import time
def DrawBoard(board):
print(" %c | %c | %c " % (board[1],board[2],board[3]))
print("___|___|___")
print(" %c | %c | %c " % (board[4],board[5],board[6]))
print("___|___|___")
print(" %c | %c | %c " % (board[7],board[8],board[9]))
print(" | | ")
board=['0','1','2','3','4','5','6','7','8','9']
print("Hello Players...!!!")
time.sleep(1)
print("Welcome to TIC-TAC-TOE")
time.sleep(1)
print("Here is the board for you....")
time.sleep(2)
DrawBoard(board)
time.sleep(1)
print("Player 1: X")
print("Player 2: O")
t=1
while(t<=9):
if(t%2!=0):
print("Player 1's turn...")
ch=int(input("Where do you place your character???"))
board[ch]='X'
DrawBoard(board)
t=t+1
else:
print("Player 2's turn...")
ch=int(input("Where do you place your character???"))
board[ch]='O'
DrawBoard(board)
t=t+1
if((board[1]=='X' and board[2]=='X' and board[3]=='X')or(board[4]=='X' and board[5]=='X' and board[6]=='X')or (board[7]=='X' and board[8]=='X' and board[9]=='X') or (board[1]=='X' and board[5]=='X' and board[9]=='X') or (board[3]=='X' and board[5]=='X' and board[7]=='X') or (board[1]=='X' and board[4]=='X' and board[7]=='X') or (board[2]=='X' and board[5]=='X' and board[8]=='X') or (board[3]=='X' and board[6]=='X' and board[9]=='X')):
print("Player 1 Won!!!")
break
else:
if(t==10):
print("Game Draw...!!!")
break
if((board[1]=='O' and board[2]=='O' and board[3]=='O')or(board[4]=='O' and board[5]=='O' and board[6]=='O')or (board[7]=='O' and board[8]=='O' and board[9]=='O') or (board[1]=='O' and board[5]=='O' and board[9]=='O') or (board[3]=='O' and board[5]=='O' and board[7]=='O') or (board[1]=='O' and board[4]=='O' and board[7]=='O') or (board[2]=='O' and board[5]=='O' and board[8]=='O') or (board[3]=='O' and board[6]=='O' and board[9]=='O')):
print("Player 2 Won!!!")
break
else:
if(t==10):
print("Game Draw...!!!")
break
|
number = input('Enter a value: ')
alpha = [chr(i) for i in range(65, 91)]
alpha.extend([chr(i) for i in range(97, 123)])
n_list = list(number)
print(n_list)
flag_p = False
flag_n = False
flag = False
if number == '0':
print('Zero')
flag = True
elif '.' in n_list:
print('Float number')
flag = True
elif '+' in n_list:
for i in range(n_list.index('+')):
if n_list[i].isnumeric():
flag_p = True
else:
flag_p = False
break
if flag_p:
for i in range(n_list.index('+')+1, len(n_list)-1):
if n_list[i].isnumeric():
flag_p = True
else:
flag_p = False
break
if flag_p and n_list[-1] == 'j':
print('Complex number')
flag = True
elif '-' in n_list:
for i in range(n_list.index('-')):
if n_list[i].isnumeric():
flag_n = True
else:
flag_n = False
break
if flag_n:
for i in range(n_list.index('-')+1, len(n_list)-1):
if n_list[i].isnumeric():
flag_n = True
else:
flag_n = False
break
if flag_n and n_list[-1] == 'j':
print('Complex number')
flag = True
elif not flag_p and not flag_n and not flag:
for i in number:
if i in alpha:
flag = True
break
if flag:
print('String')
else:
print('Real number')
|
slices = int(input('Enter the number of slices you want: '))
price = 0
if slices%2 == 0:
price += slices*120.00
else:
price += slices*123.00
print('Number of slices: {}\nPrice you have to pay: {}'.format(slices, price))
|
"""
Задача 4.
Поработайте с обычным словарем и OrderedDict.
Выполните различные операции с каждым из объектов и сделайте замеры.
Опишите полученные результаты, сделайте выводы.
"""
from collections import OrderedDict
from timeit import repeat
my_dict = {str(i): i for i in range(100)}
my_order_dict = OrderedDict([(str(i), i) for i in range(100)])
def update_dict():
copy_dict = my_dict.copy()
for i, j in copy_dict.items():
copy_dict[i] = j**2
return copy_dict
def update_order_dict():
copy_dict = my_order_dict.copy()
for i, j in copy_dict.items():
copy_dict[i] = j**2
return copy_dict
print(update_dict())
print(update_order_dict())
print("get")
print(repeat("my_dict.get('1')", setup='from __main__ import my_dict', number=10000, repeat=5))
"""[0.0006315999999999995, 0.0006248999999999977, 0.0006238000000000007, 0.0006227000000000003, 0.0006849000000000022]"""
print(repeat("my_order_dict.get('1')", setup='from __main__ import my_order_dict', number=10000, repeat=5))
"""[0.0006303000000000038, 0.0006282000000000024, 0.0008408999999999986, 0.0006306999999999979, 0.0006287999999999988]"""
print("items")
print(repeat("my_dict.items()", setup='from __main__ import my_dict', number=10000, repeat=5))
"""[0.0009653999999999982, 0.0012143000000000015, 0.0015131999999999993, 0.0015037999999999996, 0.0013030000000000055]"""
print(repeat("my_order_dict.items()", setup='from __main__ import my_order_dict', number=10000, repeat=5))
"""[0.0007039999999999963, 0.0006909000000000012, 0.0011952000000000004, 0.0011907999999999988, 0.0013977000000000017]"""
print("values")
print(repeat("my_dict.values()", setup='from __main__ import my_dict', number=10000, repeat=5))
"""[0.0007114000000000009, 0.0007170999999999983, 0.000675000000000002, 0.0006943999999999978, 0.000701299999999995]"""
print(repeat("my_order_dict.values()", setup='from __main__ import my_order_dict', number=10000, repeat=5))
"""[0.0006569000000000019, 0.000697199999999995, 0.0006985999999999937, 0.0006786000000000014, 0.0006832999999999978]"""
print("keys")
print(repeat("my_dict.keys()", setup='from __main__ import my_dict', number=10000, repeat=5))
"""[0.0007390000000000035, 0.0006597999999999951, 0.0006578, 0.0006948999999999983, 0.0007269999999999985]"""
print(repeat("my_order_dict.keys()", setup='from __main__ import my_order_dict', number=10000, repeat=5))
"""[0.0006584999999999994, 0.0006593000000000016, 0.000801099999999999, 0.0009207999999999994, 0.0006564000000000014]"""
print("update")
print(repeat("update_dict()", setup='from __main__ import update_dict', number=10000, repeat=5))
"""[0.26224800000000004, 0.27520010000000006, 0.2762133, 0.26907859999999995, 0.2987994999999999]"""
print(repeat("update_order_dict()", setup='from __main__ import update_order_dict', number=10000, repeat=5))
"""[0.4131841999999999, 0.4339313, 0.4135192000000001, 0.3926227999999998, 0.38545430000000014]"""
"""
OrderedDict не впечатлил.
При выполнении стандартных функций get, items, values, keys примерно одинаковые с обычным словарем.
При выполнении обновления значений по ключу OrderedDict проиграл по времени обычному словарю.
OrderedDict вычеркнул из своего списка колекций для постоянного использования)
"""
|
"""
Задание 3 *.
Сделать профилировку для скриптов с рекурсией и сделать,
можно так профилировать и есть ли 'подводные камни'
"""
from memory_profiler import profile, memory_usage
from time import process_time
@profile
def sum_number(a):
if a == 1:
return 1
return a + sum_number(a-1)
print(sum_number(10))
"""
Как и ожидалось, подводные камни есть, profile срабатывает на каждый вызов функции в рекурсии.
Так профилировать нет смысла, т.к. нет общей картины работы функции.
Вероятно рекурсию стоит профилировать через срез времени и памяти, причем без помощи декоратора,
т.к. декоратор также будет вызываться по количеству вызовов рекурсии.
"""
t1 = process_time()
m1 = memory_usage()
print(sum_number(10))
t2 = process_time()
m2 = memory_usage()
print(f'Выполнение заняло {t2 - t1} сек и {m2[0] - m1[0]} MiB.')
|
"""
6. В программе генерируется случайное целое число от 0 до 100.
Пользователь должен его отгадать не более чем за 10 попыток. После каждой
неудачной попытки должно сообщаться больше или меньше введенное пользователем
число, чем то, что загадано. Если за 10 попыток число не отгадано,
то вывести загаданное число.
Решите через рекурсию. Решение через цикл не принимается.
Для оценки Отлично в этом блоке необходимо выполнить 5 заданий из 7
Для оценки Отлично в этом блоке необходимо выполнить 5 заданий из 7
"""
import random
print('Игра: Угадай число от 0 до 100!')
number = random.randint(0, 100)
count = 10
def game(a, b):
if a == 0:
return print(f'Проиграли! Загаданное число: {b}')
user_number = int(input(f'Осталось попыток - {a}. Введите число: '))
if b == user_number:
return print('Победа!!!')
elif b < user_number:
print(f'Ваше число больше загаданного')
return game(a - 1, b)
else:
print(f'Ваше число меньше загаданного')
return game(a - 1, b)
game(count, number)
|
Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:57:36) [MSC v.1900 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> tup = (1,2,3,4,5,6,7,10)
>>> tup = (1,2,3,4,5,6,7,10,'hi','hello')
>>> tup[0]
1
>>> tup[-1]
'hello'
>>> tup[0:5]
(1, 2, 3, 4, 5)
>>> tup[0] = 'Hi'
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
tup[0] = 'Hi'
TypeError: 'tuple' object does not support item assignment
>>>
|
import time # This is required to include time module.
from email.utils import localtime
import calendar # This is required to include calendar module
from _datetime import datetime
import datetime
# The function time.time() returns the current system time in ticks since 12:00am, January 1, 1970(epoch).
ticks = time.time()
print(ticks)
# Get current time
cur_time = time.localtime(time.time())
print("Current time is ",cur_time)
# Time and date with format
format_time = time.asctime(time.localtime(time.time()))
print("Formatted time ",format_time)
# Getting calendar of a month
cal = calendar.month(2017,2)
print(cal)
cal = calendar.isleap(2016)
print(cal)
|
#a = 17
a = int(input("Enter the number : "))
if a % 2 == 0:
print("{} is even".format(a))
else:
print("%d is odd"%(a))
|
# Internationalization - I18N
userName = input("क्या नाम ह आपका : ")
userAge = input("कृपया अपनी उम्र बताये : ")
print("Hello",userName)
print("Your age is",userAge) |
km = int(input("Digite a velocidade atual do seu carro:"))
if km > 110:
calc = km - 110
multa = calc * 5
print("Você foi multado e terá que pagar %.2f reais." %multa)
|
import turtle_square_using_function;
your_input = 300;
if(your_input>0):
turtle_square_using_function.square();
else:
print("number : "+ str(your_input))
|
# https://leetcode.com/problems/populating-next-right-pointers-in-each-node/
import collections
def connect(root):
levels = []
next_level = [root]
while len(next_level):
levels.append(next_level)
new_next_level = []
for node in next_level:
if node.left is not None:
new_next_level.append(node.left)
if node.right is not None:
new_next_level.append(node.right)
next_level = new_next_level
for level in levels:
for i in range(len(level)):
curr_node = level[i]
right_node = level[i+1] if i+1 < len(level) else None
curr_node.next = right_node
return levels
class Node:
def __init__(self, val=None, left=None, right=None, next=None):
self.val = val
self.left = left
self.right = right
self.next = next
def print_levels(levels):
for level in levels:
for node in level:
print(node.val)
print(node.left.val) if node.left is not None else print(None)
print(node.right.val) if node.right is not None else print(None)
print(node.next.val) if node.next is not None else print(None)
print("-----------")
seven = Node(7)
six = Node(6)
five = Node(5)
four = Node(4)
three = Node(3, six, seven)
two = Node(2, four, five)
one = Node(1, two, three)
# result = connect(one)
# print_levels(result)
|
# Because the file name starts with a number, normal from ... import ... is not
# working. So the following are two ways to get around that:
# importlib (recommended)
# ref -> https://docs.python.org/3/library/importlib.html#importlib.import_module
import importlib
zero = importlib.import_module('0')
SinglyListNode = zero.SinglyListNode
print_list = zero.print_list
# __import__ (not recommended)
# ref -> https://docs.python.org/3/library/functions.html#__import__
# zero = __import__('0')
# SinglyListNode = zero.SinglyListNode
# print_list = zero.print_list
# Either of the above two ways creates that __pycache__ folder
# Merge two sorted lists
# Prompt:
# Merge two sorted linked list, with nodes carring integer values as data, in
# ascending order
# Example:
# l1 -> 2 -> 5 -> 7
# l2 -> 3 -> 11
# rl -> 2 -> 3 -> 5 -> 7 -> 11
def merge_two_sorted_lists_epi(l1, l2):
dummy_head = tail = SinglyListNode() # declarating two variables at the same time pointing to the same object node
# dummy_head created to have a reference of the head to be returned later
# tail will act as the frontier pointer
while l1 and l2:
# the smaller of the two will be added
if l1.data < l2.data:
tail.next, l1 = l1, l1.next
else:
tail.next, l2 = l2, l2.next
tail = tail.next # tail gets updated in preparation of the next iteration
tail.next = l1 or l2 # add whatever remained from either l1 or l2 at the end
return dummy_head.next # next of the dummy head is the start of the actual list
# seven = SinglyListNode(7)
# five = SinglyListNode(5, seven)
# two = SinglyListNode(2, five)
# print_list(two)
# print("-----")
# eleven = SinglyListNode(11)
# three = SinglyListNode(3, eleven)
# print_list(three)
# print("-----")
# merged_ll = merge_two_sorted_lists_epi(two, three)
# print_list(merged_ll)
# def merge_two_sorted_lists (l1, l2):
# head = l1
# l1_curr_node = l1
# l2_curr_node = l2
# while l1_curr_node.next: # this will not work if l1 had a larger head than l2
# l1_next_node = l1_curr_node.next
# if l1_curr_node.data <= l2_curr_node.data <= l1_next_node.data:
# l1_curr_node.next, l2_curr_node.next, l2_curr_node = l2_curr_node, l1_next_node, l2_curr_node.next
# l1_curr_node = l1_next_node
# if l1_curr_node.next != l2_curr_node:
# l1_curr_node.next = l2_curr_node
# return head |
# Specification:
# Create a class LeaderBoard whose interface includes the following methods:
# Method Name: add_score
# - Add a new score to the player's average. If a player doesn't exist in the
# LeaderBoard, they will be automatically added.
# Args:
# player_id(Integer): The player's ID.
# score(Integer): The score to record for the player
# Returns:
# Double: The new average score for the given player
# Method Name: top
# - Get the top player_ids on the leaderboard ordered by their average scores
# from highest to lowest
# Args:
# num_players(Integer): The maximum number of player_ids to return
# Returns:
# List < Integer >: a list of player_ids
# Method Name: reset
# - Removes any scoring information for a player, effectively
# resetting them to 0
# Args:
# player_id(Integer): The player's ID.
# Example Usage:
# Create a new LeaderBoard Instance
# leader_board = LeaderBoard()
# Add scores for players to the LeaderBoard
# leader_board.add_score(1, 50) # => 50.0
# leader_board.add_score(2, 80) # => 80.0
# leader_board.add_score(2, 70) # => 75.0
# leader_board.add_score(2, 60) # => 70.0
# leader_board.add_score(3, 90) # => 90.0
# leader_board.add_score(3, 85) # => 87.5
# Get top positions for the leaderboard
# leader_board.top(3) # => [3, 2, 1]
# leader_board.top(2) # => [3, 2]
# leader_board.top(1) # => [3]
# Reset a player 3's scores
# leader_board.reset(3) # => void
# Player 3 is now at the bottom of the leaderboard
# leader_board.top(3) # => [2, 1, 3]
# Expected values
# Player IDs will always be positive integers small enough to be
# stored as a signed 32-bit integer Scores are integers ranging from 0-100
# We have provided stubbed out code and tests for you below. Please note that these tests are not exhaustive and do not cover all corner cases. We recommend extending the given tests to ensure your code is correct.
# Your code goes here. Feel free to make helper classes if needed
import heapq
import collections
import datetime
class LeaderBoard:
_student = collections.namedtuple("student", ("score", "player_id"))
_score = collections.namedtuple("score", ("value", "expiration", "rival_id"))
def __init__(self):
self._student_dict = {}
def add_score(self, player_id, score, expiration, rival_id): # O(1)
if expiration <= self.todays_date() and rival_id is not player_id:
if player_id in self._student_dict:
self._student_dict[player_id].append(self._score(score, expiration, rival_id))
else:
self._student_dict[player_id] = [self._score(score, expiration, rival_id)]
return self.avg_within_expiration(player_id)
else:
raise ValueError("Either the score expired or the rival_id is equal to player_id")
def avg_within_expiration(self, player_id):
self.cleanup_expired(player_id)
sum = 0
for score in self._student_dict[player_id]:
sum += score.value
return sum / len(self._student_dict[player_id])
def cleanup_expired(self, player_id):
print(self._student_dict)
print(player_id)
print(self._student_dict[player_id])
scores = self._student_dict[player_id]
current_date = self.todays_date()
self._student_dict[player_id] = [score for score in scores if current_date <= score.expiration]
def todays_date(self):
return datetime.date.today()
def rivals(self, player_id):
self.cleanup_expired(player_id)
return [score.rival_id for score in self._student_dict[player_id]]
def reset(self, player_id):
if player_id in self._student_dict:
self._student_dict[player_id] = []
else:
raise NameError("Player does not exist!")
def top(self, k):
return self._kth_elements(k, "top")
def bottom(self, k):
return self._kth_elements(k, "bottom")
def _kth_elements(self, k, order):
student_heap = []
i = 0
for player_id in self._student_dict:
# if i <= len(self._student_dict):
if order == "top":
heapq.heappush(student_heap, self._student(self._student_dict[player_id], player_id))
else:
heapq.heappush(student_heap, self._student(-self._student_dict[player_id], player_id))
i += 1
if i > k:
heapq.heappop(student_heap)
return [student.player_id for student in heapq.nlargest(k, student_heap)]
# def top(self, k): # Time: O(nlogk) ; Space: O(k)
# student_heap = []
# i = 0
# for player_id in self._student_dict:
# if i <= len(self._student_dict):
# heapq.heappush(student_heap, self._student(self._student_dict[player_id], player_id))
# i += 1
# if i > k:
# heapq.heappop(student_heap)
# return [student.player_id for student in heapq.nlargest(k, student_heap)]
# def bottom(self, k):
# student_heap = []
# i = 0
# for player_id in self._student_dict:
# if i <= len(self._student_dict):
# heapq.heappush(student_heap, self._student(-self._student_dict[player_id], player_id))
# i += 1
# if i > k:
# heapq.heappop(student_heap)
# return [student.player_id for student in heapq.nlargest(k, student_heap)]
leader_board = LeaderBoard()
print(leader_board.add_score(1, 50, datetime.date.today(), 4)) # 50.0
# print(leader_board.add_score(2, 80, datetime.date(2019, 8, 23), 5)) # 80.0
print(leader_board.add_score(2, 70, datetime.date(2020, 11, 12), 2)) # 75.0
print(leader_board.add_score(2, 60, datetime.date(2020, 12, 7), 3)) # 70.0
# print(leader_board.add_score(3, 90, datetime.date(2021, 3, 21))) # 90.0
# print(leader_board.add_score(3, 85, datetime.date(2019, 9, 4))) # 87.5
# print(leader_board.add_score(4, 50)) # 50
# print(leader_board.add_score(5, 60)) # 60
# print(leader_board.add_score(5, 70)) # 65.5
print("------------------")
print(leader_board.top(3)) # [3, 2, 1]
print(leader_board.top(1)) # [3]
print(leader_board.top(2)) # [3, 2]
print("------------------")
# print(leader_board._student_dict)
# print(leader_board.kth_elements(3, "bottom"))
# print(leader_board.kth_elements(1, "bottom"))
# print(leader_board.kth_elements(2, "bottom"))
# print(leader_board.kth_elements(6, "bottom"))
# print(leader_board.reset(3))
# print(leader_board.top(3)) # [2, 1, 3]
# def bottom will return bottom k
# write some test
|
# Compute the intersection of two sorted arrays
# Prompt
# Takes two sorted arrays and returns a new array containing elements that are present in both of the input arrays.
# The input arrays may have duplicate entries, but the returned array should be free of duplicates.
# Example
# Input -> [2,3,3,5,5,6,7,7,8,12], [5,5,6,8,8,9,10,10]
# Output -> [5,6,8]
# Time: O(m), m is the largest length of the two input arrays
# Space: O(k), k is the minimum length of the two input arrays; worst case every element is unique
def intersect_two_sorted_arrays(l1, l2):
i, j, intersection = 0, 0, []
while i < len(l1) and j < len(l2):
if l1[i] == l2[j] and (l1[i] != l1[i-1] or l2[j] != l2[j-1]):
intersection.append(l1[i])
i, j = i+1, j+1
elif l1[i] < l2[j]:
i += 1
else:
j += 1
return intersection
# print(intersect_two_sorted_arrays(
# [2, 3, 3, 5, 5, 6, 7, 7, 8, 12],
# [5, 5, 6, 8, 8, 9, 10, 10]
# ))
|
import importlib
zero = importlib.import_module('0')
BinaryTree = zero.BinaryTree
traversal = zero.traversal
# Reconstruct a binary tree from traversal data
# Prompt:
# Given an inorder and preorder traversal sequence of a binary tree write a program to reconstruct the tree.
# Assume each node has a unique key
def binary_tree_from_preorder_inorder(inorder, preorder):
# Time: O(n^2) because for every stack for n, it does n work for filteration (worst case if the tree is skewed, left or right sub tree could be just n-1 per stack)
# Space: O(hn) because at any point the highest call stack is h and for every stack we create an array of n (worst case if the tree is skewed, left or right sub tree could be just n-1 per stack)
if not preorder and not inorder:
return None
root = preorder[0]
root_idx_inorder = inorder.index(root)
left_sub_inorder, right_sub_inorder = inorder[:root_idx_inorder], inorder[root_idx_inorder+1:]
left_sub_preorder = [node for node in preorder if node in left_sub_inorder]
right_sub_preorder = [node for node in preorder if node in right_sub_inorder]
left_node = binary_tree_from_preorder_inorder(left_sub_inorder, left_sub_preorder)
right_node = binary_tree_from_preorder_inorder(right_sub_inorder, right_sub_preorder)
curr_node = BinaryTree(root)
curr_node.left = left_node
curr_node.right = right_node
return curr_node
H = BinaryTree("H")
B = BinaryTree("B")
C = BinaryTree("C")
F = BinaryTree("F")
E = BinaryTree("E")
A = BinaryTree("A")
C = BinaryTree("C")
D = BinaryTree("D")
G = BinaryTree("G")
I = BinaryTree("I")
H.left = B
B.left = F
B.right = E
E.left = A
H.right = C
C.right = D
D.right = G
G.left = I
# inorder = traversal(H, "in")
# preorder = traversal(H, "pre")
# print(inorder)
# print(preorder)
# print("-----------------")
# tree = binary_tree_from_preorder_inorder(
# ['F', 'B', 'A', 'E', 'H', 'C', 'D', 'I', 'G'],
# ['H', 'B', 'F', 'E', 'A', 'C', 'D', 'G', 'I']
# )
# print(traversal(tree, "in", []))
# print(traversal(tree, "pre", []))
# Time: O(n)
# Space: O(n + h) = O(n) ; n comes from the hash map and h comes from the stacks
def binary_tree_from_preorder_inorder_epi(preorder, inorder):
# data pointing to inorder index
# first variable for an enumerate function stores the index position
node_to_inorder_idx = {data: i for i, data in enumerate(inorder)}
def binary_tree_from_preorder_inorder_helper(preorder_start, preorder_end, inorder_start, inorder_end):
# as the range between start and end becomes equal, there is no valid exclusive range
if preorder_end <= preorder_start or inorder_end <= inorder_start:
return None
root_inorder_idx = node_to_inorder_idx[preorder[preorder_start]]
left_subtree_size = root_inorder_idx - inorder_start
# if indexing started with 1, and the root's index was at 5, then the size is 4
# when indexing starts at 0, and the root's index is at 4, the size is still 4
return (
BinaryTree(
preorder[preorder_start], # current node
# all ranges bellow maintains max exclusivity
binary_tree_from_preorder_inorder_helper( # left node
# preorder_start moves by one because each node at first index is current stack's root
(preorder_start + 1), (preorder_start + 1 + left_subtree_size),
# start always stays at zerothe new root index becomes the exclusive max for the next left subtree, while
inorder_start, root_inorder_idx
),
binary_tree_from_preorder_inorder_helper( # right node
# for right side, for both preorder and inorder end's at the length which is already one more than the last index value
(preorder_start + 1 + left_subtree_size), preorder_end,
(root_inorder_idx + 1), inorder_end
)
)
)
return binary_tree_from_preorder_inorder_helper(0, len(preorder), 0, len(inorder))
|
# Binary - at most 2 children
# full - 0 or all children at every node
# perfect - all leafs at same level
# complete - all levels expect the bottom are filled with max number of childrens
# AND bottom level should be filled left to right
# Tree - no cycles
# Balanced - difference between height of left and right subtree is <= 1 AND left subtree is balanced
# AND right subtree is balanced
# Relationship between n, number of nodes and h, height of binary tree:
# height from nodes:
# -> maximum possible height => h : n - 1
# 4 - h : 0
# \
# 3 - h : 1
# \
# 2 - h : 2
# \
# 1 - h : 3
# -> minimum possible height => h : log2n
# at every depth, we have twice the amount of n
# -> nodes from height:
# -> minimum n : h + 1
# for the first edge, there are two nodes at each end. Then after for every edge, there is a node at the end
# -> maximum n : (2^(h+1)) - 1
# ref -> https://www.quora.com/What-is-the-maximum-number-of-nodes-in-a-binary-tree-Is-it-2-h-1-or-2-h+1-1/answer/Amit-Jaiswal-452
# ref -> https://www.geeksforgeeks.org/relationship-number-nodes-height-binary-tree/
# Full binary tree - the number of nonleaf nodes in a full binary tree is one less than the number of leaves.
# Perfect binary tree - contains exactly (2^(h+1)) - 1 nodes, of which 2^h are leaves
# Complete binary tree - has a height of log2n for n nodes
# Two types of skewed binary tree:
# left-skewed binary tree - no right child
# right-skewed binary tree - no left child
# Traversel
# Inorder - left -> root -> right
# Preorder - root -> left -> right
# Postorder - left -> right -> root
# Recursive implementation : O(n) time and O(h) space for the depth of call stack
# If each node has a parent attribute : O(n) and O(1) space iteratively
class BinaryTree:
def __init__(self, data=None):
self.data = data
self.left = self.right = self.parent = None
def traversal_epi(root, order):
# comment back in the specific traversel line that is in need
if root:
if order == "pre":
print("Preorder: %d" % root.data)
traversal_epi(root.left, order)
if order == "in":
print("Inorder: %d" % root.data)
traversal_epi(root.right, order)
if order == "post":
print("Postorder: %d" % root.data)
def traversal(head, order, path =[]):
if not head:
# for the case of right, if there is no head but a path was passed on from left, that path needs to be passed back for parent to be added later
if path:
return path
else:
return []
if order == "pre":
path += [head.data]
left_added_path = traversal(head.left, order, path)
if order == "in":
left_added_path += [head.data]
right_added_path = traversal(head.right, order, left_added_path)
if order == "post":
right_added_path += [head.data]
return right_added_path
# Figure: 9.5 ; page: 136
H = BinaryTree("H")
B = BinaryTree("B")
C = BinaryTree("C")
F = BinaryTree("F")
E = BinaryTree("E")
A = BinaryTree("A")
C = BinaryTree("C")
D = BinaryTree("D")
G = BinaryTree("G")
I = BinaryTree("I")
H.left = B
B.left = F
B.right = E
E.left = A
H.right = C
C.right = D
D.right = G
G.left = I
# inorder = traversal(H, "in")
# print(inorder)
# preorder = traversal(H, "pre")
# print(preorder)
|
# Buy and sell a stock once
# Prompt:
# An algorithm that determines the maximum profit that could have been made by
# buying and then selling a single share over a given day range, subject to the
# constraint that the buy and the sell have to take plae at the start of the day
# Example:
# [310, 315, 275, 295, 260, 270, 290, 230, 255, 250]
# => maximum profit is 30 with one buy at 260 and one sell at 290
def buy_and_sell_stock_once(prices):
max = float("-inf")
min = float("inf")
profit = 0
for i in reversed(range(len(prices))):
curr_profit = 0 # default value for every iteration
if prices[i] > max: # if a larger max is found
max = prices[i]
min = float("inf") # refresh the min in respect to the new max, in order to avoid making a curr_profit calculation with a previous min
elif prices[i] < min: # if a lower min is found
min = prices[i]
curr_profit = max - min # a new curr_profit can be calculated once a min is found
if curr_profit > profit: # Only if the curr_profit is larger than current global profit, update the profit
profit = curr_profit
return profit
prices_1 = [310, 315, 275, 295, 260, 270, 290, 230, 255, 250]
# print(buy_and_sell_stock_once(prices_1)) # => 30
def buy_and_sell_stock_once_epi(prices):
curr_min, profit = float("inf"), 0.0
for price in prices:
curr_profit = price - curr_min
profit = max(curr_profit, profit)
curr_min = min(price, curr_min)
return profit
prices_epi = [310, 315, 275, 295, 260, 270, 290, 230, 255, 250]
print(buy_and_sell_stock_once_epi(prices_epi)) # => 30
# The maximum profit that can be made by selling on each specific day is the
# difference of the current price and the minimum seen so far
# prices => [310, 315, 275, 295, 260, 270, 290, 230, 255, 250]
# curr_min => [310, 310, 275, 275, 260, 260, 260, 230, 230, 230]
# curr_profit => [ 0, 5, 0, 20, 0, 10, 30, 0, 25, 20]
# profit => ^
|
# Generate all nonattacking placements of n-Queens
# Background: A nonattacking placement of queens is one in which no two queens are in the same row, column, or diagonal
# Prompt: A program that returns all distinct nonattacking placements of n queens on an n x n chessboard, where n is an input
# Time Complexity:
# Brute force - O(n ^ n) time complexity. This means it will look through every position on an NxN board, N times, for N queens.
# Refactored brute force - Prevent it from checking queens occupying the same row as each other, it will still be brute force, but the possible board states drop from 16, 777, 216 to a little over 40, 000 and has a time complexity of O(n!).
# Backtracking - This is over 100 times as fast as brute force and has a time complexity of O(2^n).
# ref -> https://medium.com/@jmohon1986/timeout-the-story-of-n-queens-time-complexity-c80636d92f8b
def n_queens(n):
def solve_n_queens(row):
if row == n: # base case
result.append(list(col_placement))
# result.append(col_placement) will append the reference to col_placement created at line 37. So if col_placement is changed for a new tree route, the old insertion also changes
# result.append(list(col_placement)) creates a copy, so doesn't pass the reference and thus previous records will not get affected by future manipulation of col_placement
return
for col in range(n):
if all(
abs(c - col) not in (0, row - i)
for i, c in enumerate(col_placement[:row])
# checking previous queen placement:
# c - previous columns
# i - previous rows
# possible queen placement:
# col - current column ; iterates through all per row
# row - current row ; updates every call stack
# abs(c - col) not in (0, row - i):
# Same row detection - if the abs(c - col) is 0, that means a queen exist in c and it is the same column as col because the difference between the two is 0
# Diagonal detection - if the abs(c - col) / Δx is a value that is the same as row - i / Δy, that means a queen exist at (c, i) and the current (col, row) is at a diagonal
# col c c col
# [ -, -, -, q] i [q, _, _, _] i
# [ -, -, -, -] [-, -, -, -]
# [ -, -, -, -] [-, -, ?, -] row
# [ ?, -, -, -] row [_, -, -, -]
):
col_placement[row] = col
solve_n_queens(row + 1)
result, col_placement = [], [0] * n
# col_placement of [1, 3, 0, 2], means a queen exist in column 1 - row 0, column 3 - row 1, column 0 - row 2, column 2 - row 3
# the values in col_placement indicates the column number and the index represents the corresponding row
solve_n_queens(0)
return result
print(n_queens(4)) # => [[1, 3, 0, 2], [2, 0, 3, 1]]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.