text
stringlengths 37
1.41M
|
---|
# Date: 06.01.2021.
# Author: Sherzod Oltinbpoyev.
# Theme: Ro'yxatlar bilan ishlash.
# 1. Har bir odamga alohida xabar yuboruvchi dastur
ismlar=['Anvar','Islom','Lochin','Abdurasul','Ulug\'bek']
for ism in ismlar:
print(f"Salom {ism}")
print(f"Kod {len(ismlar)} marta takrorlandi")
# 2. 10 dan 100 gacha bo'lgan toq sonlar kubini topish
toq_sonlar=list(range(11,100,2))
for son in toq_sonlar:
print(f"{son} ning kubi {son**3} ga teng")
# 3. Yoqtirgan kinolar ro'yxatini chiqaruvchi dastur
kinolar=[]
print("Siz uchun sevimli bo'lgan 5 ta kinoni kiriting?")
for n in range(5):
kinolar.append(input(f"{n+1}-kinoni kiriting? "))
print(f"Siz yoqtirgan kinolar ro'yxati: {kinolar}")
# 4. Suhbat qilgan odamlar ro'yxatini chiqaruvchi dastur
n_people = int(input("Bugun necha kishi bn suhbat qildingiz?>>>"))
ismlar = []
for n in range(n_people):
ismlar.append(input(f"{n+1}-suhbat qilgan odamingiz kim edi: "))
print(ismlar)
|
n=int(input("Enter days number: "))
result = []
for i in range(n):
v=[]
m=int(input("Enter running number: "))
for i in range(m):
TimeS=input()
TimeS = TimeS.split()
v.append(int(TimeS[1])/int(TimeS[0]))
result.append(sum(v))
result.sort()
for i in range(len(result)-1,-1,-1):
print(result[i])
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
from __future__ import absolute_import
class CuentaAtras:
def __init__(self, tope):
self.tope = tope
def __iter__(self):
self.counter = self.tope
return self
def next(self): return self.__next__() # python 2.7
def __next__(self):
result = self.counter
self.counter -= 1
if result < 0:
raise StopIteration
return result
for i in CuentaAtras(12):
print(i, end=', ')
print()
for i in CuentaAtras(3):
print(i, end=', ')
print()
print(*CuentaAtras(7), sep=', ', end='\n')
|
# Очередь на основе двух стеков
# Операции empty, size и push не имеют циклов и не зависят от длины подаваемого списка => выполняются за O(1)
# Операция pop имеет 1 цикл и в лучшем случае она выполняется за O(1), но если self.leftStack
# не пустой, то операция pop может выполняться за O(n)
class Queue:
def __init__(self, n):
self.leftStack = [0 for x in range(n)]
self.i_left = 0
self.rightStack = [0 for x in range(n)]
self.i_right = 0
def empty(self):
return self.i_left == self.i_right
def size(self):
if self.i_right > self.i_left:
return n - elf.i_right + self.i_left
else:
return self.i_left - self.i_right
def push(self, e):
if self.i_left == len(self.leftStack):
print ("Full")
else:
self.leftStack[self.i_left] = e
self.i_left += 1
def pop(self):
if self.i_right == 0:
if self.i_left == 0:
return 'Empty'
else:
while self.i_left != 0:
self.rightStack[self.i_right] = self.leftStack[self.i_left - 1]
self.i_left -= 1
self.i_right += 1
self.i_right -= 1
return self.rightStack[self.i_right]
|
# 위상 정렬하여 각 선수 노드의 값을 누적한다.
# 그래프에 넣을때는 해당 인덱스를 선수로 하는 노드를 이중 배열로
from collections import deque
import copy
n = int(input())
graph = [[] for _ in range(n+1)]
indegree = [0]*(n+1)
times = [0]*(n+1)
result = []
for i in range(1,n+1):
tmp = list(map(int,input().split()))
times[i] = tmp[0]
for j in tmp[1:len(tmp)-1]:
graph[j].append(i)
indegree[i] += 1
def topology_sort():
q = deque()
result = copy.deepcopy(times)
for i in indegree[1:]:
if indegree[i] == 0:
q.append(i)
while q:
cur = q.popleft()
for i in graph[cur]:
result[i] = max(result[i],result[cur]+times[i])
indegree[i]-=1
if indegree[i] == 0:
q.append(i)
for r in result[1:]:
print(r)
topology_sort()
|
import os
import pandas as pd
def get_WH_data_for_given_year(data_path: str, year: int) -> pd.DataFrame:
''' Extract World Happiness data for a given year
Parameters
----------
data_path
path to the CSV data file
year
year for which to select the data
Returns
-------
df_for_given_year
A new dataframe with only data for the year selected
'''
WH_df = pd.read_csv(data_path)
selected_rows = WH_df["Year"]==year
selected_columns = WH_df.columns[2:9]
WH_year_df = WH_df.loc[selected_rows, selected_columns]
return WH_year_df
|
#!/usr/bin/python
import random
import sys
try:
num_flips = int(raw_input("Enter number of times to flip coin: "))
except:
print "Please try again and enter an integer"
sys.exit()
heads = 0
tails = 0
while num_flips > 0:
flip = random.randint(1,2)
if flip == 1:
print "Heads!"
heads += 1
else:
print "Tails!"
tails += 1
num_flips -=1
print "Total heads: " + str(heads)
print "Total tails: " + str(tails)
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
import webbrowser
pm = sys.argv[1]
input = sys.argv[2:]
args = (' '.join(input))
def usage():
print("srch - search from the commandline \n")
print("python srch <platform> <query> \n")
print('''platforms to search for
wiki Search Wikipedia for query
so Search StackOverflow for query
g Search Google for query
r Search Reddit for query
gh Search GitHub for query
devto Search dev.to for query
m Search Medium for query
yt Search Youtube for query
tw Search Twitter for query
gfg Search GeeksforGeeks for query
stx Search Stackexchange for query
q Search quora for query
url Search for url
fcc Search freecodecamp for query
shell Search explainshell for query
mdn Search MDN Web Docs for query
Usage:
$ python srch help # help menu
$ python srch g what is github commit signing\n''' )
def wiki(args):
wikipedia = 'https://en.wikipedia.org/wiki/' + str(args)
webbrowser.open(wikipedia)
def stackoverflow(args):
stackoverflow = 'https://stackoverflow.com/search?q=' + str(args)
webbrowser.open(stackoverflow)
def google(args):
google = 'https://www.google.com/search?q=' + str(args)
webbrowser.open(google)
def reddit(args):
reddit = 'https://www.reddit.com/search/?q=' + str(args)
webbrowser.open(reddit)
def github(args):
github = 'https://github.com/search?q=' + str(args)
webbrowser.open(github)
def devto(args):
devto = 'https://dev.to/search?q=' + str(args)
webbrowser.open(devto)
def medium(args):
medium = 'https://medium.com/search?q=' + str(args)
webbrowser.open(medium)
def youtube(args):
youtube = 'https://www.youtube.com/results?search_query=' + str(args)
webbrowser.open(youtube)
def twitter(args):
twitter = 'https://twitter.com/search?q=' + str(args)
webbrowser.open(twitter)
def geeksforgeeks(args):
geeksforgeeks = 'https://www.geeksforgeeks.org/search/?q=' + str(args)
webbrowser.open(geeksforgeeks)
def stackexchange(args):
stackexchange = 'https://stackexchange.com/search?q=' + str(args)
webbrowser.open(stackexchange)
def quora(args):
quora = 'https://www.quora.com/search?q=' + str(args)
webbrowser.open(quora)
def url(args):
uri ='https://' + str(args)
webbrowser.open(uri)
def freecodecamp(args):
freecodecamp = 'https://www.freecodecamp.org/news/search/?query=' + str(args)
webbrowser.open(freecodecamp)
def explainshell(args):
explainshell = 'https://explainshell.com/explain?cmd=' + str(args)
webbrowser.open(explainshell)
def mdn(args):
mozilladocs = 'https://developer.mozilla.org/en-US/search?q=' + str(args)
webbrowser.open(mozilladocs)
if pm == "--h" or pm == "--help" or pm == "-h" or pm == "-help" or pm == "help" or pm == "h":
usage()
elif pm == "wiki":
wiki(args)
elif pm == "so":
stackoverflow(args)
elif pm == "g":
google(args)
elif pm == "r":
reddit(args)
elif pm == "gh":
github(args)
elif pm =="devto":
devto(args)
elif pm == "m":
medium(args)
elif pm == "yt":
youtube(args)
elif pm == "tw":
twitter(args)
elif pm == "gfg":
geeksforgeeks(args)
elif pm == "stx":
stackexchange(args)
elif pm == "q":
quora(args)
elif pm == "url":
url(args)
elif pm == "fcc":
freecodecamp(args)
elif pm == "shell":
explainshell(args)
elif pm == "mdn":
mdn(args)
else:
print('Invalid command...\n\n')
usage()
sys.exit()
|
# Write a Python program to remove duplicates from a list.
def remove_duplicates_from_list(arg):
'''
:param arg: list of numbers
:return: arg:list
'''
return list(set(arg))
if __name__ == '__main__':
print(remove_duplicates_from_list([2, 1, 8 ,4, 8, 3, 2, 1, 5, 4]))
|
# Create a function, is_palindrome, to determine if a supplied word is
# the same if the letters are reversed.
def is_palindrome(word):
'''
:param word: string
:return: boolean
'''
return word == word[::-1]
print(is_palindrome('dad'))
print(is_palindrome('mom'))
|
# Write a Python program to remove an item from a tuple.
def remove_item_from_tuple(tup, item):
'''
:tup: tuple
:item: element of tup
:return: tuple
'''
temp = list(tup)
temp.remove(item)
return tuple(temp)
if __name__ == '__main__':
t = (2,3,4,5)
print('tuple: ', t)
print('to remove: ', 4)
print('result: ', remove_item_from_tuple(t, 4))
|
# Create a list with the names of friends and colleagues. Search for the
# name ‘John’ using a for a loop. Print ‘not found’ if you didn't find it.
friend_list = ['Ram', 'Jesus', 'Allah', 'Budha']
print('List of names:\n', friend_list)
print('Searching for John...')
flag = 0
for name in friend_list:
if name == 'John':
flag = 1
break
if flag == 0:
print('John not found!')
|
# Write a Python program to reverse a string.
def reverse_str(arg):
'''
:param arg: string
:return: string
'''
return arg[::-1]
if __name__ == "__main__":
print(reverse_str('apple'))
|
# create a word which is made up of first and last two characters of a given string
def create_word(original_word):
if len(original_word)<2:
return ''
else:
new_word = original_word[:2] + original_word[-2:]
return new_word
if __name__ == "__main__":
print(create_word('Python'))
print(create_word('Py'))
|
# replace the all the occurences of the first character of a given string with $.
# Note that first character itself should not be changed.
def replace_occurence(original_word):
first_char = original_word[0]
return first_char + original_word[1:].replace(first_char, '$')
if __name__ == "__main__":
print(replace_occurence('restart'))
print(replace_occurence('oliliyooli'))
|
# Write a Python program to unpack a tuple in several variables.
def tuple_to_list(arg):
'''
:arg: tuple
:return: list
'''
return list(arg)
def tuple_to_set(arg):
'''
:arg: tuple
:return: set
'''
return set(arg)
def tuple_to_string(arg):
'''
:arg: tuple
:return: string
'''
s = ''
for item in arg:
s += str(item)
return s
if __name__ == '__main__':
t = (2,3,4,5)
print('given tuple: ', t)
print('list: ', tuple_to_list(t))
print('set: ', tuple_to_set(t))
print('string: ', tuple_to_string(t))
|
# Write a Python program to change a given string to a new string where the first
# and last chars have been exchanged.
def rearrange_characters(arg):
'''
:param arg: word:String
:return: word:String
'''
return arg[-1] + arg[1:(len(arg)-1)] + arg[0]
if __name__ == '__main__':
print(rearrange_characters('apple'))
|
# Write a Python program to find the length of a tuple
def tuple_length(arg):
'''
:arg: tuple
:return: number
'''
return len(arg)
if __name__ == '__main__':
t = (2,3,4,5)
print('given tuple: ', t)
print('legth: ', tuple_length(t))
|
# Write a Python program to convert a list to a tuple.
def list_to_tuple(arg):
'''
:arg: list
:return: tuple
'''
return tuple(arg)
if __name__ == '__main__':
t = [2,3,4,5]
print('list: ', t)
print('tuple: ', list_to_tuple(t))
|
# use if statements to make decisions in code
# ask user for their age
age = int(input("What is your age?"))
# check if person is old enough to drive
if age >= 16 :
print("You can get your driver's licence")
else:
print("You will be old enough in {} year(s)".format(16-age))
|
# converts a mark to a grade
try:
#ask the user for their mark
mark = int(input("Enter your mark"))
# tell user their grade
# check if mark is >= 0 and <= 100
if mark >= 0 and mark <= 100:
# calculate grade
# check if grade in A range
if mark >= 90:
print("A")
# check if mark in B range
elif mark >= 70:
print("B")
# check if mark in C range
elif mark >= 50:
print("C")
# mark is a fail
else:
print("Fail")
# mark not in valid range
else:
print("Mark not eligible")
except:
print("Error: not an integer")
|
## Test for
grn1 = kop50 = kop25 = kop5 = kop1 = 0.00
money_list = [100, 50, 25, 5, 1]
answer_list = ["1 grn", "50 kop", "25 kop", "5 kop", "1 kop"]
try:
amount = float(input("Input amount of your money: "))*100
if amount < 0:
raise ValueError
except:
print("Error! Wrong input.")
else:
for i, x in enumerate(money_list):
if amount // x and amount > 0:
print("Amount of coins you need of", "\t", answer_list[i],"is\t", int(amount))
amount %= x
##Exercise!!!!!!!!!!!!!!
import random
low_int = 1
up_int = 10
answer = 0
guess = 0
while answer != 1:
try:
guess = random.randint(low_int,up_int)
print("Is that number equal", str(guess), "?")
print("Choose one of three variants",
"\n1. Your guess is right.",
"\n2. It's bigger.",
"\n3. It's less.",
"\nPress one of three buttons 1, 2, 3.")
answer = int(input())
except ValueError:
print("You need to input digits")
continue
else:
if answer == 1:
print("I'm the winer now! What the smartass I am! =)")
break
if answer == 2:
low_int = guess + 1
continue
if answer == 3:
up_int = guess - 1
continue
else:
print("You need to input only numbers 1, 2, 3.")
continue
print(" GAME OVER")
##### Exercise 3
import random
guess = random.randint(1,10)
answer = 0
low_int = 1
up_int = 10
while answer != 1:
try:
print("Is that number equal", str(guess), "?")
print("Choose one of three variants",
"\n1. Your guess is right.",
"\n2. It's bigger.",
"\n3. It's less.",
"\nPress one of three buttons 1, 2, 3.")
answer = int(input())
except ValueError:
print("You need to input digits")
continue
else:
if answer == 1:
print("I'm the winer now! What the smartass I am! =)")
break
if answer == 2:
guess = random.randint(low_int + 1, up_int)
continue
if answer == 3:
guess = random.randint(low_int, up_int - 1)
continue
if guess > 10 or guess < 0:
print("you are lying... Your head will collapse")
break
else:
print("You need to input only numbers 1, 2, 3.")
continue
print(" GAME OVER")
|
#Function fabric
def f(n):
def g(x):
return n * x
return g
double = f(2)
triple = f(3)
l = []
# Not closed, because depends on i value
for i in range(10):
def f(x):
return x * i
l.append(f)
#closed
for i in range(10):
def f(x, i=i):
return x * i
l.append(f)
# map func operate function to whole container
def double(x):
return 2 * x
l = list(map(double, [1, 2, 3, 4, 5]))
print(l)
#
def double(x):
print("double: {}".format(x))
return x * 2
for i in map(double, [1, 2, 3, 4, 5]):
print(i)
if i >5:
break
#Выводим нечетные числа
def odd(x):
return x % 2
l = list(filter(odd, [1, 2, 3, 4, 5]))
print(l)
## READ itertools !!!!!!!!!!!!!!!!!!!!!!
#lambda - using for temporary function
list(map(lambda x: 3 * x, [1, 2, 3, 4, 5]))
# поставить неограниченое количество аргументов
def f(*args):
print(args)
def sum_(*args): # could set sum(a, *args) to show that we need at least one parameter
s = 0
for i in args:
s += i
return s
def f(*args, **kwargs):
print(args, kwargs)
#>>>f (1,2,3, a=4, b=5)
#(1, 2, 3) {'a' : 4, 'b' : 5}
def f (a, b, c):
return a + b + c
t = 1, 2, 3
f(*t)
# Обертка!!!!!!!!!!!!!!!!!!!!!!!!! Wrapper
def g (*args, **kwargs):
print('g')
return f(*args, **kwargs)
#DECORATORS
def decor(f):
def wrapper():
print("in")
res =
#special syntax for decorators
@scale # the same as scale = scale(double)
def double(x):
return 2 * x
#multiple variants
actions = {1: a, 2: b, 3: c}
def default():
print('default')
actions.get(5, default)()
actions.get(3, default)()
|
#a = int(input('Primeiro valor: '))
#b = int(input('Segundo valor: '))
#c = int(input('Terceiro valor: '))
#if a > b and a > c:
# print('O maior número é {}'.format(a))
#elif b > a and b > c:
# print('o maior número é {}'.format(b))
#else:
# print('o maior número é {}'.format(c))
#print('final do programa')
#Par ou Ímpar
#a = int(input('Digite um valor: '))
#resto = a % 2
#if resto == 0:
# print('Número par!')
#else:
# print('Número impar!')
a = int(input('Primeiro Bimestre: '))
b = int(input('Segundo Bimestre: '))
c = int(input('Terceiro Bimestre: '))
d = int(input('Quarto Bimestre: '))
media = (a + b + c + d) / 4
if a <= 10 and b <= 10 and c <= 10 and d <= 10:
print ('Média: {}'.format(media))
else:
print('Algo de errado não está certo')
|
# ten_x_plus1(7) -> 71
# ten_x_plus1(1) -> 11
# print ten_x_plus1(121) -> 1211
def ten_x_plus1(x):
'''Takes the value x and computes (10 * x ) + 1
'''
return (10 * x ) + 1
#EVAL FUNCTION FOR EVALUATING A ONE LINE IF_ELSE CONDITION
def if_else(condition, trueVal, falseVal):
if condition:
return trueVal
else:
return falseVal
#HELPER FUNCTION FOR SUBSTITUTION CIPHER
def make_stringCheck(minLet,maxLet, offset):
return lambda x: if_else( ((x + offset) % maxLet) < minLet, (x + offset) % maxLet + (minLet), (x + offset) % maxLet + 1 )
# print substitution_cipher("abc Iz this Secure?",6) -> Vhij Pg aopz Zljbyl?
# print substitution_cipher("Hey you, Jack!",3) -> Lic csy, Nego!
# print substitution_cipher("The answer to the ultimate question is...",10) ->Esp lydhpc ez esp fwetxlep bfpdetzy td...
def substitution_cipher(string, offset):
'''Uses the substition cipher and substitutes the characters of
the given stringstring with the character that is offset +1 number away
Observed Special case: if capital letter, then add 7 away
'''
cipher = ''
for n in range(len(string)):
thisC = ord(string[n])
if thisC >= 65 and thisC <= 90:
findLetRegion = make_stringCheck(65,90, offset)
newPlace = findLetRegion(thisC)
elif thisC >= 97 and thisC <= 122:
findLetRegion = make_stringCheck(97,122, offset)
newPlace = findLetRegion(thisC)
else:
newPlace = (ord(string[n]))
cipher += chr(newPlace)
return cipher
# print diff_doubles([2,5,1.5,100,3,8,7]) -> [-3, -98.5, -5, 7]
# print diff_doubles([1]) -> [1]
# print diff_doubles([100,100,1.5,-1.5,50,3,7,20]) -> [0, 3.0, 47, -13]
def diff_doubles(theList):
'''Takes the difference of values in a list, subtracting the first from
the second variable. If odd, prints last variable (acts as the last subtracts
zero)
'''
length = len(theList)
numDoubles = length / 2
remainder = length % 2 == 1
newList = []
for n in range(numDoubles):
index = n*2
diff = theList[index] - theList[index+1]
newList.insert(n,diff)
if remainder:
newList.insert(numDoubles, theList[length-1])
return newList
# print future_tense(['program','debug','execute','crash','repeat']) -> ['will program', 'will debug', 'will execute', 'will crash', 'will repeat']
# print future_tense(['google']) -> ['will google']
# print future_tense(['act','blow-up','integrate','define','return','loop']) -> ['will act', 'will blow-up', 'will integrate', 'will define', 'will return', 'will loop']
def future_tense(theList):
'''Takes a list of verbs and puts them in future tense, ignoring
irregular verbs
'''
newList = []
for n in range(len(theList)):
newList.insert(n,"will " + theList[n])
return newList
#HELPER FUNCTION FOR FUNCTION past_tense THAT EVALUATES WHETHER THE GIVEN STRING CONTAINS A VOWEL
def find_vowel(string):
theVowels = ['a','e','i','o','u']
for n in range(5):
if theVowels[n] in string:
return True
return False
# print past_tense(['program','debug','execute','crash','repeat']) -> ['programmed', 'debugged', 'executed', 'crashed', 'repeated']
# print past_tense(['try']) -> ['tried']
# print past_tense(['eat','read','pick','dance','laugh','find','play','anticipate']) -> ['eated', 'readed', 'picked', 'danced', 'laughed', 'finded', 'played', 'anticipated']
def past_tense(theList):
'''Takes a list of verbs and puts them into past tense, ignoring
irregular verbs
'''
newList = []
for n in range(len(theList)):
thisWord = theList[n]
lastLetter = thisWord[-1]
prevLastVowel = find_vowel(thisWord[-2])
if lastLetter == 'e':
addSuffix = 'd'
elif lastLetter == 'y' and not prevLastVowel:
thisWord = thisWord[0:-1]
addSuffix = 'ied'
elif prevLastVowel and not find_vowel(thisWord[-3]) and not find_vowel(lastLetter) and lastLetter != 'y' and lastLetter != 'w':
addSuffix = lastLetter + "ed"
else:
addSuffix = 'ed'
newList.insert(n,thisWord + addSuffix)
return newList
# print combinations([0,1,2],2) -> [[0, 1], [0, 2], [1, 2]]
# print combinations(range(5),3) -> [[0, 1, 2], [0, 1, 3], [0, 1, 4], [0, 2, 3], [0, 2, 4], [0, 3, 4], [1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]]
# print combinations(['red','green','blue','black'],2) -> [['red', 'green'], ['red', 'blue'], ['red', 'black'], ['green', 'blue'], ['green', 'black'], ['blue', 'black']]
#
# FOR OTHER OUTPUTS SEE EXTENSIONS.TXT
def combinations(theList, r):
'''Takes a list and creates the amount of combinations defined by user
input r
'''
listSize = len(theList)
if r > listSize:
return None
newList = []
comboSize = range(r)
tmpList = []
for n in comboSize:
tmpList.append(theList[n])
newList.append(tmpList)
j = 0
while j < listSize:
finished = False
tmpList = []
i = 0
for i in reversed(range(r)):
if comboSize[i] != i + listSize - r:
finished = False;
break
else:
break
comboSize[i] += 1
for m in range(i+1, r):
comboSize[m] = comboSize[m-1] + 1
for j in comboSize:
tmpList.append(theList[j])
newList.append(tmpList)
return newList
|
'''ss377KINAROW.py
This module contains a player for K-in-a-row. It's personality is Mr T.
It takes a given game stage and computes moves, and comments accordingly.
'''
import copy
import time
import random
##
## Returns Introduction of the personality of this Player
##
def introduce():
output = "When I was growing up, my family was so poor we couldn`t afford to pay attention!"
output += "I'm a little program made by Steven Stevenson, but pitty that fool!"
output += "I believe in the Golden Rule - The Man with the Gold.. rules."
output += "Quit yo Jibber-jabber! Let's Play!"
return output
##
## Returns Personalities nickname
##
def nickname():
return "Mr. T"
##
## returns the other player's symbol
##
def other(mySide):
if mySide == 'X':
return 'O'
else:
return 'X'
##
## Prepares the the global variables, with the passed variables.
## if maxMillisecPerMove < 20, then the game cannot be played
## if the dimensions of the board is not proper, the game cannot be played
## return OK if game is ready to be played
##
def prepare(k, mRows, nColumns, maxMillisecPerMove, isPlayingX, debugging):
if k > mRows and k > nColumns:
output = "I can't be beat, I won't be beat "
output += str(k) + " in a row on a " + str(mRows) + " by " + str(nColumns) + " board! FOOL!"
return output
elif maxMillisecPerMove < 20:
output = "Geez, " + str(maxMillisecPerMove) + " milliseconds! I pitty the fool who drinks soy milk!"
return output
else:
global K, ROWS, COLS, side, debug, maxTime,debug, oldUtterance, largeUtter
K = k
numMoves = 0
ROWS = mRows
COLS = nColumns
maxTime = maxMillisecPerMove *.001
if isPlayingX:
side = "X"
else:
side = 'O'
if debugging:
debug = True
else:
debug = False
oldUtterance = []
largeUtter = []
global debugUtter
debugUtter = ""
return "OK"
##
## returns a list of all possible moves for this player given a game state
##
def successors(state):
board = state[1]
sList = []
for r in range(len(board)):
for c in range(len(board[r])):
if board[r][c] == ' ':
temp = copy.deepcopy(board)
temp[r][c] = state[0]
newState = [ other(state[0]), temp]
sList += [newState]
if board[r][c] == ' ':
temp = copy.deepcopy(board)
temp[r][c] = state[0]
newState = [ other(state[0]), temp]
sList += [newState]
return sList
##
## returns a 'dumb' move for this player
##
def makeMove(state):
global numMoves
numMoves += 1
mySide = state[0]
newBoard = copy.deepcopy(state[1])
global ROWS
global COLS
for r in range(ROWS):
for c in range(COLS):
if newBoard[ROWS - 1 -r][COLS - 1 -c] == ' ':
newBoard[0][0] = mySide
utterance = "What did you say to me paper champion? "
newState = [other(mySide), newBoard]
global pState
pState = bestState
return [newState, utterance]
##
## returns the best move for this player and an appropriate utterance
## best move is defined by the static eval function, and the use of
## a minimax search with alphabeta pruning
##
def makeGoodMove(state):
global side
startc = time.time()
[bestScore, bestState] = minimax(state[0], state, 4, -90000000, 900000000, startc)
global pState
pState = bestState
getUtterance = False
utterance = ""
global oldUtterance, largeUtter
numUtt = 0
while not getUtterance:
if debug:
break
else:
if bestScore < 5000:
uList = ["You... Naked?",
"You make me Angry",
"Dun Mess with Me!",
"I pitty the fool! ",
"Suckka!",
"If you put down one motha, you put down motha's around the world.",
"Don't mess with my motha!",
"" + other(side) + "'s are for sissies!",
"Wanna hurtz donut?",
"I'll give you a birthday present...",
"clean my gold with the special cleaner!",
"If you think I'm big, you should meet my brothers!",
"Go eat a fish!",
"Pain...",
"Snickers! ",
"Hey You with the teeth...",
"Wake Up, Fool!",
"Fool! come back here!",
"Less Jib, more Jab!",
"Want a bike? Let me get my tank! PAIN!",
"Take that toe dipper!",
"I'm going to keep my eye on you.",
"pitty!",
"It takes a smart guy to play dumb.",
"Sure you wanna go there punk!?",
"That's it you're going in the water!",
"Take that speedwalker!",
"Fool!!",
"Just half a glass short of some woopass!",
"You're a disgrace to the man race",
"Always smart to play dumb!.",
"Don't let me catch you cryin'",
"FOOL!",
"I'll play easy on you, ha Sucka!",
"Crazy Murdock!!",
"" + other(side) + "'s are fools!",
"Quit yo Jibberjabber!",
"AAAARRRRHHHHH",
"Trouble, with a capital T",
"Don't let me catch you cryin'",
"What do you mean four sucka?"
"Who you jokin'",
"sucka! I'm gonna smash you!",
"Hungry for some " + other(side) + "?",
"Get some nuts!",
"I'm educated in pain!"]
utterance = random.choice(uList)
elif bestScore > 5000:
uList = ["I'm the baddest in the world!",
"I win you lose, suckka!",
"I win, want a cookie?",
"Time to fly!"]
oldUtterance = []
utterance = random.choice(uList)
if len(oldUtterance) >= 45:
lastUtterance = oldUtterance.pop()
oldUtterance.append(lastUtterance)
if len(utterance) > 30 and largeUtter.count(utterance) == 0 and len(lastUtterance) < 30:
largeUtter.append(utterance)
oldUtterance = []
oldUtterance.append(utterance)
break
elif len(utterance) < 30 and oldUtterance.count(utterance) == 0:
oldUtterance = []
oldUtterance.append(utterance)
break
elif len(oldUtterance) > 0:
lastUtterance = oldUtterance.pop()
oldUtterance.append(lastUtterance)
if len(utterance) > 30 and largeUtter.count(utterance) == 0 and len(lastUtterance) < 30:
largeUtter.append(utterance)
oldUtterance.append(utterance)
break
elif len(utterance) < 30 and oldUtterance.count(utterance) == 0:
oldUtterance.append(utterance)
break
elif len(oldUtterance) == 0:
if len(utterance) > 30:
largeUtter.append(utterance)
oldUtterance.append(utterance)
break
if debug:
numMoves = 0
for i in range(len(bestState[1])):
numMoves += bestState[1][i].count('X')
numMoves += bestState[1][i].count('O')
global debugUtter
utterance = "In Move " + str(numMoves) + debugUtter
return [bestState, utterance]
##
## Recursively looks at different Plys of the game state to determine
## the highest scoring move throughout all the successors (given allotted time)
##
def minimax(origSide, state, depth, min, max, timer):
global debug
global numMoves
global debugUtter
global maxTime
if time.time() - timer > maxTime - K*100*.001:
return [staticEval(state), state]
sList = successors(state)
if depth == 0 or len(sList) == 0:
return [staticEval(state), state]
if state[0] == origSide:
x = min
newState = state
for poss in range(len(sList)):
thisResult = minimax(origSide, sList[poss], depth-1, x, max, timer)
thisEval = thisResult[0]
if thisEval > x:
x = thisEval
newState = sList[poss]
if x > max:
if debug:
debugUtter = " of the game, it is " + origSide + \
"'s turn, and an alpha cutoff occurs at Ply " + str(1-depth) + \
" out of 3 because provisional value is " + str(x) + \
" and the other player could get: " + str(max) +"."
return [max, newState]
return [x, newState]
else:
y = max
newState = state
for poss in range(len(sList)):
thisResult = minimax(origSide, sList[poss], depth-1, min, y, timer)
thisEval = thisResult[0]
if thisEval < y:
y = thisEval
newState = sList[poss]
if y < min:
if debug:
debugUtter = " of the game, it is " + origSide + \
"'s turn, and an beta cutoff occurs at Ply " + str(1-depth) + \
" out of 3 because provisional value is " + str(y) + \
" and the other player could get: " + str(min) +"."
return [min, newState]
return [y, newState]
## Collects a list of all possible winnings
## Evaluates the state by having a score connected to each option:
## returns an appropriate value for this current state
## (value is determined by tabulateScore())
##
def staticEval(state):
board = state[1]
global K
ROWS = len(board)
COLS = len(board[0])
cList = []
rList = []
dList = []
d2List = []
for r in range(ROWS):
for c in range(COLS):
if r+K < ROWS + 1:
temp = []
for j in range(r,K+r):
temp += [board[j][c]]
cList += [temp]
if c+K < COLS + 1:
temp = []
for j in range(c,K+c):
temp += [board[r][j]]
rList += [temp]
if c+K < COLS + 1 and r+K < ROWS + 1:
d1 = []
dr = r
dc = c
for i in range(K):
d1 += [board[dr][dc]]
dr += 1
dc += 1
dList += [d1]
if c-(K-1) > -1 and r+K < ROWS + 1:
d2 = []
dr = r
dc = c
for i in range(K):
d2 += [board[dr][dc]]
dr += 1
dc -= 1
d2List += [d2]
runningTotal = 0
runningTotal += tabulateScore(cList)
runningTotal += tabulateScore(rList)
runningTotal += tabulateScore(dList)
runningTotal += tabulateScore(d2List)
return runningTotal
##
## Tabulate score is the value processor for staticEval():
## It's function to determine the score is as follows:
## where K = num of this players entries for win
## and K-1 = num entries where 1 move away from win
## and i:K = i num of this players
## where O = num of other players entries for win
## and i:O i num of other players
## 10000K + 600(K-1) + 180(K-2) + 80(K-2 ^ i:O) + 70(K-1 ^ 1:O) + 10(2:K ^ 0:O) + 4(0:O) + 1(1:K)
## - [ 1000O + 1000(O-1 ^ 0:K) + 70(O-1 ^ 1:O) + 300(O-2 ^ O:K) + 80(O-2 ^ 1:K) + 10(2:O ^ 0:K) + 4(0:K) + 1(1:O)
##
def tabulateScore(thisList):
global side
mySide = side
global K
score = 0
otherSide = other(mySide)
for i in range(len(thisList)):
count = thisList[i].count(mySide)
otherCount = thisList[i].count(otherSide)
if thisList[i].count('-') == 0:
if count > 0:
firstSide = thisList[i].index(mySide)
if count == K:
score += 10000
if count == K-1 and otherCount == 0:
score += 600
if count == K-2 and otherCount == 0:
score += 180
if otherCount == K-2 and count == 1:
score += 80
if otherCount == K-1 and count == 1:
score +=70
if count == 2 and thisList[i][firstSide+1] == mySide and otherCount == 0:
score += 10
if otherCount == 0:
score += 4
score += 1
if otherCount > 0:
firstSide = thisList[i].index(otherSide)
if otherCount == K:
score -= 1000
if otherCount == K-1 and count == 0:
score -= 1000
if count == K-1 and otherCount == 1:
score -= 70
if otherCount == K-2 and count == 0:
score -= 300
if count == K-2 and otherCount == 1:
score -= 80
if otherCount == 2 and thisList[i][firstSide+1] == otherSide and count == 0:
score -= 10
if count == 0:
score -= 4
score -= 1
return score
|
# PdfFileWriter 可以分割寫入 PDF 檔
from PyPDF2 import PdfFileReader, PdfFileWriter
# 設定讀取 PDF 檔案,獲取 PdfFileReader 物件,此處增加宣告 strict = False
# 是因為所讀取 PDF 混用了不同的編碼方式,因此直接讀取發生 error 而無法執行,
# 宣告此一參數將使 error 改為 warning 方式出現,使程式仍能繼續。
readFile = 'E1-1-2-2-input.pdf'
pdfFileReader = PdfFileReader(readFile, strict=False)
# pdfFileReader = PdfFileReader(open(readFile, 'rb'))
# 設定輸出檔案,並獲取 PdfFileWriter 物件。
outFile = 'E1-1-2-3-output.pdf'
pdfWriter = PdfFileWriter()
# 取得讀取檔案的頁數
numPages = pdfFileReader.getNumPages()
# 從第 3 頁之後的頁面,輸出到一個新的檔案中,即分割檔案。添加完每頁,再一起保存至檔案中。
if numPages > 3:
for index in range(3, numPages):
pageObj = pdfFileReader.getPage(index)
pdfWriter.addPage(pageObj)
pdfWriter.write(open(outFile, 'wb'))
|
import re, os, argparse
import random
import check
from fractions import Fraction
''''
print 语句是为测试用,已注释掉
len_bag_randint = random.randint(2,len(bag)) 目的是为了取数,生成1个符号的式子,需要2个数,
生成3个运算符的式子需要4个数
create_expression函数目前只能生成整数式子,没有判断功能:判断式子是否合法——结果负值,除法有0等,只能简单生成式子
'''
def create_expression(erange=10):
operator = [' + ', ' - ', ' * ', ' / '] #符号
end_operator = ' ='
equation = '' #初始式子,为空
bag = [] #为随机数的空列表,随机从里面取字
nature_step = random.randrange(1, 3) #随机数的间隔
#print(nature_step)
for i in range(3):
bag.append(str(random.randrange(1, erange, nature_step)))
for i in range(1):
denominator = random.randrange(1, erange,nature_step ) #分母
molecule = random.randrange(1, erange,nature_step ) #分子
denominator,molecule = max(denominator,molecule) , min(denominator,molecule) #比较大小同时交换
fraction_number = molecule/denominator
fraction_number = Fraction('{}'.format(fraction_number)).limit_denominator() #小数转换为真分数
bag.append(str(fraction_number))
#print(bag)
len_bag_randint = random.randint(2,len(bag))
#print(len_bag_randint)
for i in range(len_bag_randint):
#随机取bag里的数
randint_number = random.randint(0,len(bag)-1)
#print("randint_number:")
#print(randint_number)
equation += bag[randint_number]
if i < len_bag_randint-1:
equation += operator[randint_number % len(operator)]
else:
equation += end_operator
bag.pop(randint_number)
return equation
#获取答案
def get_answer(question):
question = question.replace('=',' ')
t = eval(question)
t = Fraction('{}'.format(t)).limit_denominator()
return t
'''
opt():
argparse是一个Python模块:命令行选项、参数和子命令解析器。
argparse模块可以让人轻松编写用户友好的命令行接口。
程序定义它需要的参数,然后argparse将弄清楚如何从sys.argv解析出那些参数。
'''
def opt():
parser = argparse.ArgumentParser()
# 设置四个选项
parser.add_argument("-n", dest = "need", help = "生成数量")
parser.add_argument("-r", dest = "range", help = "生成范围")
parser.add_argument("-e", dest = "grade_e", help = "练习文件" )
parser.add_argument("-a", dest = "grade_a", help = "答案文件" )
args = parser.parse_args()
return args
'''
main():命令行输入参数,如:python expression.py -n 10 -r 10
生成10以内的10个式子,-n 是式子数量,-r 是数字范围
'''
def mian():
args = opt()
need_number = erange2 = 0
if args.range and args.need:
erange2 = int(args.range)
need_number = int(args.need)
for i in range(need_number):
to_file(need=need_number,erange=erange2)
#问题写入Exercises.txt,答案写入Answers.txt
def to_file(need=10, erange=10):
question_list = list()
answer_list = list()
for i in range(need):
question = create_expression(erange=erange)
answer = str(get_answer(question))
question_list.append(question)
answer_list.append(answer)
f = open('Exercises.txt', 'w')
k = open('Answers.txt', 'w')
for line in question_list:
f.write(line+'\n')
f.close()
for line in answer_list:
k.write(line+'\n')
k.close()
if __name__=='__main__':
'''
for i in range(10):
test1 = test2 = create_expression()
test1 = eval(test1)
print(test2)
print (test1)
'''
mian()
|
import multiprocessing
def motion(data):
return data+2
if __name__=="__main__":
pool = multiprocessing.Pool()
for i in range(10):
if (i % 2) == 0: # use mod operator to see if "i" is even
#result.put(i)
print(pool.apply(motion,(i,)))
else:
if i==5:
pool.terminate()
print("terminate")
pool.join()
pool=multiprocessing.Pool()
else:
continue
|
import csv
import json
import re
def get_country_name(name):
german_countries = ['Germany', 'West Germany (Germany)', 'Germany (Poland)', 'Prussia (Germany)', 'Federal Republic of Germany']
#Countries with instances of birth and organization country (combined) that is <= 10
other_countries = ['Mexico', 'Morocco', 'Romania', 'Czechoslovakia', 'Pakistan', 'Alsace (then Germany, now France)', 'Bosnia and Herzegovina', 'Argentina', 'Algeria', 'Latvia', 'South Korea', 'Turkey', 'Spain', 'Egypt', 'New Zealand', 'Taiwan', 'Saint Lucia', 'Brazil', 'Finland', 'Lithuania', 'Slovenia', 'Portugal', 'Croatia', 'Luxembourg', 'South Africa', 'Azerbaijan', 'Belarus', 'Venezuela', 'Cyprus', 'Indonesia', 'Ireland', 'Czech Republic', 'Slovakia', 'Ukraine', 'India', 'Scotland', 'Hungary', 'Israel']
actual = name
if name in german_countries:
actual = 'Germany'
pattern_matches = re.findall(r"\([a-zA-z\s]*\)", name)
if pattern_matches:
if len(pattern_matches) > 1:
print('Ambiguous country: {}'.format(name))
else:
matched = pattern_matches[0].strip('()')
print(matched)
actual = matched
if actual in other_countries:
actual = 'Other'
return actual
def main():
matrix = dict()
locations = dict()
with open('archive.csv', newline='') as csvfile:
reader = csv.DictReader(csvfile, delimiter=',')
for row in reader:
if row["Birth Country"] == "" or row['Organization Country'] == "":
continue
row["Birth Country"] = get_country_name(row["Birth Country"])
row['Organization Country'] = get_country_name(row["Organization Country"])
if row["Birth Country"] not in locations:
locations[row["Birth Country"]] = 0
if row['Organization Country'] not in locations:
locations[row["Organization Country"]] = 0
if row["Birth Country"] not in matrix:
matrix[row["Birth Country"]] = dict()
if row['Organization Country'] not in matrix[row["Birth Country"]]:
matrix[row["Birth Country"]][row['Organization Country']] = 1
else:
matrix[row["Birth Country"]][row['Organization Country']] += 1
locations[row["Birth Country"]] += 1
locations[row["Organization Country"]] += 1
# locations = sorted(locations)
# to_pop = list()
# for location, count in locations.items():
# if count < 5:
# to_pop.append(location)
# print('Popping: {}'.format(to_pop))
# for key in to_pop:
# locations.pop(key)
result = list()
names = list()
for b_location in locations.keys():
if b_location not in matrix:
vector = [0]* len(locations)
result.append(vector)
names.append(b_location)
continue
vector = list()
for o_location in locations.keys():
if o_location not in matrix[b_location]:
vector.append(0)
else:
vector.append(matrix[b_location][o_location])
names.append(b_location)
result.append(vector)
output = {
'result': result,
'names' : names
}
print(locations)
print(len(names))
# print results to json
with open('data.json', 'w') as json_file:
json.dump(output, json_file)
main()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
*
* *
* * *
* * * *
* * * * *
'''
# 打印上边的图形
# while 循环
treeheight = int(input('输入打印的高度: ')) #高度
hashes = 1
while treeheight != 0:
for i in range(hashes):
print('*',end=' ')
print()
treeheight -= 1
hashes += 1
# for 循环
treeheight = int(input('输入打印的高度: ')) #高度
for i in range(treeheight):
for j in range(i + 1):
print('*',end=' ')
print()
'''
*
* *
* *
* *
* * * * *
'''
# 打印上边的图形
# for 循环
for i in range(5):
for j in range(i + 1):
if i == 4:
print('*',end=' ')
continue
elif j == 0 or j == i:
print('*',end=' ')
else:
print(' ',end=' ')
print()
# 打印倒三角
'''
* * * * *
* * * *
* * *
* *
*
'''
# i 控制行号
# j 控制列号
# 例一
for i in range(5):
for j in range(5 - i): # 可以实现反向
print('*',end=' ')
print()
#例二,改进
# 可以使用参数控制 range 结果
for i in range(5, 0, -1):
for j in range(i, 0, -1): # 可以实现反向
print('*',end=' ')
print()
# 打印正三角形
# *
# * *
# * * *
# * * * * *
# i-for 控制行
# j-for 控制列
for i in range(6):
# 总体思路是,先打印空格,再打印星星。
for j in range(6 - i):
print('',end=' ')
for m in range(i + 1):
print('*', end=' ')
print()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# L1 = ['Hello', 'World', 18, 'Apple', None]
# L2 = [s.lower() for s in L1 if isinstance(s, str)]
# print(L2)
# if L2 == ['hello', 'world', 'apple']:
# print('测试通过!')
# else:
# print('测试失败!')
# ----------------------------------------------
# def fib(max):
# n, a, b = 0, 0, 1
# while n < max:
# print(b)
# a, b = b, a + b
# n = n + 1
# return 'done'
# fib(6)
# ------------------------------------
# def fib(max):
# n, a, b = 0, 0, 1
# while n < max:
# yield b
# a, b = b, a + b
# n = n + 1
# return 'done'
# for i in fib(6):
# print(i)
# ---------------------------------------------
# l = list(filter(lambda n: n % 2 == 0, range(1, 20)))
# print(l)
# import time
# def test():
# time.sleep(2)
# print("test is running!")
# def deco(func):
# start = time.time()
# func() #2
# stop = time.time()
# print(stop-start)
# deco(test) #1
import time
def timer(func): #5
def deco():
start = time.time()
func()
stop = time.time()
print(stop-start)
return deco
@timer
def test():
time.sleep(2)
print("test is running!")
test() #7
def fib(max):
n, a, b = 0, 0, 1
while n < max:
print(b)
a, b = b, a + b
n = n + 1
return 'done'
fib(10)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 字符串拼接,最好用.format方式,其次用%s方式,最好不要用‘+’号,
# 万恶的‘+’,会把每个符符串都开辟内存空间,不高效!
name = input('name: ').strip() # .strip()
age = input('age: ').strip()
job = input('job: ').strip()
print('InFomation of \n{}\n{}\n{}\n'.format(name, age, job))
# 函数原型
# 声明:s为字符串,rm为要删除的字符序列
# s.strip(rm) :删除s字符串中开头、结尾处,位于 rm删除序列的字符
# s.lstrip(rm) :删除s字符串中 开头处,位于 rm删除序列的字符
# s.rstrip(rm) :删除s字符串中 结尾处,位于 rm删除序列的字符
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 常用模块
# calendar
# time
# datetime
# timeit
# os
# shutil
# zip
# math
# string
# 上述所有模块使用,得先导入,string是特例
# calendar, time, datetime 的区别参考中文意思
# calendar
# 跟日历相关的模块
import calendar
# calendar: 获取一年的日历字符串
# 参数
# w = 每个日期之间的间隔字符数
# l = 每周所占用的行数
# c = 每个月之间的间隔字符数
cal = calendar.calendar(2019)
print(type(cal))
# cal = calendar.calendar(2019, l=0, c=5)
# isleap: 判断某一年是否闰年
calendar.isleap(2019)
# leapdays: 获取指定年份之间的闰年的个数
calendar.leapdays(2001, 2019)
help(calendar.leapdays)
# month() 获取某个月的日历字符串
# 格式:calendar.month(年,月)
# 回值:月日历的字符串
m3 = calendar.month(2019, 3)
print(m3)
# monthrange() 获取一个月的周几开始即和天数
# 格式:calendar.monthrange(年,月)
# 回值:元组(周几开始,总天数)
# 注意:周默认 0 -6 表示周一到周天
w, t = calendar.monthrange(2019, 3)
print(w)
print(t)
# monthcalendar() 返回一个月每天的矩阵列表
# 格式:calendar.monthcalendar(年,月)
# 回值:二级列表
# 注意:矩阵中没有天数用0表示
m = calendar.monthcalendar(2019, 3)
print(type(m))
print(m)
# prcal: 直接打印日历 print calendar
calendar.prcal(2019)
# prmonth() 直接打印整个月的日历
# 格式:calendar.prmonth(年,月)
# 返回值:无
calendar.prmonth(2019, 5)
# weekday() 获取周几
# 格式:calendar.weekday(年,月,日)
# 返回值:周几对应的数字
calendar.weekday(2019, 5, 25)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 函数
# 函数是代码的一种组织形式
# 函数应该能完成一项特定的工作,而且一般一个函数只完成一项工作
# 有些语言,分函数和过程两个概念,通俗解释是,有返回结果的叫函数,无返回结果的叫过程,
# python 不加以区分
# 函数的使用
# 函数使用需要先定义
# 使用函数,俗称调用
# 定义一个函数
# 只是定义的话不会执行
# 1. def关键字,后跟一个空格
# 2. 函数名,自己定义,起名需要遵循便令命名规则,约定俗成,大驼峰命名只给类用
# 3. 后面括号和冒号不能省,括号内可以由参数
# 4. 函数内所有代码缩进
def func():
print('我是一个函数')
print('爱生活,爱拉芳,爱图灵。')
print('函数结束了')
# 函数的调用
# 直接写出函数名字,后面小括号不能省略,括号内的内容根据情况而定
func()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# str 字符串
# str
# 转义字符
# 格式化
# 内建函数
# 字符串
# 表示文字信息
# 用单引号,双引号,三引号括起来
s = 'i love lao wang'
print(s)
s = 'i love lao wang'
print(s)
s = '''
i
love
lao
wang
'''
print(s)
# 转义字符
# 用一个特色的方表示一系列不方便写出出的内容,比如:回车键,换行符等。
# 借助反斜杠字符,一旦字符串中出现反斜杠,则反斜杠后面一个或者几个字符表示已经不是原来的意思了,进行了转义
# 在字符串中,一旦出现反斜杠就要加倍小心,可能由转义字符出现
# 不同系统对换行操作有不同的表示
# windows: \n
# Linux: \r\n
# 转义符的案例
# 想表达 let's Go
# 使用转义字符
# 案例1
s = 'Let\'s Go'
print(s)
# 案例2 使用单双引号嵌套
s = "Let's Go"
print(s)
# 表示斜杠
# 比如: c:\User\Augsnano
s = 'c:\\User\\Augsnano'
print(s)
# 表示回车换行
# 想表达的是每个单词回车效果。
s = '今夕何夕兮,搴舟中流。\n今日何日兮,得与王子同舟。\n蒙羞被好兮,不訾诟耻。\n心几烦而不绝兮,得知王子。'
print(s)
# 单个斜杠的用法
# 在 python 里,单个反斜杠表示此行未结束,出于美观,需要下一行继续
def myDemo(x, \
y, \
z):
print('这是一句话')
myDemo(1, 2, 3)
# 格式化字符串
# 把字符串按照一定格式进行打印或者填充
# 格式化分类:
# 传圣诞节模式化
# format 函数
# 字符串的传统格式化方
# 使用 % 进行格式化
# % 也叫占位符
# 占位符 用途
# %s 字符串
# %r 字符串,采用repr()的显示
# %c 单个字符
# %d 十进整数
# %i 十进整数,同%d
# %o 八进整数
# %x 十六进整数
# %e 指数,基底为e
# %E 指数,基底为E
# %f 浮点型
# %F 浮点型,同%f
# %g 指数e或浮点型,根据显示长度决定
# %G 指数E或浮点型,根据显示长度决定
# 格式字符前出现整数表示此占位符所占位置宽度
# 格式字符前边出现 “-” 表示左对齐
# 格式字符前边出现 “+” 表示右对齐
# 0位数不足用 “0” 补齐
# width 表示宽度
# pricision 精度
# https://www.cnblogs.com/gambler/p/9567165.html
# 传统格式化案例
# 用 %s 表示简单的字符串
# 占位符可以单独使用
s = 'I love %s'
print(s)
print(s %('wang'))
print(s %'wang')
print('I love %s' %('二麻子'))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 作业一
# 写一个程序,判断给定年份是否为闰年
# 闰年的定义:能够被 4 整除的年份就是闰年
year = input('请输入年份===>') # type: str
if year.isdigit(): # isdigit() 方法检测字符串是否只由数字组成。
year = int(year)
if year % 4 == 0:
print('{} 是闰年'.format(year))
else:
print('{} 不是闰年'.format(year))
else:
print('输入的是年份吗?')
# 作业二
# 给用户三次机会,猜想我们程序生成的一个数字 A,
# 每次用户猜想过后会提示数字是否正确以及用户输入数字是大于还是小于 A,
# 当机会用尽后提示用户已经输掉
import random
secert = random.randint(1, 10) # 生成随机整数
times = 3 # 用户可猜的次数
while times:
num = input('请输入数字:') # type: str
if num.isdigit():
num = int(num)
if num == secert:
print('你猜对了')
break
elif num < secert:
print('你猜的数字小了')
times -= 1
else:
print('你猜的数字大了')
times -= 1
else:
print('你输的不是数字!重来。')
else:
print('游戏结束')
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 什么是柯里化
# 指的是将原来接受两个参数的函数变成新接受一个参数的函数的过程。新的函数返回一个以原有第二个参数为参数的函数。
# 如:z = f(x, y) 转换成 z = f(x)(y)
# 实例
def add(x, y):
return x + y
# z = f(x, y)
print(add(4, 5))
def new_add(x):
return inner
# 方便记忆的写法,先写一个函数,接受第一个参数,然后返回一个新的函数, 如,返回了一个新的函数 inner。
def new_add(x):
def inner(y):
return x + y
return inner
# foo = new_add(4)
# foo(5)
print(new_add(4)(5))
# z = f(x)(y)
# 方便记忆写法,再内部再写一个函数,注意函数名为上一层函数返回的函数名,如:inner 在内部函数编写具体的函数实体。
|
import random
# set balance for testing purpose
balance = 10
rounds_played = 0
play_again = input("Press <Enter> to play... ").lower()
while play_again == "":
# increase # of rounds played
rounds_played += 1
# Print round number
print()
print("*** Round #{} ***".format(rounds_played))
chosen_num = random.randint(1, 100)
# Adjust balance
# if the random # is between 1 and 5
# user will get unicorn *add 4$ to balance
if 1 <= chosen_num <=5 :
chosen = "unicorn"
balance += 4
# if the random # is between 6 and 46
# user will get donkey *minus 1$ from balance
elif 6 <= chosen_num <=36 :
chosen = "donkey"
balance -= 1
# if the token is either horse or zebra
# minus $0.50 from the balance
else:
# if number is even token = horse
if chosen_num % 2 == 0:
chosen = "horse"
# if odd number user will get zebra
else:
chosen = "zebra"
balance -= 0.5
print("You got a {}. Your balance is ${:.2f} " .format(chosen, balance))
if balance < 1:
play_again = "xxx"
print("Sorry you have run out of money")
else:
play_again = input("Press <Enter> to play or <xxx> to quit ")
print()
print("Final Balance", balance)
|
def getalpha(prompt: str) -> str:
while True:
string = input(prompt)
if not string.isalpha(): print("Invalid input. Please only enter English letters.")
else: break
return string
name = getalpha("Please enter your name: ").lower()
other = getalpha("Please enter another word: ").lower()
vowels = ['a', 'e', 'i', 'o', 'u']
port = ""
manteau = ""
for i in range(len(name) - 2, -1, -1):
if name[i] in vowels:
port = name[:i + 1]
break
if port == "": port = name
for i in range(1, len(other) - 1):
if other[i] in vowels:
manteau = other[i + 1:]
break
if manteau == "": manteau = other
print((port + manteau).capitalize())
|
##Intro to functions
def theTruth():
"""displaying a statement"""
print ( 'Existance is pain.' )
theTruth()
|
## Or Condition
yourAge = input("How old are you?\n")
friendAge = input("Yeah but how old is your friend? haha\n")
if int(yourAge) >= 18 or int(friendAge) >=18:
print ( "Congrats. Welcome to the rest of your life." )
else:
print ("You're both so young and naive.")
|
##Function with multiple parameters/arguments: Keyword Arguments
def bookInfo(bookName, bookType, bookAuthor):
"""This function displays information about the book"""
print ( bookName.title() + ' is a(n) ' + bookType.lower() + ' book, that was written by ' + bookAuthor.title())
name = input( "Please enter a book name: \n" )
inputType = input( "What is the type of this book?\n" )
author = input( "Who is the author of this book?\n" )
bookInfo(bookName=name, bookType=inputType, bookAuthor=author)
|
#finding length
daysOfWeek = [
'monday',
'tuesday',
'wednesday',
'thursday',
'friday',
'saturday'
]
print (len(daysOfWeek) )
|
##Passing a list to a function and modifying it
def showNotCheckedInPassengers(notChecked):
"""Display not checked in passengers"""
print ( 'These passengers are not yet checked in: ' )
for passenger in notChecked:
print(' -' + passenger.title())
def checkInPassengers(notChecked,checked):
"""simulate passengers who are not checked in"""
print('\nChecking in passengers...')
while notChecked:
currentPassenger = notChecked.pop()
##Simulate checking them in
print( "Checking in: " + currentPassenger.title())
checked.append(currentPassenger)
def showCheckedPassengers(checked):
"""Show all passengers who have checked in"""
print("\nThe following passengers have been checked in: ")
for passenger in checked:
print(passenger.title())
notChecked = [
'Brent Nolan',
'Tw Flem',
'Judith',
'Harry Potter'
]
checked= []
showNotCheckedInPassengers(notChecked)
checkInPassengers(notChecked,checked)
showCheckedPassengers(checked)
|
from random import choice
import json
choices = ["Rock", "Paper", "Scissor"]
def game(played,p1_won,cmp_won):
played+=1
print("ROCK!! PAPER!! SCISSOR!!")
print("1. Rock")
print("2. Paper")
print("3. Scissor")
player_choice = choices[int(input("Choose:")) - 1]
computer_choice = choice(choices)
print("Your choice : {0}\nComputer has chosen : {1}".format(player_choice, computer_choice))
if player_choice == computer_choice:
print("It's a draw")
else:
if player_choice == 'Rock':
if computer_choice == 'Scissor':
print("You win!!")
p1_won+=1
else:
print("You lost!!")
cmp_won+=1
elif player_choice == 'Paper':
if computer_choice == 'Rock':
print("You win!!")
p1_won+=1
else:
print("You lost")
cmp_won+=1
elif player_choice == 'Scissor':
if computer_choice == 'Paper':
print("You win!!")
p1_won+=1
else:
print("You lost")
cmp_won+=1
return (played,p1_won,cmp_won)
if __name__ == "__main__":
print("Welcome to Rock-Paper Scissor")
menu_choice=int(input(
"Menu:\n" +
"1.New Game\n" +
"2.Exit\n"
))
if menu_choice == 1: #New Game
player_name = input("Enter player Name:")
print("Hello {}. Game starting...".format(player_name))
played,p1_won,cmp_won = 0, 0, 0
exit=False
while True:
played,p1_won,cmp_won=game(played,p1_won,cmp_won)
while True:
game_menu = int(input(
"Game Menu:\n" +
"1.Show score\n" +
"2.Reset score\n" +
"3.Play again\n" +
"4.Exit Game\n"
))
if game_menu == 1: #Show score
print("Show score:")
print("GAMES PLAYED : {}".format(played))
print("P1 : {}".format(p1_won))
print("CMP : {}".format(cmp_won))
print("DRAW : {}".format((played -(p1_won + cmp_won))))
elif game_menu == 2: #Reset score
played,p1_won,cmp_won = 0, 0, 0
break
elif game_menu == 3: #Play again
break
elif game_menu == 4: #Exit Game
exit=True
break
if exit:
break
"""Save Game"""
save_game = input("Save Game?\n[Y]es\n[N]o\n")[0].lower()
if save_game == 'y':
file_name = input("Enter the file name:")
output={
"name":player_name,
"game":{
"played":played,
"won":p1_won,
"lost":cmp_won,
"draw":played-(p1_won+cmp_won)
}
}
f = open(file_name + ".json", "w")
f.write(json.dumps(output, indent = 1))
else: #Exit
print("Exiting game")
|
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
def process_data(data_file):
df = pd.read_csv(os.getcwd() + "/data/" + data_file)
df = df.loc[df["death_count"] >= 100, ]
return df["death_count"].values
def compute_death_rate(population, case_array):
daily_new_death = np.array([case_array[i + 1] - case_array[i]
for i in range(len(case_array) - 1)])
population_array = np.array([population]) - case_array[: -1]
death_rate = daily_new_death / population_array
return death_rate
if __name__ == "__main__":
country_dict = {
"United Kingdom": 55980000,
"France": 1386000000,
"Italy": 60360000,
"Spain": 46940000,
"California": 39510000,
"New York": 19540000,
"New Jersey": 8882000,
"Florida": 21300000,
"Korea, South": 51470000,
"Washington": 7615000
}
for key, value in country_dict.items():
# case_array = process_data("UK.csv")
case_array = process_data(key + ".csv")
death_rate = compute_death_rate(value, case_array)
death_rate = death_rate[death_rate > 0]
plt.plot(death_rate, label=key)
# p.set_label(key)
plt.legend()
# sns.jointplot(x=range(len(alpha)), y=alpha)
|
def is_palindrome(n) -> bool:
"""
Functia determina daca un numar este palindrom sau nu
Metoda: verificarea elemtelor simetrice din lista, in functie de mijlocul listei
:param n: variabila de tip string ce poate contine un numar
:return: True daca elementul este palindrom, False daca nu este palindrom
"""
le = len(n)
for i in range(0, le // 2):
if len(n) % 2 == 1:
if n[i] != n[le-i-1]:
return False
elif n[i] != n[le-i-1]:
return False
return True
assert is_palindrome("121") is True
assert is_palindrome("12345") is False
assert is_palindrome("12344321") is True
assert is_palindrome("12") is False
assert is_palindrome("4") is True
def get_longest_all_palindromes(l_init, numar_el):
"""
Functia determina cea mai lunga secventa de numere palindrom din lista citita
Daca exista mai multe secvente de lungime maxima se va afisa prima secventa
:param l_init: O lista care contine numere intregi
:param numar_el: Un numar natural nenul
:return: Se returneaza o alta lista decat cea citita, ce contine secventa ceruta,
sau False daca nu exista secventa ceruta
"""
contmax = 0
cont = 0
for i in range(0, numar_el):
if is_palindrome(str(l_init[i])):
cont += 1
else:
cont = 0
if cont > contmax:
contmax = cont
cont = 0
l_fin = []
if contmax == 0:
return None
for i in range(0, numar_el):
if is_palindrome(str(l_init[i])):
cont += 1
l_fin.append(int(l_init[i]))
else:
cont = 0
l_fin.clear()
if cont == contmax:
return l_fin
l_init.clear()
def test_get_longest_all_palindromes():
assert get_longest_all_palindromes([12, 121, 1331, 56765, 1234], 5) == [121, 1331, 56765]
assert get_longest_all_palindromes([12, 76, 45, 89], 4) is None
assert get_longest_all_palindromes([678, 78, 3, 111], 4) == [3, 111]
assert get_longest_all_palindromes([100, 293, 69], 3) is None
def bit_count(n):
"""
Funtctia calculeaza numarul de biti 1 din scriere parametrului in baza 2
:param: un numar intreg
:return: Returneaza un numar intreg ce reprezinta numarul de biti 1 din scriere parametrului in baza 2
"""
cont = 0
while n > 0:
if n % 2 == 1:
cont+=1
n//=2
return cont
assert bit_count(7) == 3
assert bit_count(8) == 1
assert bit_count(17) == 2
assert bit_count(0) == 0
def get_longest_same_bit_counts(l_init, numar_el_bit) -> list[int]:
"""
Functia determina cea mai lunga secventa de numere care au acelasi numar de biti 1 in scrierea lor
in baza 2, din lista citita
Daca exista mai multe secvente de lungime maxima se va afisa prima secventa
:param l_init: O lista care contine numere intregi
:param numar_el_bit: Un numar natural nenul
:return: Se returneaza o alta lista decat cea citita, ce contine secventa ceruta,
sau None daca nu exista o astfel de secventa
"""
l_fin = []
contmax = 0
cont = 0
for i in range(0, numar_el_bit):
if bit_count(int(l_init[i])) > 0:
if cont == 0:
cont += 1
if i > 0:
if bit_count(int(l_init[i])) == bit_count(int(l_init[i-1])):
cont += 1
else:
if cont > contmax:
contmax = cont
cont = 1
cont = 0
for i in range(0, numar_el_bit):
if bit_count(int(l_init[i])) > 0:
if cont == 0:
cont += 1
l_fin.append(int(l_init[i]))
if i > 0:
if bit_count(int(l_init[i])) == bit_count(int(l_init[i-1])):
cont += 1
l_fin.append(int(l_init[i]))
else:
if cont == contmax:
return l_fin
cont = 1
l_fin.clear()
l_fin.append(int(l_init[i]))
def test_get_longest_same_bit_counts():
assert get_longest_same_bit_counts([0, 1, 2, 4, 6], 5) == [1, 2, 4]
assert get_longest_same_bit_counts([90, 100, 10, 3, 5, 24, 19], 7) == [10, 3, 5, 24]
assert get_longest_same_bit_counts([0, 0, 0], 3) is None
assert get_longest_same_bit_counts([0, 1, 3, 0], 4) == [1]
def is_prime(n):
"""
Functia determina daca un numar este sau nu prim
:param: un numar intreg
:return: Returneaza False daca numarul nu este prim sau True daca este prim
"""
if n < 2:
return False
else:
for d in range(2, n//2+1):
if n % d == 0:
return False
return True
def get_longest_all_not_prime(l_init) -> list[int]:
"""
Functia returneaza o lista ce contine cea mai lunga subsecventa de numere neprime
:param: o lista cu numere intregi
:return: o lista cu numere intregi sau none daca nu exista aceasta subsecventa neprime
"""
contmax = 0
cont = 0
for i in l_init:
if not is_prime(i):
cont += 1
if cont > contmax:
contmax = cont
else:
cont = 0
cont = 0
l_fin = []
for i in l_init:
if not is_prime(i):
cont += 1
l_fin.append(int(i))
if cont == contmax:
return l_fin
else:
cont = 0
l_fin.clear()
def test_get_longest_all_not_prime():
assert get_longest_all_not_prime([0, 1, 2, 3, 4]) == [0, 1]
assert get_longest_all_not_prime([4, 6, 8 ,13, 10, 17]) == [4, 6, 8]
assert get_longest_all_not_prime([11, 12, 20, 19, 22, 32, 77]) == [22, 32, 77]
def main():
test_get_longest_all_palindromes()
test_get_longest_same_bit_counts()
test_get_longest_all_not_prime()
shouldRun = True
while shouldRun:
print("Alegeti optiunea 1, 2 sau 3 in functie de exercitiul ales"
" sau x daca doriti sa iesiti")
optiune = input("Scrieti optiunea: ")
if optiune == "x":
shouldRun = False
elif optiune == "1":
numar_el = int(input("Introducei numarul de elemente din lista: "))
l_init = []
for i in range(0, numar_el):
l_init.append(input("l_init[" + str(i) + "]: "))
print("Rezultat: ", get_longest_all_palindromes(l_init, numar_el))
elif optiune == "2":
numar_el_bit = int(input("Introducei numarul de elemente din lista: "))
l_init = []
for i in range(0, numar_el_bit):
l_init.append(int(input("l_init[" + str(i) + "]: ")))
print("Rezultat: ", get_longest_same_bit_counts(l_init, numar_el_bit))
elif optiune == "3":
l_init = []
numar_el3 = int(input("Introducei numarul de elemente din lista: "))
for i in range(0, numar_el3):
l_init.append(int(input("l_init[" + str(i) + "]: ")))
print("Rezultat: ", get_longest_all_not_prime(l_init))
else:
print("Optiune incorecta. Reincercati! ")
if __name__ == '__main__':
main()
|
# -*- coding:utf-8 -*-
#直接按价格排序语句
#search food
class search_food():
def __init__(self,destination):
self.destination = destination
#按降序
self.sql1 = "select * from food where price != -1 and (city like '%{0}%' or area like '%{0}%') order by price desc".format(self.destination)
#按升序
self.sql2 = "select * from food where price != -1 and (city like '%{0}%' or area like '%{0}%') order by price asc".format(self.destination)
#search view
class search_view():
def __init__(self,destination):
self.destination = destination
#按降序
self.sql1 = "select * from view where (city like '%{0}%' or area like '%{0}%') order by price desc".format(self.destination)
#按升序
self.sql2 = "select * from view where (city like '%{0}%' or area like '%{0}%') order by price asc".format(self.destination)
#search hotel
class search_hotel():
def __init__(self,destination):
self.destination = destination
#按降序
self.sql1 = "select * from hotel where price != -1 and (city like '%{0}%' or area like '%{0}%') order by price desc".format(self.destination)
#按升序
self.sql2 = "select * from hotel where price != -1 and (city like '%{0}%' or area like '%{0}%') order by price asc".format(self.destination)
|
from generate_list import generate_random_list
from time import sleep
lista = generate_random_list(10)
for slow in range(len(lista)):
print("---" * 6)
print(f"Ordering position: {slow}")
for fast in range(slow, len(lista)):
if lista[fast] < lista[slow]:
aux = lista[fast]
lista[fast] = lista[slow]
lista[slow] = aux
# print(f"Verify slow: {lista[slow]}, fast: {lista[fast]}")
print(lista)
print(f"Found: {lista[slow]}")
|
#Question 1
my_list = ['this', True, 'student', 45, 66, 43]
new_list = my_list.copy()
print(new_list)
#Question 2
color_list = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']
color_list.remove('Red')
color_list.remove('Pink')
color_list.remove('Yellow')
print(color_list)
#Question 3
color_list = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']
color = input("What is your favourite color")
color_list.append(color)
print(color_list)
#Question 4
list1 = [10, 20, [300, 400, [5000, 6000], 500], 30, 40]
list1[2][2].append(7000)
print(list1)
|
nombre = {"giraffe":3, "singe":5}
emplacement = {"giraffe":"Cage nord-ouest"}
nombre['dahu'] = 1
nombre["singe"] = 6
print nombre
print 'singe' in nombre
print 'ornithorynque' in nombre
print nombre.keys()
print nombre.values()
print nombre.items()
liste_de_paires = nombre.items()
print dict(liste_de_paires)
for cle in nombre:
print cle
del nombre['giraffe']
print nombre
ordre = {cara: ord(cara) for cara in 'abcde' if cara != 'd'}
print ordre
|
import sys
#perform caterpillar method On^2
def solution(sum, array):
minimum_sum = -1
minimum_distance = -1
for i in range (0, len(array)):
j = i + 1
k = len(array) - 1
while j<k:
current_sum = array[i] + array[j] + array[k]
if minimum_sum == -1:
minimum_sum = current_sum
minimum_distance = abs(current_sum-sum)
elif abs(current_sum-sum) < minimum_distance:
minimum_sum = current_sum
minimum_distance = abs(current_sum-sum)
if (current_sum > sum):
k-=1;
else:
j+=1;
return minimum_sum
def main():
input_sum = int(input("enter sum:"))
input_n = int(input("number of elements:"))
i = 0
input_array = []
while (i < input_n):
input_array.append(int(input("enter element {}: ".format(i))))
i+=1
output = solution (input_sum, input_array)
print("The nearest sum is: {}", output)
if __name__=="__main__":
main()
|
#!/usr/bin/python
# WBKoetsier 9Jul2015
# very short script that uses selenium to fire up Google Chrome, get the
# Google search page, send a search term and print the full plain text
# html to stdout.
# install selenium: pip install selenium
# get the Chrome driver: http://chromedriver.storage.googleapis.com/2.16/chromedriver_linux64.zip unzipped in my ~/bin, which is already on the PATH
# imports
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from time import sleep
# fire up Chrome
browser = webdriver.Chrome()
# navigate to https://www.google.com (this opens the url with the gfe_rd and ei parameters)
browser.get('https://www.google.com')
# check if the word 'Google' is in the title (returns nothing on success)
assert 'Google' in browser.title
# no, in stead, print title to stdout
print 'Browser title before submitting search term:', browser.title
# the assert test is aborted if the text isn't found:
#>>> assert 'foo' in browser.title
#Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
#AssertionError
# catch/use the AssertionError in a real world script.
# find the search box
# the search box is an input field with the name 'q'. For example, use browser devtools
# to find the search box input element. This also tells me there is only one element
# that has name="q".
searchboxelement = browser.find_element_by_name('q') # finds first element with name attribute value = q
# use Keys to send keystrokes to the search box element: a search term and hit the return key to submit
searchboxelement.send_keys('elderberry' + Keys.RETURN)
# now give Google some time to respond and give the browser some time too!
sleep(5) # bit long perhaps, doesn't matter
# check results
print 'Browser title after submitting search term:', browser.title
# use one of the available methods to access the elements of the resulting page, for example use xpath.
# or stay with the google_search_requests.py script, print the full plain text html to stdout.
print 'Page source:'
print browser.page_source
# always close browser to clean up.
browser.quit()
|
# import the random and string packages to help generate passwords
import random
import string
# Asks the user for the length of their desired password
passLength = int(input("Welcome to my password generator! \n"
"Please enter the length of the desired password: "))
# Collects all potential data to be used in password generation
collectedData = string.ascii_letters + string.digits + string.punctuation
# Generates the password
tempPass = random.sample(collectedData, passLength)
password = "".join(tempPass)
# Displays the generated password
print("The generated password is:", password)
|
from graph_search import bfs, dfs
from vc_metro import vc_metro
from vc_landmarks import vc_landmarks
from landmark_choices import landmark_choices
# stations under construction to be taken out of dfs and bfs vertexes
stations_under_construction = ["Olympic Village"]
landmark_string = ""
for letter, landmark in landmark_choices.items():
if (letter in stations_under_construction) or (landmark_choices[letter] in stations_under_construction):
landmark_string += "CLOSED FOR CONSTRUCTION: [{} - {}]\n".format(
letter, landmark)
else:
landmark_string += "{} - {}\n".format(letter, landmark)
######################################
# Print Greeting
def greet():
print("Hi there and welcome to SkyRoute!")
print("We'll help you find the shortest route between the following Vancouver landmarks:\n" + landmark_string)
################################
# takes in None/landmark_choice keys and puts out landmarks
def start_and_end(start_point=None, end_point=None):
# if user wants to change start_point or end_point or both
if start_point and end_point:
print("\n\nYour current path is\n\nFROM: {}\nTO: {}\n".format(
landmark_choices[start_point], landmark_choices[end_point]))
change_point_str = "What would you like to change?\n\nYou can enter 'o' for 'origin',\n'd' for 'destination'\n'b' for 'both', or\n'n' for neiter.\n-> "
valid_choices_list = ["o", "d", "b", "n"]
change_point = get_valid_input(change_point_str, valid_choices_list)
# control flow to change user's input
if change_point == "n":
return start_point, end_point
else:
if change_point == "o":
start_point = get_start()
elif change_point == "d":
end_point = get_end()
elif change_point == "b":
start_point = get_start()
end_point = get_end()
# making sure
return start_and_end(start_point, end_point)
# if neither
else:
# get start and end for the None input values
if (start_point == None) and (end_point == None):
start_point = get_start()
end_point = get_end()
elif (end_point == None):
print("I see you're starting from {}.".format(
landmark_choices[start_point]))
end_point = get_end()
else:
print("I see you're heading to {}.".format(
landmark_choices[end_point]))
start_point = get_start()
# making sure
return start_and_end(start_point, end_point)
###################################
# Gets starting Point from user
def get_start():
start_pointer_letter = input(
"\nWhere are you coming from?\nType in the corresponding letter: ").lower()
while start_pointer_letter not in landmark_choices.keys():
print("""
Sorry, that's not a landmark we have data on.
Let's try this again...""")
return get_start()
return start_pointer_letter
#########################
# gets desired destination point from user
def get_end():
end_pointer_letter = input(
"\nWhere are you heading to\nType in the corresponding letter: ").lower()
while end_pointer_letter not in landmark_choices.keys():
print("""
Sorry, that's not a landmark we have data on.
Let's try this again...""")
return get_end()
return end_pointer_letter
#########################################
# validate user input given the input and
# a list of valid inputs
def get_valid_input(input_str, valid_input_list):
user_input = input(input_str)
valid_choices_str = ""
for i in valid_input_list:
valid_choices_str += "'{}' ".format(i)
# validation while loop
while user_input.lower() not in valid_input_list:
user_input = input("\nPlease choose from the following letters:\n{}\n".format(
valid_choices_str)).lower()
return user_input
##########################################
# finding new Routes given a start and an end
def new_route(start_point=None, end_point=None):
if start_point == None or end_point == None:
# starting and endling landmark_choices dict values
start_point, end_point = start_and_end(start_point, end_point)
start_station, end_station = landmark_choices[start_point], landmark_choices[end_point]
# display shortest route
all_routes = get_route(start_station, end_station)
if all_routes == None:
print("Appoligies, this route is not possible due to construction. Please try again with a different starting and ending point.")
new_route()
shortest_route = min(all_routes, key=len)
if shortest_route:
shortest_route_str = "\n".join(shortest_route)
print("The shortest route from {0} to {1}:\n{2}\n".format(
start_station, end_station, shortest_route_str))
else:
print("Unfortunately, there is currently no path between {0} and {1} due to maintenance.".format(
start_point, end_point))
# ask if user would like a new route
again_input_str = "Would you like to see another route? Enter y/n: "
again = get_valid_input(again_input_str, ["y", "n"])
while again == "y":
num_routes_shown = 0
while num_routes_shown < len(all_routes) and again == "y":
curr_route = all_routes[num_routes_shown]
curr_route_str = "\n".join(curr_route)
print("Route #{0} from {1} to {2}:\n{3}\n".format(
num_routes_shown, start_station, end_station, curr_route_str))
num_routes_shown += 1
again = get_valid_input(again_input_str, ["y", "n"])
if again == "y":
exhaused_options_again_str = "All possible routes have been printed. Would you like to restart to list of possible routes? Enter y/n "
again = get_valid_input(exhaused_options_again_str, ["y", "n"])
if again == "y":
again = get_valid_input(again_input_str, ["y", "n"])
if again == "n":
return
return
#############################################
# gets the route user wishes to take
def get_route(start_point, end_point):
# define start and end locations
start_stations = vc_landmarks[start_point]
end_stations = vc_landmarks[end_point]
# initiate route list
all_routes = []
# updated metro system with stations under construction
metro_system = get_active_stations() if stations_under_construction else vc_metro
# check to see if stations_under construction
# make it immposible for travel from one
# location to anothe
for ss in start_stations:
for es in end_stations:
possible_route = dfs(metro_system, ss, es)
if possible_route:
if possible_route not in all_routes:
all_routes.append(possible_route)
if possible_route == None:
return None
# itterating through all posible start stations
# nearest landmarks
for start_station in start_stations:
for end_station in end_stations:
route = bfs(vc_metro, start_station, end_station)
if route not in all_routes:
all_routes.append(route)
return all_routes
#########################################
# show the landmarks corespoinding with the
# station
def show_landmarks():
see_landmarks_str = "Would you like to see the list of landmarks again? Enter y/n: "
see_landmarks = get_valid_input(see_landmarks_str, ["y", "n"])
if see_landmarks == "y":
print(landmark_string)
return
#######################################
# closing function
def goodbye():
print("\nThank you for using SkyRoute!\nCome Again!\n")
####################################
# get all stations and routes that are
# unaffected by station closures
def get_active_stations():
updated_metro = vc_metro
for closed_station in stations_under_construction:
for current_station, neighboring_stations in vc_metro.items():
if current_station != closed_station:
updated_metro[current_station] -= set(
stations_under_construction)
else:
updated_metro[current_station] = set()
return updated_metro
###################################
# wrapper function
def skyroute():
# start off with a greeting
greet()
new_route()
goodbye()
skyroute()
|
#get the total charge of food.
food= float(input('enter the total charge for food: '))
#get the percentage they want to tip of travel.
tip=.18
#get the sales tax %.
sales_tax=.07
#Get the total amount of bill with tip.
whole_bill = (food+ (food *18))*.07
#display total distance.
print('The total bill is $', format(whole_bill, ',.2f'))
|
'''
Creating a linked list using iteration
Previously, we created a linked list using a very manual
and tedious method. We called next multiple times on our head node.
Now that we know about iterating over or traversing the linked list,
is there a way we can use that to create a linked list?
We've provided our solution below—but it might be a good exercise
to see what you can come up with first. Here's the goal:
See if you can write the code for the create_linked_list function below
The function should take a Python list of values as input and return the
head of a linked list that has those values
There's some test code, and also a solution, below — give it a try for
yourself first, but don't hesitate to look over the solution if you get stuck
'''
class Node:
def __init__(self, value):
self.value = value
self.next = None
### Test Code
def test_function(input_list, head):
try:
if len(input_list) == 0:
if head is not None:
print("Fail")
return
for value in input_list:
if head.value != value:
print("Fail")
return
else:
head = head.next
print("Pass")
except Exception as e:
print("Fail: " + e)
def create_linked_list(input_list):
head = None
for value in input_list:
if head is None:
head = Node(value)
else:
current_node = head
while current_node.next:
current_node = current_node.next
current_node.next = Node(value)
return head
### Test Code
input_list = [1, 2, 3, 4, 5, 6]
head = create_linked_list(input_list)
test_function(input_list, head)
input_list = [1]
head = create_linked_list(input_list)
test_function(input_list, head)
input_list = []
head = create_linked_list(input_list)
test_function(input_list, head)
|
# Priority Queues - Intuition
'''
Consider the following scenario -
A doctor is working in an emergency wing at a hospital.
When patients come in, a nurse checks their symptoms and
based on the severity of the illness, sends them to the
doctor. For e.g. a guy who has had an accident is sent
before someone who has come with a runny nose.
But there is a slight problem.
There is only one nurse and only one doctor.
In the amount of time the nurse takes to check the
symptoms, the doctor has to work alone with the patients,
hurting their overall productivity.
The doctor comes to you for help.
Your job is to write a small software in which patients will
enter their symptoms and will receive a priority number based
on their illness. The doctor has given you a list of common
ailments, and the priority in which he would prefer seeing
them. How would you solve the priority problem?
'''
# Priority Queues:
'''
Like the name suggests, a priority queue is similar to a
regular queue, except that each element in the queue has a
priority associated with it. A regular queue is a FIFO data
structure, meaning that the first element to be added to the
queue is also the first to be removed.
With a priority queue, this order of removal is instead based
on the priority. Depending on how we choose to set up the
priority queue, we either remove the element with the most
priority, or an element of the least priority.
For the sake of discussion, let's focus on removing the element
of least priority for now.
'''
# Functionality:
'''
If we were to create a PriorityQueue class,
what methods would it need to have?
Here are the two key methods:
insert - insert an element
remove - remove an element
And we can also add the same utility methods that we
had in our regular Queue class:
front - returns the element at the front of the queue
size - returns the number of elements present in the queue
is_empty - returns True if there are no elements in the queue,
and False otherwise.
As part of this functionality, we will need a way of assigning
priorities to the items.
A very common way to solve the patient-doctor problem mentioned
above would be to assign each ailment a priority. For e.g.
* A running nose may be assigned priority 1
* Fever may be assigned 2
* Accident may get a priority 10
You will find this theme recurring in all of programming.
We use numbers to effectively represent data.
For the sake of simplicity, let's only consider integers here.
Let us assume a scenario where we get integers as input and we
assign a priority on how large or small they are.
Let us say the smaller the number, the smaller its priority.
So, in our simplified version of the problem statement the
value of the integer serves as a priority.
Our goal is to create a queue where the element with the lowest
priority is removed first. Therefore, the remove method will
remove the smallest number from the priority queue. Thus, the
largest number will be the last to be removed from the priority
queue and the smallest number will be the first to be removed.
'''
# How Should We Implement It?
'''
What we've described above is just the abstract characteristics
that we expect from this data structure. As with stacks and
queues (and other abstract data types), there is more than one
way that we could implement our priority queue such that it
would exhibit the above behaviors.
However, not all implementations are ideal. When we implemented
a regular queue earlier, you may remember the enqueue and dequeue
methods had a time complexity of 𝑂(1) . Similarly, we would like
the insert and remove methods on our priority queue to be fast.
So, what underlying structure should we use to implement the
priority queue such that it will be as efficient as possible?
Let's look at some different structures and consider the pros and cons.
'''
# Arrays
'''
Earlier, we saw that one way to implement a queue was by using an array.
We could do a similar thing for priority queues.
We could use the array to store our data.
Insertion in an array is very fast.
Unless the array is full, we can do it in O(1) time.
*Note: When the array is full, we will simply create a new array
and copy all the elements from our old array to new array.
It's exactly similar to what we do for our queue's
implementation using arrays.
What about removal? We always want to remove the smallest or highest
priority data from the array, depending on if this is a max-heap or min-heap.
In the worst case, we will have to search the entire array,
which will take O(n) time. Thus, to remove the element,
the time complexity would be O(n).
This also creates an additional problem for us.
The index from which we removed the element is now empty.
We cannot leave empty indices in our array.
Over the course of operations, we will be wasting a lot of
space if we did that.
Therefore, insertion no longer happens in O(1) time.
Rather, every time we insert, we will have to look for these empty
indices and put our new element in the first empty index we find.
In the worst case, this also takes O(n) time.
Therefore, our time complexity with arrays
(for both insertion and removal) would be O(n).
'''
#LinkedList
'''
Insertion is very easy in a linked list. If we maintain a variable
to keep track of the tail of the linked list, then we can simply add
a new node at this location. Thus, insertion takes O(1) time.
For removal, we will have to traverse the entire list and find the
smallest element, which will require O(n) time.
Note that with linked lists, unlike arrays, we do not have to worry
about empty indices.
A linked linked certainly seems to be a better option than an array.
Although they have the same time complexity for removal,
the time complexity for insertion is better.
'''
# HashMap
'''
The same problem lies in HashMap as well. We can insert in O(1) time.
Although, we can remove an element from a HashMap in O(1) time, but we
have to first search for the smallest element in the map.
This will again take O(n) time.
Therefore, the time complexity of remove is O(n) for hashmaps.
'''
#Binary Search Trees
'''
Binary Search Trees are laid out according to the value of the node
that we want to insert. All elements greater than the root go to the
right of the root, and all elements smaller than the root go to the
left of the root.
If we assume that our Binary Search tree is balanced, insertion
would require O(h) time in the worst case. Similarly, removal would
also require O(h) time. Here h is the height of the binary search tree.
4
2 7
1 3 5 8
A Binary Tree is called a Balanced Binary Tree when the difference
between the heights of it's left subtree and right subtree do not
differ by more than one. Additionally, to be balanced, all the
subtrees of the binary tree must also be balanced.
For a balanced tree, we can safely approximate the height of the
tree h to log(n). Thus, both insertion and removal
require O(log(n)) time in a binary search tree.
However, in the worst case, our binary search tree might just be
a sequential list of nodes (stretching to the right or to the left).
Consider the following tree:
1
2
3
4
In such a scenario the binary search tree effectively turns into a
linked list. In this case, the time complexity would be O(n).
To avoid this situation, we would need a self-balancing tree which
would incure additional complexity.
We could use any of the above data structures to implement our
priority queue — and they would work, in the sense that they would
exhibit the outward behavior we expect in a priority queue.
However, none of them acheived our goal of having 𝑂(1) time
complexity for both insert and remove.
To do that, we will need to explore something new: A heap.
'''
# Heaps
'''
A heap is a data structure with the following two main properties:
1. Complete Binary Tree
2. Heap Order Property
1. Complete Binary Tree - Like the name suggests we use a binary
tree to create heaps. A complete binary tree is a special type
of binary tree in which all levels must be filled except for
the last level. Moreover, in the last level, the elements
must be filled from left to right.
Example A:
10
25 15
6 9
A. is a complete binary tree. Notice how every level except the
last level is filled.
Also notice how the last level is filled from left to right
Example B:
10
25 15
6 9
B. is not a complete binary tree. Although evey level is filled
except for the last level. Notice how the last level is not
filled from left to right. 25 does not have any right node and
yet there is one more node (9) in the same level towards the
right of it. It is mandatory for a complete binary tree to be
filled from left to right.
Example C:
10
25
6 9
C. is also not a binary tree. Notice how the second level is
not completely filled and yet we have elements in the third level.
The right node of `10` is empty and yet we have nodes in the next level.
- Heap Order Property - Heaps come in two flavors
- Min Heap
- Max Heap
Min Heap - In the case of min heaps, for each node, the parent
node must be smaller than both the child nodes. It's okay even
if one or both of the child nodes do not exists.
However if they do exist, the value of the parent node must be smaller.
Also note that it does not matter if the left node is greater than the
right node or vice versa. The only important condition is that the root
node must be smaller than both it's child nodes.
Max Heap - For max heaps, this condition is exactly reversed.
For each node, the value of the parent node must be larger than
both the child nodes.
Thus, for a data structure to be called a Heap, it must satisfy
both of the above properties.
1. It must be a complete binary tree
2. It must satisfy the heap order property.
If it's a min heap, it must satisfy the heap order
property for min heaps.
If it's a max heap, it should satisfy the heap order
property for max heaps.
'''
# Complete Binary Tree
'''
Let's go back to our complete binary tree A.
* n = next node can only go here.
10
25 15
6 9 (n)
If we have to insert one more node, where should the next node go?
Because A. is a complete binary tree, the next node can only go as
the left node of 15 aka (n).
Similarly, let's look back A. again. If we have to delete a node
from A., which node should we delete? Again, to ensure that our
tree remains a complete binary tree even after deleting a node,
we can only remove 9.
Thus, we know which node to remove and where to insert a new node.
Notice that both of these operations do not depend upon values of
other nodes. Rather, both insert and remove operations on a
complete binary tree depend upon the position of the last
inserted node.
This cell may require some visualization due to
the mathematics involved
Now that we know about a complete binary, let's think about it in
terms of Priority Queues. We talked about binary search trees where
the complexity for insert and remove operation would be O(log(n))
if the BST (binary search tree) is balanced.
In case of a complete binary tree, we do not have to worry about
whether the tree is balanced or not.
Max number of nodes in 1st level = 1
Max number of nodes in 2nd level = 2
Max number of nodes in 3rd level = 4
Max number of nodes in 4th level = 8
We see that there is a clear patter here.
Max number of nodes in hth level = 2^(ℎ−1)
Also, we can calculate the max number of nodes from 1st level
to hth level = (2^ℎ)-1
Similarly, we can calculate the min number of nodes from
1st level to hth level = 2^(ℎ−1)
*** Note: the minimum number of nodes from 1st level
to hth level = max number of nodes from 1st level
to (h-1)th level + 1
Thus, in a complete binary tree of height h, we can be assured
that the number of elements n would be between these
two numbers i.e.
Thus, in a complete binary tree of height h, we can be assured
that the number of elements n would be between these two numbers i.e.
2^(ℎ−1) <= 𝑛 <= (2^ℎ)−1
If we write the first inequality in base-2 logarithmic
format we would have the following:
log[base2](2^(ℎ−1)) <= log[base2]n
or
h <= log[base2] n+1
Similarly, if we write the second equality in base-2
logarithmic format:
log[base2](𝑛+1) <= log[base2]2^ℎ
or
log[base2](𝑛+1) <= ℎ
Thus the value of our height h is always:
log[base2](𝑛+1) <= ℎ <= log[base2]n + 1
We can see that the height of our complete binary tree will always
be in the order of O(h) or O(log(n))
So, if instead of using a binary search tree, we use a complete
binary tree, both insert and remove operation will have the
time complexity of log[base2]n
'''
# Heaps for Priority Queues
'''
Let's take a step back and reflect on what we have done.
1. We have examined popular data structures and observed
their time complexities.
2. We have looked at a new data structure called Heap
3. We know that Heaps have two properties -
i. CBT (Complete Binary Tree)
ii. Heap Order Property
4. We have looked at what CBT is and what Heap Order Property is
By now, it must have been clear to you that we are going to use
Heaps to create our Priority Queues. But are you convinced that
heaps are a good structure to create Priority Queues?
Answer:
1. Other than Binary Search trees, all other popular data
structures seemed to have a time complexity of O(n) for
both insertion and removal.
2. Binary Search Trees seemed like an effective data structure
with average case time complexity of O(log(n) (or O(h)) for
both the operations.
However, in the worst case, a Binary Search Tree may not be
balanced and instead behave like a linked list. In such a case,
the time complexity in terms of height would still be O(h) but
because the height of the binary search tree will be equal to
the number of elements in the tree, the actual time complexity
in terms of number of elements n would be O(n).
3. The CBT property of Heaps ensures that the tree is always balanced.
Therefore, the height h of the tree will always be equal to log(n).
4. The Heap Order Property ensures that there is some definite
structure to our Complete Binary Tree with respect to the value of
the elements. In case of a min-heap, the minimum element will
always lie at the root node. Similarly, in case of a max-heap,
the maximum element will always lie at the root node.
In both the cases, every time we insert or remove an element,
the time complexity remains O(log(n)).
Therefore, because of the time complexity being O(log(n)), we
prefer heaps over other popular data structures to create our
Priority Queues.
'''
|
'''
Breadth First Search:
Visits the tree one level at a time.
BFS in graph structure (shortest path).
Traverse a Tree (breadth first search):
You'll see breadth first search again when we learn about
graph data structures, so BFS is very useful to know.
'''
class Node(object):
def __init__(self, value=None):
self.value = value
self.left = None
self.right = None
def set_value(self, value):
self.value = value
def get_value(self):
return self.value
def set_left_child(self, left):
self.left = left
def set_right_child(self, right):
self.right = right
def get_left_child(self):
return self.left
def get_right_child(self):
return self.right
def has_left_child(self):
return self.left is not None
def has_right_child():
return self.right is not None
def __repr__(self):
return f"Node({self.get_value()})"
def __str__(self):
return f"Node({self.get_value()})"
class Tree():
def __init__(self, value=None):
self.root = Node(value)
def get_root(self):
return self.root
tree = Tree("apple")
tree.get_root().set_left_child(Node("banana"))
tree.get_root().set_right_child(Node("cherry"))
tree.get_root().get_left_child().set_left_child(Node("dates"))
'''
Tree Structure
apple
banana cherry
dates
Breadth First Search:
Breadth first traversal of the tree would visit
the nodes in this order:
# <<< ['apple', 'banana', 'cherry', 'dates']
Think Through the Algorithm:
We are walking down the tree one level at a time. So we start with
apple at the root, and next are banana and cherry, and next
is dates.
1) start at the root node
2) visit the root node's left child (banana), then right child
(cherry)
3) visit the left and right children of (banana) and (cherry).
'''
'''
Queue:
Notice that we're waiting until we visit "cherry" before visiting "dates".
It's like they're waiting in line. We can use a queue to keep track
of the order.
'''
from collections import deque
class Queue():
def __init__(self):
self.q = deque()
def enq(self,value):
self.q.appendleft(value)
def deq(self):
if len(self.q) > 0:
return self.q.pop()
else:
return None
def __len__(self):
return len(self.q)
def __repr__(self):
if len(self.q) > 0:
s = "<enqueue here>\n_________________\n"
s += "\n_________________\n".join([str(item) for item in self.q])
s += "\n_________________\n<dequeue here>"
return s
else:
return "<queue is empty>"
q = Queue()
q.enq("apple")
q.enq("banana")
q.enq("cherry")
print(q)
print(q.deq())
print(q)
'''
def breadth_first_search(node):
visit_order = list()
root = tree.get_root()
def traverse(node):
if node:
# visit root and append it to list
visit_order.append(node)
visit_order.append(node(get_right_child()))
# visit_order.append(node.get_value())
traverse(root)
return visit_order
print(breadth_first_search(tree))
'''
# dequeue the next node in the queue.
# "visit" that node
# also add its children to the queue
node = q.deq()
visit_order.append(node)
if node.has_left_child():
q.enq(node.get_left_child())
if node.has_right_child():
q.enq(node.get_right_child())
print(f"visit order: {visit_order}")
print(q)
|
'''
Problem Statement
Previously, we considered the following problem:
Given a positive integer n, write a function,
print_integers, that uses recursion to print all
numbers from n to 1.
For example, if n is 4, the function should
print 4 3 2 1.
Our solution was:
'''
def print_integers(n):
# Base Case.
if n <= 0:
return
print(n)
print_integers(n - 1)
print_integers(5)
# <<< 5
# <<< 4
# <<< 3
# <<< 2
# <<< 1
'''
Note that in Python, the stack is displayed in an "upside down" manner.
This can be seen in the illustration above—the last frame
(i.e. the frame with n = 0) lies at the top of the stack
(but is displayed last here) and the first frame (i.e., the frame with n = 5)
lies at the bottom of the stack (but is displayed first).
But don't let this confuse you. The frame with n = 0 is indeed the top
of the stack, so it will be discarded first. And the frame with n = 5
is indeed at the bottom of the stack, so it will be discarded last.
We define time complexity as a measure of amount of time it takes to run
an algorithm. Similarly, the time complexity of our function print_integers(5),
would indicate the amount of time taken to exceute our function print_integers.
But notice how when we call print_integers() with a particular value of n,
it recursively calls itself multiple times.
In other words, when we call print_integers(n), it does operations
(like checking for base case, printing number) and
then calls print_integers(n - 1).
Therefore, the overall time taken by print_integers(n) to execute would be equal
to the time taken to execute its own simple operations and the time taken to
execute print_integers(n - 1).
Let the time taken to execute the function print_integers(n) be 𝑇(𝑛) .
And let the time taken to exceute the function's own simple operations be
represented by some constant, 𝑘 .
In that case, we can say that
𝑇(𝑛)=𝑇(𝑛−1)+𝑘
where 𝑇(𝑛−1) represents the time taken to execute the function
print_integers(n - 1).
Similarly, we can represent 𝑇(𝑛−1) as
𝑇(𝑛−1)=𝑇(𝑛−2)+𝑘
We can see that a pattern is being formed here:
𝑇(𝑛)=𝑇(𝑛−1)+𝑘
𝑇(𝑛−1)=𝑇(𝑛−2)+𝑘
𝑇(𝑛−2)=𝑇(𝑛−3)+𝑘
𝑇(𝑛−3)=𝑇(𝑛−4)+𝑘 .
.
.
.
.
.
𝑇(2)=𝑇(1)+𝑘
𝑇(1)=𝑇(0)+𝑘
𝑇(0)=𝑘1
Notice that when n = 0 we are only checking the base case and then
returning. This time can be represented by some other constant, 𝑘1 .
If we add the respective left-hand sides and right-hand sides of all
hese equations, we get:
𝑇(𝑛)=𝑛𝑘+𝑘1
We know that while calculating time complexity, we tend to ignore
these added constants because for large input sizes on the order of
105 , these constants become irrelevant.
Thus, we can simplify the above to:
𝑇(𝑛)=𝑛𝑘
We can see that the time complexity of our function print_integers(n)
is a linear function of 𝑛 . Hence, we can say that the time complexity
of the function is 𝑂(𝑛) .
'''
|
'''
Reversing a String:
The goal in this notebook will be to get practice with a problem that is
frequently solved by recursion: Reversing a string.
Note that Python has a built-in function that you could use for this,
but the goal here is to avoid that and understand how it can be done
using recursion instead.
'''
# Code
def reverse_string(input):
"""
Return reversed input string
Examples:
reverse_string("abc") returns "cba"
Args:
input(str): string to be reversed
Returns:
a string that is the reverse of input
"""
# TODO: Write your recursive string reverser solution here
if len(input) == 0:
return ""
else:
first_char = input[0]
the_rest = slice(1, None)
sub_string = input[the_rest]
reversed_substring = reverse_string(sub_string)
return reversed_substring + first_char
# Test Cases
print ("Pass" if ("" == reverse_string("")) else "Fail")
print ("Pass" if ("cba" == reverse_string("abc")) else "Fail")
|
# Binary Search First and Last Indexes
'''
Problem statement
Given a sorted array that may have duplicate values,
use binary search to find the first and last indexes
of a given value.
For example, if you have the array
[0, 1, 2, 2, 3, 3, 3, 4, 5, 6] and the given value is 3,
the answer will be [4, 6] (because the value 3 occurs
first at index 4 and last at index 6 in the array).
The expected complexity of the problem is 𝑂(𝑙𝑜𝑔(𝑛)) .
'''
def first_and_last_index(arr, number):
"""
Given a sorted array that may have duplicate values,
use binary search to find the first and last indexes
of a given value.
Args:
arr(list): Sorted array (or Python list) that may
have duplicate values number(int): Value to search
for in the array
Returns:
a list containing the first and last indexes of
the given value
"""
# TODO: Write your first_and_last function here
# Note that you may want to write helper functions to
# find the start index and the end index.
# Search first occurence
first_index = find_start_index(arr, number, 0, len(arr) - 1)
# Search last occurence
last_index = find_end_index(arr, number, 0, len(arr) - 1)
return [first_index, last_index]
def find_start_index(arr, number, start_index, end_index):
# Binary search solution to search for the first
# index of the array.
if start_index > end_index:
return -1
mid_index = start_index + (end_index - start_index) // 2
if arr[mid_index] == number:
current_start_pos = find_start_index(arr, number, start_index, mid_index - 1)
if current_start_pos != -1:
start_pos = current_start_pos
else:
start_pos = mid_index
return start_pos
elif arr[mid_index] < number:
return find_start_index(arr, number, mid_index + 1, end_index)
else:
return find_start_index(arr, number, start_index, mid_index - 1)
def find_end_index(arr, number, start_index, end_index):
# Binary search solution to search fo rthe last index of
# the array.
if start_index > end_index:
return -1
# Integer division in Python3
mid_index = start_index + (end_index - start_index) // 2
if arr[mid_index] == number:
current_end_pos = find_end_index(arr, number, mid_index + 1, end_index)
if current_end_pos != -1:
end_pos = current_end_pos
else:
end_pos = mid_index
return end_pos
elif arr[mid_index] < number:
return find_end_index(arr, number, mid_index + 1, end_index)
else:
return find_end_index(arr, number, start_index, mid_index - 1)
def test_function(test_case):
input_list = test_case[0]
number = test_case[1]
solution = test_case[2]
output = first_and_last_index(input_list, number)
if output == solution:
print("Pass")
else:
print("Fail")
input_list = [1]
number = 1
solution = [0, 0]
test_case_1 = [input_list, number, solution]
test_function(test_case_1)
input_list = [0, 1, 2, 3, 3, 3, 3, 4, 5, 6]
number = 3
solution = [3, 6]
test_case_2 = [input_list, number, solution]
test_function(test_case_2)
input_list = [0, 1, 2, 3, 4, 5]
number = 5
solution = [5, 5]
test_case_3 = [input_list, number, solution]
test_function(test_case_3)
input_list = [0, 1, 2, 3, 4, 5]
number = 6
solution = [-1, -1]
test_case_4 = [input_list, number, solution]
test_function(test_case_4)
|
'''
Reversing a linked list exercise:
Given a singly linked list, return another linked
list that is the reverse of the first.
'''
#Begin helper code
class Node:
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self, value):
if self.head is None:
self.head = Node(value)
return
node = self.head
while node.next:
node = node.next
node.next = Node(value)
def __iter__(self):
node = self.head
while node:
yield node.value
node = node.next
def __repr__(self):
return str([v for v in self])
#End helper code.
#Efficiency O(n)
def reverse(linked_list):
new_list = LinkedList()
node = linked_list.head
prev_node = None
#Take node from original linked list and prepend
#to the new linked list.
for value in linked_list:
new_node = Node(value)
new_node.next = prev_node
prev_node = new_node
new_list.head = prev_node
return new_list
#Reversing a linked list test.
llist = LinkedList()
for value in [4,2,5,1,-3,0]:
llist.append(value)
flipped = reverse(llist)
is_correct = list(flipped) == list([0,-3,1,5,2,4]) and list(llist) == list(reverse(flipped))
print("Pass" if is_correct else "Fail")
|
# Build a Red-Black Tree
'''
In this notebook, we'll walk through how you might build a
red-black tree. Remember, we need to follow the red-black
tree rules, on top of the binary search tree rules.
Our new rules are:
- All nodes have a color
- All nodes have two children (use NULL nodes)
- All NULL nodes are colored black
- If a node is red, its children must be black
- The root node must be black (optional)
- We'll go ahead and implement without this for now
- Every path to its descendant NULL nodes must contain
the same number of black nodes.
'''
# Sketch
'''
Similar to our binary search tree implementation, we will
define a class for nodes and a class for the tree itself.
The Node class will need a couple new attributes. It is no
longer enough to only know the children, because we need to
ask questions during insertion like, "what color is
my parent's sibling?". So we will add a parent link as
well as the color.
'''
class Node(object):
def __init__(self, value, parent, color):
self.value = value
self.left = None
self.right = None
self.parent = parent
self.color = color
'''
For the tree, we can start with a mostly empty implementation.
However, we know we want to always insert nodes with the color
red, so let's fill in the constructor to insert the root node.
'''
class RedBlackTree(object):
def __init__(self, root):
self.root = Node(root, None, 'red')
def insert(self, new_val):
pass
def search(self, find_val):
return False
# Insertion
'''
Now how would we design our insert implementation?
We know from our experience with BSTs how most of it will work.
We can re-use that portion and augment it to assign colors
and parents.
'''
class RedBlackTree(object):
def __init__(self, root):
self.root = Node(root, None, 'red')
def insert(self, new_val):
self.insert_helper(self.root, new_val)
def insert_helper(self, current, new_val):
if current.value < new_val:
if current.right:
self.insert_helper(current.right, current, new_val)
else:
current.right = Node(new_val, current, 'red')
else:
if current.left:
self.insert_helper(current.left, current, new_val)
else:
current.left = Node(new_val, current, 'red')
# Rotations
'''
At this point, we are only making a BST, with extra attributes.
To make this a red-black tree, we need to add the extra sauce
that makes red-black trees awesome. We will sketch out some
more code for rebalancing the tree based on the case, and
fill them in one at a time.
First, we need to change our insert_helper to return the node
that was inserted so we can interrogate it when rebalancing.
'''
class RedBlackTree(object):
def __init__(self, root):
self.root = Node(root, None, 'red')
def insert(self, new_val):
self.insert_helper(self.root, new_val)
def insert_helper(self, current, new_val):
if current.value < new_value:
if current.right:
return self.insert_helper(current.right, new_val)
else:
current.right = Node(new_val, current, 'red')
return current.right
else:
if current.left:
return self.insert_helper(current.left, new_val)
else:
current.left = Node(new_val, current, 'red')
return current.left
def rebalance(self, node):
pass
# Case 1
'''
We have just inserted the root node.
If we're enforcing that the root node must be black, we can
change its color. We are not enforcing this, so we are all
done. Four to go.
'''
def rebalance(node):
if node.parent == None:
return
# Case 2
'''
We inserted under a black parent node.
This this through, we can observe the following: we inserted
a red node beneath a black node. The new children (the Null
nodes) are black by definition, and our red node replaced a
black-Null-node. So the number of black nodes for any paths
from parents is unchanged. Nothing to do in this case, either.
'''
def rebalance(node):
if node.parent == None:
return
if node.parent.color == 'black':
return
# Case 3
'''
The parent and its sibling of the newly inserted node are both
red.
Okay, we're done with free cases. In this specific case, we
can flip the color of the parent and its sibling. We know
they're both red in this case, which means the grandparent is
black. It will also need to flip. At this point we will have a
freshly painted red node at the grandparent. At that point, we
need to do the same evaluation. If the grandparent turns red,
and its sibling is also red, that's case #3 again. Guess what
that means? Time for more recursion.
We will define grandparent and pibling (a parent's sibling)
methods later, for now let's focus on the core logic.
'''
def rebalance(node):
if node.parent == None:
return
if node.parent.color == 'black':
return
# From here, we know the parent's color is red.
# Case 3
if pibling(node).color == 'red':
pibling(node).color = 'black'
node.parent.color = 'black'
grandparent(node).color = 'red'
self.rebalance(grandparent(node))
# Case #4
'''
The newly inserted node has a red parent, but that parent has
a black sibling.
These last cases get more interesting. The criteria above
actually govern cases 4 and 5. What seperates them is if the
newly inserted node is on the inside or the outside of the sub
tree. We define inside and outside like this:
inside
EITHER
- the new node is a left child of its parent, but
its parent is a right child, or
- the new node is a right child of its parent, but
its parent is a left child.
outside
- the opposite of inside, the new node and its parent
are on the same side of the grandparent.
Case 4 is to handle the inside scenario. In this case, we need
to rotate. As we will see, this will not finish balancing
the tree, but will now qualify for Case 5.
We rotate against the inside-ness of the new node. If the new
node qualifies for case 4, it needs to move into its parent's
spot.If it's on the right of the parent, that's a rotate
left. If it's on the left of the parent, that's a rotate right.
'''
def rebalance(self, node):
# Cases 1-3 are omitted for this example.
# Case #4
gp = grandparent(node)
if gp.left and node == gp.left.right:
self.rotate_left(parent(node))
elif gp.right and node == gp.right.left:
self.rotate_right(parent(node))
# TODO: Case 5
'''
To implement rotate_left and rotate_right, think about what we
want to accomplish. We want to take one of the node's children
and have it take the place of its parent. The given node
will move down to a child of the newly parental node.
'''
def rotate_left(self, node):
# Save-off the parent of the sub-tree we're rotating.
p = node.parent
node_moving_up = node.right
# After 'node' moves up, the right child will now be
# a left child.
node.right = node_moving_up.left
# 'node' moves down, to being a left child.
node_moving_up.left = node
node.parent = node_moving_up
# Now we need to connect to the sub-tree's parent
# 'node' may have been the root.
if p != None:
if node == p.left:
p.left = node_moving_up
else:
p.right = node_moving_up
node_moving_up.parent = p
def rotate_right(self, node):
# Save off the parent of the sub-tree we're rotating.
p = node.parent
node_moving_up = node.left
# After 'node' moves up, the left child will now be a
# right child
node.left = node_moving_up.right
# 'node' moves down, to be a right child.
node_moving_up.right = node
node.parent = node_moving_up
# Now we need to connect the sub-tree's parent
# 'node' may have been the root.
if p != None:
if node == p.left:
p.left = node_moving_up
else:
p.right = node_moving_up
node_moving_up.parent = p
# Case 5
'''
Now that case 4 is resolved, or if we didn't qualify for case
4, and have an outside sub-tree already, we need to rotate
again. If our new node is a left child of a left child, we
rotate right. If our new node is a right of a right child, we
rotate left. This is done on the grandparent node.
But after this rotation, our colors will be off. Remember that
for cases 3, 4, and 5, the parent of the new node is red. But
we will have rotated a red node with a red child up, which
violates our rule of all red nodes having two black children.
So after rotating, we switch the colors of the (original)
parent and grandparent nodes.
'''
def rebalance(self, node):
# cases 1-3 omitted.
# Case 4
gp = grandparent(node)
if node == gp.left.right:
self.rotate_left(node.parent)
elif node == gp.right.left:
self.rotate_right(node.parent)
# Case 5
p = node.parent
gp = p.parent
if node == p.left:
self.rotate_right(gp)
else:
self.rotate_left(gp)
p.color = 'black'
gp.color 'red'
# Results of combining all our efforts for the following:
|
# Complete Binary Trees Using Arrays
'''
Although we call them complete binary trees,
and we will always visualize them as binary trees,
we never use binary trees to create them. Instead,
we actually use arrays to create our complete
binary trees.
Let's see how.
[0][1][2][3][4][5][6][7][8]
An array is a contiguous blocks of memory with
individual "blocks" are laid out one after the
other in memory. We are used to visualizing
arrays as sequential blocks of memory.
However, if we visualize them in the following way,
can we find some similarities between arrays and
complete binary trees?
[0]
[1] [2]
[3][4] [5][6]
[7][8]
Let's think about it.
In a complete binary tree, it is mandatory for all levels before
the last level to be completely filled. If we visualize our array
in this manner, do we satisfy this property of a CBT? All we have
to ensure is that we put elements in array indices sequenially
i.e. the smaller index first and the larger index next. If we do
that, we can be assured that all levels before the last level will
be completely filled.
In a CBT, if the last level is not completely filled, the nodes
must be filled from left to right.
Again, if we put elements in the array indices sequentially,
from smaller index to larger index, we can be assured that if
the last level is not filled, it will certainly be filled from
left to right.
Thus we can use an array to create our Completer Binary Tree.
Although it's an array, we will always visualize it as complete
binary tree when talking about heaps.
Now let's talk about insert and remove operation in a heap.
We will create our heap class which with these two operations.
We also add a few utility methods for our convenience.
Finally, because we know we are going to use arrays to create
our heaps, we will also initialize an array.
Note that we are creating min heaps for now.
The max heap will follow the exact some process.
The only difference arises in the Heap Order Property.
As always we will use Python lists like C-style arrays to make
the implementation as language agnostic as possible.
'''
class Heap:
def __init__(self, initial_size):
# Initialize arrays
self.cbt = [None for _ in range(initial_size)]
# Denotes next index where new elements should go
self.next_index = 0
def insert(self, data):
pass
def remove(self):
pass
# Insert
'''
Insertion operation in a CBT is quite simple. Because we are
using arrays to implement a CBT, we will always insert at the
next_index. Also, after inserting, we will increment the
value of next_index.
However, this isn't enough. We also have to maintain the heap
order property. We know that for min-heaps, the parent node
is supposed to be smaller than both the child nodes.
n = next element should go here
10
20 40
50 30 70 60
75 n
Counting indices, we know that our next element should go at
index 8. Let's say we want to insert 15 as our next element
in the heap. In that case, we start off by inserting 15 at
index 8.
10
20 40
50 30 70 60
75 15
Remember, although we are using arrays to implement a CBT,
we will always visualize it as a binary tree. We will only
consider them as arrays while implementing them.
So, we went ahead and insert 15 at index 8. But this violates
our heap order property. We are considering min-heap and the
parent node of 15 is larger.
In such a case, we heapify. We consider the parent node of
the node we inserted and compare their values. In case of
min-heaps, if the parent node is larger than the child node
(the one we just inserted), we swap the nodes.
Now the complete binary tree looks something like
10
20 40
15 30 70 60
75 50
Is the problem solved?
Swapping the nodes for 15 and 50 certainly solved our problem.
But it also introduced a new problem. Notice 15 and 20. We are
again in the same spot. The parent node is larger than the child
node. And in a min-heap we cannot allow that. So, what do we do?
We heapify. We swap these two nodes just as we swapped our
previous two nodes.
After swapping, our CBT looks like
10
15 40
20 30 70 60
75 50
Does everything seem fine now?
We only have to consider the nodes that we swapped.
And looks like we are fine.
Now let's take a step back and see what we did.
- We first inserted our element at the possible index.
- Then we compared this element with the parent element
and swapped them after finding that our child node was
smaller than our parent node. And we did this process
again. While writing code, we will continue this process
until we find a parent which is smaller than the child node.
Because we are traversing the tree upwards while heapifying,
this particular process is more accurately called up-heapify.
Thus our insert method is actually done in two steps:
- insert
- up-heapify
'''
# Time Complexity
'''
Before talking about the implementation of insert,
let's talk about the time complexity of the insert method.
Putting an element at a particular index in an array takes O(1) time.
However, in case of heapify, in the worst case we may have to travel
from the node that we inserted right to the root node
(placed at 0th index in the array). This would take O(h) time.
In other words, this would be an O(log(n)) operation.
Thus the time complexity of insert would be O(log(n)).
'''
# Insert - implementation
'''
Although we are using arrays for our CBT (complete binary tree),
we are visualizing it as a binary tree for understanding the idea.
But when it comes to the implementation, we will have to think
about it as an array. It is an array, after all.
[0]
[1][2]
[3][4][5][6]
[7][8]
In the above image, we can safely assume that:
- index 0 is the root node of the binary tree
- index 0 is the parent node for indices 1 and 2
i.e. 1 is the left node of index 0, and 2 is the right node
- Similarly, 3 and 4 are the child nodes of index 1.
- And 5 and 6 are the child nodes of index 2
Can we deduce any pattern from this?
- If you notice carefully, the child nodes
of 0 are ---> 1 and 2
- The child nodes of 1 are ---> 3 and 4
- The child nodes of 2 are ---> 5 and 6
The child nodes of p are ---> 2*(p+1) and 2*(p+2)
i.e. the child nodes of a parent index p are placed at
indices 2*(p+1) and 2*(p+2)
Similarly, can you deduce parent indices from a child index c?
Answer: for a child node at index c, the parent node will
be located at (p-1)//2
*** Note the integer division
Using these ideas, implement the insert method.
'''
class Heap:
def __init__(self, initial_size):
# Initialize array
self.cbt = [None for _ in range(initial_size)]
# Denoting next index placing new element
self.next_index = 0
# Up-heapify before insertion.
def _up_heapify(self):
# Setting child_index to next_index
child_index = self.next_index
while child_index >= 1:
# Deducing parent indices from child index
# logic from above notes.
parent_index = (child_index-1) // 2
# Setting parent and child elements to the
# index of the complete binary tree
parent_element = self.cbt[parent_index]
child_element = self.cbt[child_index]
if parent_element > child_element:
self.cbt[parent_index] = child_element
self.cbt[child_index] = parent_element
child_index = parent_index
else:
break
def insert(self, data):
# Inserting element into the next index.
self.cbt[self.next_index] = data
# Heapify function self call.
self._up_heapify()
# Increase index by 1
self.next_index += 1
# Double the array and copy elements if next_index
# goes out of array bounds.
if self.next_index >= len(self.cbt):
# Setting up temporary CBT
temp = self.cbt
self.cbt = [None for _ in range(2*len(self.cbt))]
for index in range(self.next_index):
self.cbt[index] = temp[index]
# Remove
'''
For min-heaps, we remove the smallest element from our heaps.
For max-heaps, we remove the largest element from the heap.
By now, you must have realized that in case of min-heaps,
the minimum element is stored at the root node of the
complete binary tree. Again, we are emphasizing the fact
that we will always visualize a complete binary tree as
a binary tree and not an array.
10
20 40
15 30 70 60
75 50
Consider this CBT. Our remove operation should remove 10 from
the tree. But if we remove 10, we need to put the next smaller
element at the root node. But that will again leave one node
empty. So, we will again have to go to our next smaller
element and place it at the node that is empty. This sounds
tedious.
Rather, we use a very simple yet efficient trick to remove
the element. We swap the first node of the tree (which is
the minimum element for a min-heap) with the last node of
the tree.
If we think about the implementation of our complete binary
tree, we know that 10 will now be present at the last index
of the array. So, removing 10 is a O(1) operation.
However, you might have noticed that our complete binary tree
does not follow the heap order property which means that it's
no longer a heap. So, just like last time, we heapify.
This time however, we start at the top and heapify in downward
direction. Therefore, this is also called as down-heapify.
We look at 50 which is present at the root node, and compare
it with both it's children. We take the minimum of the three
nodes i.e. 50, 15, and 40, and place this minimum at the root
node. At the same time, we place 50 at the node which we
placed at the root node.
Following this operation, our CBT looks like:
15
50 40
20 30 70 60
75
Even now the CBT does not follow the heap order property.
So, we again compare 50 with it's child nodes and swap 50
with the minimum of the three nodes.
15
20 40
50 30 70 60
75
At this point we stop because our CBT follows the heap
order property.
'''
class Heap(object):
def __init__(self, initial_size=10):
# Initialize arrays
self.cbt = [None for _ in range[initial_size]]
# Denotes next index where new element should go
self.next_index = 0
def _down_heapify(self):
parent_index = 0
# _down_heapify while loop
# parent index mathematical logic.
while parent_index < self.next_index:
left_child_index = 2 * parent_index + 1
right_child_index = 2 * parent_index + 2
parent = self.cbt[parent_index]
left_child = None
right_child = None
min_element = parent
# check if left child exists
if left_child_index < self.next_index:
left_child = self.cbt[left_child_index]
# check if right child exists
if right_child_index < self.next_index:
right_child = self.cbt[right_child_index]
# compare with left child
if left_child is not None:
min_element = min(parent, left_child)
# compare with right child
if right_child is not None:
min_element = min(parent, right_child)
# check if parent is properly placed
if min_element == parent:
return
if min_element == left_child:
self.cbt[left_child_index] = parent
self.cbt[parent_index] = min_element
parent = left_child_index
elif min_element == right_child:
self.cbt[right_child_index] = parent
self.cbt[parent_index] = min_element
parent = right_child_index
def size(self):
return self.next_index
def remove(self):
# Remove and return element at the top of the heap.
if self.size() == 0:
return None
self.next_index -= 1
to_remove = self.cbt[0]
last_element = self.cbt[self.next_index]
# Place last element of cbt at the root.
self.cbt[0] = last_element
# we do not remove the element, rather we allow next
# `insert` operation to overwrite it
self.cbt[self.next_index] = to_remove
self._down_heapify()
return to_remove
# Final Heap
'''
Using the insert and remove functions, let's run the heap.
'''
class Heap:
def __init__(self, initial_size=10):
self.cbt = [None for _ in range(initial_size)] # initialize arrays
self.next_index = 0 # denotes next index where new element should go
def insert(self, data):
# insert element at the next index
self.cbt[self.next_index] = data
# heapify
self._up_heapify()
# increase index by 1
self.next_index += 1
# double the array and copy elements if next_index goes out of array bounds
if self.next_index >= len(self.cbt):
temp = self.cbt
self.cbt = [None for _ in range(2 * len(self.cbt))]
for index in range(self.next_index):
self.cbt[index] = temp[index]
def remove(self):
if self.size() == 0:
return None
self.next_index -= 1
to_remove = self.cbt[0]
last_element = self.cbt[self.next_index]
# place last element of the cbt at the root
self.cbt[0] = last_element
# we do not remove the elementm, rather we allow next `insert` operation to overwrite it
self.cbt[self.next_index] = to_remove
self._down_heapify()
return to_remove
def size(self):
return self.next_index
def is_empty(self):
return self.size() == 0
def _up_heapify(self):
# print("inside heapify")
child_index = self.next_index
while child_index >= 1:
parent_index = (child_index - 1) // 2
parent_element = self.cbt[parent_index]
child_element = self.cbt[child_index]
if parent_element > child_element:
self.cbt[parent_index] = child_element
self.cbt[child_index] = parent_element
child_index = parent_index
else:
break
def _down_heapify(self):
parent_index = 0
while parent_index < self.next_index:
left_child_index = 2 * parent_index + 1
right_child_index = 2 * parent_index + 2
parent = self.cbt[parent_index]
left_child = None
right_child = None
min_element = parent
# check if left child exists
if left_child_index < self.next_index:
left_child = self.cbt[left_child_index]
# check if right child exists
if right_child_index < self.next_index:
right_child = self.cbt[right_child_index]
# compare with left child
if left_child is not None:
min_element = min(parent, left_child)
# compare with right child
if right_child is not None:
min_element = min(right_child, min_element)
# check if parent is rightly placed
if min_element == parent:
return
if min_element == left_child:
self.cbt[left_child_index] = parent
self.cbt[parent_index] = min_element
parent = left_child_index
elif min_element == right_child:
self.cbt[right_child_index] = parent
self.cbt[parent_index] = min_element
parent = right_child_index
def get_minimum(self):
# Returns the minimum element present in the heap
if self.size() == 0:
return None
return self.cbt[0]
heap_size = 5
heap = Heap(heap_size)
elements = [1, 2, 3, 4, 1, 2]
for element in elements:
heap.insert(element)
print('Inserted elements: {}'.format(elements))
print('size of heap: {}'.format(heap.size()))
for _ in range(4):
print('Call remove: {}'.format(heap.remove()))
print('Call get_minimum: {}'.format(heap.get_minimum()))
for _ in range(2):
print('Call remove: {}'.format(heap.remove()))
print('size of heap: {}'.format(heap.size()))
print('Call remove: {}'.format(heap.remove()))
print('Call is_empty: {}'.format(heap.is_empty()))
# That's it for heaps! Now it's time for the
# next topic, self-balancing trees.
|
from __future__ import print_function, division
from sympy import (degree_list, Poly, igcd, divisors, sign, symbols, S, Integer, Wild, Symbol, factorint,
Add, Mul, solve, ceiling, floor, sqrt, sympify, simplify, Subs, ilcm, Matrix, factor_list, perfect_power)
from sympy.simplify.simplify import rad_rationalize
from sympy.ntheory.modular import solve_congruence
from sympy.utilities import default_sort_key
from sympy.core.numbers import igcdex
from sympy.ntheory.residue_ntheory import sqrt_mod
def diophantine(eq, param=symbols("t", Integer=True)):
"""
Simplify the solution procedure of diophantine equation ``eq`` by converting it into
a product of terms which should equal zero. For example, when solving, `x^2 - y^2 = 0`
this is treated as `(x + y)(x - y) = 0` and `x+y = 0` and `x-y = 0` are solved
independently and combined. Each term is solved by calling ``diop_solve()``.
Usage
=====
``diophantine(eq, t)`` -> Solve the diophantine equation ``eq``.
``t`` is the parameter to be used by ``diop_solve()``.
Details
=======
``eq`` should be an expression which is assumed to be zero.
``t`` is a parameter to be used in the solution.
Examples
========
>>> from sympy.solvers.diophantine import diophantine
>>> from sympy.abc import x, y, z
>>> diophantine(x**2 - y**2)
set([(-t, -t), (t, -t)])
#>>> diophantine(x*(2*x + 3*y - z))
#set([(0, n1, n2), (3*t - z, -2*t + z, z)])
#>>> diophantine(x**2 + 3*x*y + 4*x)
#set([(0, n1), (3*t - 4, -t)])
See Also
========
diop_solve()
"""
var = list(eq.expand(force=True).free_symbols)
var.sort(key=default_sort_key)
terms = factor_list(eq)[1]
sols = set([])
for term in terms:
base = term[0]
var_t, jnk, eq_type = classify_diop(base)
solution = diop_solve(base, param)
if eq_type in ["univariable", "linear", "ternary_quadratic"]:
if merge_solution(var, var_t, solution) != ():
sols.add(merge_solution(var, var_t, solution))
elif eq_type in ["binary_quadratic"]:
for sol in solution:
if merge_solution(var, var_t, sol) != ():
sols.add(merge_solution(var, var_t, sol))
return sols
def merge_solution(var, var_t, solution):
"""
This is used to construct the full solution from the solutions of sub equations.
For example when solving the equation `(x - y)(x^2 + y^2 - z^2) = 0`, solutions for
each of the equations `x-y = 0` and `x^2 + y^2 - z^2` are found independently.
Solutions for `x - y = 0` are `(x, y) = (t, t)`. But we should introduce a value
for z when we output the solution for the original equation. This function converts
`(t, t)` into `(t, t, n_{1})` where `n_{1}` is an integer parameter.
"""
# currently more than 3 parameters are not required.
n1, n2, n3 = symbols("n1, n2, n3", Integer=True)
params = [n1, n2, n3]
l = []
count1 = 0
count2 = 0
if None not in solution:
for v in var:
if v in var_t:
l.append(solution[count1])
count1 = count1 + 1
else:
l.append(params[count2])
count2 = count2 + 1
return tuple(l)
def diop_solve(eq, param=symbols("t", Integer=True)):
"""
Solves diophantine equations. Uses ``classify_diop()`` to determine the
type of eqaution and calls the appropriate solver function.
Usage
=====
``diop_solve(eq, t)`` -> Solve diophantine equation, ``eq``.
Details
=======
``eq`` should be an expression which is assumed to be zero.
``t`` is a parameter to be used in the solution.
Examples
========
>>> from sympy.solvers.diophantine import diop_solve
>>> from sympy.abc import x, y, z, w
>>> diop_solve(2*x + 3*y - 5)
(3*t - 5, -2*t + 5)
>>> diop_solve(4*x + 3*y -4*z + 5)
(3*t + 4*z - 5, -4*t - 4*z + 5, z)
>>> diop_solve(x + 3*y - 4*z + w -6)
(t, -t - 3*y + 4*z + 6, y, z)
"""
var, coeff, eq_type = classify_diop(eq)
if eq_type == "linear":
return _diop_linear(var, coeff, param)
elif eq_type == "binary_quadratic":
return _diop_quadratic(var, coeff, param)
elif eq_type == "ternary_quadratic":
x_0, y_0, z_0 = _diop_ternary_quadratic(var, coeff)
if x_0 == None:
return (None, None, None)
else:
return _parametrize_ternary_quadratic((x_0, y_0, z_0), var, coeff)
elif eq_type == "univariable":
return solve(eq)
def classify_diop(eq):
"""
Helper routine used by ``diop_solve()``. Returns a tuple containing the type of the
diophantine equation along with the variables(free symbols) and their coefficients.
Variables are returned as a list and coefficients are returned as a dict with
the keys being the variable terms and constant term is keyed to Integer(1).
Type is an element in the set {"linear", "quadratic", "pell", "pythogorean", "exponential"}
Usage
=====
``classify_diop(eq)`` -> Return variables, coefficients and type in order.
Details
=======
``eq`` should be an expression which is assumed to be zero.
Examples
========
>>> from sympy.solvers.diophantine import classify_diop
>>> from sympy.abc import x, y, z, w, t
>>> classify_diop(4*x + 6*y - 4)
([x, y], {1: -4, x: 4, y: 6}, 'linear')
>>> classify_diop(x + 3*y -4*z + 5)
([x, y, z], {1: 5, x: 1, y: 3, z: -4}, 'linear')
"""
eq = eq.expand(force=True)
var = list(eq.free_symbols)
var.sort(key=default_sort_key)
coeff = {}
diop_type = None
coeff = dict([reversed(t.as_independent(*var)) for t in eq.args])
for v in coeff.keys():
if not isinstance(coeff[v], Integer):
raise TypeError("Coefficients should be Integers")
if len(var) == 1:
diop_type = "univariable"
elif Poly(eq).total_degree() == 1:
diop_type = "linear"
elif Poly(eq).total_degree() == 2 and len(var) == 2:
diop_type = "binary_quadratic"
x = var[0]
y = var[1]
if isinstance(eq, Mul):
coeff = {x**2: 0, x*y: eq.args[0], y**2: 0, x: 0, y: 0, Integer(1): 0}
else:
for term in [x**2, y**2, x*y, x, y, Integer(1)]:
if term not in coeff.keys():
coeff[term] = Integer(0)
elif Poly(eq).total_degree() == 2 and len(var) == 3:
diop_type = "ternary_quadratic"
x = var[0]
y = var[1]
z = var[2]
for term in [x**2, y**2, z**2, x*y, y*z, x*z]:
if term not in coeff.keys():
coeff[term] = Integer(0)
else:
raise NotImplementedError("Still not implemented")
return var, coeff, diop_type
def diop_linear(eq, param=symbols("t", Integer=True)):
"""
Solves linear diophantine equations. A linear diophantine equation is an equation
of the form `a_{1}x_{1} + a_{2}x_{2} + .. + a_{n}x_{n} = 0` where `a_{1}, a_{2}, ..a_{n}`
are constants and `x_{1}, x_{2}, ..x_{n}` are variables.
Usage
=====
``diop_linear(eq)`` -> Returns a tuple containing solutions to the diophantine
equation ``eq``. Values in the tuple is arranged in the same order as the sorted
variables.
Details
=======
``eq`` is a linear diophantine equation which is assumed to be zero.
``param`` is the parameter to be used in the solution.
Examples
========
>>> from sympy.solvers.diophantine import diop_linear
>>> from sympy.abc import x, y, z, t
>>> from sympy import Integer
>>> diop_linear(2*x - 3*y - 5) #solves equation 2*x - 3*y -5 = 0
(-3*t - 5, -2*t - 5)
Here x = -3*t - 5 and y = -2*t - 5
>>> diop_linear(2*x - 3*y - 4*z -3)
(-3*t - 4*z - 3, -2*t - 4*z - 3, z)
See Also
========
diop_quadratic(), diop_ternary_quadratic()
"""
var, coeff, diop_type = classify_diop(eq)
if diop_type == "linear":
return _diop_linear(var, coeff, param)
def _diop_linear(var, coeff, param):
x, y = var[:2]
a = coeff[x]
b = coeff[y]
if len(var) == len(coeff):
c = 0
else:
c = -coeff[Integer(1)]
if len(var) == 2:
sol_x, sol_y = base_solution_linear(c, a, b, param)
return (sol_x, sol_y)
elif len(var) > 2:
X = []
Y = []
for v in var[2:]:
sol_x, sol_y = base_solution_linear(-coeff[v], a, b)
X.append(sol_x*v)
Y.append(sol_y*v)
sol_x, sol_y = base_solution_linear(c, a, b, param)
X.append(sol_x)
Y.append(sol_y)
l = []
if None not in X and None not in Y:
l.append(Add(*X))
l.append(Add(*Y))
for v in var[2:]:
l.append(v)
else:
for v in var:
l.append(None)
return tuple(l)
def base_solution_linear(c, a, b, t=None):
"""
Return the base solution for a linear diophantine equation with two
variables. Used by ``diop_linear()`` to find the base solution of a linear
Diophantine equation.
Usage
=====
``base_solution_linear(c, a, b, t)`` -> ``a``, ``b``, ``c`` are coefficients
in `ax + by = c` and ``t`` is the parameter to be used in the solution.
Details
=======
``c`` is the constant term in `ax + by = c`
``a`` is the integer coefficient of x in `ax + by = c`
``b`` is the integer coefficient of y in `ax + by = c`
``t`` is the parameter to be used in the solution
Examples
========
>>> from sympy.solvers.diophantine import base_solution_linear
>>> from sympy.abc import t
>>> base_solution_linear(5, 2, 3) # equation 2*x + 3*y = 5
(-5, 5)
>>> base_solution_linear(0, 5, 7) # equation 5*x + 7*y = 0
(0, 0)
>>> base_solution_linear(5, 2, 3, t) # equation 2*x + 3*y = 5
(3*t - 5, -2*t + 5)
>>> base_solution_linear(0, 5, 7, t) # equation 5*x + 7*y = 0
(7*t, -5*t)
"""
d = igcd(a, igcd(b, c))
a = a // d
b = b // d
c = c // d
if c == 0:
if t != None:
return (b*t , -a*t)
else:
return (S.Zero, S.Zero)
else:
x0, y0, d = extended_euclid(int(abs(a)), int(abs(b)))
x0 = x0 * sign(a)
y0 = y0 * sign(b)
if divisible(c, d):
if t != None:
return (c*x0 + b*t, c*y0 - a*t)
else:
return (Integer(c*x0), Integer(c*y0))
else:
return (None, None)
def extended_euclid(a, b):
"""
For given ``a``, ``b`` returns a tuple containing integers `x`, `y` and `d`
such that `ax + by = d`. Here `d = gcd(a, b)`.
Usage
=====
``extended_euclid(a, b)`` -> returns `x`, `y` and `gcd(a, b)`.
Details
=======
``a`` Any instance of Integer
``b`` Any instance of Integer
Examples
========
>>> from sympy.solvers.diophantine import extended_euclid
>>> extended_euclid(4, 6)
(-1, 1, 2)
>>> extended_euclid(3, 5)
(2, -1, 1)
"""
if b == 0:
return (1, 0, a)
x0, y0, d = extended_euclid(b, a%b)
x, y = y0, x0 - (a//b) * y0
return x, y, d
def divisible(a, b):
"""
Returns `True` if ``a`` is divisible by ``b`` and `False` otherwise.
"""
return igcd(int(a), int(b)) == abs(int(b))
def diop_quadratic(eq, param=symbols("t", Integer=True)):
"""
Solves quadratic diophantine equations, i.e equations of the form
`Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0`. Returns a set containing the tuples `(x, y)`
which contains the solutions. If there are no solutions then `(None, None)` is returned.
Usage
=====
``diop_quadratic(eq, param)`` -> ``eq`` is a quadratic binary diophantine
equation. ``param`` is used to indicate the parameter to be used in the solution.
Details
=======
``eq`` should be an expression which is assumed to be zero.
``param`` is a parameter to be used in the solution.
Examples
========
>>> from sympy.abc import x, y, t
>>> from sympy.solvers.diophantine import diop_quadratic
>>> diop_quadratic(x**2 + y**2 + 2*x + 2*y + 2, t)
set([(-1, -1)])
References
==========
..[1] Methods to solve Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0,[online],
Available: http://www.alpertron.com.ar/METHODS.HTM
..[2] Solving the equation ax^2+ bxy + cy^2 + dx + ey + f= 0, [online],
Available: http://www.jpr2718.org/ax2p.pdf
See Also
========
diop_linear(), diop_ternary_quadratic()
"""
var, coeff, diop_type = classify_diop(eq)
if diop_type == "binary_quadratic":
return _diop_quadratic(var, coeff, param)
def _diop_quadratic(var, coeff, t):
x, y = var[:2]
for term in [x**2, y**2, x*y, x, y, Integer(1)]:
if term not in coeff.keys():
coeff[term] = Integer(0)
A = coeff[x**2]
B = coeff[x*y]
C = coeff[y**2]
D = coeff[x]
E = coeff[y]
F = coeff[Integer(1)]
d = igcd(A, igcd(B, igcd(C, igcd(D, igcd(E, F)))))
A = A // d
B = B // d
C = C // d
D = D // d
E = E // d
F = F // d
# (1) Linear case: A = B = C = 0 -> considered under linear diophantine equations
# (2) Simple-Hyperbolic case:A = C = 0, B != 0
# In this case equation can be converted to (Bx + E)(By + D) = DE - BF
# We consider two cases; DE - BF = 0 and DE - BF != 0
# More details, http://www.alpertron.com.ar/METHODS.HTM#SHyperb
l = set([])
if A == 0 and C == 0 and B != 0:
if D*E - B*F == 0:
if divisible(int(E), int(B)):
l.add((-E/B, t))
if divisible(int(D), int(B)):
l.add((t, -D/B))
else:
div = divisors(D*E - B*F)
div = div + [-term for term in div]
for d in div:
if divisible(int(d - E), int(B)):
x0 = (d - E) // B
if divisible(int(D*E - B*F), int(d)):
if divisible(int((D*E - B*F)// d - D), int(B)):
y0 = ((D*E - B*F) // d - D) // B
l.add((x0, y0))
# (3) Parabolic case: B**2 - 4*A*C = 0
# There are two subcases to be considered in this case.
# sqrt(c)D - sqrt(a)E = 0 and sqrt(c)D - sqrt(a)E != 0
# More Details, http://www.alpertron.com.ar/METHODS.HTM#Parabol
elif B**2 - 4*A*C == 0:
if A == 0:
s = _diop_quadratic([y, x], coeff, t)
for soln in s:
l.add((soln[1], soln[0]))
else:
g = igcd(A, C)
g = abs(g) * sign(A)
a = A // g
b = B // g
c = C // g
e = sign(B/A)
if e*sqrt(c)*D - sqrt(a)*E == 0:
z = symbols("z", real=True)
roots = solve(sqrt(a)*g*z**2 + D*z + sqrt(a)*F)
for root in roots:
if isinstance(root, Integer):
l.add((diop_solve(sqrt(a)*x + e*sqrt(c)*y - root)[0], diop_solve(sqrt(a)*x + e*sqrt(c)*y - root)[1]))
elif isinstance(e*sqrt(c)*D - sqrt(a)*E, Integer):
solve_x = lambda u: e*sqrt(c)*g*(sqrt(a)*E - e*sqrt(c)*D)*t**2 - (E + 2*e*sqrt(c)*g*u)*t\
- (e*sqrt(c)*g*u**2 + E*u + e*sqrt(c)*F) // (e*sqrt(c)*D - sqrt(a)*E)
solve_y = lambda u: sqrt(a)*g*(e*sqrt(c)*D - sqrt(a)*E)*t**2 + (D + 2*sqrt(a)*g*u)*t \
+ (sqrt(a)*g*u**2 + D*u + sqrt(a)*F) // (e*sqrt(c)*D - sqrt(a)*E)
for z0 in range(0, abs(e*sqrt(c)*D - sqrt(a)*E)):
if divisible(sqrt(a)*g*z0**2 + D*z0 + sqrt(a)*F, e*sqrt(c)*D - sqrt(a)*E):
l.add((solve_x(z0), solve_y(z0)))
# (4) Method used when B**2 - 4*A*C is a square, is descibed in p. 6 of the below paper
# by John P. Robertson.
# http://www.jpr2718.org/ax2p.pdf
elif isinstance(sqrt(B**2 - 4*A*C), Integer):
if A != 0:
r = sqrt(B**2 - 4*A*C)
u, v = symbols("u, v", integer=True)
eq = simplify(4*A*r*u*v + 4*A*D*(B*v + r*u + r*v - B*u) + 2*A*4*A*E*(u - v) + 4*A*r*4*A*F)
sol = diop_solve(eq, t)
sol = list(sol)
for solution in sol:
s0 = solution[0]
t0 = solution[1]
x_0 = S(B*t0 + r*s0 + r*t0 - B*s0)/(4*A*r)
y_0 = S(s0 - t0)/(2*r)
if isinstance(s0, Symbol) or isinstance(t0, Symbol):
if check_param(x_0, y_0, 4*A*r, t) != (None, None):
l.add((check_param(x_0, y_0, 4*A*r, t)[0], check_param(x_0, y_0, 4*A*r, t)[1]))
elif divisible(B*t0 + r*s0 + r*t0 - B*s0, 4*A*r):
if divisible(s0 - t0, 2*r):
if is_solution_quad(var, coeff, x_0, y_0):
l.add((x_0, y_0))
else:
_var = var
_var[0], _var[1] = _var[1], _var[0] # Interchange x and y
s = _diop_quadratic(_var, coeff, t)
while len(s) > 0:
sol = s.pop()
l.add((sol[1], sol[0]))
# (5) B**2 - 4*A*C > 0 and B**2 - 4*A*C not a square or B**2 - 4*A*C < 0
else:
P, Q = _transformation_to_DN(var, coeff)
D, N = _find_DN(var, coeff)
solns_pell = diop_DN(D, N)
if D < 0:
for solution in solns_pell:
for X_i in [-solution[0], solution[0]]:
for Y_i in [-solution[1], solution[1]]:
x_i, y_i = (P*Matrix([X_i, Y_i]) + Q)[0], (P*Matrix([X_i, Y_i]) + Q)[1]
if isinstance(x_i, Integer) and isinstance(y_i, Integer):
l.add((x_i, y_i))
else:
# In this case equation can be transformed into a Pell equation
n = symbols("n", integer=True)
a = diop_DN(D, 1)
T = a[0][0]
U = a[0][1]
if (isinstance(P[0], Integer) and isinstance(P[1], Integer) and isinstance(P[2], Integer)
and isinstance(P[3], Integer) and isinstance(Q[0], Integer) and isinstance(Q[1], Integer)):
for sol in solns_pell:
r = sol[0]
s = sol[1]
x_n = S((r + s*sqrt(D))*(T + U*sqrt(D))**n + (r - s*sqrt(D))*(T - U*sqrt(D))**n)/2
y_n = S((r + s*sqrt(D))*(T + U*sqrt(D))**n - (r - s*sqrt(D))*(T - U*sqrt(D))**n)/(2*sqrt(D))
x_n = simplify(x_n)
y_n = simplify(y_n)
x_n, y_n = (P*Matrix([x_n, y_n]) + Q)[0], (P*Matrix([x_n, y_n]) + Q)[1]
l.add((x_n, y_n))
else:
L = ilcm(S(P[0]).q, ilcm(S(P[1]).q, ilcm(S(P[2]).q, ilcm(S(P[3]).q, ilcm(S(Q[0]).q, S(Q[1]).q)))))
k = 0
done = False
T_k = T
U_k = U
while not done:
k = k + 1
if (T_k - 1) % L == 0 and U_k % L == 0:
done = True
T_k, U_k = T_k*T + D*U_k*U, T_k*U + U_k*T
for soln in solns_pell:
X = soln[0]
Y = soln[1]
done = False
for i in range(k):
X_1 = X*T + D*U*Y
Y_1 = X*U + Y*T
x = (P*Matrix([X_1, Y_1]) + Q)[0]
y = (P*Matrix([X_1, Y_1]) + Q)[1]
if is_solution_quad(var, coeff, x, y):
done = True
x_n = S( (X_1 + sqrt(D)*Y_1)*(T + sqrt(D)*U)**(n*L) + (X_1 - sqrt(D)*Y_1)*(T - sqrt(D)*U)**(n*L) )/ 2
y_n = S( (X_1 + sqrt(D)*Y_1)*(T + sqrt(D)*U)**(n*L) - (X_1 - sqrt(D)*Y_1)*(T - sqrt(D)*U)**(n*L) )/ (2*sqrt(D))
x_n = simplify(x_n)
y_n = simplify(y_n)
x_n, y_n = (P*Matrix([x_n, y_n]) + Q)[0], (P*Matrix([x_n, y_n]) + Q)[1]
l.add((x_n, y_n))
if done:
break
return l
def is_solution_quad(var, coeff, u, v):
"""
Check whether `(u, v)` is solution to the quadratic binary diophantine equation
with the variable list ``var`` and coefficient dictionary ``coeff``. Not intended
for normal users.
"""
x = var[0]
y = var[1]
eq = x**2*coeff[x**2] + x*y*coeff[x*y] + y**2*coeff[y**2] + x*coeff[x] + y*coeff[y] + coeff[Integer(1)]
return simplify(Subs(eq, (x, y), (u, v)).doit()) == 0
def diop_DN(D, N, t=symbols("t", Integer=True)):
"""
Solves the equation `x^2 - Dy^2 = N`. Mainly concerned in the case `D > 0, D` is
not a perfect square, which is the same as generalized Pell equation. To solve the
generalized Pell equation this function Uses LMM algorithm. Refer [1] for more
details on the algorithm. Returns one solution for each class of the solutions.
Other solutions of the class can be constructed according to the values of ``D`` and ``N``.
Returns a list containing the solution tuples` (x, y)`.
Usage
=====
``diop_DN(D, N, t)`` -> D and N are integers as in `x^2 - Dy^2 = N` and ``t`` is
the parameter to be used in the solutions.
Details
=======
``D`` corresponds to the D in the equation
``N`` corresponds to the N in the equation
``t`` parameter to be used in the solutions
Examples
========
>>> from sympy.solvers.diophantine import diop_DN
>>> diop_DN(13, -4) # Solves equation x**2 - 13*y**2 = -4
[(3, 1), (393, 109), (36, 10)]
The output can be interpreted as follows: There are three fundamental
solutions to the equation `x^2 - 13y^2 = -4` given by (3, 1), (393, 109)
and (36, 10). Each tuple is in the form (x, y), i. e solution (3, 1) means
that `x = 3` and `y = 1`.
>>> diop_DN(986, 1) # Solves equation x**2 - 986*y**2 = 1
[(49299, 1570)]
See Also
========
find_DN(), diop_bf_DN()
References
==========
..[1] Solving the generalized Pell equation x**2 - D*y**2 = N, John P. Robertson,
July 31, 2004, Pages 16 - 17. [online], Available: http://www.jpr2718.org/pell.pdf
"""
if D < 0:
if N == 0:
return [(S.Zero, S.Zero)]
elif N < 0:
return []
elif N > 0:
d = divisors(square_factor(N))
sol = []
for divisor in d:
sols = cornacchia(1, -D, N // divisor**2)
if sols:
for x, y in sols:
sol.append((divisor*x, divisor*y))
return sol
elif D == 0:
if N < 0 or not isinstance(sqrt(N), Integer):
return []
if N == 0:
return [(S.Zero, t)]
if isinstance(sqrt(N), Integer):
return [(sqrt(N), t)]
else: # D > 0
if isinstance(sqrt(D), Integer):
r = sqrt(D)
if N == 0:
return [(r*t, t)]
else:
sol = []
for y in range(floor(sign(N)*(N - 1)/(2*r)) + 1):
if isinstance(sqrt(D*y**2 + N), Integer):
sol.append((sqrt(D*y**2 + N), y))
return sol
else:
if N == 0:
return [(S.Zero, S.Zero)]
elif abs(N) == 1:
pqa = PQa(0, 1, D)
a_0 = floor(sqrt(D))
l = 0
G = []
B = []
for i in pqa:
a = i[2]
G.append(i[5])
B.append(i[4])
if l != 0 and a == 2*a_0:
break
l = l + 1
if l % 2 == 1:
if N == -1:
x = G[l-1]
y = B[l-1]
else:
count = l
while count < 2*l - 1:
i = next(pqa)
G.append(i[5])
B.append(i[4])
count = count + 1
x = G[count]
y = B[count]
else:
if N == 1:
x = G[l-1]
y = B[l-1]
else:
return []
return [(x, y)]
else:
fs = []
sol = []
div = divisors(N)
for d in div:
if divisible(N, d**2):
fs.append(d)
for f in fs:
m = N // f**2
zs = sqrt_mod(D, abs(m), True)
zs = [i for i in zs if i <= abs(m) // 2 ]
if abs(m) != 2:
zs = zs + [-i for i in zs]
if S.Zero in zs:
zs.remove(S.Zero) # Remove duplicate zero
for z in zs:
pqa = PQa(z, abs(m), D)
l = 0
G = []
B = []
for i in pqa:
a = i[2]
G.append(i[5])
B.append(i[4])
if l != 0 and abs(i[1]) == 1:
r = G[l-1]
s = B[l-1]
if r**2 - D*s**2 == m:
sol.append((f*r, f*s))
elif diop_DN(D, -1) != []:
a = diop_DN(D, -1)
sol.append((f*(r*a[0][0] + a[0][1]*s*D), f*(r*a[0][1] + s*a[0][0])))
break
l = l + 1
if l == length(z, abs(m), D):
break
return sol
def cornacchia(a, b, m):
"""
Solves `ax^2 + by^2 = m` where `gcd(a, b) = 1 = gcd(a, m)` and `a, b > 0`.
Uses the algorithm due to Cornacchia. The method only finds primitive solutions,
i.e. ones with `gcd(x, y) = 1`. So this method can't be used to find the solutions
of `x^2 + y^2 = 20` since the solution `(x,y) = (4, 2)` is not primitive.
When ` a = b = 1`, only the solutions with `x \geq y` are found. For more details
see the References.
Examples
========
>>> from sympy.solvers.diophantine import cornacchia
>>> cornacchia(2, 3, 35) # equation 2x**2 + 3y**2 = 35
set([(2, 3), (4, 1)])
>>> cornacchia(1, 1, 25) # equation x**2 + y**2 = 25
set([(4, 3)])
References
===========
.. [1] A. Nitaj, "L'algorithme de Cornacchia"
.. [2] Solving the diophantine equation ax**2 + by**2 = m by Cornacchia's method,
[online], Available: http://www.numbertheory.org/php/cornacchia.html
"""
sols = set()
a1 = igcdex(a, m)[0]
v = sqrt_mod(-b*a1, m, True)
if v is None:
return None
if not isinstance(v, list):
v = [v]
for t in v:
if t < m // 2:
continue
u, r = t, m
while True:
u, r = r, u % r
if a*r**2 < m:
break
m1 = m - a*r**2
if m1 % b == 0:
m1 = m1 // b
if isinstance(sqrt(m1), Integer):
s = sqrt(m1)
sols.add((int(r), int(s)))
return sols
def PQa(P_0, Q_0, D):
"""
Returns the useful information needed to solve the Pell equation.
There are six sequences of integers defined related to the continued fraction
representation of `\\frac{P + \sqrt{D}}{Q}`, namely {`P_{i}`}, {`Q_{i}`}, {`a_{i}`},
{`A_{i}`}, {`B_{i}`}, {`G_{i}`}. Return these values as a 6-tuple in the same order
mentioned above. Refer [1] for more detailed information.
Usage
=====
``PQa(P_0, Q_0, D)`` -> ``P_0``, ``Q_0`` and ``D`` are integers corresponding to
the continued fraction `\\frac{P_{0} + \sqrt{D}}{Q_{0}}`. Also it's assumed that
`P_{0}^2 == D mod(|Q_{0}|)` and `D` is square free.
Details
=======
``P_{0}`` corresponds to the P in the continued fraction, `\\frac{P + \sqrt{D}}{Q}`
``D`` corresponds to the D in the continued fraction, `\\frac{P + \sqrt{D}}{Q}`
``Q_{0}`` corresponds to the Q in the continued fraction, `\\frac{P + \sqrt{D}}{Q}`
Examples
========
>>> from sympy.solvers.diophantine import PQa
>>> pqa = PQa(13, 4, 5) # (13 + sqrt(5))/4
>>> next(pqa) # (P_0, Q_0, a_0, A_0, B_0, G_0)
(13, 4, 3, 3, 1, -1)
>>> next(pqa) # (P_1, Q_1, a_1, A_1, B_1, G_1)
(-1, 1, 1, 4, 1, 3)
References
==========
.. [1] Solving the generalized Pell equation x^2 - Dy^2 = N, John P. Robertson,
July 31, 2004, Pages 4 - 8.
http://www.jpr2718.org/pell.pdf
"""
A_i_2 = B_i_1 = 0
A_i_1 = B_i_2 = 1
G_i_2 = -P_0
G_i_1 = Q_0
P_i = P_0
Q_i = Q_0
while(1):
a_i = floor((P_i + sqrt(D))/Q_i)
A_i = a_i*A_i_1 + A_i_2
B_i = a_i*B_i_1 + B_i_2
G_i = a_i*G_i_1 + G_i_2
yield P_i, Q_i, a_i, A_i, B_i, G_i
A_i_1, A_i_2 = A_i, A_i_1
B_i_1, B_i_2 = B_i, B_i_1
G_i_1, G_i_2 = G_i, G_i_1
P_i = a_i*Q_i - P_i
Q_i = (D - P_i**2)/Q_i
def diop_bf_DN(D, N, t=symbols("t", Integer=True)):
"""
Uses brute force to solve the equation, `x^2 - Dy^2 = N`. Mainly concerned with the
generalized Pell equation which is the case when `D > 0, D` is not a perfect square.
For more information on the case refer [1]. Let `t, u` be the minimal positive solution
such that `t^2 - Du^2 = 1`(i. e. solutions to the equation `x^2 - Dy^2 = 1`) then this
method requires that `\sqrt{\\frac{\mid N \mid (t \pm 1)}{2D}}` is not too large.
Usage
=====
``diop_bf_DN(D, N, t)`` -> ``D`` and ``N`` are coefficients in `x^2 - Dy^2 = N` and
``t`` is the parameter to be used in the solutions.
Details
=======
``D`` corresponds to the D in the equation
``N`` corresponds to the N in the equation
``t`` parameter to be used in the solutions
Examples
========
>>> from sympy.solvers.diophantine import diop_bf_DN
>>> diop_bf_DN(13, -4)
[(3, 1), (-3, 1), (36, 10)]
>>> diop_bf_DN(986, 1)
[(49299, 1570)]
See Also
========
diop_DN()
References
==========
.. [1] Solving the generalized Pell equation x**2 - D*y**2 = N, John P. Robertson,
July 31, 2004, Page 15.
http://www.jpr2718.org/pell.pdf
"""
sol = []
a = diop_DN(D, 1)
u = a[0][0]
v = a[0][1]
if abs(N) == 1:
return diop_DN(D, N)
elif N > 1:
L1 = 0
L2 = floor(sqrt(S(N*(u - 1))/(2*D))) + 1
elif N < -1:
L1 = ceiling(sqrt(S(-N)/D))
L2 = floor(sqrt(S(-N*(u + 1))/(2*D))) + 1
else:
if D < 0:
return [(S.Zero, S.Zero)]
elif D == 0:
return [(S.Zero, t)]
else:
if isinstance(sqrt(D), Integer):
return [(sqrt(D)*t, t), (-sqrt(D)*t, t)]
else:
return [(S.Zero, S.Zero)]
for y in range(L1, L2):
if isinstance(sqrt(N + D*y**2), Integer):
x = sqrt(N + D*y**2)
sol.append((x, y))
if not equivalent(x, y, -x, y, D, N):
sol.append((-x, y))
return sol
def equivalent(u, v, r, s, D, N):
"""
Returns True if two solutions to the `x^2 - Dy^2 = N` belongs to the same
equivalence class and False otherwise. Two solutions `(u, v)` and `(r, s)` to
the above equation fall to the same equivalence class iff both `(ur - Dvs)`
and `(us - vr)` are divisible by `N`. See reference [1]. No check is performed to
test whether `(u, v)` and `(r, s)` are actually solutions to the equation.
User should take care of this.
Usage
=====
``equivalent(u, v, r, s, D, N)`` -> `(u, v)` and `(r, s)` are two solutions of the
equation `x^2 - Dy^2 = N` and all parameters involved are integers.
Examples
========
>>> from sympy.solvers.diophantine import equivalent
>>> equivalent(18, 5, -18, -5, 13, -1)
True
>>> equivalent(3, 1, -18, 393, 109, -4)
False
References
==========
.. [1] Solving the generalized Pell equation x**2 - D*y**2 = N, John P. Robertson,
July 31, 2004, Page 12.
http://www.jpr2718.org/pell.pdf
"""
return divisible(u*r - D*v*s, N) and divisible(u*s - v*r, N)
def length(P, Q, D):
"""
Returns the length of aperiodic part + length of periodic part of
continued fraction representation of `\\frac{P + \sqrt{D}}{Q}`. It is important
to remember that this does NOT return the length of the periodic
part but the addition of the legths of the two parts as mentioned above.
Usage
=====
``length(P, Q, D)`` -> ``P``, ``Q`` and ``D`` are integers corresponding to the
continued fraction `\\frac{P + \sqrt{D}}{Q}`.
Details
=======
``P`` corresponds to the P in the continued fraction, `\\frac{P + \sqrt{D}}{Q}`
``D`` corresponds to the D in the continued fraction, `\\frac{P + \sqrt{D}}{Q}`
``Q`` corresponds to the Q in the continued fraction, `\\frac{P + \sqrt{D}}{Q}`
Examples
========
>>> from sympy.solvers.diophantine import length
>>> length(-2 , 4, 5) # (-2 + sqrt(5))/4
3
>>> length(-5, 4, 17) # (-5 + sqrt(17))/4
4
"""
x = P + sqrt(D)
y = Q
x = sympify(x)
v, res = [], []
q = x/y
if q < 0:
v.append(q)
res.append(floor(q))
q = q - floor(q)
num, den = rad_rationalize(1, q)
q = num / den
while 1:
v.append(q)
a = int(q)
res.append(a)
if q == a:
return len(res)
num, den = rad_rationalize(1,(q - a))
q = num / den
if q in v:
return len(res)
def transformation_to_DN(eq):
"""
This function transforms general quadratic `ax^2 + bxy + cy^2 + dx + ey + f = 0`
to more easy to deal with `X^2 - DY^2 = N` form.
This is used to solve the general quadratic by transforming it to the latter form.
Refer [1] for more detailed information on the transformation. This function returns
a tuple (A, B) where A is a 2 * 2 matrix and B is a 2 * 1 matrix such that,
Transpose([x y]) = A * Transpose([X Y]) + B
Usage
=====
``transformation_to_DN(eq)`` -> where ``eq`` is the quadratic to be transformed.
Examples
========
>>> from sympy.abc import x, y
>>> from sympy.solvers.diophantine import transformation_to_DN
>>> from sympy.solvers.diophantine import classify_diop
>>> A, B = transformation_to_DN(x**2 - 3*x*y - y**2 - 2*y + 1)
>>> A
Matrix([
[1/26, 3/26],
[ 0, 1/13]])
>>> B
Matrix([
[-6/13],
[-4/13]])
A, B returned are such that Transpose((x y)) = A * Transpose((X Y)) + B.
Substituting these values for ``x`` and ``y`` and a bit of simplifying work will give
an equation of the form `x^2 - Dy^2 = N`.
>>> from sympy.abc import X, Y
>>> from sympy import Matrix, simplify, Subs
>>> u = (A*Matrix([X, Y]) + B)[0] # Transformation for x
>>> u
X/26 + 3*Y/26 - 6/13
>>> v = (A*Matrix([X, Y]) + B)[1] # Transformation for y
>>> v
Y/13 - 4/13
Next we will substitute these formulas for `x` and `y` and do ``simplify()``.
>>> eq = simplify(Subs(x**2 - 3*x*y - y**2 - 2*y + 1, (x, y), (u, v)).doit())
>>> eq
X**2/676 - Y**2/52 + 17/13
By multiplying the denominator appropriately, we can get a Pell equation in the
standard form.
>>> eq * 676
X**2 - 13*Y**2 + 884
If only the final equation is needed, ``find_DN()`` can be used.
See Also
========
find_DN()
References
==========
.. [1] Solving the equation ax^2 + bxy + cy^2 + dx + ey + f = 0,
John P.Robertson, May 8, 2003, Page 7 - 11.
http://www.jpr2718.org/ax2p.pdf
"""
var, coeff, diop_type = classify_diop(eq)
if diop_type == "binary_quadratic":
return _transformation_to_DN(var, coeff)
def _transformation_to_DN(var, coeff):
x, y = var[:2]
a = coeff[x**2]
b = coeff[x*y]
c = coeff[y**2]
d = coeff[x]
e = coeff[y]
f = coeff[Integer(1)]
g = igcd(a, igcd(b, igcd(c, igcd(d, igcd(e, f)))))
a = a // g
b = b // g
c = c // g
d = d // g
e = e // g
f = f // g
X, Y = symbols("X, Y", integer=True)
if b != Integer(0):
B = (S(2*a)/b).p
C = (S(2*a)/b).q
A = (S(a)/B**2).p
T = (S(a)/B**2).q
# eq_1 = A*B*X**2 + B*(c*T - A*C**2)*Y**2 + d*T*X + (B*e*T - d*T*C)*Y + f*T*B
coeff = {X**2: A*B, X*Y: 0, Y**2: B*(c*T - A*C**2), X: d*T, Y: B*e*T - d*T*C, Integer(1): f*T*B}
A_0, B_0 = _transformation_to_DN([X, Y], coeff)
return Matrix(2, 2, [S(1)/B, -S(C)/B, 0, 1])*A_0, Matrix(2, 2, [S(1)/B, -S(C)/B, 0, 1])*B_0
else:
if d != Integer(0):
B = (S(2*a)/d).p
C = (S(2*a)/d).q
A = (S(a)/B**2).p
T = (S(a)/B**2).q
# eq_2 = A*X**2 + c*T*Y**2 + e*T*Y + f*T - A*C**2
coeff = {X**2: A, X*Y: 0, Y**2: c*T, X: 0, Y: e*T, Integer(1): f*T - A*C**2}
A_0, B_0 = _transformation_to_DN([X, Y], coeff)
return Matrix(2, 2, [S(1)/B, 0, 0, 1])*A_0, Matrix(2, 2, [S(1)/B, 0, 0, 1])*B_0 + Matrix([-S(C)/B, 0])
else:
if e != Integer(0):
B = (S(2*c)/e).p
C = (S(2*c)/e).q
A = (S(c)/B**2).p
T = (S(c)/B**2).q
# eq_3 = a*T*X**2 + A*Y**2 + f*T - A*C**2
coeff = {X**2: a*T, X*Y: 0, Y**2: A, X: 0, Y: 0, Integer(1): f*T - A*C**2}
A_0, B_0 = _transformation_to_DN([X, Y], coeff)
return Matrix(2, 2, [1, 0, 0, S(1)/B])*A_0, Matrix(2, 2, [1, 0, 0, S(1)/B])*B_0 + Matrix([0, -S(C)/B])
else:
# TODO: pre-simplification: Not necessary but may simplify
# the equation.
return Matrix(2, 2, [S(1)/a, 0, 0, 1]), Matrix([0, 0])
def find_DN(eq):
"""
This function returns a tuple, `(D, N)` of the simplified form `x^2 - Dy^2 = N`
corresponding to the general quadratic `ax^2 + bxy + cy^2 + dx + ey + f = 0`.
Solving the general quadratic is then equivalent to solving the equation `X^2 - DY^2 = N`
and transforming the solutions by using the transformation matrices returned by
`transformation_to_DN()`.
Usage
=====
``find_DN(eq)`` -> where ``eq`` is the quadratic to be transformed.
Examples
========
>>> from sympy.abc import x, y
>>> from sympy.solvers.diophantine import find_DN
>>> find_DN(x**2 - 3*x*y - y**2 - 2*y + 1)
(13, -884)
Interpretation of the output is that we get `X^2 -13Y^2 = -884` after transforming
`x^2 - 3xy - y^2 - 2y + 1` using the transformation returned by transformation_to_DN().
See Also
========
transformation_to_DN()
References
==========
.. [1] Solving the equation ax^2 + bxy + cy^2 + dx + ey + f = 0,
John P.Robertson, May 8, 2003, Page 7 - 11.
http://www.jpr2718.org/ax2p.pdf
"""
var, coeff, diop_type = classify_diop(eq)
if diop_type == "binary_quadratic":
return _find_DN(var, coeff)
def _find_DN(var, coeff):
x, y = var[:2]
X, Y = symbols("X, Y", integer=True)
A , B = _transformation_to_DN(var, coeff)
u = (A*Matrix([X, Y]) + B)[0]
v = (A*Matrix([X, Y]) + B)[1]
eq = x**2*coeff[x**2] + x*y*coeff[x*y] + y**2*coeff[y**2] + x*coeff[x] + y*coeff[y] + coeff[Integer(1)]
simplified = simplify(Subs(eq, (x, y), (u, v)).doit())
coeff = dict([reversed(t.as_independent(*[X, Y])) for t in simplified.args])
for term in [X**2, Y**2, Integer(1)]:
if term not in coeff.keys():
coeff[term] = Integer(0)
return -coeff[Y**2]/coeff[X**2], -coeff[Integer(1)]/coeff[X**2]
def check_param(x, y, a, t):
"""
Check if there is a number modulo ``a`` such that ``x`` and ``y`` are both
integers. If exist, then find a parametric representation for ``x`` and ``y``.
Here ``x`` and ``y`` are functions of ``t``.
"""
k, m, n = symbols("k, m, n", Integer=True)
p = Wild("p", exclude=[k])
q = Wild("q", exclude=[k])
ok = False
for i in range(a):
z_x = simplify(Subs(x, t, a*k + i).doit()).match(p*k + q)
z_y = simplify(Subs(y, t, a*k + i).doit()).match(p*k + q)
if (isinstance(z_x[p], Integer) and isinstance(z_x[q], Integer) and
isinstance(z_y[p], Integer) and isinstance(z_y[q], Integer)):
ok = True
break
if ok == True:
x_param = x.match(p*t + q)
y_param = y.match(p*t + q)
if x_param[p] == 0 or y_param[p] == 0:
if x_param[p] == 0:
l1, junk = Poly(y).clear_denoms()
else:
l1 = 1
if y_param[p] == 0:
l2, junk = Poly(x).clear_denoms()
else:
l2 = 1
return x*ilcm(l1, l2), y*ilcm(l1, l2)
eq = S(m -x_param[q])/x_param[p] - S(n - y_param[q])/y_param[p]
lcm_denom, junk = Poly(eq).clear_denoms()
eq = eq * lcm_denom
return diop_solve(eq, t)[0], diop_solve(eq, t)[1]
else:
return (None, None)
def diop_ternary_quadratic(eq):
"""
Solves the general quadratic ternary form, `ax^2 + by^2 + cz^2 + fxy + gyz + hxz = 0`.
Returns a tuple `(x, y, z)` which is a base solution for the above equation. If there
are no solutions, `(None, None, None)` is returned.
Usage
=====
``diop_ternary_quadratic(eq)`` -> Return a tuple containing an basic solution to ``eq``.
Details
=======
``eq`` should be an homogeneous expression of degree two in three variables
and it is assumed to be zero.
Examples
========
>>> from sympy.abc import x, y, z
>>> from sympy.solvers.diophantine import diop_ternary_quadratic
>>> diop_ternary_quadratic(x**2 + 3*y**2 - z**2)
(1, 0, 1)
>>> diop_ternary_quadratic(4*x**2 + 5*y**2 - z**2)
(1, 0, 2)
>>> diop_ternary_quadratic(45*x**2 - 7*y**2 - 8*x*y - z**2)
(28, 45, 105)
>>> diop_ternary_quadratic(x**2 - 49*y**2 - z**2 + 13*z*y -8*x*y)
(9, 1, 5)
"""
var, coeff, diop_type = classify_diop(eq)
if diop_type == "ternary_quadratic":
return _diop_ternary_quadratic(var, coeff)
def _diop_ternary_quadratic(_var, coeff):
x, y, z = _var[:3]
var = [x]*3
var[0], var[1], var[2] = _var[0], _var[1], _var[2]
# Equations of the form B*x*y + C*z*x + E*y*z = 0 and At least two of the
# coefficients A, B, C are non-zero.
# There are infinitely many solutions for the equation.
# Ex: (0, 0, t), (0, t, 0), (t, 0, 0)
# Equation can be re-written as y*(B*x + E*z) = -C*x*z and we can find rather
# unobviuos solutions. Set y = -C and B*x + E*z = x*z. The latter can be solved by
# using methods for binary quadratic diophantine equations. Let's select the
# solution which minimizes |x| + |z|
if coeff[x**2] == 0 and coeff[y**2] == 0 and coeff[z**2] == 0:
if coeff[x*z] != 0:
sols = diophantine(coeff[x*y]*x + coeff[y*z]*z - x*z)
s = sols.pop()
min_sum = abs(s[0]) + abs(s[1])
for r in sols:
if abs(r[0]) + abs(r[1]) < min_sum:
s = r
min_sum = abs(s[0]) + abs(s[1])
x_0, y_0, z_0 = s[0], -coeff[x*z], s[1]
else:
var[0], var[1] = _var[1], _var[0]
y_0, x_0, z_0 = _diop_ternary_quadratic(var, coeff)
return simplified(x_0, y_0, z_0)
if coeff[x**2] == 0:
# If the coefficient of x is zero change the variables
if coeff[y**2] == 0:
var[0], var[2] = _var[2], _var[0]
z_0, y_0, x_0 = _diop_ternary_quadratic(var, coeff)
else:
var[0], var[1] = _var[1], _var[0]
y_0, x_0, z_0 = _diop_ternary_quadratic(var, coeff)
else:
if coeff[x*y] != 0 or coeff[x*z] != 0:
# Apply the transformation x --> X - (B*y + C*z)/(2*A)
A = coeff[x**2]
B = coeff[x*y]
C = coeff[x*z]
D = coeff[y**2]
E = coeff[y*z]
F = coeff[z**2]
_coeff = dict()
_coeff[x**2] = 4*A**2
_coeff[y**2] = 4*A*D - B**2
_coeff[z**2] = 4*A*F - C**2
_coeff[y*z] = 4*A*E - 2*B*C
_coeff[x*y] = 0
_coeff[x*z] = 0
X_0, y_0, z_0 = _diop_ternary_quadratic(var, _coeff)
if X_0 == None:
return (None, None, None)
l = (S(B*y_0 + C*z_0)/(2*A)).q
x_0, y_0, z_0 = X_0*l - (S(B*y_0 + C*z_0)/(2*A)).p, y_0*l, z_0*l
elif coeff[z*y] != 0:
if coeff[y**2] == 0:
if coeff[z**2] == 0:
# Equations of the form A*x**2 + E*yz = 0.
A = coeff[x**2]
E = coeff[y*z]
b = (S(-E)/A).p
a = (S(-E)/A).q
x_0, y_0, z_0 = b, a, b
else:
# Ax**2 + E*y*z + F*z**2 = 0
var[0], var[2] = _var[2], _var[0]
z_0, y_0, x_0 = _diop_ternary_quadratic(var, coeff)
else:
# A*x**2 + D*y**2 + E*y*z + F*z**2 = 0, C may be zero
var[0], var[1] = _var[1], _var[0]
y_0, x_0, z_0 = _diop_ternary_quadratic(var, coeff)
else:
# Ax**2 + D*y**2 + F*z**2 = 0, C may be zero
x_0, y_0, z_0 = _diop_ternary_quadratic_normal(var, coeff)
return simplified(x_0, y_0, z_0)
def transformation_to_normal(eq):
"""
Transform the general ternary quadratic equation `eq` to the ternary quadratic
normal form, i.e to the form `ax^2 + by^2 + cz^2 = 0`. Returns the transfromation
Matrix which is a 3X3 Matrix. This is not used in solving ternary quadratics.
Only implemented for the sake of completeness.
"""
var, coeff, diop_type = classify_diop(eq)
if diop_type == "ternary_quadratic":
return _transformation_to_normal(var, coeff)
def _transformation_to_normal(var, coeff):
_var = [var[0]]*3
_var[1], _var[2] = var[1], var[2]
x, y, z = var[:3]
if coeff[x**2] == 0:
# If the coefficient of x is zero change the variables
if coeff[y**2] == 0:
_var[0], _var[2] = var[2], var[0]
T = _transformation_to_normal(_var, coeff)
T.row_swap(0, 2)
T.col_swap(0, 2)
return T
else:
_var[0], _var[1] = var[1], var[0]
T = _transformation_to_normal(_var, coeff)
T.row_swap(0, 1)
T.col_swap(0, 1)
return T
else:
# Apply the transformation x --> X - (B*Y + C*Z)/(2*A)
if coeff[x*y] != 0 or coeff[x*z] != 0:
A = coeff[x**2]
B = coeff[x*y]
C = coeff[x*z]
D = coeff[y**2]
E = coeff[y*z]
F = coeff[z**2]
_coeff = dict()
_coeff[x**2] = 4*A**2
_coeff[y**2] = 4*A*D - B**2
_coeff[z**2] = 4*A*F - C**2
_coeff[y*z] = 4*A*E - 2*B*C
_coeff[x*y] = 0
_coeff[x*z] = 0
T_0 = _transformation_to_normal(_var, _coeff)
return Matrix(3, 3, [1, S(-B)/(2*A), S(-C)/(2*A), 0, 1, 0, 0, 0, 1]) * T_0
elif coeff[y*z] != 0:
if coeff[y**2] == 0:
if coeff[z**2] == 0:
# Equations of the form A*x**2 + E*yz = 0.
# Apply transformation y -> Y + Z ans z -> Y - Z
return Matrix(3, 3, [1, 0, 0, 0, 1, 1, 0, 1, -1])
else:
# Ax**2 + E*y*z + F*z**2 = 0
_var[0], _var[2] = var[2], var[0]
T = _transformtion_to_normal(_var, coeff)
T.row_swap(0, 2)
T.col_swap(0, 2)
return T
else:
# A*x**2 + D*y**2 + E*y*z + F*z**2 = 0, F may be zero
_var[0], _var[1] = var[1], var[0]
T = _transformation_to_normal(_var, coeff)
T.row_swap(0, 1)
T.col_swap(0, 1)
return T
else:
return Matrix(3, 3, [1, 0, 0, 0, 1, 0, 0, 0, 1])
def simplified(x, y, z):
"""
Simplify the solution `(x, y, z)`.
"""
if x == None or y == None or z == None:
return (x, y, z)
g = igcd(x, igcd(y, z))
return x // g, y // g, z // g
def parametrize_ternary_quadratic(eq):
"""
Returns the parametrized general solution for the ternary quadratic
equation ``eq`` which has the form `ax^2 + by^2 + cz^2 + fxy + gyz + hxz = 0`.
Examples
========
>>> from sympy.abc import x, y, z
>>> from sympy.solvers.diophantine import parametrize_ternary_quadratic
>>> parametrize_ternary_quadratic(x**2 + y**2 - z**2)
(2*p*q, p**2 - q**2, p**2 + q**2)
Here `p` and `q` are two co-prime integers.
>>> parametrize_ternary_quadratic(3*x**2 + 2*y**2 - z**2 - 2*x*y + 5*y*z - 7*y*z)
(2*p**2 - 2*p*q - q**2, 2*p**2 + 2*p*q - q**2, 2*p**2 - 2*p*q + 3*q**2)
>>> parametrize_ternary_quadratic(124*x**2 - 30*y**2 - 7729*z**2)
(-1410*p**2 - 363263*q**2, 2700*p**2 + 30916*p*q - 695610*q**2, -60*p**2 + 5400*p*q + 15458*q**2)
References
==========
.. [1] The algorithmic resolution of Diophantine equations, Nigel P. Smart,
London Mathematical Society Student Texts 41, Cambridge University Press, Cambridge, 1998.
"""
var, coeff, diop_type = classify_diop(eq)
if diop_type == "ternary_quadratic":
x_0, y_0, z_0 = _diop_ternary_quadratic(var, coeff)
return _parametrize_ternary_quadratic((x_0, y_0, z_0), var, coeff)
def _parametrize_ternary_quadratic(solution, _var, coeff):
x, y, z = _var[:3]
x_0, y_0, z_0 = solution[:3]
v = [x]*3
v[0], v[1], v[2] = _var[0], _var[1], _var[2]
if x_0 == None:
return (None, None, None)
if x_0 == 0:
if y_0 == 0:
v[0], v[2] = v[2], v[0]
z_p, y_p, x_p = _parametrize_ternary_quadratic((z_0, y_0, x_0), v, coeff)
return x_p, y_p, z_p
else:
v[0], v[1] = v[1], v[0]
y_p, x_p, z_p = _parametrize_ternary_quadratic((y_0, x_0, z_0), v, coeff)
return x_p, y_p, z_p
x, y, z = v[:3]
r, p, q = symbols("r, p, q", Integer=True)
eq = x**2*coeff[x**2] + y**2*coeff[y**2] + z**2*coeff[z**2] + x*y*coeff[x*y] + y*z*coeff[y*z] + z*x*coeff[z*x]
eq_1 = Subs(eq, (x, y, z), (r*x_0, r*y_0 + p, r*z_0 + q)).doit()
eq_1 = eq_1.expand(force=True)
A, B = eq_1.as_independent(r, as_Add=True)
x = A*x_0
y = (A*y_0 - simplify(B/r)*p).expand(force=True)
z = (A*z_0 - simplify(B/r)*q).expand(force=True)
return x, y, z
def diop_ternary_quadratic_normal(eq):
"""
Currently solves the quadratic ternary diophantine equation, `ax^2 + by^2 + cz^2 = 0`.
Here the coefficients `a`, `b`, and `c` should be non zero. Otherwise the equation will be
a quadratic binary or univariable equation. If solvable, returns a tuple `(x, y, z)` that
satisifes the given equation. If the equation does not have integer solutions,
`(None, None, None)` is returned.
Usage
=====
``diop_ternary_quadratic_normal(eq)`` -> where ``eq`` is an equation of the form
`ax^2 + by^2 + cz^2 = 0`.
Examples
========
>>> from sympy.abc import x, y, z
>>> from sympy.solvers.diophantine import diop_ternary_quadratic_normal
>>> diop_ternary_quadratic_normal(x**2 + 3*y**2 - z**2)
(1, 0, 1)
>>> diop_ternary_quadratic_normal(4*x**2 + 5*y**2 - z**2)
(1, 0, 2)
>>> diop_ternary_quadratic_normal(34*x**2 - 3*y**2 - 301*z**2)
(4, 9, 1)
"""
var, coeff, diop_type = classify_diop(eq)
if diop_type == "ternary_quadratic":
return _diop_ternary_quadratic_normal(var, coeff)
def _diop_ternary_quadratic_normal(var, coeff):
x, y, z = var[:3]
a = coeff[x**2]
b = coeff[y**2]
c = coeff[z**2]
if a*b*c == 0:
raise ValueError("Try factoring out you equation or using diophantine()")
g = igcd(a, igcd(b, c))
a = a // g
b = b // g
c = c // g
a_0 = square_factor(a)
b_0 = square_factor(b)
c_0 = square_factor(c)
a_1 = a // a_0**2
b_1 = b // b_0**2
c_1 = c // c_0**2
a_2, b_2, c_2 = pairwise_prime(a_1, b_1, c_1)
A = -a_2*c_2
B = -b_2*c_2
# If following two conditions are satisified then there are no solutions
if A < 0 and B < 0:
return (None, None, None)
if (sqrt_mod(-b_2*c_2, a_2) == None or sqrt_mod(-c_2*a_2, b_2) == None or
sqrt_mod(-a_2*b_2, c_2) == None):
return (None, None, None)
z_0, x_0, y_0 = descent(A, B)
if divisible(z_0, c_2) == True:
z_0 = z_0 // abs(c_2)
else:
x_0 = x_0*(S(z_0)/c_2).q
y_0 = y_0*(S(z_0)/c_2).q
z_0 = (S(z_0)/c_2).p
x_0, y_0, z_0 = simplified(x_0, y_0, z_0)
# Holzer reduction
if sign(a) == sign(b):
x_0, y_0, z_0 = holzer(x_0, y_0, z_0, abs(a_2), abs(b_2), abs(c_2))
elif sign(a) == sign(c):
x_0, z_0, y_0 = holzer(x_0, z_0, y_0, abs(a_2), abs(c_2), abs(b_2))
else:
y_0, z_0, x_0 = holzer(y_0, z_0, x_0, abs(b_2), abs(c_2), abs(a_2))
x_0 = reconstruct(b_1, c_1, x_0)
y_0 = reconstruct(a_1, c_1, y_0)
z_0 = reconstruct(a_1, b_1, z_0)
l = ilcm(a_0, ilcm(b_0, c_0))
x_0 = abs(x_0*l//a_0)
y_0 = abs(y_0*l//b_0)
z_0 = abs(z_0*l//c_0)
return simplified(x_0, y_0, z_0)
def square_factor(a):
"""
Returns an integer `c` s.t. `a = c^2k, \ c,k \in Z`. Here `k` is square free.
Examples
========
>>> from sympy.solvers.diophantine import square_factor
>>> square_factor(24)
2
>>> square_factor(36)
6
>>> square_factor(1)
1
"""
f = factorint(abs(a))
c = 1
for p, e in f.items():
c = c * p**(e//2)
return c
def pairwise_prime(a, b, c):
"""
Transform `ax^2 + by^2 + cz^2 = 0` into an equation `a'x^2 + b'y^2 + c'z^2 = 0`
where `a', b', c'` are pairwise prime. Returns a tuple containing `a', b', c'`. `gcd(a, b, c)`
should equal `1` for this to work. The solutions for `ax^2 + by^2 + cz^2 = 0` can be recovered
from the solutions of the latter equation.
Examples
========
>>> from sympy.solvers.diophantine import pairwise_prime
>>> pairwise_prime(6, 15, 10)
(5, 2, 3)
See Also
========
make_prime(), reocnstruct()
"""
a, b, c = make_prime(a, b, c)
b, c, a = make_prime(b, c, a)
c, a, b = make_prime(c, a, b)
return a, b, c
def make_prime(a, b, c):
"""
Transform the equation `ax^2 + by^2 + cz^2 = 0` to an equation
`a'x^2 + b'y^2 + c'z^2 = 0` with `gcd(a', b') = 1`. Returns the
tuple `(a', b', c')`. Note that in the returned tuple `gcd(a', c')` and
`gcd(b', c')` can take any value.
Examples
========
>>> from sympy.solvers.diophantine import make_prime
>>> make_prime(4, 2, 7)
(2, 1, 14)
See Also
========
pairwaise_prime(), reconstruct()
"""
g = igcd(a, b)
if g != 1:
f = factorint(g)
for p, e in f.items():
a = a // p**e
b = b // p**e
if e % 2 == 1:
c = p*c
return a, b, c
def reconstruct(a, b, z):
"""
Reconstruct the `z` value of a solution of `ax^2 + by^2 + cz^2` from
the `z` value of a solution of an equation which is a transformed form of the
above equation.
"""
g = igcd(a, b)
if g != 1:
f = factorint(g)
for p, e in f.items():
if e %2 == 0:
z = z*p**(e//2)
else:
z = z*p**((e//2)+1)
return z
def ldescent(A, B):
"""
Uses Lagrange's method to find a non trivial solution to `w^2 = Ax^2 + By^2` where
`A \\neq 0` and `B \\neq 0` and `A` and `B` are square free. Output a tuple
`(w_0, x_0, y_0)` which is a solution to the above equation.
Examples
========
>>> from sympy.solvers.diophantine import ldescent
>>> ldescent(1, 1) # w^2 = x^2 + y^2
(1, 1, 0)
>>> ldescent(4, -7) # w^2 = 4x^2 - 7y^2
(2, -1, 0)
This means that `x = -1, y = 0` and `w = 2` is a solution to the equation `w^2 = 4x^2 - 7y^2`
>>> ldescent(5, -1) # w^2 = 5x^2 - y^2
(2, 1, -1)
References
==========
.. [1] The algorithmic resolution of Diophantine equations, Nigel P. Smart,
London Mathematical Society Student Texts 41, Cambridge University Press, Cambridge, 1998.
.. [2] Efficient Solution of Rational Conices, J. E. Cremona and D. Rusin, Mathematics of Computation,
Volume 00, Number 0.
"""
if abs(A) > abs(B):
w, y, x = ldescent(B, A)
return w, x, y
if A == 1:
return (S.One, S.One, 0)
if B == 1:
return (S.One, 0, S.One)
r = sqrt_mod(A, B)
Q = (r**2 - A) // B
if Q == 0:
B_0 = 1
d = 0
else:
div = divisors(Q)
B_0 = None
for i in div:
if isinstance(sqrt(abs(Q) // i), Integer):
B_0, d = sign(Q)*i, sqrt(abs(Q) // i)
break
if B_0 != None:
W, X, Y = ldescent(A, B_0)
return simplified((-A*X + r*W), (r*X - W), Y*(B_0*d))
# In this module Descent will always be called with inputs which have solutions.
def descent(A, B):
"""
Lagrange's `descent()` with lattice-reduction to find solutions to `x^2 = Ay^2 + Bz^2`.
Here `A` and `B` should be square free and pairwise prime. Always should be called with
``A`` and ``B`` so that the above equation has solutions. This is more faster than
the normal Lagrange's descent algorithm because the gaussian reduction is used.
Examples
========
>>> from sympy.solvers.diophantine import descent
>>> descent(3, 1) # x**2 = 3*y**2 + z**2
(1, 0, 1)
`(x, y, z) = (1, 0, 1)` is a solution to the above equation.
>>> descent(41, -113)
(-16, -3, 1)
References
==========
.. [1] Efficient Solution of Rational Conices, J. E. Cremona and D. Rusin, Mathematics of Computation,
Volume 00, Number 0.
"""
if abs(A) > abs(B):
x, y, z = descent(B, A)
return x, z, y
if B == 1:
return (1, 0, 1)
if A == 1:
return (1, 1, 0)
if B == -1:
return (None, None, None)
if B == -A:
return (0, 1, 1)
if B == A:
x, z, y = descent(-1, A)
return (A*y, z, x)
w = sqrt_mod(A, B)
x_0, z_0 = gaussian_reduce(w, A, B)
t = (x_0**2 - A*z_0**2) // B
t_2 = square_factor(t)
t_1 = t // t_2**2
x_1, z_1, y_1 = descent(A, t_1)
return simplified(x_0*x_1 + A*z_0*z_1, z_0*x_1 + x_0*z_1, t_1*t_2*y_1)
def gaussian_reduce(w, a, b):
"""
Returns a reduced solution `(x, z)` to the congruence `X^2 - aZ^2 \equiv 0 \ (mod \ b)`
so that `x^2 + |a|z^2` is minimal.
Details
=======
Here ``w`` is a solution of the congruence `x^2 \equiv a \ (mod \ b)`
References
==========
.. [1] Gaussian lattice Reduction [online]. Available: http://home.ie.cuhk.edu.hk/~wkshum/wordpress/?p=404
.. [2] Efficient Solution of Rational Conices, J. E. Cremona and D. Rusin, Mathematics of Computation,
Volume 00, Number 0.
"""
u = (0, 1)
v = (1, 0)
if dot(u, v, w, a, b) < 0:
v = (-v[0], -v[1])
if norm(u, w, a, b) < norm(v, w, a, b):
u, v = v, u
while norm(u, w, a, b) > norm(v, w, a, b):
k = dot(u, v, w, a, b) // dot(v, v, w, a, b)
u, v = v, (u[0]- k*v[0], u[1]- k*v[1])
u, v = v, u
if dot(u, v, w, a, b) < dot(v, v, w, a, b)/2 or norm((u[0]-v[0], u[1]-v[1]), w, a, b) > norm(v, w, a, b):
c = v
else:
c = (u[0] - v[0], u[1] - v[1])
return c[0]*w + b*c[1], c[0]
def dot(u, v, w, a, b):
"""
Returns a special dot product of the vectors `u = (u_{1}, u_{2})` and `v = (v_{1}, v_{2})`
which is defined in order to reduce solution of the congruence equation `X^2 - aZ^2 \equiv 0 \ (mod \ b)`.
"""
u_1, u_2 = u[:2]
v_1, v_2 = v[:2]
return (w*u_1 + b*u_2)*(w*v_1 + b*v_2) + abs(a)*u_1*v_1
def norm(u, w, a, b):
"""
Returns the norm of the vector `u = (u_{1}, u_{2})` under the dot product defined by
`u \cdot v = (wu_{1} + bu_{2})(w*v_{1} + bv_{2}) + |a|*u_{1}*v_{1}` where `u = (u_{1}, u_{2})`
and `v = (v_{1}, v_{2})`.
"""
u_1, u_2 = u[:2]
return sqrt(dot((u_1, u_2), (u_1, u_2), w, a, b))
def holzer(x_0, y_0, z_0, a, b, c):
"""
Simplify the solution `(x_{0}, y_{0}, z_{0})` of the equation `ax^2 + by^2 = cz^2`
with `a, b, c > 0` and `z_{0}^2 \geq \mid ab \mid` to a new reduced solution such that
`z^2 \leq \mid ab \mid`.
"""
while z_0 > sqrt(a*b):
if c % 2 == 0:
k = c // 2
u_0, v_0 = base_solution_linear(k, y_0, -x_0)
else:
k = 2*c
u_0, v_0 = base_solution_linear(c, y_0, -x_0)
w = -(a*u_0*x_0 + b*v_0*y_0) // (c*z_0)
if c % 2 == 1:
if w % 2 != (a*u_0 + b*v_0) % 2:
w = w + 1
x = (x_0*(a*u_0**2 + b*v_0**2 + c*w**2) - 2*u_0*(a*u_0*x_0 + b*v_0*y_0 + c*w*z_0)) // k
y = (y_0*(a*u_0**2 + b*v_0**2 + c*w**2) - 2*v_0*(a*u_0*x_0 + b*v_0*y_0 + c*w*z_0)) // k
z = (z_0*(a*u_0**2 + b*v_0**2 + c*w**2) - 2*w*(a*u_0*x_0 + b*v_0*y_0 + c*w*z_0)) // k
x_0, y_0, z_0 = x, y, z
return x_0, y_0, z_0
|
import random
computer_number = random.randint(1, 10)
win = 0
while win != 1:
input_value = int(input('Imput your guss: '))
if input_value == computer_number:
print('Congratulations! You have win the prize! Your guess is correct!!!')
win = 1
elif input_value < computer_number:
print('Try again! Your number less then computer guss...')
elif input_value > computer_number:
print('Try again... this time your number is greater...')
else:
print('You have to enter number...')
|
class PQ:
class Node:
def __init__(self, ele, parent = None, left = None, right = None):
self._data = ele
self._p = parent
self._l = left
self._r = right
def __init__(self):
self._root = None
self._size = 0
def fuck_merge(self,T2):
n1 = self._root
n2 = T2._root
while n2 and n1:
if n2._data > n1._data:
n1._l = nn
n2 = n2._l
def merge(self, T2):
n1 = self._root
n2 = T2._root
condition = False
if n1._data > n2._data:
condition = True
while n2 and n1:
if n2._data > n1._data:
next = n1._l
n1._l = n2
n1 = next
n2 = n2._l
else:
next = n2._l
n2._l = n1
n2 = next
n1 = n1._l
if condition:
if n1 != None:
p = T2._root
while p._l:
p = p._l
p._l = n1
self._root = T2._root
T2._root = None
else:
if n2 != None:
p = self._root
while p._l:
p = p._l
p._l = n2
T2._root = None
def insert(self, e):
Temp_T = PQ()
Temp_T._root = PQ.Node(e)
self.merge(Temp_T)
def extract_min(self):
LT = PQ()
LT._root = self._root._l
RT = PQ()
RT._root = self._root._r
LT.merge(RT)
self._root = LT._root
def flip(self,n):
n._l, n._r = n._r, n._l
def flip_left(self, n = None):
if n == None:
n = self._root
self.flip(n)
if self._l:
return self.flip_left(n = n._left)
#Just Call draw_tree on the root node and it will draw the tree
#Your node class must use ._l ._r and ._data
def subtree_size(node):
if node is None:
return 0
else:
return 1+subtree_size(node._l)+subtree_size(node._r)
def draw_tree(node,level=1,x=500,parx=None,pary=None):
XSEP=15
YSEP=30
fill(0)
textAlign(CENTER,CENTER)
textSize(15)
lsize=subtree_size(node._l)
myx,myy=x+lsize*XSEP,YSEP*level
text(str(node._data),myx,myy)
if node._l is not None:
draw_tree(node._l,level+1,x,myx,myy)
if node._r is not None:
draw_tree(node._r,level+1,x+(lsize+1)*XSEP,myx,myy)
if parx is not None:
strokeWeight(10)
stroke(0,255,0,30)
line(parx,pary,myx,myy)
def setup():
size(1000,1000)
def draw():
draw_tree(T1._root)
T1 = PQ()
T2 = PQ()
T1._root = PQ.Node(1)
T1._root._r = PQ.Node(8, T1._root)
T2._root = PQ.Node(2)
T2._root._r = PQ.Node(12, T2._root)
T2._root._l = PQ.Node(3, T2._root)
T1.merge(T2)
#T1.insert(10)
|
class PositionalList:
class Node:
__slots__ = ('_prev','_next','_data') #Saves space and stores data
def __init__(self, prev, data, nxt): #This is what Node looks like
self._prev = prev
self._next = nxt
self._data = data
class Position:
def __init__(self, node, lst):
self._node = node
self._list = lst
def element(self):
return self._node._data
def __init__(self):
self._len = 0
self._head = self.Node(None, None, None)
self._tail = self.Node(self._head,None,None)
self._head._next = self._tail #So now we have the empty list [X,X,Head]<->[Tail,X,X]
def _add_between(self, ln, rn, x): #Take the left and right node to know where to add between
nn = self.Node(ln,x,rn) #create new node
ln._next = nn
rn._prev = nn
def add_first(self,x): #Add after first element of list
self._add_between(self._head,self._head._next,x)
def add_last(self,x): #Add after last element of list
self._add_between(self._tail, self._tail._prev,x)
def add_before(self, p, x):
self._add_between(p._node._prev, p._node, x)
def add_after(self, p, x):
self._add_between(p._node, p._node._next, x)
def delete(self, p): #Define everything you want to change, give it a name
rn = p._node._next
ln = p._node._prev
mn = p._node
ln._next = rn
rn.prev = ln
mn._next = None
mn._prev = None #the node's arrows has been moved to None isolated, while the ln and rn are now connected
p._node = rn
def replace(self, p, x):
p._node._data = x
def first(self):
return self.Position(self._head._next,self)
def after(self, p):
np = self.Position(p._node._next, self) #Create the new position
if np._node == self._tail:
return None
else:
return np
def before(self, p):
np = self.Position(p._node._prev, self) #Create the new position
if np._node == self._head:
return None
else:
return np
def __iter__(self):
p = self.first()
while p:
yield (p.element())
p = self.after(p)
|
#crear ciclo for que permita ingresar n temperaturas donde n es un numero ingresado por teclado
#mostrar cuantas temperaturas estan por sobre cero y cuantas estan bajo o igual a cero.
sobrecero=0
bajocero=0
veces= int(input("Cuantas temperaturas quiere ingresar ? : "))
for i in range(veces):
tempe= float(input("Ingrese temperatura: "))
if (tempe>0):
sobrecero=sobrecero+1
else:
bajocero=bajocero+1
#mostrar datos
print("La cantidad de temperaturas mayores a cero es: " + str(sobrecero))
print("La cantidad de temperaturas menores o iguales a cero es: " + str(bajocero))
|
from db import Db
class Customer:
def __init__(self, first_name, last_name, phone, email,
address1, address2, postal_code, city, country,
customer_id=None, added_by=None):
self.first_name = first_name
self.last_name = last_name
self.phone = phone
self.email = email
self.address1 = address1
self.address2 = address2
self.postal_code = postal_code
self.city = city
self.country = country
self.customer_id = customer_id
self.added_by = added_by
def save(self):
'''If self has been populated by database data - UPDATE.
Otherwise - INSERT a new record.'''
db = Db()
if self.customer_id != None:
query = 'UPDATE customer SET first_name = ?, last_name = ?, phone = ?, email = ?, address1 = ?, address2 = ?, postal_code = ?, city = ?, country = ?, added_by = ? WHERE customer_id = ?'
data = (self.first_name, self.last_name, self.phone, self.email,self.address1, self.address2, self.postal_code, self.city, self.country, self.added_by, self.customer_id)
else:
query = 'INSERT INTO customer(first_name, last_name, phone, email, address1, address2, postal_code, city, country) VALUES(?,?,?,?,?,?,?,?,?)'
data = (self.first_name, self.last_name, self.phone, self.email, self.address1, self.address2, self.postal_code, self.city, self.country)
db.execute(query, data)
db.commit()
def build_from_row(row):
if row is None:
return None
customer = Customer(row[0], row[1], row[2], row[3], row[4],
row[5], row[6], row[7], row[8], row[9])
if len(row) >= 11:
customer.customer_id = row[9]
customer.added_by = row[10]
return customer
# Note: this is a CLASS function (no self!)
def get(customer_id):
'''Get a single Customer object that corresponds to the customer id.
If none found, return None.'''
query = 'select first_name, last_name, phone, email, address1, address2, postal_code, city, country, customer_id, added_by from customer where customer_id = ?'
db = Db()
db.execute(query,(customer_id,))
row = db.fetchone()
if row is None:
return None
return Customer.build_from_row(row)
# Note: this is a CLASS function (no self!)
def get_all():
'''Get a list of Customer objects - one for each row in the
relevant table in the database.'''
db = Db()
db.execute('select first_name, last_name, phone, email, address1, address2, postal_code, city, country, customer_id, added_by from customer')
rows = db.fetchall()
cust_obj_list = []
for row in rows:
cust_obj_list.append(Customer.build_from_row(row))
return cust_obj_list
|
from sign import Sign
class Board:
''' generic board of 3X3 which can represent a classic tic tac toe board
and also a board made of other boards which used in super tic tac toe '''
def __init__(self, empty_square_generator):
'''function builds new board
empty_square_generator -- function with no parameters which returns the representation of square in the board
(can be a sign (X/O/-) or a board itself etc) and returns an empty board'''
# initialize empty board
self.__winner = Sign.E # winner hasn't charged yet
self.__squares = [0,0,0] # 3 rows
self.__squares[0] = [empty_square_generator(), empty_square_generator(), empty_square_generator()]
self.__squares[1] = [empty_square_generator(), empty_square_generator(), empty_square_generator()]
self.__squares[2] = [empty_square_generator(), empty_square_generator(), empty_square_generator()]
def get_from_board(self, indices:tuple):
return self.__squares[indices[1]][indices[0]]
def insert(self, indices: tuple , add):
x = indices[0]
y = indices[1]
self.__squares[y][x] = add
x = indices[1]
y = indices[0]
# check whether this move lead to winning:
# check if previous move caused a win on vertical line
if not self.__squares[0][y] == Sign.E and self.__squares[0][y] == self.__squares[1][y] == self.__squares [2][y]:
self.__winner = add
# check if previous move caused a win on horizontal line
if not self.__squares[x][0] == Sign.E and self.__squares[x][0] == self.__squares[x][1] == self.__squares [x][2]:
self.__winner = add
# check if previous move was on the main diagonal and caused a win
if x == y and not self.__squares[0][0] == Sign.E and self.__squares[0][0] == self.__squares[1][1] == self.__squares [2][2]:
self.__winner = add
# check if previous move was on the secondary diagonal and caused a win
if x + y == 2 and not self.__squares[0][2] == Sign.E and self.__squares[0][2] == self.__squares[1][1] == self.__squares [2][0]:
self.__winner = add
def get_winner(self):
return self.__winner
def is_active(self)->bool:
return self.get_winner() == Sign.E
def __str__(self):
res = ''
for i in self.__squares:
res += str(i)
res += '\n'
return res
def set_winner(self, winner:Sign):
self.__winner = winner
def __repr__(self):
return str(self)
# todo improve str method so it will print properly the board made of boards
|
"""
Given a tuple of numbers, iterate through it and print only those
numbers which are divisible by 5
"""
myTuple = (5, 6, 20, 33, 45, 62)
print("Given list is ", myTuple)
for element in myTuple:
if (element % 5 == 0):
print (element)
|
import bike_db_access
import kiosk_db_access
import datetime
# Handles most of the logic of the bike rental program Bikes can be checked out
# from a kiosk if the kiosk is not empty. Bikes can be returned to a kiosk if
# the kiosk is not full. Bikes can also be in transit, meaning that the bike is
# not at any kiosk
# check out a bike from a kiosk. If there are no bikes available at the kiosk
# it prints out a message to that effect
# otherwise, it checks out the first bike in the list returned by
# BikeDBAccess.retrieveByKiosk by setting that bike's atKiosk value to 'N'
# and writing that change to the database
def do_checkout():
print("Enter the kiosk id where you want a bike")
kiosk_id = input()
print("Checking availability of kiosk "+kiosk_id+ "...\n")
getAvailability = bike_db_access.num_bikes_at_kiosk(kiosk_id)
if(getAvailability > 0):
print("Bikes found at this kiosk")
available = bike_db_access.bike_checkout(kiosk_id)
print("Displaying available bikes at kiosk "+str(kiosk_id)+"\n")
for bike in available:
print("Bike Id: {} \tModel: {} \tCurrent Kiosk: {} \tTime Arrived: {}".format(bike.bikeID, bike.model, bike.currentKioskID, bike.timeArrived ))
print("\nPlease enter the bikeID that you would like to checkout from the list above")
bike_id = input()
kiosk = bike_db_access.retrieve_by_kiosk(kiosk_id, bike_id)
if(kiosk):
print("You have successfully checked out bike# "+ str(bike_id))
else:
print("You have entered a bike ID that does not exist at this kiosk. Please try again.")
else:
print("No available bikes at this kiosk")
# fill in the rest of the code
# return a bike to a kiosk. If the kiosk is full, it prints out a message
# otherwise, it asks the user for the bike id. If the bike is not in the system
# it prints out an error message. If the bike is already checked in, it also
# prints out an error message. Otherwise it sets the bike's current kiosk id to
# the current kiosk, its time of arrival value to the current date and time
# and its at_kiosk value to 'Y'. It then writes those changes to the database
def do_return():
print("Enter the kiosk id")
kid = input()
kiosk = kiosk_db_access.retrieve_by_kiosk(kid)
num_bikes = bike_db_access.num_bikes_at_kiosk(kid)
if num_bikes == kiosk.maxcapacity:
print("This kiosk is full. You must find another")
else:
print("Enter the bike id")
bike_id = input()
bike = bike_db_access.retrieve_by_id(bike_id)
if bike is None:
print("That bike is not in our system")
return
if (bike.atKiosk == 'Y'):
print("This bike is already checked in")
return
result = bike_db_access.update(bike.bikeID, bike.model, kid, datetime.datetime.now(), 'Y')
if result:
print("Bike #{} was returned to kiosk {} at time {}".format(bike.bikeID,kid, datetime.datetime.now()))
else:
print("There was an error returning this bike")
# this reads the kiosk id from the user and
# prints out the number of bikes that are currently
# at the kiosk and checked in (at_kiosk = 'Y')
def list_number():
print("Enter the kiosk id")
kid = input()
result = kiosk_db_access.getBikeCountByKiosk(kid)
if (result >= 1):
print("Total number of bikes at kiosk: "+str(kid)+" is: "+str(result))
else:
print("No bikes available at this kiosk")
# fill in the rest of the code
# hint - use a query that returns the count rather than
# retrieving bike records and counting them in Python
# more efficient if there are lots of records
# this gets the bike id from the user and prints out its kiosk
# if it is checked in and a message that it is in transit if
# it is not currently checked in
def get_location():
print("Enter the bike id")
bike_id = input()
location = bike_db_access.getBikeLocation(bike_id)
status = (location.atKiosk)
if (status == 'y'):
print("\nBike available at kiosk "+ str(location.currentKioskID) + "\nThe location of this bike is:")
print(location.addr1 +" "+ location.addr2)
print(location.city + " "+location.stat + " " + location.zip)
else:
print('In transit')
# fill in the rest of the code
# this gets a kiosk id from the user and prints out a report with
# full information on the kiosk and each bike checked into the kiosk
# the bikes are sorted by id
def show_report():
print("Enter the kiosk id")
kiosk_id = input ()
kiosk = kiosk_db_access.retrieve_by_kiosk(kiosk_id)
if (kiosk is None):
print("This kiosk is not in the system")
return
print("Report for kiosk {}".format(kiosk_id))
print("Location: {} {} {}".format(kiosk.addr1, kiosk.city, kiosk.stat))
print("Current date and time "+ str(datetime.datetime.now()))
bikes = bike_db_access.showReport(kiosk_id)
if len(bikes) == 0:
print("There are currently no bikes at this kiosk")
else:
sorted(bikes,key=lambda bike:bike.bikeID)
for bike in bikes:
print("bike id: {} \tModel: {} \ttime arrived: {}".format(bike.bikeID, bike.model,bike.timeArrived ))
print("Welcome to the Bike Kiosk Manager")
print("Enter C to checkout a bike, R to return a bike, N to find out the number of bikes at a kiosk, L to find the current location of a bike, S to show the report, Q to quit")
cmd = input()
while cmd != 'Q':
if cmd == 'C':
do_checkout()
if cmd == 'R':
do_return()
if cmd == 'N':
list_number()
if cmd == 'L':
get_location()
if cmd == 'S':
show_report()
print("\nEnter C to checkout a bike, R to return a bike, N to find out the number of bikes at a kiosk, L to find the current location of a bike, S to show the report, Q to quit")
cmd = input()
print("Bye!")
|
# Program 2: Vypocet faktorialu (rekurzivne)
#navratova hodnota 0
def factorial(n):
if n < 2:
result = 1
else:
# else cast prikazu vetveni, jednoradkovy komentar, negeneruje DEDENT
decremented_n = n - 1
temp_result = factorial(decremented_n)
result = n * temp_result
return result
# end of factorial function
# Hlavni telo programu
print('Zadejte cislo pro vypocet faktorialu: ')
a = inputi()
if a < 0.0: # pred porovnanim probehne implicitni konverze int na float
print('Faktorial nelze spocitat')
else:
vysl = factorial(a)
print('Vysledek je:', vysl)
|
class Circle():
# class object attribute
pi = 3.14
# user defined attribute
def __init__(self,radius = 1):
self.radius = radius
# method
def circumference(self):
cir = 2 * Circle.pi * self.radius # you can call pi using class because this is class object attribute
print(f'The circumference of circle having radius {self.radius} : {cir}')
def area(self):
are = self.pi * (self.radius ** 2)
print(f'The area of circle having radius {self.radius} : {are}')
r = float(input('Enter the radius of the circle : '))
cir = Circle(r)
cir.circumference()
cir.area()
|
# Inheritance can be defined as the process where one class acquires the properties (methods and fields) of another
class Animal(): # perent class
def __init__(self):
print('Animal created !!')
def eat(self):
print('I eat grass.')
# Ani = Animal()
# Ani.eat()
class Dog(Animal): # this our child class and
# we want the charectarestic of perent class
# Also see in child class.
def __init__(self):
Animal.__init__(self) # we inherited the Animal class in Dog class
print('Dog created!!')
# overwritting a method
def eat(self):
print('Dog love bones !!')
def bark(self): #new Method for Dog class.
print('Woof !!')
dg = Dog()
dg.eat()
dg.bark()
|
# How to use python in a console:
# python can be executed directly from the command line using "py" or "python"
# when wanting to exit python, use exit()
# How to run python programs:
# py "PATH TO PROGRAM.py"
# How Python works:
# Python is an Interpreter based language.
# Python Code -> Interpreter -> Machine Code
# Indentation:
# The number of spaces depends on the programmer but has to be at least 1.
# It also has to be consistent throughout the same block of code to make
# Python happy.
# Or if you want to keep your sanity, use the same Indentation
# throughout your whole program, and always use 4 spaces.
print("Python uses Indentation to indicate a block of code")
if (True):
print("Hi") # This is an Indentation of 1 space
if (True):
print("Hi again") # 4 spaces Indentation
if (True == True):
print("True is true")
elif (True == False):
print("True is false?!")
else:
print("Neither true nor false?!")
# Comments:
# Python lets you write comments with #
# Comments can be used to explain a program or they can be used to prevent
# code from executing.
print("Hello World")
# print("Hello Wolf")
# Variables:
# Naming a variable must follow some rules:
# 1. variables have to start with a letter or an underscore character
# 2. variables can only contain A-z, 0-9 and underscores _
# According to PEP8, which is a popular collection of guidelines to make code
# more readable, and which is followed by many programmers worldwide,
# variables should be in snake_case (all lowercase letters with underscores).
# In Python, variables are created when you assign a value to them.
# Python internally does two things: create an object (everything in python
# is an object) with a value, and assign the variable to reference the ID
# where the object is (similar to a pointer in C/C++).
# Unlike in C or other languages, you can not declare a variable without
# a value.
# Python automatically determines the type of the variable.
# Variables are case sensitive, meaning x != X (!= means does not equal)
x = 5
X = 6
print(x, X) # Output: 5 6
# Multiple variables can be declared in one line
a, b, c = 1, 2, 3
print(a, b, c)
# Or multiple variables with the same value can be created
d = e = f = 4
print(d, e, f)
# Good to know: Python caches numbers between -5 and 256 to prevent those
# numbers from being generated over and over again. TLDR:
# python identity "is" means pointing to the same object,
# but python equality "==" means same value, but it does not need to be the
# same object.
a = b = 557
if a is b:
print("Same ID for a and b")
c = 556
c += 1
if c is b:
print("c is also the same ID")
elif c == b:
print("c is not the same object as b, but has the same value")
else:
print("Wait, this shouldn't happen, oops.")
# Unpacking a collection of values in a list, touple, etc.
fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x, y, z, sep=", ")
# While we're at it:
# Touples touple_ = ('v1', 'v2', 'v3')
# Lists list_ = ['v1', 'v2', 'v3']
# But more later.
# Variables can change their type after they have been set
print("For x = 5, x is:", x, "and of type:", type(x))
x = "now in HD"
print("For x = \"now in HD\", x is:", x, "and of type:", type(x))
# Variable Casting means changing the type of a variable and can be done with
# <type>(<variable>). You can get the type of a variable with type(<var>).
x = 2
print("For x = 2, x is:", x, "and of type:", type(x))
x = str(2)
print("For x = str(2), x is:", x, "and of type:", type(x))
print("When casting without assigning a new value to x with int(x),\n",
"int(x) is:", int(x), "and of type:", type(int(x)))
print("But x is still:", x, "and of type:", type(x))
# Single or double quotes both work for strings.
# You can use the + operator to concatenate (connect) strings the same way you
# can use operators to do calculations with numbers:
a, b, c = "Hello", ", ", "World!"
print(a + b + c)
a = a + b + c
print(a)
# Output for both: Hello, World!
# But you can't use the - operator to remove a part of a string.
# And you can not add a number to a string.
# Global vs Local Space:
# Variables that are created outside of functions are global.
# This means they are accessible by all functions
# Whereas local variables override global variables but only inside
# the function where they are called.
x = 1
def func1():
"""Set the value of a local variable x to 2 and print x"""
x = 10
print(x)
def func2():
"""Print the global variable x if it exists"""
if 'x' in globals():
print(x)
else:
print("Could not find a global variable x")
#another solution:
def func3():
"""Print a variable x without checking if it exists but catch the error
to prevent the program from crashing and create a global variable x.
"""
try:
print(x)
except BaseException as e:
print(e)
func1()
func2()
func3()
del(x)
func1()
func2()
func3()
# you can change global variables inside functions:
x = 1
def func4():
"""Change the value of the global variable x"""
global x
x = 2
func2() # 1
func4() # change x to 2 globally
func2() # 2
# Datatypes:
# Python has a few built-in datatypes:
# Text:
# str
# Anything between single or double quotes
"""strings in python are arrays of bytes representing unicode characters,
like in C or other popular programming languages.
Python does not have a NULL character to terminate the string. In fact,
string objects in python are immutable (meaning they can not be changed),
so in order to do anything, a new object needs to be created.
PYTHON IS WEIRD.
"""
s = "hello"
s = 'hello'
mults = """Multiline strings can also be created using triple quotes.
In this case the line breaks are at the same position as the line breaks
in the code."""
# Numeric:
# int
# Any whole number, positive or negative
"""The default type of int depends on your processor architecture.
Python automatically converts the integer type in the background
to prevent overflow errors.
32bit architecture: Int32
64bit architecture: Int64
Here's a recap for min and max values for different integer types:
Int8: [
-128,
127]
Int16: [
-32768,
32767]
Int32: [
-2147483648,
2147483647]
Int64: [
-9223372036854775808,
9223372036854775807]
Int128: [
-170141183460469231731687303715884105728,
170141183460469231731687303715884105727]
And the unsigned integers:
UInt8: [
0,
255]
UInt16: [
0,
65535]
UInt32: [
0,
4294967295]
UInt64: [
0,
18446744073709551615]
UInt128: [
0,
340282366920938463463374607431768211455]
the command type() will always return "int" however.
In other languages you can use:
Int16 = short
Int32 = int
Int64 = long
Int128 = long long
"""
i = 1
i = 2
# float
# Any number with a decimal point or written in scientific notation
# scientific notation: e = power of 10, example: 2e2 = 2 * (10*10) = 200
"""
Python also handles floats differently than some other programming languages.
What Python calls float would be a double in C or Java.
More specifically, this is called float64.
But unlike int64, float64 does not mean you get 64 bits to play with.
float64: 11 bits exponent + 52 bits mantissa + 1 bit sign = 64 bit
BUUUUT things get weird and complicated fast beyond that.
And with that I mean I don't understand it much.
Here's what I found:
float = 4 byte = 32bit
double = 8 byte = 64bit = float64 in Python
long double = 10 byte = 80bit = float96/float128 in Python
long doubles are also called extended doubles, and are not always standard.
For example, float128 does not exist on some Windows machines.
There seem to be some errors that some people run into regarding this.
Best to keep this in mind to stick with regular floats,
don't try to typecast (convert the type) manually to float128,
and let Python handle the rest automatically.
Bonus fact to make things even more weird and confusing with floats:
This is more along the lines of processor architecture, so you definitely
don't need to know this, but sometimes, not always, in the mantissa of a float,
the leading first bit is dropped because it's a 1 for any non-zero value.
This increases the precision because it gives you a whole extra bit
to work with, but you have to keep in mind that there should be a 1
before the number. x87 extended precision does not follow this.
"""
f = 1.0
f = 2e2
# complex
# complex numbers with two parts: real and imaginary.
# the j indicates the imaginary part of the number.
# will not explain complex numbers here. See Math part for specifics.
c = 1j
c = 2+1j
# For all numeric data types, +, -, * and / work.
# You can typecast (convert) between the data types and also do operations
# across different data types. Python will then use the stronger data type
# for the output to prevent loss of precision.
# For example: 1 + 2 = 3 (type int) but 1 + 2.0 = 3.0 (type float)
"""
There are many more operations you can do of course. You can round floats,
truncate (aka. "cut") them, use advanced math functions,
or you could print a formatted version while keeping the precision of a float.
All of this will be handled later.
"""
# Sequence:
# list
list_ = [1, 2.0, "apple"]
# touple
touple_ = ("1", "2",)
# range
range_ = range(0,6,2)
# Mapping:
# dict
dictionary_ = {"name": "John", "age": 36}
# Set:
# set
set_ = {"name", "age", "number"}
# frozenset
frozenset_ = frozenset({"name", "age", "number"})
# Boolean:
# bool
true_ = True
# Binary:
# bytes
bytes_ = b"hello"
# bytearray
bytearray_ = bytearray(5)
# memoryview
memoryview_ = memoryview(bytes(5))
# As mentioned previously, the data type can be viewed with type(<var>)
# Something to note:
# Python defaults to lists over arrays, but lists require more space than
# C arrays, because objects need to be constructed for each included item.
list1 = [1,2,3]
print(type(list1))
# Because there's more than enough space and lists are nicer to work with
# than arrays, I'll leave it at this note. But there's a thin wrapper that
# can create a C-style array if it's really necessary, but needs to be imported
# before use.
# In C, an array is a consecutive block of memory assigned/allocated for easy
# data access and manipulation. C arrays are not dynamic,
# but they can be dynamically allocated and reallocated using functions.
# String operations:
# Strings are arrays and can be accessed as such
s = "abc"
print(s[0], s[1], s[2])
# You can loop through a string with:
for char_ in s:
print(char_, end='')
print() # new line
# the length of a string can be accessed with len():
print(len(s))
# or calculated manually using the above method:
s_count = 0
for char_ in s:
s_count += 1
print(s_count)
# to check if something is contained in a string we can use the keyword "in":
if "d" in s:
print("yup, there's a \"d\" in the string s:", s)
elif "a" in s:
print("yup, there's an \"a\" in the string s, but no \"d\":", s)
else:
print("This shouldn't happen")
# you can also use the keyword not to check for something not being present:
if "d" not in s:
print("Told you there was no \"d\"")
else:
print("Where did that \"d\" come from?")
# Note: at this point I'm starting to get really frustrated from constantly
# having to escape my double quotes and I'm seriously considering switching to
# single quotes for my strings because those would be a lot faster anyway.
# EITHER WAY:
# string slicing:
# you can return or check a range of characters by using a range:
# [start:end(not included):step]
s = 'hello, world!'
print(s[0:5])
# you can do silly things with this:
s = 'tacocat'
print(s) # print s
print(s[::-1]) # print s backwards
print(s[::2]) # only print every second character of s
# You can use negative indexing to start counting from the back:
print(s[:4], s[4:], 'backwards is spelled', s[:-4:-1], s[-4::-1])
s = '1234567'
print(s[:4], s[4:], 'backwards is spelled', s[:-4:-1], s[-4::-1])
# note this only works for strings so:
# i = 1234567
# print(i[0:3])
# does not execute, but typecasting might work in some cases for this:
i = 1234567
print(str(i)[0:3])
a = ' hi hoLLO'
print(a)
# strip removes leading and trailing whitespace
a = a.strip()
print(a)
# uppercase and lowercase operations are built into python:
# along with a whole array of other string related operations:
print(a.upper())
print(a.lower())
print(a.capitalize())
print(a.casefold())
# replace replaces something in a string:
a = a.replace("hi", "Hello,")
a = a.replace("hoLLO", "World!")
print(a)
# split string returns a list with a specified separator:
a1, a2 = a.split()
print(a.split())
print("a1:", a1, "a2:", a2)
# strings can be concatenated (think i mentioned that before)
b = a1 + " " + a2
print(b)
# String formatting:
# as mentioned somewhere before, strings and numbers can't be concatenated.
# another method than typecasting is to format something into a string:
age = 30 # or any user input
txt = 'Hello, I am {} years old'
# do things
print(txt.format(age))
# this can also take multiple inputs:
item_ = {"id": 122, "name": "Valve Index", "price": 999.00, "instock": 2}
quantity_ = 3
order_ = "Hello, I want to buy {0} of the item {1} for the total price of {2}"
print(order_.format(quantity_, item_["name"], (quantity_*item_["price"])))
if(item_["instock"] >= quantity_):
print("Your order can be completed.",
"Proceed to checkout or continue shopping?")
else:
print(("We can only offer {0} of the item {1} for a total price of {2}")
.format(item_["instock"], item_["name"],
(item_["instock"]*item_["price"])))
print("Would you like to change your order?")
# you can use numbers for the positions or you can use identifiers,
# or you can just use empty placeholders.
amt = 5
txt = "{amount} Pcs For Only ${price:.2f}! {}!"
print(txt.format("What a steal", price = 2.990, amount = amt))
# you can also use funny little smiley faces to format the placeholders
# https://www.w3schools.com/python/ref_string_format.asp for more information.
txt = ("{:<8}\n" # left aligned with a space of 8
+ "{:>8}\n" # right aligned with a space of 8
+ "{:^8}\n" # centered with a space of 8
+ "{:=8}\n" # places sign on the left
+ "{:+8}\n" # uses a +/- sign for positive/negative
+ "{:-8}\n" # uses a - sign for negative only (positive without sign)
+ "{: 8}\n" # uses a space for pos or minus for negative
+ "{:,}\n" # uses a comma for thousand separator
+ "{:_}\n" # uses a underscore for thousand spearator
+ "{:b}\n" # binary format
+ "{:c}\n" # converts value to corresponding unicode character
+ "{:d}\n" # decimal format
+ "{:e}\n" # scientific format, lowercase e
+ "{:E}\n" # scientific format, uppercase E
+ "{:f}\n" # fix/float point number, in lowercase (inf/nan)
+ "{:F}\n" # fix/float point number, but in uppercase (INF/NAN)
+ "{:g}\n" # general format
+ "{:G}\n" # general format, uppercase for scientific notation E
+ "{:o}\n" # octal format
+ "{:x}\n" # hex format, lowercase
+ "{:X}\n" # hex format, uppercase
+ "{:n}\n" # number format
+ "{:%}" # percentage format
)
# print(txt.format(100,200,300,-400,500,600,700,800,900,1000,
# 1100,1200,1300,1400,1500,1600,1700,1800,1900,2000,
# 2100,2200,2300))
# Escape characters:
# The backslash is used to escape some characters with special functions
# for example an escaped \" is considered as a string character instead of
# part of the code (to close the string).
# \n = new line
# \r = carriage return
# \t = tab
# \b = backspace
# \f = form feed
# \ooo = octal value
# \xhh = hex value
# string operations should have their own chapter, i should have known
# that this gets complicated.
# a number of string operations can be found
# at https://www.w3schools.com/python/python_strings_methods.asp
# Booleans:
# Booleans are either True or False
# They are the result of comparisons, or can be returned by functions,
# or they can be evaluated in other ways.
# most Values when evaluated will return True.
# None, 0, or empty Values like empty strings will return False.
# Operators:
# Operators are used to perform operations on variables and values
# Arithmetic:
(1 + 1) # Addition
(1 - 1) # Subtraction
(1 * 1) # Multiplication
(1 / 1) # Division
(1 % 1) # Modulus (returns the rest of a floor division 16 % 5 = 1)
(1 // 1) # Floor division (any flat division 16 // 5 = 3)
(1 ** 1) # Exponentiation (x to the power of y, like 3 ** 2 = 3² = 3 * 3 = 9)
# Bitwise Operations:
# a little harder to wrap your head around but:
a = 50 # 0011 0010
b = 25 # 0001 1001
c = 75 # 0100 1011
# the bin() function will give you the binary representation of
# what it contains, without leading zeroes, and with an identifier that
# it's a binary number (0b) before the number.
print(bin(a)) # output: 0b110010
# another way to print binary is to use the string format function
print("{:b}".format(a).rjust(8,"0")) # output: 00110010
# x >> y shifts x's bits to the right y times, dropping the rightmost bit and
# filling with zeroes from the left.
# NOT the same as x // (2**y), but behaves similarly in a margin.
50 >> 1 # 0001 1001
# x << y shifts bits to the left y times filling the rightmost bit with y.
# again, behaves similarly to x * (2**y) in a margin.
50 << 1 # 0110 0100
print(bin(50 << 1))
# Assignment:
x = 1 # Assign the value to the variable
x += 1 # Add 1 to the variable x, same as x = x + 1
x -= 1 # Subtract 1 from the variable x, same as x = x - 1
x *= 1 # multiply x by value and assign
x /= 1 # divide x by value and assign
x %= 1 # modulo of x by value
x //= 1 # floor division of x by value
x **= 1 # x to exponent of 1
#
|
"""To Define Methods"""
# def num_sum():
# print(3 + 2)
# num_sum()
#
# """With Argument"""
# def sum_num(n1 , n2):
# print (n1 + n2)
#
# sum_num(3,4)
#
# """Return Value"""
# def sum_num(n1,n2):
# """Get some of two numbers
# :param n1:
# :param n2:
# :return :
# """
# return n1 + n2
# sum1 = sum_num(4,5)
# print(sum1)
""" With the Positional Parameter"""
def sum_num (n1 = 4 , n2 = 10):
return n1 + n2
sum1 = sum_num(10)
sum1 = sum_num(20,10)
sum1 = sum_num(n2=20)
sum1 = sum_num(n1=20)
print(sum1)
|
"""Nested Dictionary is a data type which store the another dictionary on a single key
d = {'k1' : {'nestk1': 'newvalue1', 'nestk2' : 'newvalue2'}}
d['k1']['nestk1']
"""
cars = {'BMW':{'model' : '550i', 'year': 2016},'benz':{'model' : 'E350', 'year': 2018}}
bmw_model = cars['BMW']['model']
print(bmw_model)
print(cars['benz']['year'])
|
from jogo_da_velha import JogodaVelha
humano_escolha, bot_escolha, dificuldade = '','','',
while humano_escolha != 'O' and humano_escolha != 'X': # escolha do x ou o e dificuldade
try:
print('')
print('Bem vindo ao jogo da velha, professor Allan!')
humano_escolha = input('Escolha X or O: ').upper()
except (KeyError, ValueError):
print('Tente novamente!')
if humano_escolha == 'X':
bot_escolha = 'O'
else:
bot_escolha = 'X'
while dificuldade != '1' and dificuldade != '2' and dificuldade != '3':
try:
dificuldade = input('Escolha sua dificuldade: \nFácil[1]\nMédio[2]\nDifícil[3]\n').upper()
except (KeyError, ValueError):
print('Tente novamente!')
jogo = JogodaVelha(humano_escolha, bot_escolha, dificuldade) #inicio das jogadas
primeiro_movimento = 'H'
while len(jogo.celulas_vazias(jogo.tabuleiro)) > 0 and not jogo.game_over(jogo.tabuleiro): #loop principal do jogo
if primeiro_movimento:
jogo.vez_bot()
primeiro_movimento = ''
jogo.vez_humano()
jogo.vez_bot()
if jogo.wins(jogo.tabuleiro, jogo.HUMANO):
print(f'Sua vez[{jogo.humano_escolha}]')
jogo.mostra_tabuleiro(jogo.tabuleiro)
print('Você ganhou, aff...')
elif jogo.wins(jogo.tabuleiro, jogo.BOT):
print(f'Minha vez! Deixe eu pensar... [{jogo.bot_escolha}]')
jogo.mostra_tabuleiro(jogo.tabuleiro)
print('Perdeste! Hahah')
else:
jogo.mostra_tabuleiro(jogo.tabuleiro)
print('Ih, deu velha...')
exit()
|
"""Template code for M3C 2016 Homework 3
"""
import numpy as np
import matplotlib.pyplot as plt
def visualize(e):
"""Visualize a network represented by the edge list
contained in e
"""
def degree(N0,L,Nt,display=False):
"""Compute and analyze degree distribution based on degree list, q,
corresponding to a recursive network (with model parameters specified
as input.
"""
if __name__ == "__main__":
|
import copy
#Flight Itinerary
#Done by: Chiew Jun Hao and Zhang Hao
class Flight:
def __init__(self, start_city, start_time, end_city, end_time):
self.start_city = start_city
self.start_time = start_time
self.end_city = end_city
self.end_time = end_time
def __str__(self):
return str((self.start_city, self.start_time))+' -> '+ str((self.end_city, self.end_time))
def matches(self, city, time):
return self.start_city == city and self.start_time >= time
__repr__ = __str__
flightDB = [Flight('Rome', 1, 'Paris', 4),
Flight('Rome', 3, 'Madrid', 5),
Flight('Rome', 5, 'Istanbul', 10),
Flight('Paris', 2, 'London', 4),
Flight('Paris', 5, 'Oslo', 7),
Flight('Paris', 5, 'Istanbul', 9),
Flight('Madrid', 7, 'Rabat', 10),
Flight('Madrid', 8, 'London', 10),
Flight('Istanbul', 10, 'Constantinople', 10)]
itinerary=[]
def prt_flights(flights):
print("################current path###############")
for i in flights:
print(i.__str__)
print("###############################")
def prt_buffer(buffer):
for i in buffer:
for j in i:
print(j.__str__)
print("###")
#BFS
#each function is a node
def find_itinerary(start_city, start_time, end_city, deadline):
#store all the flights
buffer = []
#marks the node that is barren
explored = []
#initialise first split
for i in flightDB:
path=[]
if i.matches(start_city,start_time) and i.end_city not in explored and i.end_time <= deadline:
path.append(i)
buffer.append(path)
# j=buffer[-1][-1]
# print j.end_city
#while loop runs algorithm until there is no more path left
while len(buffer) != 0:
#takes the last element in the stack, pop it and add start city to explored list
current_path= copy.deepcopy(buffer[0])
node = buffer[0][-1]
print("\n"+node.__str__())
explored.append(node.start_city)
buffer.pop(0)
prt_flights(current_path)
#exit when path is found
if node.end_city == end_city:
print("FFFFFFFFFFFFFFFFFFOOOOOOOOOOOOOOOOOOUND")
print(len(current_path))
return prt_result(current_path)
#expand the nodes and append the new path to the end of the buffer
for i in flightDB:
if i.matches(node.end_city,node.end_time) and i.end_city not in explored and i.end_time <= deadline:
#append because BFS, change if DFS
newPath = copy.deepcopy(current_path)
newPath.append(i)
buffer.append(newPath)
prt_buffer(buffer)
return None
def prt_result(path):
itinerary = ""
for f in path:
itinerary += str(f.__str__)
return itinerary
def find_shortest_itinerary(start_city, end_city):
for i in range(1,11):
print("\n#############################"+str(i)+"#########################################")
result = find_itinerary(start_city,1,end_city,i)
if result is not None:
return result
break
# print find_itinerary('Rome', 1, "London", 10)
############# Part 4 ################
#Yes, it will improve. Say the goal is to go from Rome to Istanbul within 8
# there is a direct flight from Rome to Istanbul that has an end time of 9, it will be identified and algorithm will exit should the deadline >9,
# however, if the deadline is progressively introduced,
# this direct flight node will be pruned. The algorithm will then take on other path and hopefully eventually find a legit path to Istabul
print(find_shortest_itinerary("Rome","Paris"))
|
board=[["-" for i in range(3)] for i in range(3)]
def alleq(l,player=False):
return l[0]==l[1]==l[2]==player
def myinput(x,y):
return (x,y) if board[x][y]=='-' else myinput(int(input("Enter an x value\n")),int(input("Enter a y value\n")))
def gameplay(player):
(x,y)=myinput(int(input("Enter an x value\n")),int(input("Enter a y value\n")))
board[x][y]=player
[print(i) for i in [j for j in board]]
return (not alleq( [alleq(w,player) for w in [[board[x][i] for i in range(0,3)],[board[i][y] for i in range(0,3)],
[board[i][j] for i in range(0,3) for j in range(0,3) if i+j==2]]] )) or alleq([board[i][i] for i in range(0,3)],player)
def playloop(num,player):
return (player+' wins!') if gameplay(player) else ( playloop(num+1,'O' if player=='X' else 'X') if num<9 else "It's a draw!")
print(playloop(1,'X'))
|
import math
number = int(input(" Please enter any Number to find factorial : "))
fact = math.factorial(number)
print("The factorial of %d = %d" %(number, fact))
|
from turtle import *
mode('logo')
speed(1)
shape('turtle')
for i in range(5):
forward(100)
right(72)
mainloop()
|
'''
# 1
for number in range(1,11):
print(number)
#2
start = int(input('Start from: '))
end = int(input('End from: '))
for number in range(start,end + 1):
print(number)
#3
for number in range(1,11):
if number %2 != 0:
print(number)
#4
size = 5
for i in range(size):
print('*' * size)
#5
square = int(input("How big is the square? "))
for number in range(square):
print('*' * square)
#6
height = int(input("height size? "))
weight = int(input("weight size? "))
for number in range(1,h+1):
if x == 1:
print('*' * w)
elif x == h:
print('*' * W)
else:
print('*' + ' ' * (w-2) + '*')
#7
print(' * ')
print(' *** ')
print(' ***** ')
print('******* ')
#8
h = 4
for x in range(1,5):
print(' ' * (h-x) + '*' * x + '*' * (x-1) + ' ' * (h-x))
'''
#9
x = range(1,11)
for y in x:
for z in x:
mu = y * z
print(y,'',)
|
import urllib.request
import json
def display_album(id):
"""photo album - take the id from the keyboard and print photo id and titles on the console
:param id: An integer id
:return:
"""
with urllib.request.urlopen("https://jsonplaceholder.typicode.com/photos?albumId=" + str(id)) as url:
data = json.loads(url.read().decode())
if not data:
print(f'There is no data corresponding to that id: {id}')
item_list = []
for element in data:
if element['id']:
item_list.append('['+ str(element['id']) + ']' + ' '+ element['title'])
return item_list
|
import turtle
def circle_for_turtle():
for i in range(4):
turtle.fd(x)
turtle.rt(90)
turtle.shape("classic")
x = 40
for i in range(10):
circle_for_turtle()
turtle.lt(135)
turtle.penup()
turtle.fd((20**2*2)**0.5)
turtle.pendown()
turtle.rt(135)
x += 40
|
Chemistry_theory = int(input("Enter your Chemistry Theory Marks (out of 75): "))
if Chemistry_theory > 0 or Chemistry_theory < 75:
Chemistry_practical = int(input("Enter your Chemistry Practical Marks (out of 25): "))
Biology_theory = int(input("Enter your Biology Theory Marks (out of 75): "))
Biology_practical = int(input("Enter your Biology Practical Marks (out of 25): "))
Sindhi_Salees = int(input("Enter your Sindhi Salees Marks (out of 75): "))
English = int(input("Enter your English Marks (out of 75): "))
Pakistan_Studies = int(input("Enter your Pakistan Studies Marks (out of 50): "))
Total_marks = (Chemistry_practical+Chemistry_theory+Biology_theory+Biology_practical+Sindhi_Salees+English+Pakistan_Studies)
percent_chemistry_theory = int(Chemistry_theory/75*100)
percent_chemistry_practical = int(Chemistry_practical/25*100)
percent_biology_theory = int(Biology_theory/75*100)
percent_biology_practical = int(Biology_practical/25*100)
percent_sindhi_salees = int(Sindhi_Salees/75*100)
percent_english = int(English/75*100)
percent_pakistan_studies = int(Pakistan_Studies/75*100)
percent_total_marks = int(Total_marks/425*100)
print("Here's your Mark Sheet")
print("===================================================================")
print(" MARK SHEET ")
print("-------------------------------------------------------------------")
print("| Subject Name | Marks Obtained | Total Marks | Percentage |")
print("| Chemistry Theory | "+str(Chemistry_theory)+" | 75 | "+str(percent_chemistry_theory)+"% |")
print("| Chemistry Practical | "+str(Chemistry_practical)+" | 25 | "+str(percent_chemistry_practical)+"% |")
print("| Biology Theory | "+str(Biology_theory)+" | 75 | "+str(percent_biology_theory)+"% |")
print("| Biology Practical | "+str(Biology_practical)+" | 25 | "+str(percent_biology_practical)+"% |")
print("| Sindhi Salees | "+str(Sindhi_Salees)+" | 75 | "+str(percent_sindhi_salees)+"% |")
print("| English | "+str(English)+" | 75 | "+str(percent_english)+"% |")
print("| Pakistan Studies | "+str(Pakistan_Studies)+" | 75 | "+str(percent_pakistan_studies)+"% |")
print("| Total | "+str(Total_marks)+" | 425 | "+str(percent_total_marks)+"% |")
else:
print('The marks should be between o and 75')
|
from sys import argv
user_range = int(argv[1])
def demo_range(num):
for i in range(num):
print i
def print_all_evens(num):
"""Print all even numbers between 0 and num."""
for i in range(2, num, 2):
print i
def count_down(num):
"""Count down from num to 0."""
for i in range(num, -1, -1):
print i
if __name__ == '__main__':
demo_range(user_range)
# print_all_evens(user_range)
# count_down(user_range)
|
def sum_of_digits(n):
n = str(n)
if n[0] == '-':
n = n[1::]
#m = 0
#for i in range(len(n)):
# m += int(n[i])
return sum([int(i) for i in n])
return m
print(sum_of_digits(-10))
|
def is_number_balanced(number):
number = str(number)
half_n = len(number)//2
if len(number) % 2:
number = number[:half_n:] + number[half_n + 1::]
left = number[:half_n:]
right = number[half_n::]
left = [int(i) for i in list(left)]
right = [int(i) for i in list(right)]
return sum(left) == sum(right)
print(is_number_balanced(1238033))
|
import unittest
from sort_array import sort_fractions
class TestSortFractions(unittest.TestCase):
def test_with_two_fractions(self):
fractions = [(2, 3), (1, 2)]
excpected = [(1, 2), (2, 3)]
fractions = sort_fractions(fractions)
self.assertEqual(fractions, excpected)
def test_with_descending_argument_given(self):
fractions = [(2, 3), (1, 2), (1, 3)]
excpected = [(2, 3), (1, 2), (1, 3)]
fractions = sort_fractions(fractions, ascending=False)
self.assertEqual(fractions, excpected)
def test_with_only_one_fraction_shall_return_it(self):
fractions = [(2, 50)]
result = sort_fractions(fractions, ascending=False)
self.assertEqual(result, fractions)
def test_with_no_fractions(self):
fractions = []
result = sort_fractions(fractions, ascending=False)
self.assertEqual(result, fractions)
def test_with_negative_element(self):
fractions = [(5, 6), (22, 78), (22, 7), (7, 8), (-9, 6), (15, 32)]
excpected = [(-9, 6), (22, 78), (15, 32), (5, 6), (7, 8), (22, 7)]
fractions = sort_fractions(fractions)
self.assertEqual(fractions, excpected)
if __name__ == '__main__':
unittest.main()
|
_userArray = list()
while True:
_userinput = input('Please enter a number. Type "Done" when finished')
if _userinput == 'Done':
break
try:
_userinput = float(_userinput)
except:
print('You entered a invalid number')
continue
_userArray.append(_userinput)
print('The largest number is ',max(_userArray))
print('The smallest number is ',min(_userArray))
|
# tree.py
# Constructor
def tree(value, branches=[]):
for branch in branches:
assert is_tree(branch), 'branches must be trees'
return [value] + list(branches)
# Selector
def root(tree):
return tree[0]
def branches(tree):
return tree[1:]
def is_leaf(tree):
return not branches(tree)
def is_tree(tree):
if type(tree) != list or len(tree) < 1:
return False
for branch in branches(tree):
if not is_tree(branch):
return False
return True
def height(t):
"""Return the height of a tree"""
if is_leaf(t):
return 1
else:
return 1 + max(map(height, branches(t)))
def square_tree(t):
"""Return a tree with the square of every element in t"""
if is_leaf(t):
t = tree(t[0]**2)
else:
t = tree(t[0]**2, [square_tree(t) for t in branches(t)])
return t
def tree_size(t):
"""Return the size of a tree."""
if is_leaf(t):
return 1
else:
return 1 + sum(map(tree_size, branches(t)))
def tree_max(t):
"""Return the max of a tree."""
if is_leaf(t):
return t[0]
else:
return max(t[0], max(map(tree_max, branches(t))))
def find_path(tree, x):
"""
>>> find_path(t, 5)
[2, 7, 6, 5]
"""
if tree[0] == x:
return [x]
elif not is_leaf(tree):
subpaths = list(map(find_path, branches(tree), [x]*len(branches(tree))))
# import pdb; pdb.set_trace()
noneempty_subpath = list(filter(lambda x: x is not None, subpaths))
if len(noneempty_subpath) <= 0:
return None
else:
return [tree[0]] + noneempty_subpath[0]
else:
return None
def hailstone_tree(n, h):
"""
Generates a tree of hailstone numbers that will
reach N, with height H.
>>> hailstone_tree(1, 0)
[1]
>>> hailstone_tree(1, 4)
[1, [2, [4, [8, [16]]]]]
>>> hailstone_tree(8, 3)
[8, [16, [32, [64]], [5, [10]]]]
"""
if h == 0:
return tree(n)
else:
if (n-1) % 3 == 0 and n > 1:
return tree(n, [hailstone_tree(2 * n, h - 1), hailstone_tree((n - 1) // 3, h - 1)])
else:
return tree(n, [hailstone_tree(2 * n, h - 1)])
if __name__ == "__main__":
t = tree(1,[tree(3,[tree(4),tree(5),tree(6)]), tree(2)])
t = tree(2, [tree(7, [tree(3), tree(6, [tree(5), tree(11)])]), tree(15)])
t_square = square_tree(t)
print(t)
print(t_square)
print(height(t_square))
print(tree_size(t_square))
print(tree_max(t))
print(find_path(t, 6))
t = hailstone_tree(1, 4)
print(t)
|
import unittest
from user import User
class Test(unittest.TestCase):
"""
Testing users
"""
def setUp(self):
"""Setup method creating user instance"""
self.user = User()
#User Registration tests
def test_registration_empty_name(self):
"""test account creation with an empty name field"""
output=self.user.registration('[email protected]','','pass','pass')
self.assertEqual(4, output, "Please fill your name")
def test_registration_empty_email(self):
"""test account creation with an empty email field"""
output=self.user.registration('','gilo','pass','pass')
self.assertEqual(4, output, "Email is missing")
def test_registration_empty_password(self):
"""test account creation with an empty password field"""
output=self.user.registration('[email protected]','gilo','','pass')
self.assertEqual(4, output, "Password is missing")
def test_registration_empty_cpassword(self):
"""test account creation with an empty password field"""
output=self.user.registration('[email protected]','gilo','pass','')
self.assertEqual(4, output, "Please confirm password")
def test_password_is_cpassword(self):
"""test if password is cpassword"""
output=self.user.registration('[email protected]','gilo','pass456','password')
self.assertEqual(2, output, "Password do not match")
def test_password_length(self):
"""test if password length"""
output=self.user.registration('[email protected]','gilo','pass','pass')
self.assertEqual(12, output, "Password is too short")
#User Login tests
def test_login_empty_email(self):
"""Email blank"""
output = self.user.login('','pass')
self.assertEqual(4, output, "Email cant be blank")
def test_login_empty_password(self):
"""Blank password"""
output = self.user.login('[email protected]','')
self.assertEqual(4, output, "Password cant be blank")
def test_email_not_registered(self):
"""Email not registered"""
self.user.registration('[email protected]','gilo','pass','pass')
output = self.user.login('[email protected]','1234')
self.assertEqual(7, output, "Email not registered")
def test_login_wrong_password(self):
"""wrong password"""
self.user.registration('[email protected]','gilo','pass','pass')
output = self.user.login('[email protected]','1234')
self.assertEqual(7, output, "Wrong password")
#Email already registered
#Successfully registered
if __name__ == "__main__":
unittest.main()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# check##################################
age = 1
if age >= 18:
print('adult');
else:
print('teenager');
#变量
#变量的概念基本上和初中代数的方程变量是一致的,只是在计算机程序中,变量不仅可以是数字,还可以是任意数据类型。
#变量在程序中就是用一个变量名表示了,变量名必须是大小写英文、数字和_的组合,且不能用数字开头
a = 123 # a是整数
print(a)
a = 'ABC' # a变为字符串
print(a)
x = 10
x = x + 2
print(x);
a = 'ABC'
b = a
a = 'XYZ'
print(b)
print(a + b)
#常量
#所谓常量就是不能变的变量,比如常用的数学常数π就是一个常量。在Python中,通常用全部大写的变量名表示常量:
PI = 3.14159265359
print(10 / 3);
print(10 // 3); #地板除
print(8 // 3); #地板除
print(10 % 3); #求余数
#inf(无限大)
n = 123
f = 456.789
s1 = 'Hello, world'
s2 = 'Hello, \'Adam\''
s3 = r'Hello, "Bart"'
s4 = r'''Hello,
Lisa!'''
print(n);
print(f);
print(s1);
print(s2);
print(s3);
print(s4);
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# check##################################
# 要调用一个函数,需要知道函数的名称和参数,比如求绝对值的函数abs,只有一个参数。可以直接从Python的官方网站查看文档:
# http://docs.python.org/3/library/functions.html#abs
print(abs(100));
print(abs(-105));
print(abs(12.34));
# print(abs(1, 2));调用函数的时候,如果传入的参数数量不对,会报TypeError的错误,并且Python会明确地告诉你:abs()有且仅有1个参数,但给出了两个
# print(abs('a'));如果传入的参数数量是对的,但参数类型不能被函数所接受,也会报TypeError的错误,并且给出错误信息:str是错误的参数类型:
#而max函数max()可以接收任意多个参数,并返回最大的那个
print(max(2, 3, 1, -5));
#Python内置的常用函数还包括数据类型转换函数,比如int()函数可以把其他数据类型转换为整数
print(int(1.12))
print(float(112))
print(str(112))
print(bool(1))
a= abs#函数名其实就是指向一个函数对象的引用,完全可以把函数名赋给一个变量,相当于给这个函数起了一个“别名”:
print(a(-1))
n1 = 255
n2 = 1000
print(hex(n1));
print(hex(n2));
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.