text stringlengths 37 1.41M |
|---|
#using python 3.6.4
import datetime
#import calendar
def last_day_of_month(any_day):
next_month = any_day.replace(day=28) + datetime.timedelta(days=4) # this will never fail
return next_month - datetime.timedelta(days=next_month.day)
CurrentDate = datetime.date.today()
print("Η σημερινη ημερομηνια ειναι: " + str(CurrentDate))
CurrentYear = CurrentDate.year
CurrentMonth = CurrentDate.month
CurrentDay = CurrentDate.day
CurrentWeekday=CurrentDate.weekday()
NumberOfDays=0
#A for loop in which 'y' are the years 'm' are the months and 'd' are the days
for y in range(CurrentYear + 1,CurrentYear + 11):
#Get the maximum days of the months.calendar.monthrange(year,month)tupple(month,day)
#maxdaystupple = calendar.monthrange(y,CurrentMonth)
maxdays = last_day_of_month(datetime.date(y,CurrentMonth,1)).day
#maxdays = maxdaystupple[1]
for d in range(1,maxdays + 1):
#an h hmera ths CurrentWeekday (Opou pairnei times apo 0-6 me MONDAY=0) einai idia me thn hmera calendar.weekday(y,CurrentMonth,d)
#kai h CurrentDay einai idia me d opou d einai h hmera tou mhna me times apo 1-31 tote auxise tis zitoumenes meres kata 1
if datetime.date(y,CurrentMonth,d).weekday()==CurrentWeekday and CurrentDay==d:
NumberOfDays+=1
print(NumberOfDays)
print("Τα επόμενα 10 χρόνια θα υπαρχουν "+str(NumberOfDays)+" μερες που θα είναι " + str(CurrentDay)+"ες του τωρινου μηνα!")
|
# Generators
def generator_func(num):
for i in range(num):
# after yielding i, it pauses and remembers the last yield
yield i
g = generator_func(10)
# when next(g) is called, the generator_func will pick up from last yield and yields next value until it reaches the last index of range
# when the end is reached, StopIteration error occurs.
# The range() function is a generator and when the range ends, the for loop detects the StopIteration error and stops the loop accordingly. This functionality is hidden away under the hood of for loop
next(g) # 0
next(g) # 1
print(next(g)) # 2
# ============================================================
# Print Fibonacci sequence upto n number
# using generator function ( uses less memory as the numbers are yeilded one by one. Only one number is stored in the memory at a time.)
def fib(num):
a = 0
b = 1
for i in range(num):
yield a
temp = a
a = b
b = temp + a
for x in fib(20):
print(x)
# =============================================================
# using list (uses more memory as all the output numbers are stored in memory)
def fib2(num):
a = 0
b = 1
result = []
for i in range(num):
result.append(a)
temp = a
a = b
b = temp + a
return result
# [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181]
print(fib2(20))
# ===============================================================
|
from functools import reduce
# 1. Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5, between 2000 and 3200 (both included).The numbers obtained should be printed in a comma-separated sequence on a single line.
def find_divisible_by_7(start_num, end_num):
# no particular reason to use set here
my_set = set()
for num in range(start_num, end_num + 1):
if num % 7 == 0 and num % 5 != 0:
my_set.add(num)
return print(my_set)
find_divisible_by_7(1, 70)
# using lambda expression
print(list(filter(lambda item: item % 7 == 0 and item % 5 != 0, list(range(1, 70)))))
# another solution
for i in range(1, 70):
if i % 7 == 0 and i % 5 != 0:
print(i, end=',')
print("\b") # for ending the prompt in a new line
# =====================================================================
# 2. Write a program which can compute the factorial of a given numbers.The results should be printed in a comma-separated sequence on a single line. Suppose the following input is supplied to the program: 8 Then, the output should be: 40320
def find_factorial(n):
temp = 1
for i in range(1, n+1):
temp *= i
return print(temp)
find_factorial(8)
# using lambda expression
print(reduce(lambda acc, item: acc * item, list(range(1, 9))))
# using recursion
n = int(input())
def fact(x): return 1 if x <= 1 else x*fact(x-1)
print(fact(n))
# ==========================================================================
# 3. With a given integral number n, write a program to generate a dictionary that contains (i, i * i) such that is an integral number between 1 and n (both included). and then the program should print the dictionary.Suppose the following input is supplied to the program: 8
# Then, the output should be:
# {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}
# using comprehensions
my_dict = {item: item * item for item in list(range(1, 10))}
print(my_dict)
# ==========================================================================
# 4. Write a program which accepts a sequence of comma-separated numbers from console and generate a list and a tuple which contains every number.Suppose the following input is supplied to the program:
# 34, 67, 55, 33, 12, 98
# Then, the output should be:
# ['34', '67', '55', '33', '12', '98']
# ('34', '67', '55', '33', '12', '98')
def some_func(*args):
print(str(args))
print(list(args))
some_func(1, 2, 3)
# ====================================================================================
# 5 Define a class which has at least two methods:
# getString: to get a string from console input
# printString: to print the string in upper case.
class some_class:
def __init__(self):
pass
def getString(self):
self.user_name = input('Enter your name: ')
def printString(self):
return print(self.user_name.upper())
obj = some_class() # makes a new object using some_class()
# help(obj)
obj.getString()
obj.printString()
# ================================================================================ |
""" Initialize data structures """
CFG = {} # Context Free Grammar
CYK = [] # CYK Matrix
""" Auxiliar Methods """
def print_matrix( cyk ):
""" Print current state of the Matrix """
for row in cyk:
print row
print "=" * 20
def populate_matrix( cyk, w ):
""" Initialize Matrix """
for i in range( len(w) ):
cyk.append( ["0"] * len(w) )
def print_grammar( cfg ):
""" Visualize the Grammar defined by the user """
print "==========\n"
for k in cfg.keys():
print k + " -> " + "|".join (cfg[k] )
print "\n========= ="
def in_grammar( letter ):
""" Check whether the letter can be obtained by a non terminal symbol """
temp = []
for k in CFG.keys():
if letter in CFG[k]:
temp.append(k)
return temp
def cyk_algorithm_step1( word, cyk ):
""" Check each character of the string if it can be produced by the CFG """
i = j = 0
for c in word:
non_term_symbols = in_grammar(c)
if non_term_symbols:
cyk[i][j] = non_term_symbols
else:
cyk[i][j] = []
i, j = i + 1, j + 1
def cyk_algorithm( word, cyk ):
cyk_algorithm_step1( word, cyk )
# Iterate over matrix
tempList = []
for k in range(1, len(word) ):
print_matrix( cyk )
i = j = 0
tempList = []
while j < len(word) - 1:
if j + 1 == len(word) - 1:
tempList = []
if j == k + i:
i += 1
j = i
for m in cyk[i][j]:
for n in cyk[j + 1][k + i]:
posible_symbols = in_grammar( m + n )
#print "Ps: "
#print posible_symbols
tempList = list( set(tempList) | set(posible_symbols) )
#print "temp: "
#print tempList
#print "insert cyk"
if posible_symbols:
cyk[i][k + i] = tempList
j += 1
""" Main """
n = raw_input("Insert number of Non-terminal Symbols of the CFG: ")
print
for i in range ( int(n) ):
print "---Symbol %s---\n" % str(i + 1)
x = raw_input('Insert Initial symbol ( >[X]< -> Y ): ')
y = raw_input('\nInsert the productions of that symbol ( X -> >[Y1]|[Y2]< ): ')
y.replace(" ", "")
CFG[x] = y.split("|")
print_grammar( CFG )
word = raw_input("Insert string to verify whether it belongs to the CFG: ")
populate_matrix( CYK, word )
cyk_algorithm( word, CYK )
print_matrix( CYK )
|
#!/usr/bin/env python3
#
import sys
import time
_description_ = """
Import time and sleep for one second to provide a countdown.
Use for loop. Call a function to to print the countdown.
"""
_author_ = """Ian Stewart - December 2016
Hamilton Python User Group - https://hampug.pythonanywhere.com
CC0 https://creativecommons.org/publicdomain/zero/1.0/ """
# Program: snip_l2_03_c.py
print("Program {} has started...".format(sys.argv[0]))
def print_function(counter):
"Print the countdown."
if counter == 0:
print("\t...we have liftoff...")
return
print("\t{} seconds to go...".format(counter))
# reversed(range(6)) will produce countdown values from 5 down to 0
for countdown in reversed(range(6)):
print_function(countdown)
time.sleep(1)
print("End of program.")
input("Press Enter key to end program")
sys.exit()
"""
To check code style:
Linux...
$ python3 -m pep8 --statistic --ignore=E701 snip_l2_03_c.py
Install pep8 on Linux: $ sudo apt-get install python3-pep8
Windows...
> python -m pep8 --statistic --ignore=E701 snip_l2_03_c.py
Install pep8 on Windows: >pip3 install pep8
More information: https://www.python.org/dev/peps/pep-0008/
"""
|
#!/usr/bin/env python3
#
print("The window creation has been appended to configure a red background")
import tkinter
tkinter.Tk().configure(background="red")
# Add the following delay mechanism, so the Tk Window can be observed...
input("Hit Return key to exit")
"""
The tkinter.Tk() to launch a window is appended with the code configure the
backgournd of the Window to be a red colour.
Note: Obtaining other key words to the configure() function:
>>> print(tkinter.Tk().configure().keys())
dict_keys(['screen', 'relief', 'height', 'background', 'padx', 'class',
'pady', 'bg', 'use', 'menu', 'takefocus', 'container', 'highlightbackground',
'highlightcolor', 'borderwidth', 'highlightthickness', 'bd', 'cursor',
'width', 'visual', 'colormap'])
Author: Ian Stewart.
Date: 2016 July
This script is licensed CC0 https://creativecommons.org/publicdomain/zero/1.0/
1 2 3 4 5 6 7 7
1234567890123456789012345678901234567890123456789012345678901234567890123456789
"""
|
#!/usr/bin/env python3
#
import sys
import math
_description_ = """
Locate prime numbers. Use recursive division up to the square root of
the integer being tested for being a prime
int(math.sqrt(integer_under_test))
Provide statistics and better listing.
"""
_author_ = """Ian Stewart - December 2016
Hamilton Python User Group - https://hampug.pythonanywhere.com
CC0 https://creativecommons.org/publicdomain/zero/1.0/ """
# Program: snip_l2_21_b.py
start_prompt = 0
range_prompt = 100
prime_list = []
start_integer = input("Input start integer [{}]: ".format(start_prompt))
if start_integer == "":
start_integer = start_prompt
try:
start_integer = int(start_integer)
except:
print("Invalid start integer: {}. Exiting".format(start_integer))
sys.exit()
range_integer = input("Input range [{}]: ".format(range_prompt))
if range_integer == "":
range_integer = range_prompt
try:
range_integer = int(range_integer)
except:
print("Invalid range integer: {}. Exiting".format(range_integer))
sys.exit()
for i in range(start_integer, start_integer + range_integer + 1):
max_value = int(math.sqrt(i))
is_prime = True
for j in range(2, max_value + 1):
if i % j == 0:
is_prime = False
break
else:
continue
if is_prime is True:
prime_list.append(i)
print("\n{} prime numbers in the range {} to {}, as follows..."
.format(len(prime_list), start_integer, start_integer + range_integer))
for prime in prime_list:
print("{: >20}".format(prime))
sum_of_prime = 0
for prime in prime_list:
sum_of_prime = sum_of_prime + prime
print("The sum of the prime numbers is: {}".format(sum_of_prime))
input("Press Enter key to end program")
sys.exit()
"""
To check code style:
Linux...
$ python3 -m pep8 --statistic --ignore=E701 snip_l2_21_b.py
Install pep8 on Linux: $ sudo apt-get install python3-pep8
Windows...
> python -m pep8 --statistic --ignore=E701 snip_l2_21_b.py
Install pep8 on Windows: >pip3 install pep8
More information: https://www.python.org/dev/peps/pep-0008/
"""
|
#!/usr/bin/env python3
#
import sys
_description_ = """
Use input () function to get data from the User at the command line.
Use while True loop to ensure data is entered or data is of the desired
type.
"""
_author_ = """Ian Stewart - December 2016
Hamilton Python User Group - https://hampug.pythonanywhere.com
CC0 https://creativecommons.org/publicdomain/zero/1.0/ """
# Program: snip_l2_05_a.py
print("Program {} has started...".format(sys.argv[0]))
# Input a string or hit return for the prompted colour of "Blue".
data = input("\nEnter your favourite colour [Blue]: ")
if data == "":
data = "Blue"
print("Favourite colour is: {}".format(data))
# Input a string. If nothing is input then repeat the input query.
while True:
data = input("\nEnter your name: ")
if data == "":
print("No data was entered. Please re-enter...")
continue
else:
break
print("Your name is: {}".format(data))
# Input a numeric string. Try converting the string to a float. If it won't
# convert to a float, then repeat the input query.
while True:
data = input("\nInput a numeric value [1.0]: ")
if data == "":
data = 1.0
try:
data = float(data)
break
except ValueError as e:
print("Value Error: {}".format(e))
print("Please re-enter...")
continue
print("Valid data entered. Value: {}".format(data))
print("End of program.")
input("Press Enter key to end program")
sys.exit()
"""
To check code style:
Linux...
$ python3 -m pep8 --statistic --ignore=E701 snip_l2_05_a.py
Install pep8 on Linux: $ sudo apt-get install python3-pep8
Windows...
> python -m pep8 --statistic --ignore=E701 snip_l2_05_a.py
Install pep8 on Windows: >pip3 install pep8
More information: https://www.python.org/dev/peps/pep-0008/
"""
|
# RADIUS = 10
import math
def input_radius():
"""Get User input from the console."""
radius = input("Enter the radius of the circle: ")
return float(radius)
def calculate_circle_area(radius):
"""Supplied with the radius, calculate the area of a circle."""
area = math.pi * radius ** 2
return area
if __name__ == "__main__":
"""Launch circle program."""
radius = input_radius()
circle_area = calculate_circle_area(radius)
print(circle_area)
|
#!/usr/bin/env python3
#
from tkinter import *
from tkinter import ttk
class MainWindow(ttk.Frame):
"""Create the main window"""
def __init__(self, parent):
ttk.Frame.__init__(self, parent)
self.parent = parent
self.parent.title("Fibonacci series")
self.label = ttk.Label(self, text="")
self.button_1 = ttk.Button(self, text="Fibonacci series",
command=self.on_click_1)
self.button_2 = ttk.Button(self, text="Clear",
command=self.on_click_2)
self.label.pack()
self.button_1.pack()
self.button_2.pack()
self.pack()
self.fibonacci_list = [0,1]
def on_click_1(self):
for i in range(1, 15):
self.fibonacci_list.append(self.fibonacci_list[i-1] +
self.fibonacci_list[i])
self.label.configure(text=self.fibonacci_list)
self.fibonacci_list = [0,1]
print("Debug Message: Button 1 clicked")
def on_click_2(self):
self.label.configure(text="")
self.fibonacci_list = [0,1]
print("Debug Message: Button 2 clicked")
if __name__ == "__main__":
print("Starting Fibonacci python program")
root = Tk()
root.geometry("350x100+200+200")
application = MainWindow(root)
root.mainloop()
"""
Fibonacci series - tkinter. Has .py extension, so it opens a console window.
Fibonacci series with .py extension - This will launch the tkinter GUI as well
as a console window. The "debug" information will be printed to the console
window.
Author: Ian Stewart.
Date: 2016 July
This script is licensed CC0 https://creativecommons.org/publicdomain/zero/1.0/
1 2 3 4 5 6 7 7
1234567890123456789012345678901234567890123456789012345678901234567890123456789
"""
|
#!/usr/bin/env python3
#!
print("Fibonacci series...")
fibonacci_list = [0,1]
for i in range(1,15):
fibonacci_list.append(fibonacci_list[i-1] + fibonacci_list[i])
print(fibonacci_list)
input("Hit Return key to exit")
"""
Fibonacci series with .py extension - Uses console window, but pauses so the
console window may be read and close once Return key is hit.
When the file is double-clicked to launch it will open a console window,
display the fibonacci series, and then display the message "Hit Return key to
exit". This provides time to view the fibonacci numbers which are the output
of the program.
Author: Ian Stewart.
Date: 2016 July
This script is licensed CC0 https://creativecommons.org/publicdomain/zero/1.0/
1 2 3 4 5 6 7 7
1234567890123456789012345678901234567890123456789012345678901234567890123456789
"""
|
# Reject a string that won't convert to a floating point value.
# If invalid data entry, then ask for the data again.
def input_radius(prompt):
"""Get User input from the console. Must be integer or floating point"""
while True:
radius = input("Enter the radius of the circle [{}]: ".format(prompt))
if radius == "":
radius = prompt
try:
return float(radius)
except ValueError as e:
print("Error: {}".format(e))
print("Please re-enter the radius. Enter an integer or a float...")
continue
prompt = 10
radius = input_radius(prompt)
print("Value of radius is {}".format(radius))
|
#!/usr/bin/env python3
#
import tkinter
print("The geometry() function to modify the Windows dimensions and position.")
# Use tkinters Tk()
tkinter.Tk().geometry("400x100+200+500")
tkinter.mainloop()
"""
Set the Windows geometry. Values are in pixels.
Note: There can be no spaces in the string. E.g.
.geometry("400x500") <-- is OK
.geometry("400 x 500") <-- will fail.
Accepts just the dimensions, or may include the position on the desktop. E.g.
geometry("Width x Height")
OR
geometry("Width x Height + PositionX on Desktop + Position Y on Desktop")
Author: Ian Stewart.
Date: 2016 July
This script is licensed CC0 https://creativecommons.org/publicdomain/zero/1.0/
1 2 3 4 5 6 7 7
1234567890123456789012345678901234567890123456789012345678901234567890123456789
"""
|
#!/usr/bin/env python
import random
import sys
import os
import codecs
from utils import *
from Crypto.Cipher import AES
BLOCK_SIZE = 16
IV = b'This is easy HW!'
# HW - Utility function
def blockify(text, block_size=BLOCK_SIZE):
"""
Cuts the bytestream into equal sized blocks.
Args:
text should be a bytestring (i.e. b'text', bytes('text') or bytearray('text'))
block_size should be a number
Return:
A list that contains bytestrings of maximum block_size bytes
Example:
[b'ex', b'am', b'pl', b'e'] = blockify(b'example', 2)
[b'01000001', b'01000010'] = blockify(b'0100000101000010', 8)
"""
new_text = []
for i in range(0, len(text), block_size):
new_text.append(text[i:(i + block_size)])
return new_text
# HW - Utility function
def validate_padding(padded_text):
"""
Verifies if the bytestream ends with a suffix of X times 'X' (eg. '333' or '22')
Args:
padded_text should be a bytestring
Return:
Boolean value True if the padded is correct, otherwise returns False
"""
suffix = padded_text[-1]
for x in padded_text[-suffix:]:
if suffix != x:
return False
return True
# HW - Utility function
def pkcs7_pad(text, block_size=BLOCK_SIZE):
"""
Appends padding (X times 'X') at the end of a text.
X depends on the size of the text.
All texts should be padded, no matter their size!
Args:
text should be a bytestring
Return:
The bytestring with padding
"""
x = block_size - (len(text) % block_size)
text += chr(x) * x
return text
# HW - Utility function
def pkcs7_depad(text):
"""
Removes the padding of a text (only if it's valid).
Tip: use validate_padding
Args:
text should be a bytestring
Return:
The bytestring without the padding or None if invalid
"""
if validate_padding(text):
return text[:-text[-1]]
return None
def aes_dec_cbc(k, c, iv):
"""
Decrypt a ciphertext c with a key k in CBC mode using AES as follows:
m = AES(k, c)
Args:
c should be a bytestring (i.e. a sequence of characters such as 'Hello...' or '\x02\x04...')
k should be a bytestring of length exactly 16 bytes.
iv should be a bytestring of length exactly 16 bytes.
Return:
The bytestring message m
"""
aes = AES.new(k, AES.MODE_CBC, iv)
m = aes.decrypt(c)
depad_m = pkcs7_depad(m)
return depad_m
def check_cbcpad(c, iv):
"""
Oracle for checking if a given ciphertext has correct CBC-padding.
That is, it checks that the last n bytes all have the value n.
Args:
c is the ciphertext to be checked.
iv is the initialization vector for the ciphertext.
Note: the key is supposed to be known just by the oracle.
Return 1 if the pad is correct, 0 otherwise.
"""
key = b'za best key ever'
if aes_dec_cbc(key, c, iv) != None:
return 1
return 0
def string_to_list_int(list_of_characters):
return [x for x in list_of_characters]
def get_random_list(size = BLOCK_SIZE):
return [random.randint(0, 256) for i in range(BLOCK_SIZE)]
def list_int_to_string(list_of_ints):
new_str = ""
for i in list_of_ints:
new_str += chr(i)
return new_str
def convert(my_str):
new = ""
for x in my_str:
new += x
return new
if __name__ == "__main__":
ctext = "918073498F88237C1DC7697ED381466719A2449EE48C83EABD5B944589ED66B77AC9FBD9EF98EEEDDD62F6B1B8F05A468E269F9C314C3ACBD8CC56D7C76AADE8484A1AE8FE0248465B9018D395D3846C36A4515B2277B1796F22B7F5B1FBE23EC1C342B9FD08F1A16F242A9AB1CD2DE51C32AC4F94FA1106562AE91A98B4480FDBFAA208E36678D7B5943C80DD0D78C755CC2C4D7408F14E4A32A3C4B61180084EAF0F8ECD5E08B3B9C5D6E952FF26E8A0499E1301D381C2B4C452FBEF5A85018F158949CC800E151AECCED07BC6C72EE084E00F38C64D989942423D959D953EA50FBA949B4F57D7A89EFFFE640620D626D6F531E0C48FAFC3CEF6C3BC4A98963579BACC3BD94AED62BF5318AB9453C7BAA5AC912183F374643DC7A5DFE3DBFCD9C6B61FD5FDF7FF91E421E9E6D9F633"
ciphertext = bytes.fromhex(ctext)
msg = ""
ct_in_blocks = blockify(ciphertext)
r = get_random_list(BLOCK_SIZE)
for current_block in ct_in_blocks:
padding = [0] * 16
buf = []
for j in range(0, 16):
for i in range(0, 256):
r[BLOCK_SIZE - (j + 1)] = i
cs = r[:(15 - j)] + [i] + [(j + 1) ^ val for val in padding[15 - j + 1:]]
if (check_cbcpad(current_block, bytes(cs))):
buf.append(chr(r[15 - j] ^ (j + 1) ^ IV[15 - j]))
padding[15 - j] = r[15 - j] ^ (j+1)
buf.reverse()
IV = current_block
for i in buf:
msg += i
print(msg)
|
import random
def _random_item(collection):
return collection[ random.randrange( len(collection) ) ]
class Codes:
background = 0
foreground = 1
temporary = 2
forbidden = 3
class Path:
def __init__(self, position, parent = None):
self.position = position
self.parent = parent
if parent:
self.length = parent.length + 1
else:
self.length = 1
def add(self, v):
"""Return a tuple containing v+position."""
return v[0]+self.position[0], v[1]+self.position[1]
def avg(self):
"""Return the average position of this and it's parent."""
x = ( self.parent.position[0] + self.position[0] ) / 2
y = ( self.parent.position[1] + self.position[1] ) / 2
return x,y
def truncate(self, p):
node = self.parent
while node and node.position != p:
node = node.parent
return node
# maze object uses color codes to describe walls, floors, and temp-paths
# these codes are 0:wall, 1:floor, 2:temp, 3:off-limits
class Maze:
def __init__(self, size):
# note: size is the number of nodes in the maze, not the actual size
self.size = 1 + 2 * size[0], 1 + 2 * size[1]
self.width = self.size[0]
self.height = self.size[1]
self.path = None
# setup maze grid
self.grid = []
for y in range(self.height):
self.grid.append([])
for x in range(self.width):
self.grid[y].append(0)
# setup book-keepers
self.empty = []
self.updates = {}
self.initialized = False
self.full = False
for y in range(1, self.height, 2):
for x in range(1, self.width, 2):
self.empty.append( (x,y) )
def init(self):
if not self.path:
self.resetPath()
else:
self.step()
x,y = self.path.position
# check if we've made a loop, eat it if we have
code = self.grid[y][x]
if code == Codes.temporary:
self.draw(Codes.background)
self.path = self.path.truncate(self.path.position)
self.draw(Codes.temporary)
return
# check if we got a long way away, end if we have
elif self.path.length >= 40:
self.draw(Codes.foreground)
self.path = None
self.initialized = True
# otherwise, just print it
else:
self.draw(Codes.temporary)
def update(self):
# handle edge cases: all done, and un-initialized
if self.full:
return
if not self.initialized:
self.init()
return
# handle an empty path
if not self.path:
self.resetPath()
if not self.path:
self.full = True
return
self.draw(Codes.temporary)
else:
self.step()
x,y = self.path.position
code = self.grid[y][x]
if code == Codes.background:
self.draw(Codes.temporary)
elif code == Codes.foreground:
self.draw(Codes.foreground)
node = self.path
while node:
if node.position in self.empty:
self.empty.remove(node.position)
node = node.parent
self.path = None
elif code == Codes.temporary:
self.draw(0)
self.path = self.path.truncate(self.path.position)
self.draw(2)
def step(self):
"""Extend the path in a legal direction."""
# make a list of potential targets
potentials = []
for v in ( (0,-2), (2,0), (0,2), (-2,0) ):
potentials.append(self.path.add(v))
# cull the list
candidates = []
for x,y in potentials:
if x < 0 or y < 0:
continue
if x >= self.width or y >= self.height:
continue
if self.grid[y][x] == Codes.forbidden:
continue
p = self.path.parent
if p and p.parent and (x,y) == p.parent.position:
continue
candidates.append( (x,y) )
# pick one of the candidates
p = _random_item(candidates)
self.path = Path(p, self.path)
def resetPath(self):
self.draw(0)
if len(self.empty) > 0:
p = self.empty[ random.randrange(len(self.empty)) ]
self.path = Path(p)
def draw(self, color):
"""Draw contents of path into the grid, tracking updates."""
if not self.path:
return
# draw the head
x,y = self.path.position
self.grid[y][x] = color
self.updates[ (x,y) ] = color
# draw the tail
node = self.path
target = node.parent
while target:
x,y = target.position
self.grid[y][x] = color
self.updates[ (x,y) ] = color
x,y = node.avg()
self.grid[y][x] = color
self.updates[(x,y)] = color
node = target
target = target.parent
def getUpdates(self):
ups = self.updates
self.updates = {}
return ups
if __name__ == "__main__":
m = Maze( (10,10) )
for i in range(10):
m.update()
print "empty: ", m.empty
print "updates:", m.updates
print "grid: ", m.grid
|
# -*- coding: UTF-8 -*-
#使用梯度下降解决线性回归
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
points_num = 100
vectors = []
#用numpy的正太随机分布函数生产100个点
#y = 0.1 * x + 0.2
for i in xrange(points_num):
x1 = np.random.normal(0.0, 0.66)
y1 = 0.1 * x1 + 0.2 + np.random.normal(0.0, 0.04)
vectors.append([x1,y1])
x_data = [v[0] for v in vectors]
y_data = [v[1] for v in vectors]
plt.plot(x_data,y_data,'r*',label="original data")
plt.title("Linear Regression using Gradient Descent")
plt.legend()
plt.show()
# 构建线性回归模型
W = tf.Variable(tf.random_uniform([1], -1.0, 1.0))
b = tf.Variable(tf.zeros([1]))
y = W * x_data + b
#定义损失函数cost function
loss = tf.reduce_mean(tf.square(y-y_data))
#使用梯度下降优化器来优化损失函数
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss)
#创建会话
sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)
for step in xrange(20):
sess.run(train)
print("Step=%d,Loss=%f,Weight=%f,Bias=%f")\
%(step,sess.run(loss),sess.run(W),sess.run(b))
#绘制图像
plt.plot(x_data,y_data,'r*',label="original data")
plt.title("Linear Regression using Gradient Descent")
plt.plot(x_data,sess.run(W) * x_data + sess.run(b),label="Fitted line")
plt.legend()
plt.xlabel('x')
plt.ylabel('y')
plt.show()
sess.close()
|
# Usage: python a2_bonus_checker.py 'your_answer_here.py'
# 'your_answer_here.py' should contain function can_be_combined()
import sys
import random
import a2
import a2_bonus
LOWER_LENGTH = 10
UPPER_LENGTH = 50
LOWER_FRAGMENTS = 3
UPPER_FRAGMENTS = 8
def get_complement(nucleotide):
""" (str) -> str
Return the complement of nucleotide
>>> get_complement('A')
T
>>> get_complement('T')
A
>>> get_complement('C')
G
>>> get_complement('G')
C
"""
if nucleotide == 'A': return 'T'
if nucleotide == 'T': return 'A'
if nucleotide == 'C': return 'G'
return 'C'
def get_complementary_sequence(dna):
""" (str) -> str
Return the complementary DNA sequence of dna
>>> get_complementary_sequence('GATTACA')
CTAATGT
>>> get_complementary_sequence('AT')
TA
"""
complement = ''
for c in dna:
complement += get_complement(c)
return complement
def generate_strands(length, num_fragments, swaps):
dna1 = [random.choice('ATCG') for _ in range(length)]
for _ in range(swaps):
i = random.randint(0, length-1)
j = random.randint(0, length-1)
dna1[i], dna1[j] = dna1[j], dna1[i]
dna1 = ''.join(dna1)
dna2 = get_complementary_sequence(dna1)
dna1 += dna2
indices = [0, length, 2*length] + random.sample([x for x in range(1, 2 * length) if x != length], num_fragments - 2)
indices.sort()
fragments = []
for i in range(num_fragments):
fragments.append(dna1[indices[i]:indices[i+1]])
return fragments
if __name__ == '__main__':
module = __import__(sys.argv[1].replace('.py', ''))
random.seed(42)
iterations = 0
while True:
length = random.randint(LOWER_LENGTH, UPPER_LENGTH)
num_fragments = random.randint(LOWER_FRAGMENTS, UPPER_FRAGMENTS)
swaps = random.randint(0, 1)
fragments = generate_strands(length, num_fragments, swaps)
assert(len(fragments) == num_fragments)
assert(min(len(s) for s in fragments) != 0)
reference_answer = a2_bonus.can_be_combined(fragments)
if swaps == 0:
assert(reference_answer)
answer = module.can_be_combined(fragments)
if reference_answer != answer:
print(fragments)
print('reference answer = {}, answer = {}'.format(reference_answer, answer))
sys.exit(0)
iterations += 1
if iterations % 10000 == 0:
print('Total number of test cases = {}'.format(iterations), end='\r')
sys.stdout.flush()
|
def get_length(dna):
""" (str) -> int
Return the length of the DNA sequence dna.
>>> get_length('ATCGAT')
6
>>> get_length('ATCG')
4
"""
return len(dna)
def is_longer(dna1, dna2):
""" (str, str) -> bool
Return True if and only if DNA sequence dna1 is longer than DNA sequence
dna2.
>>> is_longer('ATCG', 'AT')
True
>>> is_longer('ATCG', 'ATCGGA')
False
"""
return get_length(dna1) > get_length(dna2)
def count_nucleotides(dna, nucleotide):
""" (str, str) -> int
Return the number of occurrences of nucleotide in the DNA sequence dna.
>>> count_nucleotides('ATCGGC', 'G')
2
>>> count_nucleotides('ATCTA', 'G')
0
"""
return dna.count(nucleotide)
def contains_sequence(dna1, dna2):
""" (str, str) -> bool
Return True if and only if DNA sequence dna2 occurs in the DNA sequence
dna1.
>>> contains_sequence('ATCGGC', 'GG')
True
>>> contains_sequence('ATCGGC', 'GT')
False
"""
return dna2 in dna1
def is_valid_sequence(dna):
""" (str) -> bool
Return True only if dna sequence is valid. Sequence is valid if and only if
dna only contains characters in {'A', 'T', 'C', 'G'}.
>>> is_valid_sequence('BAD')
False
>>> is_valid_sequence('GATC')
True
"""
valid = True
valid_char = ['A', 'T', 'C', 'G']
for c in dna:
if c not in valid_char:
valid = False
break
return valid
def insert_sequence(dna1, dna2, index):
""" (str, str, int) -> str
Return result of dna2 inserted into dna1 at the given index.
>>> insert_sequence('CCGG', 'AT', 2)
'CCATGG'
>>> insert_sequence('CCGG', 'AT', 0)
'ATCCGG'
>>> insert_sequence('CCGG', 'AT', 4)
'CCGGAT'
"""
return dna1[:index] + dna2 + dna1[index:]
def get_complement(nucleotide):
""" (str) -> str
Return the nucleotide's complement
note: complement pairs are [(A,T), (C,G)]
>>> get_complement('A')
'T'
>>> get_complement('G')
'C'
"""
compliment = None
if nucleotide == 'A':
compliment = 'T'
elif nucleotide == 'T':
compliment = 'A'
elif nucleotide == 'C':
compliment = 'G'
elif nucleotide == 'G':
compliment = 'C'
return compliment
def get_complementary_sequence(dna):
""" (str) -> str
Return the complementary sequence of dna
>>> get_complementary_sequence('ATAG')
'TATC'
>>> get_complementary_sequence('CCAT')
'GGTA'
"""
result = ''
for c in dna:
result += get_complement(c)
return result
|
import a1
import unittest
class TestSwapK(unittest.TestCase):
""" Test class for function a1.swap_k. """
def test_swap_k_1(self):
""" Test empty list """
L = []
k = 0
a1.swap_k(L, k)
expected = []
self.assertEqual(L, expected)
def test_swap_k_2(self):
""" Test single element case and k = 0 case """
L = [1]
k = 0
a1.swap_k(L, k)
expected = [1]
self.assertEqual(L, expected)
def test_swap_k_3(self):
""" Test k = 1 """
L = [1,2,3,4,5,6]
k = 1
a1.swap_k(L, k)
expected = [6,2,3,4,5,1]
self.assertEqual(L, expected)
def test_swap_k_4(self):
""" Test 1 < k < len(L) // 2 """
L = [1,2,3,4,5,6]
k = 2
a1.swap_k(L, k)
expected = [5,6,3,4,1,2]
self.assertEqual(L, expected)
def test_swap_k_5(self):
""" Test k = len(L) // 2 """
L = [1,2,3,4,5,6]
k = 3
a1.swap_k(L, k)
expected = [4,5,6,1,2,3]
self.assertEqual(L, expected)
if __name__ == '__main__':
unittest.main(exit=False)
|
# Do not import any modules. If you do, the tester may reject your submission.
# Constants for the contents of the maze.
# The visual representation of a wall.
WALL = '#'
# The visual representation of a hallway.
HALL = '.'
# The visual representation of a brussels sprout.
SPROUT = '@'
# Constants for the directions. Use these to make Rats move.
# The left direction.
LEFT = -1
# The right direction.
RIGHT = 1
# No change in direction.
NO_CHANGE = 0
# The up direction.
UP = -1
# The down direction.
DOWN = 1
# The letters for rat_1 and rat_2 in the maze.
RAT_1_CHAR = 'J'
RAT_2_CHAR = 'P'
class Rat:
""" A rat caught in a maze. """
# Write your Rat methods here.
def __init__(self, symbol, row, col):
""" (Rat, int, int) -> NoneType
Initialises the rat with it's character representation and it's position in the maze. Sets
the number of sprouts it has eaten to 0.
"""
self.symbol = symbol
self.row = row
self.col = col
self.num_sprouts_eaten = 0
def set_location(self, row, col):
""" (Rat, int, int) -> NoneType
Updates location of the rat.
>>> rat = Rat('J',2,3)
>>> rat.set_location(3,4)
>>> rat.row
3
>>> rat.col
4
"""
self.row = row
self.col = col
def eat_sprout(self):
""" (Rat, int, int) -> NoneType
Updates the number of sprouts eaten by the rat so far.
>>> rat = Rat('J',2,3)
>>> rat.eat_sprout()
>>> rat.eat_sprout()
>>> rat.num_sprouts_eaten
2
"""
self.num_sprouts_eaten += 1
def __str__(self):
""" (Rat) -> str
Returns string of the form
'symbol at (row, col) ate num_sprouts_eaten sprouts.'
>>> rat = Rat('J',2,3)
>>> rat.eat_sprout()
>>> rat.eat_sprout()
>>> rat
'J at (2, 3) ate 2 sprouts.'
"""
return '{} at ({}, {}) ate {} sprouts.'.format(
self.symbol,
self.row,
self.col,
self.num_sprouts_eaten)
class Maze:
""" A 2D maze. """
# Write your Maze methods here.
def __init__(self, maze, rat_1, rat_2):
""" (Maze, list of list of str, Rat, Rat) -> NoneType
Initialises maze with the input maze string and the positions two rats.
"""
self.maze = maze
self.rat_1 = rat_1
self.rat_2 = rat_2
self.num_sprouts_left = 0
self.refresh_rats_pos()
for r in range(len(maze)):
for c in range(len(maze[r])):
if maze[r][c] == SPROUT:
self.num_sprouts_left += 1
def is_wall(self, row, col):
""" (Maze, int, int) -> bool
Returns true if there is a wall in position (row, col) of the maze.
"""
return self.maze[row][col] == WALL
def get_character(self, row, col):
""" (Maze, int, int) -> str
Returns the character at the position (row, col) of the maze.
"""
return self.maze[row][col]
def move(self, rat, vrt, hrz):
""" (Maze, Rat, int, int) -> bool
Moves the rat to the specified position if it's not a wall.
If the rat moves onto a sprout, it will be eaten.
Returns true iff there is no wall in the way
"""
row = rat.row + vrt
col = rat.col + hrz
if (not self.is_wall(row, col) and
(rat.symbol == self.rat_1.symbol or
rat.symbol == self.rat_2.symbol)):
self.maze[rat.row][rat.col] = HALL
rat.set_location(row, col)
if self.get_character(row, col) == SPROUT and self.num_sprouts_left > 0:
rat.eat_sprout()
self.num_sprouts_left -= 1
self.refresh_rats_pos()
return True
return False
def refresh_rats_pos(self):
self.maze[self.rat_1.row][self.rat_1.col] = self.rat_1.symbol
self.maze[self.rat_2.row][self.rat_2.col] = self.rat_2.symbol
def __str__(self):
""" (Maze) -> str
Returns the status of the maze.
"""
maze_map = '\n'.join([''.join(self.maze[r]) for r in range(len(self.maze))])
scores = str(self.rat_1) + '\n' + str(self.rat_2)
return maze_map + '\n' + scores
|
class Predictor:
"""An interface for all expected predictor behaviour."""
def define_and_fit(self, model_file):
"""
Interface for defining and fitting a predictor.
Must be implemented for each new predictor you want to use.
:param model_file: string of the file path where the model should be saved.
:returns: the fitted model
"""
raise NotImplementedError
def set_predictions(self):
"""
Interface for setting 3 class variables:
train_pred: list of output values of the training data
correct_pred: DataFrame of a subset of the training data that was classified correctly.
incorrect_pred: DataFrame of a subset of the training data that was classified incorrectly.
"""
raise NotImplementedError
def get_prediction(self, x):
"""
Interface for getting the prediction of the model on instance(s) x.
:param x: Series/array of input value(s) for which you want the prediction
:returns: the raw prediction(s)
"""
raise NotImplementedError
def get_prediction_proba(self, x):
"""
Only for classification models:
Interface for getting the prediction prob of the model on instance(s) x.
:param x: Series/array of input value(s) for which you want the prediction
:returns: the raw prediction(s)
"""
raise NotImplementedError
def get_second_prediction(self, x):
"""
Interface for getting the secondary prediction of the model on the instance x.
:param x: Series/array of input value(s) for which you want the prediction
:returns: the secondary prediction as an int
"""
raise NotImplementedError
def get_data_corr_predicted_as(self, noc):
"""
Interface for getting all training data correctly predicted as a certain NOC.
:param noc: int representing the groun truth NOC value you want the data from.
:returns: DataFrame of all training data correctly predicted as noc.
"""
raise NotImplementedError |
class InputProcessor():
def __init__(self, inputToProcess, chessNotation="simplified"):
self.inputToProcess = inputToProcess
self.chessNotation = chessNotation
self.pieceAbbreviations = ("p", "r", "n", "b", "k", "q")
def processInput(self, board, side):
# Heavily simplified chess notation, simply includes the beginning and ending spots of the move. Castles are still 0-0 or O-O
if self.chessNotation == "simplified":
# Castling not implemented yet
if self.inputToProcess == "0-0" or self.inputToProcess == "O-O":
kingRow = 0 if side == "white" else 7
if board[kingRow][4] != " " and ["kingside"] in board[kingRow][4].availableMoves(kingRow, 4, board):
return [True, "kingside"]
elif self.inputToProcess == "0-0-0" or self.inputToProcess == "O-O-O":
kingRow = 0 if side == "white" else 7
if board[kingRow][4] != " " and ["queenside"] in board[kingRow][4].availableMoves(kingRow, 4, board):
return [True, "queenside"]
elif len(self.inputToProcess) == 4 or len(self.inputToProcess) == 5:
try:
location = [int(self.inputToProcess[1]) - 1, ord(self.inputToProcess[0].lower()) - 97,
int(self.inputToProcess[3]) - 1, ord(self.inputToProcess[2].lower()) - 97]
if len(self.inputToProcess) == 5:
location.append(self.inputToProcess[4].lower())
if (board[location[0]][location[1]] == board[location[2]][location[3]] or
(board[location[2]][location[3]] != " " and
board[location[0]][location[1]].side == board[location[2]][location[3]].side) or
not location[2:] in board[location[0]][location[1]].availableMoves(location[0], location[1], board)):
return [False, -1, -1, -1, -1]
except:
return [False, -1, -1, -1, -1]
else:
return [True] + location
return [False, -1, -1, -1, -1]
|
sum = 0
for i in range(101):
sum += i
print('Summen av de 100 første tallene er', sum)
produkt = 1
i = 1
while produkt < 1000:
i += 1
produkt *= i
print('Løkken kjørte', i, 'ganger og produktet ble', produkt)
tall1 = int(input('Skriv inn et tall: '))
tall2 = int(input('Skriv inn et nytt tall: '))
produkt = int(input('Hva er {} * {}? '. format(tall1, tall2)))
svar = tall1 * tall2
while produkt != svar:
produkt = int(input('Hva er {} * {}? '.format(tall1, tall2)))
print('Stemmer. Svaret er', tall1*tall2)
|
n = int(input('Skriv inn et tall: '))
r = int(input('Skriv inn et tall: '
''))
sum = 0
while -1 < r < 1:
|
# -*- coding:utf-8 -*-
import threading
import _thread
import time
"""
1.线程
1.1 创建一个线程
1.2 自定义线程类
1.3 线程安全之使用Lock
1.4 线程安全之使用RLock
1.5 线程安全之使用信用量
1.6 线程安全之使用条件
1.7 线程安全之使用事件
"""
# 1.1 创建一个线程
# def func(i):
# print("%d threading is running" % i)
#
#
# threads = []
# for i in range(5):
# t = threading.Thread(target=func, args=(i,))
# threads.append(t)
# t.start()
# # t.join()
# print("Main exited")
# 1.2 自定义线程类
# exit_flag = 0
#
#
# class myThread(threading.Thread):
# def __init__(self, threadID, name, counter):
# threading.Thread.__init__(self)
# self.threadID = threadID
# self.name = name
# self.counter = counter
#
# def run(self):
# print("Starting " + self.name)
# print_time(self.name, self.counter, 5)
# print("Exiting " + self.name)
#
#
# def print_time(thread_name, delay, counter):
# while counter:
# # if exit_flag:
# # # 线程可以主动退出
# # _thread.exit()
# time.sleep(delay)
# print("%s: %s" % (thread_name, time.ctime(time.time())))
# counter = counter - 1
#
# thread1 = myThread(1, "Thread-1", 1)
# thread2 = myThread(2, "Thread-2", 2)
#
# thread1.start()
# thread2.start()
#
# thread1.join()
# thread2.join()
#
# print(123)
# print("Exiting Main Thread")
# 1.3 线程安全之Lock锁
# shared_with_lock = 0
# shared_with_no_lock = 0
# lock = threading.Lock()
#
#
# # 有锁的情况下
# def increment_with_lock():
# global shared_with_lock
# for i in range(10000):
# lock.acquire()
# shared_with_lock += 1
# lock.release()
#
#
# def decrement_with_lock():
# global shared_with_lock
# for i in range(10000):
# lock.acquire()
# shared_with_lock -= 1
# lock.release()
#
#
# # 无锁的情况下
# def increment_without_lock():
# global shared_with_no_lock
# for i in range(100000):
# shared_with_no_lock += 1
#
#
# def decrement_whithout_lock():
# global shared_with_no_lock
# for i in range(100000):
# shared_with_no_lock -= 1
#
#
# t1 = threading.Thread(target=increment_without_lock())
# t2 = threading.Thread(target=decrement_whithout_lock())
#
# t3 = threading.Thread(target=increment_with_lock())
# t4 = threading.Thread(target=decrement_with_lock())
#
# t1.start()
# t2.start()
# t3.start()
# t4.start()
#
# t1.join()
# t2.join()
# t3.join()
# t4.join()
# print("无锁的情况下,共享变量为: %s" % shared_with_no_lock)
# print("有锁的情况下,共享变量为: %s" % shared_with_lock)
#
#
# # 1.4 线程安全之RLock锁
# rlock = threading.RLock()
#
# # 初始化共享资源
# abce = 0
#
# # 本线程访问共享资源
# rlock.acquire()
# abce = abce + 1
#
# # 这个线程访问共享资源会被阻塞
# rlock.acquire()
# abce = abce + 2
# rlock.release()
# rlock.release()
# print(abce)
# 1.5 线程安全之信号量
# semaphore = threading.Semaphore(2)
#
#
# def worker(id):
# print("thread {0} acquire semaphore".format(id))
# semaphore.acquire()
# print("thread {0} do something".format(id))
# time.sleep(2)
# semaphore.release()
# print("thread {0} release semahore".format(id))
#
#
# for i in range(10):
# t = threading.Thread(target=worker, args=(i,))
# t.start()
# 1.6 线程安全之条件
# item = []
# condition = threading.Condition()
#
#
# class consumer(threading.Thread):
# def __init__(self):
# threading.Thread.__init__(self)
#
# def consumer(self):
# global item, condition
# condition.acquire()
# if len(item) == 0:
# condition.wait()
# print("conumser: 我释放了锁,我正在等待唤醒")
# item.pop()
# print("Consumer notify : consumed 1 item")
# print("Consumer notify : items to consume are " + str(len(item)))
# condition.notify()
# condition.release()
#
# def run(self):
# for i in range(5):
# time.sleep(2)
# self.consumer()
#
#
# class producer(threading.Thread):
# def __init__(self):
# threading.Thread.__init__(self)
#
# def producer(self):
# global item, condition
# condition.acquire()
# if len(item) == 4:
# condition.wait()
# print("producer: 我释放了锁,我正在等待唤醒")
# item.append(1)
# print("producer notify : consumed 1 item")
# print("producer notify : items to consume are " + str(len(item)))
# condition.notify()
# condition.release()
#
# def run(self):
# for i in range(5):
# time.sleep(1)
# self.producer()
#
#
# t1 = consumer()
# t2 = producer()
#
# t1.start()
# t2.start()
# t1.join()
# t2.join()
# 1.7 线程安全之使用事件
from threading import Thread, Event
import random
items = [1, 2, 3, 4, 5, 6]
event = Event()
def print_a():
global items, event
for i in range(1,3,5):
event.wait()
print(i)
def print_b():
global items, event
for i in range(2,4,6):
event.wait()
print(i)
t1 = threading.Thread(target=print_a)
t2 = threading.Thread(target=print_b)
t1.start()
t2.start()
t1.join()
t2.join()
event.set() |
# -*- coding:utf-8 -*-
from abc import ABCMeta, abstractclassmethod
"""
策略模式之一:
场景: 小明离职,同事选择交通工具去聚餐
"""
class Vehicle(metaclass=ABCMeta):
"""
策略抽象基类
"""
@abstractclassmethod
def running(cls):
pass
class Walk(Vehicle):
"""
步行策略类
"""
def running(cls):
print("I am Walking!!!")
class Subway(Vehicle):
"""
火车策略类
"""
def running(cls):
print("I am drive Subway!!!")
class Bicycle(Vehicle):
"""
自行车策略类
"""
def running(cls):
print("I am drive Bicycle!!!")
class Classmate:
"""
"""
def __init__(self, name, vehicle):
self.__name = name
self.__vehicle = vehicle
def party(self):
self.__vehicle.running()
print("我做了其他额外的封装任务")
# 使用了走路策略,并且通过上下文类的封装方法来实现具体的封装行为
walk = Walk()
person1 = Classmate("person1", walk)
person1.party()
person2 = Classmate("person2", Subway())
person2.party() |
#Estrutura de Dados: Fila
#FIFO: First In, First Out
class Fila:
def __init__(self): # Construtor da classe
self.fila = []
def __repr__(self): # Retorna uma representação visual do objeto
return self.fila.__repr__()
def tamanho(self): # Retorna o tamanho da fila
return len(self.fila)
def adicionar(self, n): # Adiciona itens no fim da fila
self.fila.append(n)
def remover(self): # Remove itens do início da fila caso ela não esteja vazia
if self.tamanho() != 0:
del self.fila[0]
|
#take input list
print("How many numbers in your list:");
num = 0;
try:
num = int(input())
except TypeError:
print("not an integer defaulting to 10 numbers");
num = 10;
li = []
for i in range(num):
li.append(int(input()))
#count inversion
count = 0
# 4 8 20 6 7 9 = 4 6 7 8 9
def numMergeInversion(li, start, end, mid):
print("start: " + str(start) + " mid: "+ str(mid) + " end: "+ str(end));
for i in range(start, end+1):
print(li[i],end=" ")
print()
anotherLi = []
count = 0
middle = mid
for i in range (start, end+1):
if start >= mid:
break;
elif mid > end:
break;
if li[start] <= li[mid]:
anotherLi.append(li[start])
start += 1
else:
anotherLi.append(li[mid])
count += (mid - middle + 1)
mid += 1
if start >= mid:
for i in range(mid, end+1):
anotherLi.append(li[i])
elif mid > end:
anotherLi.append(li[start])
for i in range(start+1, middle):
anotherLi.append(li[i])
count += (end - middle + 1)
li = anotherLi
print("inversions: " + str(count))
return count
def numInversion(li, start, end):
if start >= end:
return 0;
else:
return numInversion(li,start, (start+end)//2) + \
numInversion(li,(start+end)//2 + 1, end) + \
numMergeInversion(li,start,end, (start+end)//2+1);
print(numInversion(li, 0, num -1))
print("sorted")
for i in range (num-1):
print(li[i],end=" ")
|
x = int(input("How long do you sleep at night?"))
y = int(input("How long do you sleep during the day?"))
print (x * 60 + y) |
a = int(input())
b = int(input())
c = int(input())
d = int(input())
print("\t", end="")
for j in range(c, d + 1):
print("\t", j, sep="", end="")
for i in range(a, b+1):
print("\n", i, end="")
for x in range(c, d+1):
print("\t", (i * x), end="")
print(end="") |
x = str(input())
sum1 = int(x[0]) + int(x[1]) + int(x[2])
sum2 = int(x[3]) + int(x[4]) + int(x[5])
if sum1 == sum2:
print("Счастливый")
else:
print("Обычный") |
#!/usr/bin/env python3
import numpy as np
N = 2**np.linspace(3, 8, 6, dtype=int)
OSR = np.linspace(1, 8, 8, dtype=int)
print(" ",N)
def f(M, levels):
return [max(1, int(c)) for c in np.floor(np.divide(levels, 2**(M-1)))]
ans = []
for M in OSR:
ans.append(f(M, N))
print(M, f(M, N))
|
import random,methods,os,subprocess
import yfinance as yf
import pandas as pd
import csv
import matplotlib.pyplot as plt
subprocess.Popen('python interest.py')
while True:
print()
print("Welcome to the bank!")
print()
print("1 to create a new account,2 to check balance,3 to deposit, 4 to transfer, 5 to delete account,6 to change password,7 to enter casino,8 to enter the stock market, else leave bank")
opt=int(input("Enter option: "))
if opt==1:
try:
account=input("Enter account name: ")
amount=int(input("Enter amount: "))
while True:
print("Password should be over 5 characters in length, has to contain atleast one uppercase and lowercase character,one number,and one of the following symbols (@!#$%^&*-+)")
password=input("Enter password: ")
if methods.pass_strength(password):
print("Strong password!")
break
else:
print("Weak password! Enter another password")
email=input("Enter email id: ")
verid=random.randint(10000,99999)
msg="Welcome to python bank!\nHere is your verification code:\n"+str(verid)+"\nWe hope to continue serving you in the future.\n\n\n\nPlease ignore this message if it doesn't concern you"
methods.mail(email,'Python bank verification code',msg)
print("Verification email has been sent to your id")
verified=False
while True:
verid_input=int(input("Enter verification id(Enter 0 to resend email, 1 to exit):"))
if verid_input==verid:
print("Verified!")
verified=True
break
elif verid_input==0:
print("Email resent")
methods.mail(email,'Python bank verification code',msg)
continue
elif verid_input==1:
break
else:
print("Wrong id")
if verified:
methods.create(account,amount,password,email)
except:
print("Invalid details")
print()
elif opt==2:
try:
account=input("Enter account name: ")
password=input("Enter password: ")
k=methods.balance(account,password)
print("AccountName = ",k[0]," Balance = ",k[1]," Password = ",k[2]," Email = ",k[3])
except:
print("Invalid account details")
print()
elif opt==3:
try:
account=input("Enter account name: ")
amount=int(input("Enter amount: "))
methods.update(account,amount)
k=methods.money(account)
print(amount,"added to account.")
except:
print("Invalid account details")
print()
elif opt==4:
try:
acc1=input("Enter account name of sender: ")
acc2=input("Enter account name of receiver: ")
amount=int(input("Enter amount: "))
k=methods.money(acc1)
k=methods.money(acc2)
methods.transfer(acc1,acc2,amount)
print(amount,"transferred from",acc1,"to",acc2)
except:
print("Invalid account details")
print()
elif opt==5:
try:
account=input("Enter account name: ")
password=input("Enter password: ")
k=methods.balance(account,password)[1]
methods.del_account(account,password)
print("Account deleted")
except:
print("Invalid account details")
print()
elif opt==6:
try:
forgot=int(input("Enter 1 to enter old and new password, Enter 0 to send email if password forgotten: "))
if forgot==1:
account=input("Enter account name: ")
pass1=input("Enter old password: ")
k=methods.balance(account,pass1)[1]
while True:
pass2=input("Enter new password: ")
if methods.pass_strength(pass2):
print("Strong password!")
break
else:
print("Weak password! Enter another password")
methods.change_password(account,pass1,pass2)
elif forgot==0:
account=input("Enter account name: ")
k=methods.display(account)
msg="This is an email from python bank.\n"+"Your password is "+str(k[2])+"\n Thank you for using our service.\n\n\n\n Please ignore this email if it's not meant for you."
methods.mail(k[3],'Your forgotten password',msg)
except:
print("Invalid details")
elif opt==7:
print()
try:
print("Enter account details to enter casino!")
account=input("Enter account name: ")
password=input("Enter password: ")
k=methods.balance(account,password)[1]
except:
print("Wrong account details")
continue
print()
while True:
print()
print("Welcome to the casino!")
print()
print("Enter 1 for Slot Machine, 2 for Dice Game, 3 for Higher or Lower, 4 for Tossing, 5 for Blackjack, else leave")
choice=int(input("Enter choice of game: "))
if choice==1:
print()
print("Welcome to the Slot Machine! Enter the amount you want to bet!")
print("If 2 slots are equal then you win your money back and if 3 slots are equal you win twice the amount of the bet!")
while True:
print("You have $",methods.money(account))
print("Enter 0 for bet to stop playing")
bet=int(input("Enter the amount to bet: "))
if bet==0:
break
else:
methods.update(account,-bet)
L=["◆","⬤","★"]
x=random.choice(L)
y=random.choice(L)
z=random.choice(L)
print(x, y, z)
if x==y==z:
print("Jackpot!")
print("You win $",2*bet)
methods.update(account,2*bet)
elif x==y or y==z or x==z:
print("2 in a row!")
print("You get back $",bet)
methods.update(account,bet)
elif choice==2:
print()
print("welcome to dice round")
print("the rules are simple. if you get even number you will get 100 more added, if you get odd you will lose 300")
while True:
play=int(input("Enter 0 to quit or 1 to continue playing: "))
i=random.randint(1,6)
if i%2==0:
print("You earn 100$")
methods.update(account,100)
elif i%2!=0:
print("You lose 300$")
methods.update(account,-300)
if methods.money(account)<=0 or play==0:
print("Game over!")
break
print(methods.money(account))
elif choice==3:
print()
print("Welcome to Higher or Lower.")
print("Guess whether a card is higher or lower than your current one ")
D={"Ace":1, "2":2, "3":3, "4":4, "5":5, "6":6, "7":7, "8":8, "9":9, "10":10, "Jack":11, "Queen":12, "King":13}
keys = list(D.keys())
print(keys)
x=random.choice(keys)
print("You got a",x)
while True:
y=random.choice(keys)
guess=int(input("Enter 1 to guess higher and 0 to guess lower. Else -1 to quit the game: "))
print("You got a",y)
if D[y]>D[x] and guess==1:
print("Higher! You win 100$")
methods.update(account,100)
elif D[y]<D[x] and guess==0:
print("Lower! You win 100$")
methods.update(account,100)
elif D[y]>D[x] and guess==0 or D[y]<D[x] and guess==1:
methods.update(account,-200)
print("Wrong! You lose 200$")
elif guess==-1 or methods.money(account)<=0:
print("You quit Higher or Lower!")
break
print(methods.money(account))
x=y
elif choice==4:
print()
while True:
bet=int(input("Enter bet"))
if bet==0:
break
flip=random.randint(1,2)
if flip ==1:
methods.update(account,bet)
print("Heads. You just won " + str(bet) + " dollars. Your total money is " + str(methods.money(account)) + " dollars remaining.")
else:
methods.update(account,-bet)
print("Tails. You just lost " + str(bet) + " dollars. Your total money is " + str(methods.money(account)) + " dollars remaining.")
elif choice==5:
L = ['Spades','Clubs','Diamonds','Hearts']
D = {2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,10:10,'Ace':11,'King':10,'Queen':10,'Jack':10}
while True:
L1= []
L1= []*21
bet = int(input("How much do you want to bet?"))
if bet > methods.money(account):
print("You don't have enough money")
continue
compvalue = 0
methods.update(account,-bet)
profit = 0
v=random.randint(1,13)
w=random.randint(1,13)
value = 0
z=0
y=0
f = 0
for i in D:
card1suit = random.choice(L)
card1value = D[i]
card1name = i
z+=1
if z == v:
L1+=[i]
break
for i in D:
card2suit = random.choice(L)
card2value = D[i]
card2name = i
y+=1
if y == w:
L1+=[i]
break
print("Your Cards are:-", card1suit ,card1name, "and" ,card2suit ,card2name)
value+= card1value + card2value
compvalue= random.randint(2,20)
while True:
while f == 0:
while True:
x = input("Do you want to draw or stand?")
if x == "Draw" or x== "draw":
v= random.randint(1,13)
z=0
for i in D:
if z == v:
print("You drew", random.choice(L), i)
value+= D[i]
L1+= [i]
print("Value is", value)
break
z+=1
elif x == "Stand" or x == "stand":
f=1
break
else:
print("That isnt a valid option")
continue
break
break
if compvalue <= 16:
while compvalue <= 16:
compvalue+= random.randint(1,9)
p=9
elif compvalue > 16:
p =9
if value > 21 and compvalue < 21 :
a = 0
for i in L1:
if i == "Ace":
value -=10
a = 1
L1.remove(i)
print("Value of Ace became 1. New Value is = ", value)
if a == 1:
pass
elif a == 0:
print("Your final Value is",value)
print("House Value is",compvalue)
print("You bust. House Wins")
break
elif compvalue > 21 and value < 21 :
print("Your final Value is",value)
print("House Value is",compvalue)
print("House busts. You win")
profit += 2*bet
break
elif value == 21 and compvalue !=21:
print("Your final Value is",value)
print("House Value is",compvalue)
print("Blackjack. You win")
profit += 3*bet
break
elif compvalue == 21 and value !=21:
a = 0
for i in L1:
if i == "Ace":
value -=10
a = 1
L1.remove(i)
print("Value of Ace became 1. New Value is = ", value)
if value == 21:
print("Your final Value is",value)
print("House Value is",compvalue)
print("You Draw")
profit = bet
break
elif value != 21:
print("Your final Value is",value)
print("House Value is",compvalue)
print("Blackjack. House wins")
break
elif compvalue >21 and value>21:
a = 0
for i in L1:
if i == "Ace":
value -=10
a = 1
L1.remove(i)
print("Value of Ace became 1. New Value is = ", value)
break
if a == 1:
print("Your final Value is", value)
print("House Value is",compvalue)
print("You Win")
profit += 2*bet
break
print("Your final Value is",value)
print("House Value is",compvalue)
print("You Draw")
profit = bet
break
elif value > compvalue and f== 1 and p==9:
print("Your final Value is",value)
print("House Value is",compvalue)
print("You win")
profit += 2*bet
break
elif compvalue> value and f== 1 and p==9:
print("Your final Value is",value)
print("House Value is",compvalue)
print("House wins")
break
elif compvalue == value and f== 1 and p==9:
print("Your final Value is",value)
print("House Value is",compvalue)
print("You Draw")
profit = bet
break
methods.update(account,profit)
print("You have", methods.money(account),"money left.")
d= input("Do you want to continue.Yes or No only.")
if d == "Yes" or d=="yes":
continue
elif d == "No" or d=="no":
break
break
else:
break
elif opt==8:
print()
try:
print("Enter account details to enter stock market!")
account=input("Enter account name: ")
password=input("Enter password: ")
k=methods.balance(account,password)[1]
except:
print("Wrong account details")
continue
print()
while True:
print()
print("Welcome to the stock market!")
print("TSLA MSFT AAPL GOOG WORK UBER SHOP NVDA NFLX AMD")
stock=input("Which stock do you want to trade(Enter 0 to exit): ")
if stock=="0":
break
try:
shares=int(input("How many shares do you want to buy?: "))
data=yf.Ticker(stock)
data=data.history(interval='1mo',start='2010-1-1', end='2020-1-1')
data.to_csv(stock+'results.csv')
except:
break
with open(stock+'results.csv','r') as F:
DL=csv.reader(F)
next(DL)
for i in DL:
if i[2]=='':
continue
initial=i[2]
print("You bought",shares,"shares of",stock,'for',i[2],"per share.")
print("1 month later")
break
for i in DL:
if i[2]=='':
continue
print('The current stock price is ',i[2],' do you wish to wait 1 month before selling it?')
wait=int(input("Enter 0 to sell stock, 1 to wait,2 to view graph: "))
curr_date=i[0]
if wait==0:
final=i[2]
print("You sold",shares,"shares of",stock,'for',float(final)*shares)
methods.update(account,shares*(float(final)-float(initial)))
break
elif wait==2:
with open(stock+'results.csv','r') as F:
D=csv.reader(F)
next(D)
x=[]
y=[]
for j in D:
if j[2]=='':
continue
x+=[j[0]]
y+=[float(j[2])]
if curr_date==j[0]:
break
plt.plot(x, y)
plt.xlabel('Date')
plt.ylabel('Stock Price')
plt.title(stock)
plt.show()
else:
break
|
password = "contraseña"
contraseña_usuario = input("introduce contraseña")
if password.capitalize() == contraseña_usuario.capitalize() :
print("contraseña correcta")
else:
print("contraseña incorrecta")
|
from collections import defaultdict
import sys
def mc_evaluation(policy, env, num_episodes, discount_factor=1.0):
"""
First-visit MC Policy Evaluation. Calculates the value function
for a given policy using sampling.
Args:
policy: A function that maps an observation to action probabilities.
env: OpenAI gym environment.
num_episodes: Nubmer of episodes to sample.
discount_factor: Lambda discount factor.
Returns:
A dictionary that maps from state to value.
The state is a tuple -- containing the players current sum, the dealer's one showing card (1-10 where 1 is ace)
and whether or not the player holds a usable ace (0 or 1) -- and the value is a float.
"""
# Keeps track of sum and count of returns for each state
# to calculate an average. We could use an array to save all
# returns (like in the book) but that's memory inefficient.
returns_sum = defaultdict(float)
returns_count = defaultdict(float)
# The final value function
V = defaultdict(float)
for i_episode in range(1, num_episodes + 1):
# Print out which episode we're on, useful for debugging.
if i_episode % 1000 == 0:
print("\rEpisode {}/{}.".format(i_episode, num_episodes), end="")
sys.stdout.flush()
# Generate an episode.
# An episode is an array of (state, action, reward) tuples
episode = []
state = env.reset()
for t in range(100):
action = policy(state)
next_state, reward, done, _ = env.step(action)
episode.append((state, action, reward))
if done:
break
state = next_state
# Find all states the we've visited in this episode
# We convert each state to a tuple so that we can use it as a dict key
states_in_episode = set([tuple(x[0]) for x in episode])
for state in states_in_episode:
# Find the first occurance of the state in the episode
first_occurence_idx = next(i for i,x in enumerate(episode) if x[0] == state)
# Sum up all rewards since the first occurance
G = sum([x[2]*(discount_factor**i) for i,x in enumerate(episode[first_occurence_idx:])])
# Calculate average return for this state over all sampled episodes
returns_sum[state] += G
returns_count[state] += 1.0
V[state] = returns_sum[state] / returns_count[state]
return V |
import pygame
class Bullet:
bulletX: float
bulletY: float
def __init__(self, xCord, yCord):
self.bulletX = xCord
self.bulletY = yCord
class missile(Bullet):
bullet_Img: pygame.image
bullet_speed: int
bullet_dir: bool
bullet_position:int
def __init__(self, xCord, yCord, dir, img):
super().__init__(xCord, yCord)
self.bullet_speed = 0
self.bullet_Img = pygame.image.load(img)
self.bullet_dir = dir
def get_bullet_x(self):
return self.bulletX
def get_bullet_y(self):
return self.bulletY
def get_bullet_position(self):
return self.bullet_position
def move_bullet(self, screen):
if (self.bullet_dir):
screen.blit(self.bullet_Img, (self.bulletX + 16 + self.bullet_speed, self.bulletY + 10))
self.bullet_position = self.bulletX + 16 + self.bullet_speed #bullet position after the shoot
else:
screen.blit(self.bullet_Img, (self.bulletX + 16 - self.bullet_speed, self.bulletY + 10))
self.bullet_position = self.bulletX + 16 - self.bullet_speed # bullet position after the shoot
self.bullet_speed += 5
#set the direction and fire the bullet
def set_bullet_dir(self, screen):
self.move_bullet(screen)
|
##########--------------------------------------------- 2 sum problem ----------------------------------------------##########
from datetime import datetime
# Class to implement algorithm for 2 sum problem
class twoSum:
# Initialising class variable
def __init__(self):
self.data = []
self.sumDict = dict()
self.pairs = 0
# Function to import data from text file
'''
Input: Text file containing data
Output: array of sorted input data
'''
def importData(self, filename):
with open(filename,"r") as file:
for line in file:
self.data.append(int(line.strip('\n')))
start = datetime.now()
self.data.sort()
print(f"Time taken to sort input data = {datetime.now()-start}.")
# Function to implement binary search
'''
Input: Key to look for
Output: Index or False if element is not found in the array
'''
def binaryIntervalSearch(self, key, bound = "upper"):
low = 0
high = len(self.data)-1
middle = 0
while low <= high:
middle = (low + high) // 2
# Check if the key is less than the middle element
# or greater than middle element or equal to it.
if self.data[middle] > key:
high = middle - 1
elif self.data[middle] < key:
low = middle + 1
else:
return middle
# Returning intervals if key not found
if bound == "upper":
return max(low,0)
elif bound == "lower":
return max(high,0)
# Function to check if there is a pair of integers which when summed together are equal
# to the given number
'''
Input: Expected sum of the pair of number
Output: Pair of numbers
'''
def checkSum(self):
validSum = set()
start = datetime.now()
for index, x in enumerate(self.data,1):
upper = self.binaryIntervalSearch(-10000-x, "upper")
lower = self.binaryIntervalSearch(10000-x, "lower")
if upper == lower:
arr = [self.data[upper]]
else:
arr = self.data[min(upper, lower): max(upper,lower)+1]
arr = [x + y for y in arr]
for element in arr:
if element >= -10000 and element <= 10000:
validSum.add(element)
print(f"Time taken to calculate valid sums = {datetime.now()-start}.")
print(f"\nLength of the set = {len(validSum)}")
if __name__ == "__main__":
algorithm = twoSum()
algorithm.importData("2sum.txt")
start = datetime.now()
# print("\n",algorithm.data,"\n")
algorithm.checkSum()
print(f"\nTotal time taken = {datetime.now() - start}.\n")
|
my_foods=['pizza','falafel','carrot cake']
my_foods.append('apple')
print("我喜欢的食物有:")
for food in my_foods:
print(food) |
person_information1 = {'first_name': '尚', 'last_name': '若冰', 'age': '20', 'city': '昆明'}
person_information2 = {'first_name': '倪', 'last_name': '尔', 'age': '19', 'city': '长沙'}
person_information3 = {'first_name': '张', 'last_name': '颍', 'age': '19', 'city': '江西'}
people = [person_information1, person_information2, person_information3]
for information in people:
print(information)
print(person_information1['first_name'])
print(person_information1['last_name'])
print(person_information1['age'])
print(person_information1['city'])
|
river = {'nile': 'egypt', 'yellow river': 'China', 'Yangest river': 'China'}
river_name = ['nile', 'yellow river', 'Yangest river']
for name in river.keys():
print(name.title())
if name in river_name:
print("The " + name.title() + " through " + river[name].title())
for river_name in river.keys():
print("\n" + river_name)
for country_name in river.values():
print("\n" + country_name)
|
animals = ['dog', 'cat', 'pig']
for pet in animals:
print("A" + pet + "would make a great prt!")
print("Any of these animals would make a great pet!")
|
"""
Two words are blanagrams if they are anagrams but exactly one letter has been substituted for another.
Given two words, check if they are blanagrams of each other.
Example
For word1 = "tangram" and word2 = "anagram", the output should be
checkBlanagrams(word1, word2) = true;
For word1 = "tangram" and word2 = "pangram", the output should be
checkBlanagrams(word1, word2) = true.
Since a word is an anagram of itself (a so-called trivial anagram), we are not obliged to rearrange letters. Only the substitution of a single letter is required for a word to be a blanagram, and here 't' is changed to 'p'.
For word1 = "silent" and word2 = "listen", the output should be
checkBlanagrams(word1, word2) = false.
These two words are anagrams of each other, but no letter substitution was made (the trivial substitution of a letter with itself shouldn't be considered), so they are not blanagrams.
Input/Output
[execution time limit] 4 seconds (py3)
[input] string word1
A string consisting of lowercase letters.
Guaranteed constraints:
1 ≤ word1.length ≤ 100.
[input] string word2
A string consisting of lowercase letters.
Guaranteed constraints:
word2.length = word1.length.
[output] boolean
Return true if word1 and word2 are blanagrams of each other, otherwise return false.
"""
def checkBlanagrams(word1, word2):
# checked if the words are anagrams, then False
if sorted(word1) == sorted(word2):
return False
# check if the words are blanagrams just off by one letter
# compare the letters of one word to that of the other full word
def compare_words(a_word, b_word):
result = False
counter = 0
matching_letters = len(a_word) - 1
for i in range(len(a_word)):
# this should check and del to account for dup chars
if a_word[i] in b_word:
counter +=1
if counter >= matching_letters: # checking that the words are off by one letter
result = True
return result
return (compare_words(word1,word2) and compare_words(word2, word1))
word1 = "tangram"
word2 = "anagram"
print(checkBlanagrams(word1, word2))
# checked if the words are anagrams, then False
# compare letters of word1 sorted and letters of word2 sorted
# if equal they are not a Blanagram, return false
# write a compare function
# check if the words are blanagrams just off by one letter
# compare the letters of one word to that of the other full word
# set result to False
# set counter to zero
# calculate matching_letters = length of word1 - 1
# for each letter in word1
# check if letter is also in word2
# add to counter
# if counter greater >= matching letters
# return True
"""
The space complexity is O(n) because the operation slicing
The time complexity is O(1) because the linked list is of fixed length.
and we are iterating once with a fixed length. which is constant
""" |
#!/bin/env python
class Animal(object):
pass
class Dog(object):
def __init__(self): pass
class Cat(object):
def __init__(self): pass
doggy = Dog()
assert type(doggy) == Dog
# Animal: fail
assert type(doggy) == Animal
print type(doggy)
# Cat: fail
assert type(doggy) == Cat
# int: fail
assert type(doggy) == int
|
def bubble_sort(items):
for pass_num in range(len(items)-1,0,-1):
for i in range(pass_num):
if items[i]>items[i+1]:
temp = items[i]
items[i] = items[i+1]
items[i+1] = temp
return items
def merge_sort(items):
if len(items) <= 1:
return items
else:
return merge_sort([a for a in items[1:] if a <= items[0]]) + [items[0]] +\
merge_sort([a for a in items[1:] if a > items[0]])
def quick_sort(items):
if len(items) <= 1:
return items
else:
return quick_sort([b for b in items[1:] if b <= items[0]]) + [items[0]] +\
quick_sort([b for b in items[1:] if b > items[0]])
|
print("===LIST TEMAN DHEA===")
nama_teman = ['Alip', 'Audi', 'Ambon', 'Ayak', 'Echa', 'Rizal', 'Duha', 'Vika', 'Riki', 'Nina']
#isi indeks 4,6, dan 7
print("\n",nama_teman[4],"\n", nama_teman[6],"\n", nama_teman[7])
#mengganti nama teman di list 3,5, dan 9
nama_teman[3] = 'Alyn'
nama_teman[5] = 'Hasna'
nama_teman[9] = 'Nadiya'
print ('')
nama_teman.append('Hani')
nama_teman.append('Rafika')
#iteration
for x in nama_teman :
print(x)
print(len(nama_teman)) |
def getMinimumIndex (list):
minIndex = 0
for i in range (len(list)):
if list [i] < list [minIndex]:
minIndex = i
return minIndex
initialList = eval(input())
sortedList = []
for i in range (len(initialList)):
minIndex = getMinimumIndex(initialList)
sortedList.append(initialList[minIndex])
initialList.pop(minIndex)
print(sortedList) |
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnupt@gmail.com
# Name: Sudoku Solver.py
# Creation Time: 2017/7/2
###########################################
'''
Write a program to solve a Sudoku puzzle by filling the empty cells.
Empty cells are indicated by the character '.'.
You may assume that there will be only one unique solution.
'''
class Solution(object):
def solveSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""
def isValid(x,y):
tmp = board[x][y]
board[x][y] = '.'
for i in range(9):
if board[i][y] == tmp:
return False
for j in range(9):
if board[x][j] == tmp:
return False
for i in range(3):
for j in range(3):
if board[(x/3)*3+i][(y/3)*3+j] == tmp:
return False
board[x][y] = tmp
return True
def dfs(board):
for i in range(9):
for j in range(9):
if board[i][j]=='.':
for k in '123456789':
board[i][j]=k
if isValid(i,j) and dfs(board):
return True
board[i][j]='.'
return False
return True
dfs(board)
|
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnjupt@gmail.com
# Name: Reverse Bits.py
# Creation Time: 2018/3/5
###########################################
'''
Reverse bits of a given 32 bits unsigned integer.
For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000).
Follow up:
If this function is called many times, how would you optimize it?
Related problem: Reverse Integer
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
'''
class Solution(object):
def reverseBits(self, n):
"""
:type n: int
:rtype: int
"""
ret=0
flag=0
while(flag<32):
ret=(ret<<1)+(n&1)
n=n>>1
flag=flag+1
return ret |
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnjupt@gmail.com
# Name: Count of Smaller Numbers After Self.py
# Creation Time: 2017/9/1
###########################################
'''
You are given an integer array nums and you have to return a new counts array. The counts array has the property where counts[i] is the number of smaller elements to the right of nums[i].
Example:
Given nums = [5, 2, 6, 1]
To the right of 5 there are 2 smaller elements (2 and 1).
To the right of 2 there is only 1 smaller element (1).
To the right of 6 there is 1 smaller element (1).
To the right of 1 there is 0 smaller element.
Return the array [2, 1, 1, 0].
'''
# S2
class Node(object):
def __init__(self,val):
self.val = val
self.small = 0
self.left = None
self.right = None
self.cnt = 1
# S3
class BSTree(object):
def __init__(self):
self.root = None
def insert(self,val):
if self.root == None:
self.root = Node(val)
return 0
root = self.root
cnt = 0
while(root):
if val < root.val:
root.small +=1
if root.left is None:
root.left = Node(val)
break
root = root.left
elif val > root.val:
cnt += root.small + root.cnt
if root.right is None:
root.right = Node(val)
break
root = root.right
else:
cnt += root.small
root.cnt +=1
break
return cnt
class SegmentTree(object):
def __init__(self,num):
self.segment = [0] * (4 * num + 10)
def query(self,node,i,j,start,end):
if start>=i and end<=j:
return self.segment[node]
elif end < i or start > j:
return 0
else:
mid = (start + end) / 2
p1 = self.query(2 * node, i, j, start, mid)
p2 = self.query(2 * node + 1, i, j, mid+1, end)
return p1 + p2
def update(self,node,start,end,val):
if start == end:
self.segment[node] +=1
else:
mid = (start+end)/2
if mid>=val:
self.update(2*node,start,mid,val)
else:
self.update(2*node+1,mid+1,end,val)
self.segment[node]+=1
class Solution(object):
def countSmaller(self,nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
maparray = sorted(list(set(nums)))
dict_ = {}
for i in range(len(maparray)):
dict_[maparray[i]] = i
seg_tree = SegmentTree(len(maparray))
ret = [0 for i in range(len(nums))]
for i in range(len(nums)):
idx = len(nums)-1-i
q = dict_[nums[idx]]
ret[idx] = seg_tree.query(1,0,q-1,0,len(maparray)-1)
seg_tree.update(1,0,len(maparray)-1,q)
return ret
def countSmaller_solution2(self,nums): # binary search tree
"""
:type nums: List[int]
:rtype: List[int]
"""
if len(nums)==0:
return []
root = BSTree()
ret = [0 for i in range(len(nums))]
for i in range(len(nums)):
idx = len(nums)-1-i
ret[idx]= root.insert(nums[idx])
return ret
def countSmaller_solution1(self, nums): # binary search insert
"""
:type nums: List[int]
:rtype: List[int]
"""
if len(nums)==0:
return []
new_array = []
ret = [0 for i in range(len(nums))]
def getindex(num):
if new_array == []:
new_array.append(num)
return 0
start = 0
end = len(new_array)
while(start<end):
mid = (start+end)/2
if new_array[mid]>=num:
end = mid
else:
start = mid+1
new_array.insert(end,num)
return end
for i in range(len(nums)):
idx = len(nums)-1-i
ret[idx] = getindex(nums[idx])
return ret
S = Solution()
print S.countSmaller([76,99,51,9,21,84,66,65,36,100,41]) |
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnupt@gmail.com
# Name: Subsets.py
# Creation Time: 2017/7/11
###########################################
'''
Given a set of distinct integers, nums, return all possible subsets.
Note: The solution set must not contain duplicate subsets.
For example,
If nums = [1,2,3], a solution is:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
'''
class Solution(object):
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
ret=[]
if not len(nums):
return ret
for i in range(2**(len(nums))):
tmp=[]
state=list('{:b}'.format(i))
state=['0']*(len(nums)-len(state))+state
for j in range(len(state)):
if state[j]=='1':
tmp.append(nums[j])
ret.append(tmp)
return ret |
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnjupt@gmail.com
# Name: Palindrome Linked List.py
# Creation Time: 2018/2/17
###########################################
'''
Given a singly linked list, determine if it is a palindrome.
Follow up:
Could you do it in O(n) time and O(1) space?
'''
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head==None:
return None
p1=None
p2=head
while(p2):
tmp=p2.next
p2.next=p1
p1=p2
p2=tmp
return p1
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if head==None or head.next==None:
return True
fast=head
slow=head
while(fast and fast.next):
slow=slow.next
fast=fast.next.next
if fast:
slow=self.reverseList(slow.next)
else:
slow=self.reverseList(slow)
while(slow):
if head.val!=slow.val:
return False
slow=slow.next
head=head.next
return True |
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnjupt@gmail.com
# Name: Find K-th Smallest Pair Distance.py
# Creation Time: 2018/4/22
###########################################
'''
Given an integer array, return the k-th smallest distance among all the pairs. The distance of a pair (A, B) is defined as the absolute difference between A and B.
Example 1:
Input:
nums = [1,3,1]
k = 1
Output: 0
Explanation:
Here are all the pairs:
(1,3) -> 2
(1,1) -> 0
(3,1) -> 2
Then the 1st smallest distance pair is (1,1), and its distance is 0.
Note:
2 <= len(nums) <= 10000.
0 <= nums[i] < 1000000.
1 <= k <= len(nums) * (len(nums) - 1) / 2.
'''
import collections
import bisect
import collections
import bisect
class Solution(object):
def smallestDistancePair(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
cnt = collections.Counter(nums)
keys, vals = [], []
for key in sorted(cnt):
keys.append(key)
vals.append(cnt[key] + (vals and vals[-1] or 0))
def countNums(val):
idx = bisect.bisect_right(keys, val)
if idx: return vals[idx - 1]
return 0
def smallerThan(val):
ans = 0
for i, key in enumerate(keys):
ans += (countNums(key + val) - vals[i]) * cnt[key] + cnt[key] * (cnt[key] - 1) / 2
return ans
lo = min(keys[x + 1] - keys[x] for x in range(len(keys) - 1)) if max(cnt.values()) == 1 else 0
hi = keys[-1] - keys[0]
while lo <= hi:
mi = (lo + hi) / 2
if smallerThan(mi) >= k: hi = mi - 1
else: lo = mi + 1
return lo
S = Solution()
print S.smallestDistancePair([1,3,1],1) |
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnjupt@gmail.com
# Name: Range Addition II.py
# Creation Time: 2018/1/8
###########################################
'''
Given an m * n matrix M initialized with all 0's and several update operations.
Operations are represented by a 2D array, and each operation is represented by an array with two positive integers a and b, which means M[i][j] should be added by one for all 0 <= i < a and 0 <= j < b.
You need to count and return the number of maximum integers in the matrix after performing all the operations.
Example 1:
Input:
m = 3, n = 3
operations = [[2,2],[3,3]]
Output: 4
Explanation:
Initially, M =
[[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
After performing [2,2], M =
[[1, 1, 0],
[1, 1, 0],
[0, 0, 0]]
After performing [3,3], M =
[[2, 2, 1],
[2, 2, 1],
[1, 1, 1]]
So the maximum integer in M is 2, and there are four of it in M. So return 4.
'''
class Solution(object):
def maxCount(self, m, n, ops):
"""
:type m: int
:type n: int
:type ops: List[List[int]]
:rtype: int
"""
mincol = m
minrow = n
for op in ops:
mincol = min(mincol,op[0])
minrow = min(minrow,op[1])
return mincol*minrow |
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnjupt@gmail.com
# Name: Path Sum II.py
# Creation Time: 2017/7/20
###########################################
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: List[List[int]]
"""
ret = []
def dfs(root,sum,tmp):
if root != None:
if root.left == None and root.right == None: # leaf node
if root.val == sum:
tmp.append(root.val)
ret.append(tmp[:])
else:
tmp.append(root.val)
dfs(root.left,sum-root.val,tmp[:])
dfs(root.right,sum-root.val,tmp[:])
dfs(root,sum,[])
return ret
|
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnjupt@gmail.com
# Name: Ugly Number.py
# Creation Time: 2018/3/22
###########################################
'''
Write a program to check whether a given number is an ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7.
Note:
1 is typically treated as an ugly number.
Input is within the 32-bit signed integer range.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
'''
|
###########################################
# Author: Tinkle
# E-mail: shutingnupt@gmail.com
# Name: Unique Binary Search Trees II.py
# Creation Time: 2018/5/16
###########################################
'''
Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1 ... n.
Example:
Input: 3
Output:
[
[1,null,3,2],
[3,2,null,1],
[3,1,null,null,2],
[2,1,3],
[1,null,2,null,3]
]
Explanation:
The above output corresponds to the 5 unique BST's shown below:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
'''
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def generateTrees(self, n):
"""
:type n: int
:rtype: List[TreeNode]
"""
arrays = [i for i in range(1, n + 1)]
return self.dp(arrays)
def dp(self, arrays):
if len(arrays) == 1:
return [TreeNode(arrays[0])]
ret = []
for k in range(len(arrays)):
num = arrays[k]
l = arrays[0:k]
r = arrays[k + 1:]
left = self.dp(l)
right = self.dp(r)
if left == []:
for j in range(len(right)):
Node = TreeNode(num)
Node.right = right[j]
ret.append(Node)
if right == []:
for i in range(len(left)):
Node = TreeNode(num)
Node.left = left[i]
ret.append(Node)
for i in range(len(left)):
for j in range(len(right)):
Node = TreeNode(num)
Node.left = left[i]
Node.right = right[j]
ret.append(Node)
return ret
S = Solution()
print S.generateTrees(3)
|
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnupt@gmail.com
# Name: Length of Last Word.py
# Creation Time: 2017/7/6
###########################################
'''
Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.
If the last word does not exist, return 0.
Note: A word is defined as a character sequence consists of non-space characters only.
For example,
Given s = "Hello World",
return 5.
'''
class Solution(object):
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
if s == '':
return 0
x = 0
for i in range(len(s)):
if s[i] != ' ':
if i == 0 or s[i - 1] == ' ':
x = 1
else:
x += 1
return x
|
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnjupt@gmail.com
# Name: Count Numbers with Unique Digits.py
# Creation Time: 2017/9/8
###########################################
'''
Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10n.
Example:
Given n = 2, return 91. (The answer should be the total numbers in the range of 0 ≤ x < 100, excluding [11,22,33,44,55,66,77,88,99])
'''
class Solution(object):
def countNumbersWithUniqueDigits(self, n):
"""
:type n: int
:rtype: int
"""
dp=[1]
for i in range(1,n+1):
if i==1:
dp.append(10)
else:
tmp=9
flag=9
j=i-1
while(j>0):
tmp=tmp*flag
flag=flag-1
j=j-1
dp.append(dp[-1]+tmp)
return dp[-1]
|
###########################################
# Author: Tinkle
# E-mail: shutingnupt@gmail.com
# Name: Container With Most Water.py
# Creation Time: 2017/6/23
###########################################
'''
Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai).
n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines,
which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container and n is at least 2.
'''
class Solution(object):
def maxArea(self,height):
'''
:param height: list[(int,int)]
:return: int
'''
ma = 0
start = 0
end = len(height)-1
while(start<end):
ma = max(ma,min(height[start],height[end])*(end-start))
if(height[start]<height[end]):
k = start
while(k<end and height[k]<=height[start]):
k = k+1
start = k
else:
k = end
while(k>start and height[k]<=height[end]):
k = k-1
end = k
return ma
S = Solution()
print S.maxArea([1,1]) |
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnjupt@gmail.com
# Name: K-th Symbol in Grammar.py
# Creation Time: 2018/2/9
###########################################
'''
On the first row, we write a 0. Now in every subsequent row, we look at the previous row and replace each occurrence of 0 with 01, and each occurrence of 1 with 10.
Given row N and index K, return the K-th indexed symbol in row N. (The values of K are 1-indexed.) (1 indexed).
Examples:
Input: N = 1, K = 1
Output: 0
Input: N = 2, K = 1
Output: 0
Input: N = 2, K = 2
Output: 1
Input: N = 4, K = 5
Output: 1
Explanation:
row 1: 0
row 2: 01
row 3: 0110
row 4: 01101001
Note:
N will be an integer in the range [1, 30].
K will be an integer in the range [1, 2^(N-1)].
'''
class Solution(object):
def kthGrammar(self, N, K):
"""
:type N: int
:type K: int
:rtype: int
"""
if N == 1: return 0
ans = self.kthGrammar(N - 1, (K + 1) / 2)
return 0 if ans ^ (K%2) else 1
S = Solution()
print S.kthGrammar(4,5) |
###########################################
# Author: Tinkle
# E-mail: shutingnupt@gmail.com
# Name: Swap Nodes in Pairs.py
# Creation Time: 2017/6/30
###########################################
'''
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
'''
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
ans = ListNode(0)
ans.next = head
tmp = ans
while (tmp!=None and tmp.next!=None and tmp.next.next!=None):
p1 = tmp.next
p2 = tmp.next.next
tmp1 = p2.next
p2.next = p1
p1.next = tmp1
tmp.next = p2
tmp = tmp.next.next
return ans.next
head = ListNode(1)
#head.next = ListNode(2)
#head.next.next = ListNode(3)
#head.next.next.next = ListNode(4)
S = Solution()
a = S.swapPairs(head)
while(a!=None):
print a.val
a = a.next
|
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnjupt@gmail.com
# Name: Find Minimum in Rotated Sorted Array.py
# Creation Time: 2017/7/30
###########################################
'''
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
Find the minimum element.
You may assume no duplicate exists in the array.
'''
class Solution(object):
def findMin(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
start = 0;
end = len(nums) - 1
while (start < end):
mid = start + (end - start) / 2
if mid != len(nums) - 1 and nums[mid] > nums[mid + 1]:
return nums[mid + 1]
elif nums[mid] < nums[start]:
end = mid
elif nums[mid] > nums[end]:
start = mid
else:
return nums[start]
return nums[start]
|
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnjupt@gmail.com
# Name: Different Ways to Add Parentheses.py
# Creation Time: 2017/8/25
###########################################
'''
Given a string of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. The valid operators are +, - and *.
Example 1
Input: "2-1-1".
((2-1)-1) = 0
(2-(1-1)) = 2
Output: [0, 2]
Example 2
Input: "2*3-4*5"
(2*(3-(4*5))) = -34
((2*3)-(4*5)) = -14
((2*(3-4))*5) = -10
(2*((3-4)*5)) = -10
(((2*3)-4)*5) = 10
Output: [-34, -14, -10, -10, 10]
'''
class Solution(object):
def diffWaysToCompute(self, input):
"""
:type input: str
:rtype: List[int]
"""
ret = []
for i in range(len(input)):
if input[i] == '-' or input[i] == '+' or input[i] == '*':
left = self.diffWaysToCompute(input[:i])
right = self.diffWaysToCompute(input[i+1:])
for j in range(len(left)):
for k in range(len(right)):
if input[i]=='-':
ret.append(left[j]-right[k])
if input[i]=='+':
ret.append(left[j]+right[k])
if input[i]=='*':
ret.append(left[j]*right[k])
if len(ret)==0:
ret.append(int(input))
return ret
S = Solution()
print S.diffWaysToCompute('2*3-4*5') |
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnupt@gmail.com
# Name:Set Matrix Zeroes.py
# Creation Time: 2017/7/10
###########################################
'''
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
'''
class Solution(object):
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
m = len(matrix)
if m==0:
return
n = len(matrix[0])
mark=1
for i in range(m):
if matrix[i][0] == 0:
mark = 0
for j in range(1,n):
if matrix[i][j]==0:
matrix[i][0]=0
matrix[0][j]=0
#print matrix,mark
for i in range(m):
for j in range(0,n-1):
if matrix[m-1-i][0]==0 or matrix[0][n-1-j]==0:
matrix[m-1-i][n-1-j]=0
if mark == 0:
matrix[m - 1 - i][0] = 0 |
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnupt@gmail.com
# Name: Add Binary.py
# Creation Time: 2017/7/7
###########################################
'''
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
'''
class Solution(object):
def swap(self,a,b):
a1,b1=list(a),list(b)
a1.reverse()
b1.reverse()
max_num=max(len(a1),len(b1))
if len(a1)<max_num:
a1=a1+['0']*(max_num-len(a1))
else:
b1=b1+['0']*(max_num-len(b1))
return a1,b1
def addBinary(self, aa, bb):
"""
:type a: str
:type b: str
:rtype: str
"""
ret=[]
flag=0
a,b=self.swap(aa,bb)
for i in range(len(a)):
tmp=int(a[i])+int(b[i])+flag
if tmp/2==1:
flag=1
else:
flag=0
ret.append(str(tmp%2))
if flag==1:
ret.append('1')
ret.reverse()
return ''.join(ret) |
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnjupt@gmail.com
# Name: 2 Keys Keyboard.py
# Creation Time: 2018/1/5
###########################################
'''
Initially on a notepad only one character 'A' is present. You can perform two operations on this notepad for each step:
Copy All: You can copy all the characters present on the notepad (partial copy is not allowed).
Paste: You can paste the characters which are copied last time.
Given a number n. You have to get exactly n 'A' on the notepad by performing the minimum number of steps permitted. Output the minimum number of steps to get n 'A'.
Example 1:
Input: 3
Output: 3
Explanation:
Intitally, we have one character 'A'.
In step 1, we use Copy All operation.
In step 2, we use Paste operation to get 'AA'.
In step 3, we use Paste operation to get 'AAA'.
'''
class Solution(object):
def minSteps(self, n):
"""
:type n: int
:rtype: int
"""
if n <=1:
return 0
dp = [0 for i in range(n+1)]
for i in range(2,n+1):
dp[i]=i
for k in range(2,i/2+1):
if i%k==0:
dp[i]=min(dp[i],dp[k]+i/k)
return dp[-1]
S = Solution()
print S.minSteps(6) |
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnjupt@gmail.com
# Name: Binary Tree Right Side View
# Creation Time: 2017/8/13
###########################################
'''
Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
For example:
Given the following binary tree,
1 <---
/ \
2 3 <---
\ \
5 4 <---
You should return [1, 3, 4].
'''
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if root == None:
return []
queue = []
queue.append((root,0))
ret = []
while(len(queue)):
cur = queue.pop()
cur_node = cur[0]
index = cur[1]
if index>=len(ret):
ret.append(cur_node.val)
if cur_node.left:
queue.append((cur_node.left,index+1))
if cur_node.right:
queue.append((cur_node.right,index+1))
return ret
root = TreeNode(1)
root.left = TreeNode(2)
root.left.left = TreeNode(4)
root.right = TreeNode(3)
S = Solution()
print S.rightSideView(root)
|
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnjupt@gmail.com
# Name: Majority Element.py
# Creation Time: 2018/3/5
###########################################
'''
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
Seen this question in a real interview before?
'''
class Solution:
# @param {integer[]} nums
# @return {integer}
def majorityElement(self, nums):
bit = [0] * 32
for num in nums:
for j in xrange(32):
bit[j] += num >> j & 1
res = 0
for i, val in enumerate(bit):
if val > len(nums) // 2:
if i == 31:
res = -((1 << 31) - res)
else:
res |= 1 << i
return res |
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnjupt@gmail.com
# Name: Maximum XOR of Two Numbers in an Array.py
# Creation Time: 2017/10/11
###########################################
'''
Given a non-empty array of numbers, a0, a1, a2, … , an-1, where 0 ≤ ai < 231.
Find the maximum result of ai XOR aj, where 0 ≤ i, j < n.
Could you do this in O(n) runtime?
Example:
Input: [3, 10, 5, 25, 2, 8]
Output: 28
Explanation: The maximum result is 5 ^ 25 = 28.
'''
import sys
class Node(object):
def __init__(self):
self.val = [None,None]
class Solution(object):
def findMaximumXOR(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if nums == [] or len(nums)<2:
return 0
root = Node()
ret = -sys.maxint
for num in nums:
tmp = root
i = 30
while(i>=0):
bit = num & (1<<i)
if bit!=0:
bit=1
if tmp.val[bit]==None:
tmp.val[bit]=Node()
tmp = tmp.val[bit]
i-=1
tmp = root
res = 0
i = 30
while(i>=0):
bit = num & (1<<i)
if bit !=0:
bit = 1
if tmp.val[1-bit]==None:
tmp = tmp.val[bit]
res += bit<<i
else:
tmp = tmp.val[1-bit]
res += (1-bit)<<i
i-=1
ret = max(ret,res^num)
return ret
def findMaximumXOR1(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if nums == [] or len(nums)<2:
return 0
root = Node()
for num in nums:
tmp = root
i = 30
while(i>=0):
bit = num & (1<<i)
if bit!=0:
bit=1
if tmp.val[bit]==None:
tmp.val[bit]=Node()
tmp = tmp.val[bit]
i-=1
ret = -sys.maxint
for num in nums:
tmp = root
res = 0
i = 30
while(i>=0):
bit = num & (1<<i)
if bit !=0:
bit = 1
if tmp.val[1-bit]==None:
tmp = tmp.val[bit]
res += bit<<i
else:
tmp = tmp.val[1-bit]
res += (1-bit)<<i
i-=1
ret = max(ret,res^num)
return ret
S = Solution()
print S.findMaximumXOR([3,10,5,25,2,8]) |
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnjupt@gmail.com
# Name: Employee Importance.py
# Creation Time: 2018/4/7
###########################################
"""
# Employee info
class Employee(object):
def __init__(self, id, importance, subordinates):
# It's the unique id of each node.
# unique id of this employee
self.id = id
# the importance value of this employee
self.importance = importance
# the id of direct subordinates
self.subordinates = subordinates
"""
class Solution(object):
def getImportance(self, employees, id):
"""
:type employees: Employee
:type id: int
:rtype: int
"""
emp = dict()
visited = dict()
for employee in employees:
emp[employee.id] = employee
def dfs(idx):
if idx in visited:
return 0
visited[idx] = True
ret=emp[idx].importance
for sub in emp[idx].subordinates:
ret+=dfs(sub)
return ret
return dfs(id) |
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnjupt@gmail.com
# Name: Perfect Squares.py
# Creation Time: 2017/8/26
###########################################
'''
Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.
For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9.
'''
class Solution(object):
def numSquares(self, n):
"""
:type n: int
:rtype: int
"""
dp = [i for i in range(n+1)]
for i in range(n+1):
j=1
while(i+j*j<=n):
dp[i+j*j] = min(dp[i+j*j],dp[i]+1)
j +=1
#print dp
return dp[n]
S = Solution()
print S.numSquares(100)
|
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnupt@gmail.com
# Name: Longest Palindromic Subsequence.py
# Creation Time: 2018/3/17
###########################################
'''
Given a string s, find the longest palindromic subsequence's length in s. You may assume that the maximum length of s is 1000.
Example 1:
Input:
"bbbab"
Output:
4
One possible longest palindromic subsequence is "bbbb".
Example 2:
Input:
"cbbd"
Output:
2
One possible longest palindromic subsequence is "bb".
'''
class Solution(object):
def longestPalindromeSubseq(self, s):
"""
:type s: str
:rtype: int
"""
size = len(s)
s1 = s[::-1]
if s1 == s: return size
dp = [[0]*(size+1) for i in range(size+1)]
for i in range(size):
for j in range(size):
if s[i]==s1[j]:
dp[i+1][j+1] = dp[i][j]+1
else:
dp[i+1][j+1] = max(dp[i][j+1],dp[i+1][j])
return dp[size][size] |
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnjupt@gmail.com
# Name: Implement strStr().py
# Creation Time: 2017/1/21
###########################################
'''
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
'''
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if needle=='':
return 0
haystack = '#'+haystack
n = len(haystack)
needle = '#'+needle
m = len(needle)
pos = self.compute_prefix_func(needle)
q = 0
for i in range(1,n):
while(q>0 and needle[q+1]!=haystack[i]):
q = pos[q]
if needle[q+1] == haystack[i]:
q = q+1
if q == m-1:
return i-(m-1)
if q == m - 1:
return n - m
return -1
def compute_prefix_func(self,pattern):
'''
:param pattern: str
:return: list[int]
'''
newpatter = pattern
length = len(newpatter)
pos = [0 for i in range(length)]
k =0
for q in range(2,length):
while(k>0 and newpatter[k+1]!=newpatter[q]):
k = pos[k]
if newpatter[k+1]==newpatter[q]:
k = k+1
pos[q] = k
return pos
|
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnjupt@gmail.com
# Name: Number of Atoms.py
# Creation Time: 2018/3/6
###########################################
'''
Given a chemical formula (given as a string), return the count of each atom.
An atomic element always starts with an uppercase character, then zero or more lowercase letters, representing the name.
1 or more digits representing the count of that element may follow if the count is greater than 1. If the count is 1, no digits will follow. For example, H2O and H2O2 are possible, but H1O2 is impossible.
Two formulas concatenated together produce another formula. For example, H2O2He3Mg4 is also a formula.
A formula placed in parentheses, and a count (optionally added) is also a formula. For example, (H2O2) and (H2O2)3 are formulas.
Given a formula, output the count of all elements as a string in the following form: the first name (in sorted order), followed by its count (if that count is more than 1), followed by the second name (in sorted order), followed by its count (if that count is more than 1), and so on.
Example 1:
Input:
formula = "H2O"
Output: "H2O"
Explanation:
The count of elements are {'H': 2, 'O': 1}.
Example 2:
Input:
formula = "Mg(OH)2"
Output: "H2MgO2"
Explanation:
The count of elements are {'H': 2, 'Mg': 1, 'O': 2}.
Example 3:
Input:
formula = "K4(ON(SO3)2)2"
Output: "K4N2O14S4"
Explanation:
The count of elements are {'K': 4, 'N': 2, 'O': 14, 'S': 4}.
'''
import collections
class Solution(object):
def countOfAtoms(self, formula):
"""
:type formula: str
:rtype: str
"""
stack = [collections.defaultdict(int)]
idx = 0
while(idx<len(formula)):
token = formula[idx]
if token>='A' and token<='Z':
ch = token
idx+=1
cnt=0
while (idx < len(formula) and formula[idx]>='a' and formula[idx]<='z'):
ch+=formula[idx]
idx += 1
while (idx < len(formula) and formula[idx].isdigit()):
cnt = cnt*10+int(formula[idx])
idx += 1
if cnt:
stack[-1][ch]+=cnt
else:
stack[-1][ch]+= 1
idx-=1
elif token=='(':
stack.append(collections.defaultdict(int))
elif token==')':
idx +=1
cnt = 0
while(idx<len(formula) and formula[idx].isdigit()):
cnt = cnt*10+int(formula[idx])
idx+=1
if cnt:
for key in stack[-1]:
stack[-1][key] = stack[-1][key]*cnt
tstack = stack.pop()
for key in tstack:
stack[-1][key]+=tstack[key]
idx-=1
idx+=1
ret = ''
for x in sorted(stack[-1].items(),key=lambda x:x[0]):
if x[1]!=1:
ret+=x[0]+str(x[1])
else:
ret+=x[0]
return ret
S = Solution()
print S.countOfAtoms("H2O")
print S.countOfAtoms("Mg(OH)2")
print S.countOfAtoms("K4(ON(SO3)2)2") |
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnjupt@gmail.com
# Name: Longest Consecutive Sequence.py
# Creation Time: 2017/7/22
###########################################
'''
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
Your algorithm should run in O(n) complexity.
'''
class Solution(object):
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
Map = {}
for num in nums:
Map[num] = True
ret = 0
for k,v in Map.items():
if not v:
continue
left = k-1
right = k+1
while(left in Map and Map[left]):
Map[left] = False
left = left-1
while(right in Map and Map[right]):
Map[right] = False
right = right+1
ret = max(ret,right-left-1)
return ret
|
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnjupt@gmail.com
# Name: Reverse Vowels of a String.py
# Creation Time: 2017/9/8
###########################################
'''
Write a function that takes a string as input and reverse only the vowels of a string.
Example 1:
Given s = "hello", return "holle".
Example 2:
Given s = "leetcode", return "leotcede".
Note:
The vowels does not include the letter "y".
'''
class Solution(object):
def reverseVowels(self,s):
dic=['a','o','e','i','u','A','O','E','I','U']
if s == '':
return s
start = 0
end = len(s)-1
tmp = list(s)
while(True):
while(start<end and tmp[start] not in dic):
start +=1
while(start<end and tmp[end] not in dic):
end -=1
if start>=end:
break
else:
t = tmp[start]
tmp[start] = tmp[end]
tmp[end] = t
start+=1
end -=1
return ''.join(tmp)
def reverseVowels_(self, s):
"""
:type s: str
:rtype: str
"""
dic=['a','o','e','i','u','A','O','E','I','U']
context=[]
index=[]
for i in range(len(s)):
if s[i] in dic:
context.append(s[i])
index.append(i)
context.reverse()
tmp=list(s)
for i in range(len(index)):
tmp[index[i]]=context[i]
return ''.join(tmp) |
# - * - coding:utf8 - * - -
###########################################
# Author: Tinkle
# E-mail: shutingnjupt@gmail.com
# Name: Create Maximum Number.py
# Creation Time: 2017/9/2
###########################################
'''
Given two arrays of length m and n with digits 0-9 representing two numbers. Create the maximum number of length k <= m + n from digits of the two. The relative order of the digits from the same array must be preserved. Return an array of the k digits. You should try to optimize your time and space complexity.
Example 1:
nums1 = [3, 4, 6, 5]
nums2 = [9, 1, 2, 5, 8, 3]
k = 5
return [9, 8, 6, 5, 3]
Example 2:
nums1 = [6, 7]
nums2 = [6, 0, 4]
k = 5
return [6, 7, 6, 0, 4]
Example 3:
nums1 = [3, 9]
nums2 = [8, 9]
k = 3
return [9, 8, 9]
'''
class Solution(object):
def maxNumber(self, nums1, nums2, k):
"""
:type nums1: List[int]
:type nums2: List[int]
:type k: int
:rtype: List[int]
"""
def getmaxarray(nums,t):
stack = []
size = len(nums)
for idx in range(size):
while stack and stack[-1]<nums[idx] and len(stack)+size-idx>t:
stack.pop()
if len(stack)<t:
stack.append(nums[idx])
return stack
def merge(nums1,nums2):
ans = []
while nums1 or nums2:
if nums1 > nums2:
ans.append(nums1[0])
nums1 = nums1[1:]
else:
ans.append(nums2[0])
nums2 = nums2[1:]
return ans
ret = []
if len(nums1)>len(nums2):
nums1,nums2 = nums2,nums1
len1,len2 = len(nums1),len(nums2)
for idx in range(max(0,k-len2),min(k,len1)+1):
tmp = merge(getmaxarray(nums1,idx),getmaxarray(nums2,k-idx))
ret = max(tmp,ret)
return ret
S = Solution()
print S.maxNumber([9, 1, 2, 5, 8, 3],[3, 4, 6, 5],5) |
###########################################
# Author: Tinkle
# E-mail: shutingnupt@gmail.com
# Name: K-diff Pairs in an Array.py
# Creation Time: 2018/4/18
###########################################
'''
defined as an integer pair (i, j), where i and j are both numbers in the array and their absolute difference is k.
Example 1:
Input: [3, 1, 4, 1, 5], k = 2
Output: 2
Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5).
Although we have two 1s in the input, we should only return the number of unique pairs.
Example 2:
Input:[1, 2, 3, 4, 5], k = 1
Output: 4
Explanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5).
Example 3:
Input: [1, 3, 1, 5, 4], k = 0
Output: 1
Explanation: There is one 0-diff pair in the array, (1, 1).
Note:
The pairs (i, j) and (j, i) count as the same pair.
The length of the array won't exceed 10,000.
All the integers in the given input belong to the range: [-1e7, 1e7].
'''
import collections
class Solution(object):
def findPairs(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
if k<0:
return 0
dicts = collections.defaultdict(int)
ret = 0
for num in nums:
dicts[num]+=1
for num in dicts:
if k == 0 and dicts[num]>1:
ret+=1
if k!=0 and num+k in dicts:
ret+=1
return ret
|
class Board:
pieces = {
"O": [(0, 0), (0, -1), (-1, 0), (-1, -1)],
"I": [(-2, 0), (-1, 0), (0, 0), (1, 0)],
"S": [(0, 0), (1, 0), (0, -1), (-1, -1)],
"Z": [(-1, 0), (0, 0), (0, -1), (1, -1)],
"L": [(-1, 0), (-1, -1), (0, 0), (1, 0)],
"J": [(-1, 0), (0, 0), (1, 0), (1, -1)],
"T": [(-1, 0), (0, -1,), (0, 0), (1, 0)]
}
colors = {
" ": "grey",
"O": "yellow",
"I": "cyan",
"S": "red",
"Z": "green",
"L": "orange",
"J": "pink",
"T": "purple"
}
def __init__(self, numRows, numCols, sqwidth):
self.board = [[" " for i in range(numCols)] for j in range(numRows)]
self.rows = numRows
self.cols = numCols
self.centerCol = self.cols // 2 - 1
self.square_width = sqwidth
self.currentPieceCoord = None
self.currentPieceType = " "
def __repr__(self):
s = ""
for i in range(self.rows):
s += "|"
for j in range(self.cols):
s += str(self.board[i][j]) + "|"
s += "\n"
return s
def add_piece(self, piece):
piece_schematic = Board.pieces[piece]
curPieceCoord = []
for coordinate in piece_schematic:
coord = (0-coordinate[1], self.centerCol-coordinate[0])
self.board[coord[0]][coord[1]] = piece
curPieceCoord.append(coord)
self.currentPieceCoord = curPieceCoord
self.currentPieceType = piece
def moveCurDown(self):
for i in range(len(self.currentPieceCoord)):
cod = self.currentPieceCoord[i]
self.board[cod[0]][cod[1]] = " "
self.currentPieceCoord[i] = (cod[0] + 1, cod[1])
self.board[self.currentPieceCoord[i][0]][self.currentPieceCoord[i][1]] = self.currentPieceType
def piece_at(self, row, col):
return self.board[row][col]
def main():
b = Board(20, 10, 10)
#print(b)
b.add_piece("O")
print(b)
if __name__ == "__main__":
main()
|
'''
Your function should take in a single parameter (a string `word`)
Your function should return a count of how many occurences of ***"th"*** occur within `word`. Case matters.
Your function must utilize recursion. It cannot contain any loops.
'''
def count_th(word):
th_count = 0
th_index = word.find("th")
if th_index >= 0 and th_index+2 >= len(word):
return 1
elif th_index >= 0:
th_count += 1
slice_word = word[(th_index+2):]
th_count += count_th(slice_word)
return th_count
count_th("thhtthht")
|
#!python
#cython: language_level=3
import collections
from collections.abc import Iterable
from scipy.sparse import vstack
import numpy as np
import pandas as pd
def quicksort(xs):
if not xs:
return []
return quicksort([x for x in xs if x < xs[0]]) + [x for x in xs if x == xs[0]] + quicksort(
[x for x in xs if x > xs[0]])
def batch(iterable, n: int = 1):
"""
Return a dataset in batches (no overlap)
:param iterable: the item to be returned in segments
:param n: length of the segments
:return: generator of portions of the original data
"""
for ndx in range(0, len(iterable), n):
yield iterable[ndx:max(ndx+n, 1)]
def window(seq, n, fillvalue=None, step=1):
"""Return a sliding window of width *n* over the given iterable.
>>> all_windows = window([1, 2, 3, 4, 5], 3)
>>> list(all_windows)
[(1, 2, 3), (2, 3, 4), (3, 4, 5)]
When the window is larger than the iterable, *fillvalue* is used in place
of missing values::
>>> list(window([1, 2, 3], 4))
[(1, 2, 3, None)]
Each window will advance in increments of *step*:
>>> list(window([1, 2, 3, 4, 5, 6], 3, fillvalue='!', step=2))
[(1, 2, 3), (3, 4, 5), (5, 6, '!')]
To slide into the iterable's items, use :func:`chain` to add filler items
to the left:
>>> iterable = [1, 2, 3, 4]
>>> n = 3
>>> padding = [None] * (n - 1)
>>> list(window(itertools.chain(padding, iterable), 3))
[(None, None, 1), (None, 1, 2), (1, 2, 3), (2, 3, 4)]
"""
if n < 0:
raise ValueError('n must be >= 0')
if n == 0:
yield tuple()
return
if step < 1:
raise ValueError('step must be >= 1')
it = iter(seq)
window = collections.deque([], n)
append = window.append
# Initial deque fill
for _ in range(n):
append(next(it, fillvalue))
yield tuple(window)
# Appending new items to the right causes old items to fall off the left
i = 0
for item in it:
append(item)
i = (i + 1) % step
if i % step == 0:
yield tuple(window)
# If there are items from the iterable in the window, pad with the given
# value and emit them.
if (i % step) and (step - i < n):
for _ in range(step - i):
append(fillvalue)
yield tuple(window)
def extend_timeseries_dates(timeseries, n_new_periods):
"""
Given a set of datetimes, add n number of new datetimes equally spaced after the existing ones and return it
:param timeseries: an iterable of datetime objects spaced less than 1 month apart
:param n_new_periods: an integer of the number of new periods to be added
:return: a list of the original dates with the new dates appended to the end
Notes:
1. Cannot support Month & Year iterations. Must be divisible into days/hours/minutes/etc.
2. Dates need to be sorted ahead of time, otherwise the time interval will be very odd
"""
if isinstance(timeseries[0], pd._libs.tslibs.timestamps.Timestamp):
timeseries = timeseries.tz_localize(None)
timeseries = list([np.datetime64(x) for x in timeseries.copy()])
avg_timedelta = np.mean([x[1]-x[0] for x in window(timeseries, 2)])
for _ in range(n_new_periods):
timeseries.append(timeseries[-1]+avg_timedelta)
return timeseries
def iter_check(x):
return not isinstance(x, str) and isinstance(x, Iterable)
def flatten(xs):
if len(xs)>0 and iter_check(xs[0]):
return flatten([item for sublist in xs for item in sublist])
else:
return xs
def flat_map(func, iterable):
"""
Flat Map - nothing further required
:param func: function
:param iterable: iterable
:return: generator
"""
for element in flatten([x for x in map(func, iterable)]):
yield element
def flatten_dict(d, parent_key='', sep='->'):
items = []
for k, v in d.items():
new_key = parent_key + sep + k if parent_key else k
if isinstance(v, dict):
items.extend(flatten_dict(v, new_key, sep=sep).items())
else:
items.append((new_key, v))
return dict(items)
def balanced_random_sample(data: np.array, stratum: np.array, how: str = 'both',
fixed_size: int = None, random_state = None, #drop_undersized_classes: bool = False,
with_replacement: bool = True) -> (np.array, np.array):
"""
Create a random sample that balances the classes so that the training data is not wildly skewed to a single class
Parameters
----------
data : np.array
the training data (X) values that we are going to sample from. It should line up with the stratum data
which will be used to select which rows are going to make it into the sample.
stratum : np.array
the column/data (y) that is going to be used to determine the classes/groupings that we are sampling for.
how : str {'undersampe', 'oversample', 'both'}
'undersample': take a random sample from the larger classes, and use most/all data from the smallest
'oversample': use most/all of the largest class, and resample from the smaller classes to increase the sample
sizes
'both': 50th percentile of sizes, and oversample/undersample from the larger/smaller classes to balance
them
fixed_size : int
the fixed sample size for the classes. Overrides the 'how' parameter
random_state : int or None
initialization value for the random number generator
with_replacement : bool
if True, will sample with replacement.
#drop_undersized_classes: bool - TODO: build support for this
Returns
-------
(data_sample: np.array, stratum_sample: np.array) - will return a tuple of two arrays, the first is the sampled
data, and the second is the corresponding stratum labels.
Examples
--------
>>> collections.Counter(y)
Counter({'class_1': 300,
'class_2': 100})
>>> X_sample, y_sample = balanced_random_sample(X, y)
>>> collections.Counter(y_sample)
Counter({'class_1': 100,
'class_2': 100})
"""
# Handle the random seeding
if isinstance(random_state, int):
np.random.seed(random_state)
stratum_counter = collections.Counter(stratum)
n_classes = len(stratum_counter.keys())
# Main switching
if how == 'undersample':
class_size = int(np.min(list(stratum_counter.values())))
elif how == 'oversample':
class_size = int(np.max(list(stratum_counter.values())))
elif how == 'both':
class_size = int(np.percentile(list(stratum_counter.values()), 50))
else:
raise ValueError("Invalid value passed for 'how' parameter. Must be in {'undersample', 'oversample', 'both}.")
if fixed_size is not None:
class_size = fixed_size
data_result = None
stratum_result = None
# for each class
for strat in stratum_counter.keys():
# Get the indexes of the stratum that are part of this class
idxs = np.where(stratum == strat)[0]
# Use np.random.choice to select the indexes that we will keep/use
choice_idxs = np.random.choice(idxs, size=class_size, replace=with_replacement)
# Add the sampled data in with the final values
if data_result is None:
stratum_result = stratum[choice_idxs]
data_result = data[choice_idxs]
else:
stratum_result = np.concatenate((stratum_result, stratum[choice_idxs]))
data_result = vstack((data_result, data[choice_idxs]))
# randomly sort the final array (shuffle
final_idx = np.arange(len(stratum_result))
np.random.shuffle(final_idx)
# return the sorted values
return data_result[final_idx], stratum_result[final_idx]
|
# Import turtle graphics library
import turtle
# Import math functions
from math import *
from random import *
def random_color(turtle):
r, g, b = randint(0, 255), randint(0, 255), randint(0, 255)
turtle.pencolor((r, g, b))
# draw a square centered at the current cursor position
# TODO 1: convert drawSquareFromCenter() to use a loop to draw the 4 sides of the square
def drawSquareFromCenter(turtle,x):
turtle.penup()
turtle.forward(-x / 2)
turtle.right(90)
turtle.forward(x / 2)
turtle.left(90)
for i in range(4):
random_color(turtle)
turtle.pendown()
turtle.forward(x)
turtle.left(90)
turtle.penup()
turtle.forward(x / 2)
turtle.left(90)
turtle.forward(x / 2)
turtle.right(90)
# right turn movement function to move from corner to center of square
def moveToCenterRightAngle(turtle, size):
turtle.penup()
turtle.forward(size/2)
turtle.left(90)
turtle.forward(size/2)
turtle.right(90)
# diagonal movement function between centers of 2 squares
def moveToCenterDiagonal(turtle, sizeSrc, sizeDest):
turtle.penup()
dx = (sizeDest - sizeSrc) / 2
dy = (sizeSrc + sizeDest) / 2
dist = sqrt(dx**2 + dy**2)
angle = degrees(atan2(dx, dy))
turtle.left(angle)
turtle.forward(dist)
turtle.right(angle)
# equilateral triangle function
# TODO 2: convert drawEquiTriangle() to use a loop to draw the 3 sides of the triangle
def drawEquiTriangle(turtle, size):
turtle.pendown()
for i in range(3):
random_color(turtle)
turtle.forward(size)
turtle.left(120)
turtle.penup()
# right triangle function
def drawRightTriangle(turtle, base, height):
random_color(turtle)
hyp = sqrt(base**2 + height**2)
angle = degrees(atan2(base, height))
turtle.pendown()
turtle.forward(base)
turtle.left(90)
turtle.forward(height)
turtle.left(180 - angle)
turtle.forward(hyp)
turtle.left(90 + angle)
turtle.penup()
# isoosceles triangle function
def drawIsoTriangle(turtle, base, height):
random_color(turtle)
side = sqrt((base/2)**2 + height**2)
angle = degrees(atan2(height, base/2))
turtle.pendown()
turtle.forward(base)
turtle.left(180 - angle)
turtle.forward(side)
turtle.left(angle * 2)
turtle.forward(side)
turtle.left(180 - angle)
turtle.penup()
# TODO 3: implement drawRegHexagon(turtle, size) so that it calls
# TODO 3: drawEquiTriangle() within a loop to draw a regular hexagon with triangles
# TODO 3: make sure to return the cursor to its original location and orientation
def drawRegHexagon(turtle, size):
for i in range(6):
drawEquiTriangle(turtle, size)
turtle.lt(60)
# TODO 4: implement a function that uses a loop to generate a hexagon using
# TODO 4: incrementally increasing equilateral triangles
# TODO 4: use the loop counter to calculate the sizes of the sides of the hexagon so that each
# TODO 4: side is size/5 pixels bigger than the previous side
# TODO 4: the last triangle drawn will be twice the size of the first triangle drawn
# TODO 4: make sure to return the cursor to its original location and orientation
def drawPinwheelHexagon(turtle, size):
current_size = size
for i in range(6):
current_size += (size / 5)
drawEquiTriangle(turtle, current_size)
turtle.lt(60)
# TODO 5: implement a function that draws a 4-pointed star, using the following functions:
# TODO 5: drawSquareFromCenter() and drawIsoTriangle()
# TODO 5: after drawing the center square, use a loop to draw the 4 points of the star around the square
# TODO 5: the name of the function should be drawStar(), and it should accept the following 3 parameters:
# TODO 5: turtle: the turtle object that will do the drawing
# TODO 5: size: the size of the center square (also the base of the isosceles triangles)
# TODO 5: height: the height of the isosceles triangles that make up the points of the star
# TODO 5: make sure to return the cursor to its original location and orientation
def drawStar(turtle,size,height):
drawSquareFromCenter(turtle,size)
distance = size/2
turtle.bk(distance)
turtle.lt(90)
turtle.bk(distance)
turtle.rt(90)
for i in range(4):
drawIsoTriangle(turtle,size,-height)
turtle.fd(size)
turtle.lt(90)
turtle.fd(distance)
turtle.lt(90)
turtle.fd(distance)
turtle.rt(90)
def main():
# get user input
size = int(input('Enter size for EquiTriangles, base of IsoTriangles, and square in star: '))
height = int(input('Enter height for IsoTriangles (points of star): '))
radius = int(input('Enter radius of star constellation: '))
stars = int(input('Enter number of stars in constellation: '))
# create turtle
bob = turtle.Turtle()
screen = turtle.Screen()
screen.colormode(255)
bob.pensize(2.5)
# draw equilateral triangle
drawEquiTriangle(bob, size)
# wait for user
input("[ Press any key to draw isosceles triangle ]")
bob.clear()
# draw isosceles triangle
drawIsoTriangle(bob, size, height)
# wait for user
input("[ Press any key to draw regular hexagon ]")
bob.clear()
# draw regular hexagon
drawRegHexagon(bob, size)
# wait for user
input("[ Press any key to draw pinwheel hexagon ]")
bob.clear()
# draw pinwheel hexagon using equilateral triangles
drawPinwheelHexagon(bob, size)
# wait for user
input("[ Press any key to draw the central star ]")
bob.clear()
# TODO 6: call the function to draw 4-pointed star at center
# TODO 6: size specifies the size of the square and the base of the iso triangles
# TODO 6: height specifies the height of the iso triangles (points of the stars)
drawStar(bob,size,height)
# wait for user
input("[ Press any key to draw the constellation of stars ]")
# TODO 7: use a loop to draw a constellation of stars around the central star
# TODO 7: radius specifies the distance from the origin to the center of each star
# TODO 7: stars specifies the # of stars to draw around the central star
# TODO 7: make sure that the stars are evenly spaced around the central star
# TODO 7: make sure to return the cursor to its original location and orientation
for i in range(stars):
distance = radius
bob.fd(distance)
random_color(bob)
drawStar(bob, size, height)
bob.bk(distance)
angle = int(360 / stars)
bob.rt(angle)
# Press any key to exit
input("Press any key to exit")
main()
|
# Import turtle graphics library
import turtle
# Import math functions
from math import *
# Function to draw a square about the current position
def drawSquareFromCenter(turtle, x):
turtle.penup()
turtle.forward(-x / 2)
turtle.right(90)
turtle.forward(x / 2)
turtle.left(90)
turtle.pendown()
turtle.forward(x)
turtle.left(90)
turtle.forward(x)
turtle.left(90)
turtle.forward(x)
turtle.left(90)
turtle.forward(x)
turtle.left(90)
turtle.penup()
turtle.forward(x / 2)
turtle.left(90)
turtle.forward(x / 2)
turtle.right(90)
# TODO: Right turn movement function
def moveToCenterRightTurn(turtle, x,):
turtle.pu()
turtle.fd(x/2)
turtle.rt(270)
turtle.fd(x/2)
turtle.rt(90)
# TODO: Diagonal movement function
def moveToCenterDiagonal(turtle,x,y):
# TODO: Complete program to call functions to draw pinwheel
side_a = (x/2)-(y/2)
side_o = (x/2)+(y/2)
hyp = sqrt(side_a**2 + side_o**2)
theta = degrees(cos(side_a/hyp))
turtle.lt(theta)
turtle.fd(hyp)
turtle.rt(theta)
turtle.rt(90)
def main():
size1 = int(input('Enter size for first square: '))
size2 = int(input('Enter size for first square: '))
size3 = int(input('Enter size for first square: '))
size4 = int(input('Enter size for first square: '))
#Create Turtle Object
bob = turtle.Turtle()
# Draw first square
moveToCenterRightTurn(bob,size1)
drawSquareFromCenter(bob, size1)
moveToCenterRightTurn(bob,-size1)
# Move towards the second sqaure
bob.rt(90)
moveToCenterRightTurn(bob,size2)
# Draw second square
drawSquareFromCenter(bob,size2)
#move to third square
bob.lt(180)
moveToCenterDiagonal(bob,size2,size3)
#draw the third sqaure
drawSquareFromCenter(bob,size3)
#move towards the last square
moveToCenterDiagonal(bob,size3,size4)
#draw the last square
drawSquareFromCenter(bob,size4)
main() |
import json
import io
import argparse
def replaceArray(jsonString):
"""
Replaces json arrays with pseudo arrays for firebaseStr
Example: ["Foo", "Bar"] -> {"0": "Foo", "1": "Bar"}
"""
if jsonString[0] != "[" or jsonString[-1] != "]":
# return None if its not a valid json array
return None
origIndex = 1
resIndex = 1
res = "{"
itemCount = 0
bracketCount = 0
# check if its an object array or string array
isJsonObjectArray = jsonString[origIndex] == "{"
if not isJsonObjectArray:
res += "\"" + str(itemCount) + "\":"
resIndex += len(str(itemCount)) + 3
while origIndex < len(jsonString):
c = jsonString[origIndex]
if c == "]":
# because we recurse everytime we see "[", "]" is always a return
res += "}"
resIndex += 1
origIndex += 1
return (res, origIndex, resIndex)
elif c == "[":
subRes = replaceArray(jsonString[origIndex:])
origIndex += subRes[1]
resIndex += subRes[2]
res += subRes[0]
elif c == "{" and isJsonObjectArray:
if bracketCount == 0:
res += "\"" + str(itemCount) + "\":"
resIndex += len(str(itemCount)) + 3
bracketCount += 1
res += c
resIndex += 1
origIndex += 1
elif c == "}" and isJsonObjectArray and bracketCount == 1:
# end of object in array reached
res += c
resIndex += 1
origIndex += 1
itemCount += 1
bracketCount -= 1
elif c == "}" and isJsonObjectArray:
res += c
resIndex += 1
origIndex += 1
bracketCount -= 1
elif c == "," and jsonString[origIndex - 1] == "\"" and not isJsonObjectArray:
# no arrays of mixed type so ", means you're in an array of strings
itemCount += 1
res += c + "\"" + str(itemCount) + "\":"
resIndex += 2 + len(str(itemCount))
origIndex += 1
else:
res += c
resIndex += 1
origIndex += 1
print("DEBUG: WHY AM I HERE")
return (res, origIndex) # should not happen because string should always end in "]"
def removeJsonArrays(jsonString):
""" Takes a json string and returns a json string that is accetable
by Firebase
"""
curr = 0
last = 0
res = ""
while curr < len(jsonString):
if jsonString[curr] == "[":
res += jsonString[last:curr]
last = curr
(subRes, curr, __ignore__) = replaceArray(jsonString[curr:])
print(subRes)
res += subRes.strip(",")
curr += 1
return res
def monsterListToFirebase(monsterJson):
""" Returns a json string that has been formatted to work with Firebase
monsterJson: the original json file with monster info
"""
firebaseStr = "\"monsters\" : {"
for monster in monsterJson:
firebaseStr += addMonster(monster) + ","
#all except last character to fix fencepost comma
firebaseStr = firebaseStr[:-1] + " }"
return firebaseStr
def addMonster(monster):
mId = monster["id"]
mName = monster["name"]
mAtk = monster["atk_max"]
mHp = monster["hp_max"]
mRcv = monster["rcv_max"]
mElement = monster["element"]
mElement2 = monster["element2"] if monster["element2"] else -1
types = [monster["type"], monster["type2"], monster["type3"]]
types = [type for type in types if type is not None]
mLeaderSkill = monster["leader_skill"] if monster["leader_skill"] else "N/A"
res = " \"{id}\" : {{ \"name\" : \"{name}\", "
res += "\"num\" : {id}, "
res += "\"hp\" : {hp}, "
res += "\"atk\" : {atk}, "
res += "\"rcv\" : {rcv}, "
res += "\"attributes\" : {{\"0\": {element}, \"1\": {element2}}}, "
res += "\"leader_skill\" : \"{leaderSkill}\""
res += "}}"
return res.format(id=mId, name=mName, hp=mHp, atk=mAtk, rcv=mRcv,
element=mElement, element2=mElement2,
leaderSkill=mLeaderSkill)
def indexByName(leaderJson):
res = "{"
leaderArray = json.loads(leaderJson)
for i in leaderArray:
skill = leaderArray[i]
name = skill["name"]
description = skill["description"]
res += "\"" + name + "\": {"
res += "\"description\":\"" + description + "\","
if "skills" in skill:
res += "\"skills\":" + json.dumps(skill["skills"])
res = res.strip(",") + "},"
res = res.strip(",") + "}"
return res
def leaderJsonToFirebase(leaderJson):
res = "\"leader_skills\":"
res += indexByName(removeJsonArrays(leaderJson))
return res
def main():
parser = argparse.ArgumentParser(description="Reformats json for Firebase")
parser.add_argument("-m", required=True,
help="The monster info json file from https://www.padherder.com/api/monster")
parser.add_argument("-l", required=True,
help="The leaderskill json file")
parser.add_argument("-o", required=True, help="Output file name")
args = parser.parse_args()
monsterFile = open(args.m, encoding="utf-8")
monsterJson = json.load(monsterFile)
monsterFile.close()
leaderFile = open(args.l, encoding="utf-8")
leaderJsonString = leaderFile.read()
leaderFile.close()
res = "{"
res += monsterListToFirebase(monsterJson) + ","
res += leaderJsonToFirebase(leaderJsonString)
res += "}"
outFile = open(args.o, "w", encoding="utf-8")
outFile.write(res)
outFile.close()
if __name__ == "__main__":
main() |
from Tkinter import *
form = Tk()
form.title=("Add New Stock")
Label(form , text="Add new Stock" , font = "Lato 20")
stock_symbol = Label(form , text= "Stock" , font = "Lato 15" , fg = 'White', bg='Black')
stock_symbol.grid(row=0,column=0)
number_of_units = Label(form , text= "Number of stocks" , font = "Lato 15" , fg = 'White', bg='Black')
number_of_units.grid(row=1,column=0)
price= Label(form, text="Price per Share" ,font = "Lato 15" , fg = 'White', bg='Black')
price.grid(row=2,column=0)
date_purchase= Label(form , text ="Date of Purchase" ,font = "Lato 15" , fg = 'White', bg='Black')
date_purchase.grid(row=3,column=0)
form.mainloop()
|
import pygame
pygame.init()
(6, 0)
SIZE_HEIGHT = 600
SIZE_WIDTH = 800
screen = pygame.display.set_mode((SIZE_WIDTH,SIZE_HEIGHT))
pygame.display.set_caption('Summative')
clock = pygame.time.Clock()
BLACK = (0,0,0)
WHITE = (255,255,255)
GREEN = (0,255,0)
BLUE = (0,0,255)
RED = (255,0,0)
#crashed = False
#chance=0
#count=0
#color=[255,50,255]
#def powerBar(chance,color):
#pygame.draw.rect(screen,color,(100,100,110,chance))
##DOESNT WORK IN A FUNCTION
#def game():
##gameloop
#global crashed, chance, count
#while crashed!=True:
#for event in pygame.event.get(): #gets any event that happens
#if event.type == pygame.QUIT:
#crashed=True
#pygame.draw.rect(screen,BLACK,(0,0,SIZE_WIDTH,SIZE_HEIGHT))
#pygame.draw.rect(screen,RED,(100,100,110,200))
##1st half it increments slowly
#if chance<100:
#chance+=3
#color[1]+=3
#color[0]-=3
#color[2]-=3
##second half is faster
#else:
#chance+=4
#color[1]+=3
#color[0]-=3
#color[2]-=3
#if event.type ==pygame.KEYDOWN:
#if event.key ==pygame.K_SPACE:
#count+=1
#break
#powerBar(chance,color)
#if chance>202:
#break
#pygame.display.flip()
#clock.tick(60)
#pygame.quit()
##if they didn't press space at all (fail)
#if count==0:
#chance=0
#print(str(int((chance/201)*100))+"%")
#game()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
break
screen.fill(BLACK)
if event.type ==pygame.KEYDOWN:
if event.key ==pygame.K_RIGHT:
x = 0
color=[255,50,255]
pygame.draw.rect(screen,WHITE,(500,100,200,50))
pygame.display.flip()
counter = 0
while counter!=151:
if counter<100:
pygame.draw.rect(screen,color,(500,100,x,50))
x+=1
else:
pygame.draw.rect(screen,color,(500,100,x,50))
x+=2
if event.type ==pygame.KEYDOWN:
if event.key==pygame.K_SPACE:
break
pygame.display.flip()
clock.tick(60)
counter+=1
if event.type ==pygame.KEYDOWN:
if event.key==pygame.K_SPACE:
break
elif event.key==pygame.K_LEFT:
x = 0
xPos = 300
color=[255,50,255]
pygame.draw.rect(screen,WHITE,(100,100,200,50))
pygame.display.flip()
counter = 0
while counter!=151:
if counter<100:
pygame.draw.rect(screen,color,(xPos,100,x,50))
x+=1
xPos-=1
else:
pygame.draw.rect(screen,color,(xPos,100,x,50))
x+=2
xPos-=2
if event.type ==pygame.KEYDOWN:
if event.key==pygame.K_SPACE:
break
pygame.display.flip()
clock.tick(60)
counter+=1
if event.type ==pygame.KEYDOWN:
if event.key==pygame.K_SPACE:
break
pygame.display.flip()
clock.tick(20)
pygame.quit()
quit() |
# a93323883be13012
import urllib.request
import json
import sqlite3
import ast
from WeatherFunctions import newZipcode
from time import sleep
#-999 = a null value
#A basic conversion of precipitation to snow can be used to obtain an approximate snow reading. If snow precipitation
# is listed as e.g. 0.05 inches, this is water equivalent. Multiply by about 12 to get snow in inches. In the above
# example, 0.05 x 12 = 0.6 inches of snow. Dry, fluffy snow has much less water in it, and one should use a conversion
# factor of about 20 instead.
#
# sleep(3600)
from UserZipcodes import zipcodes
#fetches weather data through weather underground api and inserts it into the db
for zipcode in zipcodes:
#create a list of currently tracked zipcodes
conn = sqlite3.connect('Alerted.db')
c = conn.cursor()
c.execute('SELECT ZipCode FROM WeatherData')
zipcodes = [row for row in c.fetchall()]
zipcodes = [i[0] for i in zipcodes]
if zipcode not in zipcodes:
#inputs new zipcode into db if not exists
newZipcode(zipcode)
else:
pass
url = 'http://api.wunderground.com/api/a93323883be13012/hourly/conditions/q/%s.json' % zipcode
f = urllib.request.urlopen(url)
json_string = f.read()
weather = json.loads(json_string)
conn = sqlite3.connect('Alerted.db')
c = conn.cursor()
c.execute('UPDATE WeatherData SET Weather = ? WHERE Zipcode = ?', (str(weather), zipcode,))
conn.commit()
c.close()
from WeatherFunctions import *
SnowFall(weather, zipcode)
zipcode = str(55124)
conn = sqlite3.connect('Alerted.db')
c = conn.cursor()
c.execute('SELECT Weather From WeatherData WHERE Zipcode = ?', (zipcode,))
#converts tuple back to dict
weather = c.fetchone()
p = ''.join(weather)
t = ast.literal_eval(p)
from WeatherFunctions import *
SnowFall(t,zipcode)
|
text = ("Hey You!") #"Hy Y!" NEED TO REMOVE a, e, i, o, u
vowel = ["a", "e", "i", "o" ,"u", "A", "E", "I", "O", "U"]
def anti_vowel(text):
word = ""
for l in text:
if l not in "aeiouAEIOU":
word += l
return word
print(anti_vowel(text))
|
# Importing libraries
import numpy as np
import pandas as pd # data processing
import datetime # for datetime conversion
from pandas_datareader import data as pdr # for loading Yahoo finance data
def csv_file_operation(df):
# Concatenating Trader Name for convenience
df["Trader_name"] = df["firstName"] + df["lastName"] # Concatenateing Traders' name
df['tradeDatetime'] = pd.to_datetime(df['tradeDatetime']) # Converting Datatype of column to "Datetime"
df_amazon = df.loc[df["stockSymbol"] == "AMZN"] # Slicing dataset for Amazon stock
df_amazon['Date'] = df_amazon['tradeDatetime'].dt.date # Extracting date from tradeDatetime
df_amazon['Date'] = pd.to_datetime(df_amazon['Date'], format='%Y-%m-%d') # Converting Datatype of column to "Datetime"
return df_amazon # returns Amazon data from given CSV file
def yahoo_file_operation(data):
data["Date"] = data.index # creating "Date" column for merging
data.reset_index(drop=True, inplace=True)
data.columns = data.columns.droplevel(1) #dropping secondary index
return data # returns Data from Yahoo finance
def merged(df_amazon, data):
merged = pd.merge(df_amazon, data, on='Date', how='outer') #merging Amazon data with Yahoo finance data
suspicious_high = merged[merged.iloc[:, 7] >= merged["High"]] # Condition for suspicious trader
suspicious_low = merged[merged.iloc[:, 7] <= merged["Low"]] # Condition for suspicious trader
suspicious = pd.concat([suspicious_high, suspicious_low]) # merging suspicious dataframe
list_susp = suspicious["Trader_name"].value_counts() # This returns suspicious traders list
print(list_susp) # Printing the result
return list_susp # This is list of suxpicious traders
if __name__ == "__main__":
# path of the dataset
path = '/home/beast/PycharmProjects/Question_Answering/traders_data.csv'
## initializing Parameters
start = "2020-02-01"
end = "2021-03-31"
symbols = ["AMZN"]
# Getting the data from yahoo finance
data = pdr.get_data_yahoo(symbols, start, end)
# Reading the csv file given
df = pd.read_csv(path)
merged(csv_file_operation(df), yahoo_file_operation(data)) |
def quickSort(arr):
#todo: check for single element in array
quickSortHelper(arr,0,len(arr)-1)
def quickSortHelper(arr,first,last):
if first < last:
partitionPosition = partition(arr, first, last)
quickSortHelper(arr,first,partitionPosition-1)
quickSortHelper(arr,partitionPosition+1,last)
def partition(arr, first, last):
pivotvalue = arr[first]
leftmark = first + 1
rightmark = last
done = False
while not done:
while leftmark <= rightmark and arr[leftmark] <= pivotvalue:
leftmark = leftmark + 1
while arr[rightmark] >= pivotvalue and rightmark >= leftmark:
rightmark = rightmark - 1
if rightmark < leftmark:
done = True
else:
temp = arr[leftmark]
arr[leftmark] = arr[rightmark]
arr[rightmark] = temp
temp = arr[first]
arr[first] = arr[rightmark]
arr[rightmark] = temp
return rightmark
arr = [2,5,4,6,7,3,1,4,12,11]
quickSort(arr)
print(arr)
|
def sortInWaveForm(arr):
right = len(arr)-1
for i in range(0,len(arr),2):
if i>0 and arr[i]<arr[i-1]:
arr[i],arr[i-1] = arr[i-1],arr[i]
if i<right and arr[i]<arr[i+1]:
arr[i],arr[i+1] = arr[i+1],arr[i]
print(arr)
#90 10 49 1 5 2 23
arr = [10, 90, 49, 2, 1, 5, 23]
sortinWaveForm(arr)
|
"""
This file contains stack implementation with python list
Stack()
push(item)
pop()
peek()
isEmpty()
size()
displayAllElements()
"""
class MyStack:
def __init__(self):
self.items = []
def push(self,item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
if len(self.items)< 1 :
return None
else:
return self.items[len(self.items)-1]
def isEmpty(self):
return len(self.items) == 0
def size(self):
return len(self.items)
def displayAllElements(self):
if self.isEmpty():
print("Stack is empty")
else:
print(self.items)
def displayAllElementsInReverseOrder(self):
if self.isEmpty():
print("Stack is empty")
else:
temp = []
i = len(self.items)-1
while i != -1:
temp.append(self.items[i])
i -= 1
print(temp)
"""
stack = MyStack()
stack.push(5)
stack.push(6)
stack.push(50)
stack.displayAllElements()
print(stack.peek())
stack.pop()
stack.displayAllElements()
print(stack.size())
"""
|
class SinglyListNode():
def __init__(self,value):
self.value = value
self.nextnode = None
class LinkedList():
def __init__(self,value):
newNode = SinglyListNode(value)
self.head = newNode
self.tail = newNode
self.size = 1
def appendNode(self,value):
newNode = SinglyListNode(value)
self.tail.nextnode = newNode
self.tail = newNode
self.size += 1
def insertAfterNode(self,value,index):
if index<1 or index > self.size:
print("Invalid index value")
return
elif index == self.size:
self.appendNode(value)
return
else:
i= 1
node = self.head
while i<index:
node = node.nextnode
i += 1
newNode = SinglyListNode(value)
temp = node.nextnode
node.nextnode = newNode
newNode.nextnode = temp
self.size +=1
def deleteNodeWithKey(self,value):
node= self.head
if node.value == value:
self.head = node.nextnode
#node = None
return
prevNode = node
node = node.nextnode
while node != None:
if node.value == value:
prevNode.nextnode = node.nextnode
#node = None
return
prevNode = node
node = node.nextnode
print("Node not found!")
return
def traverseList(self):
node = self.head
while node != None:
print(node.value)
node = node.nextnode
"""
list = LinkedList(10)
list.appendNode(20)
list.appendNode(30)
#list.traverseList()
list.insertAfterNode(15,3)
list.appendNode(40)
list.insertAfterNode(50,5)
list.deleteNodeWithKey(15)
list.traverseList()
"""
|
class TwoStacks:
def __init__(self,arraySize):
self.arraySize = arraySize
self.array = [None]*self.arraySize
self.stack1Top = -1
self.stack2Top = self.arraySize
def stack1Push(self,ele):
if self.stack1Top<self.stack2Top-1:
self.stack1Top += 1
self.array[self.stack1Top] = ele
else:
print("overflow")
return None
def stack2Push(self,ele):
if self.stack1Top<self.stack2Top-1:
self.stack2Top -= 1
self.array[self.stack2Top] = ele
else:
print("overflow")
return
def stack1Pop(self):
if self.stack1Top< 0:
print("stack empt")
return None
else:
ele = self.array[self.stack1Top]
self.array[self.stack1Top] = None
self.stack1Top -=1
return ele
def stack2Pop(self):
if self.stack2Top > self.arraySize-1:
print("stack empt")
return None
else:
ele = self.array[self.stack2Top]
self.array[self.stack2Top] = None
self.stack2Top += 1
return ele
stack = TwoStacks(6)
stack.stack1Push(10)
stack.stack1Push(20)
stack.stack1Push(30)
#stack.stack1Push(40)
stack.stack2Push("A")
stack.stack2Push("B")
stack.stack2Push("C")
stack.stack2Push("D")
print(stack.stack2Pop())
print(stack.stack2Pop())
print(stack.stack1Pop())
print(stack.stack1Pop())
|
"""
約数の数を素数要素の面積のように考える方法
素因数分解を利用して解く解法
ただしN <= 10**10の条件下でTLE
"""
from collections import Counter
N = int(input())
# 素数を求める関数
def factorize(n):
factorys = []
rest_num = n
i = 2
while rest_num > 1:
if rest_num % i == 0:
factorys.append(i)
rest_num //= i
else:
i += 1
return factorys
arr = Counter(factorize(N))
ans = 1
for k, v in arr.items():
temp = 0
for i in range(v+1):
temp += k**i
ans *= temp
sum_div = ans - N
if sum_div == N:
print("Perfect")
elif sum_div < N:
print("Deficient")
else:
print("Abundant") |
"""
マスターオブ整数
"""
from collections import Counter
N, P = map(int, input().split())
# Pを素因数分解する
if N == 1:
print(P)
exit()
prime_list = []
for i in range(2, int(P**0.5) + 1):
if P % i == 0:
while P % i == 0:
prime_list.append(i)
P //= i
prime_count = Counter(prime_list)
ans = 1
for k,v in prime_count.items():
if v >= N:
ans *= k ** (v//N)
print(ans) |
"""
マスターオブ整数,素数
約数の総和
"""
"""
約数列挙の回答
"""
N = int(input())
if N == 1:
print("Deficient")
exit()
divisor = []
for i in range(2, int(N**0.5) + 1):
if N % i == 0:
if i != N//i:
divisor.append(i)
divisor.append(N//i)
else:
divisor.append(i)
sum_div = sum(divisor) + 1
if sum_div == N:
print("Perfect")
elif sum_div < N:
print("Deficient")
else:
print("Abundant") |
T = list(input())
for i, s in enumerate(T):
if s == "?":
T[i] = "D"
print("".join(T)) |
# introduction to Classes -
class Student: ## user defined datatype
def __init__(self, name='Python'): # constructor
self.name = name
print("Hello World")
def welcome(self):
print(self.name)
print('Welcome to python programming')
obj = Student('Gurjas')
obj.welcome()
obj1 = Student()
obj1.welcome()
# Introduction to Inheritance
class BaseClass:
def __init__(self):
self.var_1 = 2
print("Base Class")
def helloFxn(self, a = 10):
print("Hello Inside base class")
class DerivedClass(BaseClass):
def __init__(self):
super().__init__()
print("Derived Class")
super().helloFxn(a=20)
self.helloFxn()
def helloFxn(self):
print("Hello inside derived class")
obj = DerivedClass()
## Static -- Students Class
class Student:
def __init__(self, name, address="Dehradun", phone = 0):
self.name = name
self.address = address
self.phone = phone
print("Welcome to Brillica Services")
def display_data(self):
print("Printing students details")
print(self.name)
print(self.address)
print(self.phone)
name = input('Enter your name')
address = input('Enter your address')
phone = input('Enter your phone number')
if ((len(address)>1) & (len(phone)>1)):
phone = int(phone)
obj = Student(name=name, address=address, phone=phone)
obj.display_data()
elif (len(address)>1 & (len(phone)==0)):
obj = Student(name, address)
obj.display_data()
elif (len(phone)>1 & (len(address)==0)):
phone = int(phone)
obj = Student(name=name, phone=phone)
obj.display_data()
else:
obj = Student(name)
obj.display_data()
## Dynamic -- Students Class
class Student:
def __init__(self, name, address="Dehradun", phone = 0):
self.name = name
self.address = address
self.phone = phone
print("Welcome to Brillica Services")
def display_data(self):
print("Printing students details")
print(self.name)
print(self.address)
print(self.phone)
students_count = input('Enter the number of records you want')
students_count = int(students_count)
students_records = []
for i in range(students_count):
print('Enter the details of student:')
name = input('Enter the name of the student')
address = input('Enter the address of the student')
phone = input('Enter the phone number of the student')
obj : Student
if ((len(address) > 1) & (len(phone) > 1)):
phone = int(phone)
obj = Student(name=name, address=address, phone=phone)
elif (len(address)>1 & (len(phone)==0)):
obj = Student(name, address)
elif (len(phone)>1 & (len(address)==0)):
phone = int(phone)
obj = Student(name=name, phone=phone)
else:
obj = Student(name)
students_records.append(obj)
for i in students_records:
i.display_data()
|
# # Lambda - function - Filter, Reduce, Map
list_var = [10, 34, 15, 52, 15, 67, 32, 18]
# without lambda function
# new_list = []
#
# def list_filter(list_var):
# for i in list_var:
# if (i>30):
# # return i
# # print(i)
# new_list.append(i)
#
# list_filter(list_var)
# print(new_list)
# using lambda
new_list = list(filter(lambda x: x>30, list_var))
print(new_list)
# # map
dictionary = {
0: 'Sunday',
1: 'Monday',
2: 'Tuesday',
3: 'Wednesday',
4: 'Thursday',
5: 'Friday',
6: 'Saturday'
}
list_weeks = [7, 2, 8, 1, 3, 1, 4, 5, 0, 2, 1, 0, 4]
list_weekdays = list(map(lambda x:
dictionary.get(x, "Not found"),
list_weeks))
print(list_weekdays)
# reduce
from functools import reduce
list_var = [9, 3, 2, 43, 9, 232, 34]
multiplication = reduce(lambda x,y : x*y, list_var)
print("Multiplication result is: ", multiplication)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.