text
stringlengths 37
1.41M
|
---|
"""Scans a given path (folder) for .wav files recursively and copys all of
them into a new folder.
"""
from pathlib import Path
import shutil
import click
from wavlength import get_files
@click.command()
@click.option('--scan_folder', default='.', help='The folder to scan.')
@click.option('--copy_folder', default='./collected_wavs', help='The folder top copy to.')
def collect(scan_folder, copy_folder):
"""Scan a given folder and copies all .wav files into a new folder."""
files = get_files(Path(scan_folder))
copy_folder = Path(copy_folder)
copy_id = 0
if not copy_folder.is_dir():
copy_folder.mkdir()
print(f'{len(files)} have been found and will be copied.')
for wavfile in files:
copy_id += 1
try:
shutil.copy(wavfile.resolve(), copy_folder.resolve())
#Rename the copied file to avoid file collisions
new_file = Path(copy_folder.joinpath(wavfile.name))
new_file.rename(copy_folder.joinpath(wavfile.name.replace('.wav', f'-{copy_id}.wav')))
except Exception as e:
print(e)
if __name__ == '__main__':
collect() |
def somethingElse():
pass
class Base:
"""This is the Base class to rule all classes"""
someVar = "Some shared value"
def __init__(self,id='',desc='No Description'):
print("Base class init fx")
self.id = id
self.address = ''
self.description = desc
self.data = dict()
def doSomething(self,someValue):
"""This is the do something function\n
input: someValue [Should be a string]\n
output: Garbage print of lalalala
"""
self.somethingElse()
return f"Doing something with {someValue} from {self.id}"
def somethingElse(self):
print("Lalalala")
def __str__(self):
return f"This is Base object id: {self.id}"
class Child(Base):
def __init__(self):
super().__init__("whatever","something")
print("Child class init fx")
def advFx(self):
return "This is an added functionality"
class OtherChild(Base):
pass
class Person:
name = ""
age = 0
id = ''
from tikiClass import Tiki
Tiki().stayAtHome()
# miklasObj = Child()
# # miklasObj.doSomething('child stuff')
# print(miklasObj.advFx())
# tikiObj = Base(desc='Whatever',id='tiki123')
# lorenzoObj = Base("lorenzo23","Lorenzo is suave")
# print(tikiObj.doSomething(42))
# print(tikiObj)
# print(tikiObj.someVar)
# tikiObj.someVar = "Dangit! Tiki changed the value"
# print(tikiObj.someVar)
# print(lorenzoObj.someVar)
# print(tikiObj.id)
# print(tikiObj.description)
# print(lorenzoObj.id) |
#This is Patrick's text base RPG adventure.
class Player:
""" You are the player """
def __init__(self, name, prof, maxhp, level, attack, defense = 5):
self.name = name
self.life = 1
self.attack = attack
self.defense = defense
self.hp = 100
self.xp = 0
def level_up(self, level):
while hero.xp >= Player.level2:
pass
def game_over(self):
pass
def death(self):
if life >= 0:
print("game_over")
else:
pass
class Mage(Player):
pass
class Warrior(Player):
def __init__(self):
super().__init__(name = input("What is your characters name?"), prof = "Warrior", attack = 10, defense = 10,
maxhp = 100, level = 1)
self.prof = "Warrior"
self.maxhp = 100
self.level = 1
####################### This is what I was in the middle of working on it.
def profession():
print("What is your class?",'\n',
" press W for Warrior",'\n',
" press M for Mage")
pclass=input(">>>")
if pclass == "W":
Prof = Warrior()
elif pclass == "M":
Prof = Mage()
#profession()
#player_name = input("what is your name?")
#profession
x = Warrior()
print(x.prof)
|
# Find the difference between the square of the sum and the sum of the squares of the first N natural numbers.
def difference_of_squares(n):
# if n % 2 == 1:
# median = (n + 1) / 2
# num_pairs = (n - 1) / 2
# else:
# median = 0
# num_pairs = n / 2
#
# square_of_sum = (n + 1) * num_pairs + median
square_of_sum = (n * (n + 1) / 2) ** 2
sum_of_square = (n * (n + 1) * (2 * n + 1)) / 6
difference = abs(square_of_sum - sum_of_square)
return difference
|
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 14 20:10:31 2017
@author: Usuryjskij
"""
import pygame
from pygame.locals import*
GREEN = ( 0, 204, 0)
cant_place_ship = [[False]*10,[False]*10,[False]*10,[False]*10,[False]*10,[False]*10,[False]*10,[False]*10,[False]*10,[False]*10]
class Ship(object):
def __init__(self,shipsize,board):
self.shipsize = shipsize
self.placed = False
self.position = []
self.board = board
self.dead = False
self.hits = shipsize
############################# Place your ships ################################
def placeBoat(self,screen,user_ships):
ship_flag = True
while ship_flag:
for event in pygame.event.get():
vertic = pygame.key.get_pressed()
if(event.type==MOUSEBUTTONDOWN and not vertic[K_SPACE]):
temppos = event.pos
if(temppos[0]>553 and temppos[0]<803 and temppos[1]>self.board and temppos[1]<self.board+250):
recx = int((temppos[0]-553)/25)
recy = int((temppos[1]-self.board)/25)
if(self.checkPlace(recx,recy,vertic) == True):
for i in range(self.shipsize):
if(recx+self.shipsize-1 > 9):
pygame.draw.rect(screen,GREEN,(555+(10-self.shipsize+i)*25,self.board+2+recy*25,22,22))
user_ships[10-self.shipsize+i][recy] = True
self.position +=[(10-self.shipsize+i,recy)]
self.setCollision(10-self.shipsize+i,recy)
else:
pygame.draw.rect(screen,GREEN,(555+(recx+i)*25,self.board+2+recy*25,22,22))
user_ships[recx+i][recy] = True
self.position +=[(recx+i,recy)]
self.setCollision(recx+i,recy)
self.placed = True
pygame.display.update()
ship_flag = False
break
else:
print("Kolizja, zrob jeszcze raz")
elif(event.type==MOUSEBUTTONDOWN and vertic[K_SPACE]):
temppos = event.pos
if(temppos[0]>553 and temppos[0]<803 and temppos[1]>self.board and temppos[1]<self.board+250):
recx = int((temppos[0]-553)/25)
recy = int((temppos[1]-self.board)/25)
if(self.checkPlace(recx,recy,vertic) == True):
for i in range(self.shipsize):
if(recy >= 6):
pygame.draw.rect(screen,GREEN,(555+(recx)*25,self.board+2+(10-self.shipsize+i)*25,22,22))
user_ships[recx][10-self.shipsize+i] = True
self.position += [(recx,10-self.shipsize+i)]
self.setCollision(recx,10-self.shipsize+i)
else:
pygame.draw.rect(screen,GREEN,(555+(recx)*25,self.board+2+(recy+i)*25,22,22))
user_ships[recx][recy+i] = True
self.position += [(recx,recy+i)]
self.setCollision(recx,recy+i)
self.placed = True
pygame.display.update()
ship_flag = False
break
################################# Set collision ###############################
def setCollision(self,recx,recy):
if(recx == 0 and recy == 0):
cant_place_ship[recx][recy] = True
cant_place_ship[recx+1][recy] = True
cant_place_ship[recx][recy+1] = True
cant_place_ship[recx+1][recy+1] = True
elif(recx == 9 and recy == 9):
cant_place_ship[recx][recy] = True
cant_place_ship[recx-1][recy] = True
cant_place_ship[recx][recy-1] = True
cant_place_ship[recx-1][recy-1] = True
elif(not recx == 0 and not recx == 9 and recy == 0):
for i in range(2):
for j in range(3):
cant_place_ship[recx-1+j][recy+i] = True
elif(not recx == 0 and not recx == 9 and recy == 9):
for i in range(2):
for j in range (3):
cant_place_ship[recx-1+j][recy-i] = True
elif(not recy == 0 and not recy == 9 and recx == 0):
for i in range(3):
for j in range(2):
cant_place_ship[recx+j][recy-1+i] = True
elif(not recy == 0 and not recy == 9 and recx == 9):
for i in range(3):
for j in range(2):
cant_place_ship[recx-j][recy-1+i] = True
elif(recx == 0 and recy == 9):
cant_place_ship[recx][recy] = True
cant_place_ship[recx+1][recy] = True
cant_place_ship[recx][recy-1] = True
cant_place_ship[recx+1][recy-1] = True
elif(recx == 9 and recy == 0):
cant_place_ship[recx][recy] = True
cant_place_ship[recx-1][recy] = True
cant_place_ship[recx][recy+1] = True
cant_place_ship[recx-1][recy-1] = True
else:
for i in range(3):
for j in range(3):
cant_place_ship[recx-1+i][recy-1+j] = True
##############################################################################
############################## Check place ##################################
def checkPlace(self,recx,recy,vertic):
flag = True
if(vertic[K_SPACE] == False):
for i in range(self.shipsize):
if(recx+self.shipsize-1 > 9):
if(cant_place_ship[10-self.shipsize+i][recy] == True):
flag = False
else:
if(cant_place_ship[recx+i][recy] == True):
flag = False
elif(vertic[K_SPACE] == True):
for i in range(self.shipsize):
if(recy >= 6):
if(cant_place_ship[recx][10-self.shipsize+i] == True):
flag = False
else:
if(cant_place_ship[recx][recy+i] == True):
flag = False
return flag
def hit(self):
self.hits -= 1
if(self.hits == 0):
self.dead = True
|
import string
from typing import List
class Solution:
def isAlienSorted(self, words: List[str], order: str) -> bool:
# approach 1: replace each character with uppercase original alphabet
# 'hello' -> 'AGBBO'
# check whether the list is in sorted order
# O(NK) time, O(NK) space
for alien, orig in zip(order, string.ascii_uppercase):
for idx, w in enumerate(words):
words[idx] = w.replace(alien, orig)
for i in range(len(words)-1):
if words[i] > words[i+1]:
return False
return True
|
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
# O(n) time, O(1) space
if not l1:
return l2
if not l2:
return l1
ptr1, ptr2 = l1, l2
ans = curr_node = ListNode(-101)
while ptr1 and ptr2:
if ptr1.val <= ptr2.val:
curr_node.next = ptr1
curr_node = curr_node.next
ptr1 = ptr1.next
else:
curr_node.next = ptr2
curr_node = curr_node.next
ptr2 = ptr2.next
curr_node.next = ptr2 if not ptr1 else ptr1
return ans.next
|
from typing import List
class Solution:
def wiggleMaxLength(self, nums: List[int]) -> int:
# one-pass through nums and record the sign of the previous difference
# also record the last "transition number"
# O(n) time, O(1) memory
if len(nums) == 1:
return len(nums)
if len(nums) == 2:
return 1 if nums[0] == nums[1] else 2
max_length = 1
is_increasing = 0
for i in range(1, len(nums)):
if nums[i] == nums[i-1] or (nums[i] - nums[i-1]) * is_increasing > 0:
continue
elif is_increasing == 0:
is_increasing = 1 if nums[i] > nums[i-1] else -1
max_length += 1
else:
max_length += 1
is_increasing *= -1
return max_length
sol = Solution()
print(sol.wiggleMaxLength([1,4,3,8,2,6]))
print(sol.wiggleMaxLength([1,1,1,1]))
|
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def maxPathSum(self, root: TreeNode) -> int:
# traverse the tree using dfs
# for node i:
# maxsum = max(maxsum, left + val + right)
# return val + max(left, right)
def traversal(node: TreeNode) -> int:
"""
updates max sum with paths not involving parents,
and returns max sum using node as intermediate point.
"""
if not node:
return 0
left_path = traversal(node.left)
right_path = traversal(node.right)
maxsum[0] = max(
maxsum[0],
left_path if left_path > 0 else -2**31,
right_path if right_path > 0 else -2**31,
node.val,
node.val + left_path + right_path
)
return node.val + max(left_path, right_path, 0)
maxsum = [-2**31]
through_root = traversal(root)
return max(maxsum[0], through_root)
|
class Solution:
def halvesAreAlike(self, s: str) -> bool:
# O(n) time, O(n) space
isVowel = [1 if c in ['a', 'e', 'i', 'o', 'u'] else 0 for c in s.lower()]
return sum(isVowel[:len(s)//2]) == sum(isVowel[len(s)//2:])
sol = Solution()
print(sol.halvesAreAlike("Book"))
print(sol.halvesAreAlike("BoOk"))
|
import heapq
from typing import List
class Solution:
def furthestBuilding(self, heights: List[int], bricks: int, ladders: int) -> int:
# BFS approach
# at each building, take all viable options in the queue, move forward using bricks or ladders
# O(2**H) time
# use bricks first, and record number of bricks used in a heap
# when run out of bricks, replace highest number of bricks with a ladder
# O(HlogK) time, O(H) space
brick_list = []
heapq.heapify(brick_list)
for idx in range(1, len(heights)):
if (diff := heights[idx] - heights[idx-1]) > 0:
heapq.heappush(brick_list, -diff)
bricks -= diff
while bricks < 0:
if ladders > 0:
ladders -= 1
bricks -= heapq.heappop(brick_list) if brick_list else 0
else:
return idx - 1
return len(heights)-1
|
from typing import List
from collections import Counter
from itertools import accumulate
class Solution:
def leastBricks(self, wall: List[List[int]]) -> int:
# record the brick boundaries of each row in a counter
# find the boundary that has max count
# O(N) time, O(N) space, N is the number of bricks
count = Counter()
for row in wall:
count.update(list(accumulate(row[:-1])))
return len(wall) - (max(count.values()) if count else 0)
sol = Solution()
print(sol.leastBricks([[1], [1]]))
|
from typing import List
class Solution:
def missingNumber(self, nums: List[int]) -> int:
return (len(nums)+1) * (len(nums)) // 2 - sum(nums)
sol = Solution()
print(sol.missingNumber([0]))
print(sol.missingNumber([0, 1]))
print(sol.missingNumber([0, 3, 1]))
|
class Solution:
def removePalindromeSub(self, s: str) -> int:
# insight: answer is at most 2
if not s:
return 0
elif s == s[::-1]:
return 1
else:
return 2
sol = Solution()
print(sol.removePalindromeSub(""))
print(sol.removePalindromeSub("ababa"))
print(sol.removePalindromeSub("aaabbb"))
|
# locals() 지역 이름공간
global_var = 77
def myfunc():
global global_var
global_var += 1
print(global_var)
myfunc()
var = 77
def func():
global var
var = 100
print(locals())
func()
print(var)
def local_func():
var = 100
print(locals())
local_func() |
# Duplicate number in an array
# Approach 1 - Sum of numbers - Time complexity= O(n) space complexity= O(1)
# If array contains consecutive numbers
num=list(map(int, input().split()))
sum=0
for i in num:
sum=sum+i
print(int(sum-(((len(num)-1)*(len(num)))/2)))
# Duplicate number in an array
# Approach 2 - Sum of numbers
# If numbers are not consecutive
num=list(map(int, input().split()))
sum1=0
sum2=0
num_set=list(set(num))
for i in num:
sum1=sum1+i
for i in num_set:
sum2=sum2+i
print(sum1-sum2)
|
# Check Rotations
'''
1. Create a temp string and store concatenation of str1 to
str1 in temp.
temp = str1.str1
2. If str2 is a substring of temp then str1 and str2 are
rotations of each other.
'''
st1=str(input())
st2=str(input())
st1=st1+st1
n=st1.count(st2)
if(n>0):
print("They are Rotations")
else:
print("They are not Rotations") |
# Check if All Digits
st1 = str(input())
flag = 0
for i in st1:
if(i.isdigit()==True):
flag+=1
if(flag==len(st1)):
print("All Digits")
else:
print("Not All Digits") |
# https://www.geeksforgeeks.org/find-one-extra-character-string/
# Find one extra character in a string
st1=str(input())
st2=str(input())
count=0
for i in st2:
if(i not in st1):
print(i)
else:
n1=str.count(st1,i)
n2=str.count(st2,i)
if(n2>n1):
print(i)
break
|
# Remove Punctuations
# https://www.geeksforgeeks.org/removing-punctuations-given-string/
st=str(input())
for i in '''!"#$%&'()*+,-./:;?@[\]^_`{|}~<>''':
if(i in st):
st=st.replace(i,'')
print(st)
|
file = open("advent_day2_input.txt", "r")
f = file.readlines()
for line1 in f:
for line2 in f:
distance = sum([1 for x, y in zip(line1, line2) if x.lower() != y.lower()])
if distance == 1:
print "line1: " + line1 + " , line2: " + line2
#for line in f:
# for char in line:
# if line.count(char) == 2:
# count2+=1
# print "count2: " + str(count2)
# break
# for char in line:
# if line.count(char) == 3:
# count3+=1
# print "count3: " + str(count3)
# break
#checksum = count2 * count3
#print str(checksum)
|
import re
from collections import Counter
def splits(text, start=0, L=10):
"Return a list of all (first, rest) pairs; start <= len(first) <= L."
return [(text[:i], text[i:])
for i in range(start, min(len(text), L)+1)]
def product(nums):
"Multiply the numbers together. (Like `sum`, but with multiplication.)"
result = 1
for x in nums:
result *= x
return result
def memo(f):
"Memoize function f, whose args must all be hashable."
cache = {}
def fmemo(*args):
if args not in cache:
cache[args] = f(*args)
return cache[args]
fmemo.cache = cache
return fmemo
class NorvigSpell:
def __init__(self, bow, alphabet = 'abcdefghijklmnopqrstuvwxyz'):
N = sum(bow.values())
self.alphabet = alphabet
self.COUNTS = {k: float(i)/N for k, i in bow.items()}
def Pword(self, word):
"Returns the propbability of word to appear"
if word in self.COUNTS:
return self.COUNTS[word]
return 0.01/(len(self.COUNTS)*len(word))
@memo
def correct(self, word):
"Find the best spelling correction for this word."
# Prefer edit distance 0, then 1, then 2; otherwise default to word itself.
candidates = (self.known(self.edits0(word)) or
self.known(self.edits1(word)) or
self.known(self.edits2(word)) or
{word})
return max(candidates, key=self.COUNTS.get)
def known(self, words):
"Return the subset of words that are actually in the dictionary."
return {w for w in words if w in self.COUNTS}
def edits0(self, word):
"Return all strings that are zero edits away from word (i.e., just word itself)."
return {word}
def edits2(self, word):
"Return all strings that are two edits away from this word."
return {e2 for e1 in self.edits1(word) for e2 in self.edits1(e1)}
def edits1(self, word):
"Return all strings that are one edit away from this word."
pairs = self.splits(word)
deletes = [a+b[1:] for (a, b) in pairs if b]
transposes = [a+b[1]+b[0]+b[2:] for (a, b) in pairs if len(b) > 1]
replaces = [a+c+b[1:] for (a, b) in pairs for c in self.alphabet if b]
inserts = [a+c+b for (a, b) in pairs for c in self.alphabet]
return set(deletes + transposes + replaces + inserts)
def splits(self, word):
"Return a list of all possible (first, rest) pairs that comprise word."
return [(word[:i], word[i:])
for i in range(len(word)+1)]
def correct_text(self, text):
"Correct all the words within a text, returning the corrected text."
return re.sub('[a-zA-Z]+', self.correct_match, text)
def correct_match(self, match):
"Spell-correct word in match, and preserve proper upper/lower/title case."
word = match.group()
return self.case_of(word)(self.correct(word.lower()))
def case_of(self, text):
"Return the case-function appropriate for text: upper, lower, title, or just str."
return (str.upper if text.isupper() else
str.lower if text.islower() else
str.title if text.istitle() else
str)
def Pwords(self, words):
"Probability of words, assuming each word is independent of others."
return product(self.Pword(w) for w in words)
@memo
def segment(self, text):
"Return a list of words that is the most probable segmentation of text."
if not text:
return []
candidates = ([self.correct(first)] + self.segment(rest) for (first, rest) in splits(text, 1))
return max(candidates, key=self.Pwords)
|
class Heap:
def __init__(self):
self.values = []
self.size = 0
def insert(self, x):
self.values.append(x)
self.size += 1
self._sift_up(self.size - 1)
def _sift_up(self, i):
while i != 0 and self.values[i] < self.values[(i - 1) // 2]:
self.values[i], self.values[(i - 1) // 2] = self.values[(i - 1) // 2], self.values[i]
i = (i - 1) // 2
def extract_min(self):
if not self.size:
return None
tmp = self.values[0]
self.values[0] = self.values[-1]
self.values.pop()
self.size -= 1
self._sift_down(0)
return tmp
def _sift_down(self, i):
while 2*i + 1 < self.size:
j = i
if self.values[2*i + 1] < self.values[i]:
j = 2*i + 1
if 2*i + 2 < self.size and self.values[2*i + 2] < self.values[j]:
j = 2*i + 2
if i == j:
break
self.values[i], self.values[j] = self.values[j], self.values[i]
i = j
if __name__ == '__main__':
heap = Heap()
[heap.insert(i) for i in range(7, 0, -1)]
print(heap.values, heap.size)
print(heap.extract_min())
print(heap.values, heap.size)
|
def manhattan_distance(point_a: tuple, point_b: tuple) -> bool:
"""
:param point_a:
:param point_b:
:return:
"""
return True if (abs(point_b[0] - point_a[0]) + abs(point_b[1] - point_a[1])) % 2 == 0 else False
if __name__ == '__main__':
# Вводятся координаты начальной и целевой клеток шахматной доски. Определить, одинакового ли цвета обе клетки.
x_start = int(input())
y_start = int(input())
x_target = int(input())
y_target = int(input())
# Если L1 кратна 2, значит обе клетки одинакового цвета, иначе - разного
print("YES") if manhattan_distance((x_start, y_start), (x_target, y_target)) else print("NO")
|
import cv2
import numpy as np
image = cv2.imread('../images/input.jpg')
## 1. here display translation(圖像位移)!!!!
# Store height and width of the image
height, width = image.shape[:2]
quarter_height, quarter_width = height/4, width/4
# T = | 1 0 Tx |
# | 0 1 Ty | 是一個二維陣列
# 寬度位移Tx距離,高度位移Ty距離
# T is our translation matrix
T = np.float32([[1, 0, quarter_width], [0, 1,quarter_height]])
print(T)
# We use warpAffine to transform the image using the matrix, T
img_translation = cv2.warpAffine(image, T, (width, height))
cv2.imshow('Translation', img_translation)
## 2.Rotations , cv2.getRotationMatrix2D(rotation_center_x, rotation_center_y, angle of rotation, scale) anticlockwise
# Divide by two to rototate the image around its centre
rotation_matrix = cv2.getRotationMatrix2D((width/2, height/2), 90, 0.5) #最後的參數可同時做縮放,1為原始大小
#若縮放調整為0.5,而圖上不想要有黑邊,需直接調整大小
rotated_image1 = cv2.warpAffine(image, rotation_matrix, (width, height))
cv2.imshow('Rotated Image', rotated_image1)
# another method
rotated_image2 = cv2.transpose(image)
#大小一模一樣
cv2.imshow('Rotated Image - Method 2', rotated_image2)
#左右翻轉
flipped = cv2.flip(image, 1)
cv2.imshow('Horizontal Flip', flipped)
cv2.waitKey()
cv2.destroyAllWindows() |
def fizz_buzz(arg):
"""a function that returns FizzBuzz, Fizz or Buzz for multiples of both 5 and 3, 3 or 5 respectively"""
if isinstance(arg, int):
if arg % 5 == 0 and arg % 3 == 0:
return "FizzBuzz"
elif arg % 3 == 0:
return "Fizz"
elif arg % 5 == 0:
return "Buzz"
else:
return arg
else:
return arg
|
fizz = []
buzz = []
fizzbuzz = []
for x in range(1, 101):
n = ''
if x % 3 == 0:
n += 'fizz'
fizz.append(n)
if x % 5 == 0 and x % 3 != 0:
buzz.append('buzz')
if x % 5 == 0:
n += 'buzz'
if n == 'fizzbuzz':
fizzbuzz.append('fizzbuzz')
if x % 5 != 0 and x % 3 != 0:
n = x
print(n)
print(len(fizz))
print(len(buzz))
print(len(fizzbuzz))
|
#Leetcode N932
# For some fixed N, an array A is beautiful if it is a permutation of the integers 1, 2, ..., N, such that:
# For every i < j, there is no k with i < k < j such that A[k] * 2 = A[i] + A[j].
# Given N, return any beautiful array A. (It is guaranteed that one exists.)
class Solution(object):
def beautifulArray(self, N):
memo = {1: [1]}
def f(N):
if N not in memo:
odds = f((N+1)/2)
evens = f(N/2)
memo[N] = [2*x-1 for x in odds] + [2*x for x in evens]
return memo[N]
return f(N) |
import datetime
import time
def main():
date=datetime.datetime.now()
print date.year
print date.month
print date.day
print date.hour
print date.minute
print date.second
print "{}_{}_{}__{}_{}_{}".format(date.year,date.month,date.day,date.hour,date.minute,date.second)
main()
|
import random
def start_game():
the_table = database()
game_table = database()
index = 0
difficult_level = 0
while index < 1:
difficult = input("Válassz nehézséget (1-3): ")
if difficult in ['1', '2', '3']:
difficult_level = difficult
index += 1
else:
print("Hibás nehézségi szint!")
start_number = 0
end_number = 8
game_table = create_game_table(game_table, difficult_level, start_number, end_number)
play_game(the_table, game_table, difficult_level)
def create_game_table(game_table, difficult_level, start_number, end_number):
for i in range(0, len(game_table)):
numbers = set()
while len(numbers) < (int(difficult_level) * 2) - 1:
number = random_int(start_number, end_number)
numbers.add(number)
for num in numbers:
game_table[i][num] = " "
return game_table
def random_int(start, end):
number = random.randint(start, end)
return number
def play_game(the_table, game_table, difficult_level):
result = 0
number_of_space = ((int(difficult_level) * 2) - 1) * 9
while number_of_space > 0:
print_table(game_table)
actual_row = check_character("Adja meg a sor betűjelét (A-I): ")
actual_column = int(check_number("Adja meg az oszlop számát (1-9): ")) - 1
actual_number = check_number("Adja meg a kívánt számot (1-9): ")
if game_table[actual_row][actual_column] == " ":
game_table[actual_row][actual_column] = actual_number
result += check_result(the_table, actual_row, actual_column, actual_number)
number_of_space -= 1
else:
print("Ez a hely már foglalt!")
end_game(game_table, result)
def check_result(the_table, actual_row, actual_column, actual_number):
good_answer = 0
if the_table[actual_row][actual_column] == actual_number:
good_answer += 1
return good_answer
def end_game(game_table, result):
print_table(game_table)
print("Neked " + str(result) + " pontod lett!")
index = 0
while index < 1:
answer = input("Szeretnél új játékot? (Y / N) ")
if answer == 'Y':
index += 1
elif answer == 'N':
exit()
else:
print("Hibás válasz!")
start_game()
def check_character(question):
characters = {'A':0, 'B':1, 'C':2, 'D':3, 'E':4, 'F':5, 'G':6, 'H':7, 'I':8}
index = 0
actual_row_number = 9
while index < 1:
character = input(question)
if character in characters:
actual_row_number = characters.get(character)
index += 1
elif(character == 'q'):
exit()
else:
print("Hibás karakter!")
return actual_row_number
def check_number(question):
index = 0
actual_number = 0
while index < 1:
number = input(question)
if number in ['1', '2', '3', '4', '5', '6', '7', '8', '9']:
actual_number = number
index += 1
else:
print("Hibás szám!")
return actual_number
def print_table(game_table):
rows = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']
print(" 1 2 3 4 5 6 7 8 9 ")
print(" =========================")
for i in range(0, len(game_table)):
print('%s | %s %s %s | %s %s %s | %s %s %s |' % (
rows[i], game_table[i][0], game_table[i][1], game_table[i][2], game_table[i][3], game_table[i][4],
game_table[i][5], game_table[i][6], game_table[i][7], game_table[i][8]))
if i % 3 == 2:
print(" =========================")
def database():
table = [
['4', '3', '9', '8', '6', '7', '2', '5', '1'],
['1', '7', '8', '5', '4', '2', '6', '3', '9'],
['6', '5', '2', '9', '3', '1', '8', '4', '7'],
['7', '4', '3', '1', '9', '8', '5', '6', '2'],
['5', '2', '6', '4', '7', '3', '1', '9', '8'],
['8', '9', '1', '6', '2', '5', '4', '7', '3'],
['3', '1', '7', '2', '5', '4', '9', '8', '6'],
['9', '8', '4', '3', '1', '6', '7', '2', '5'],
['2', '6', '5', '7', '8', '9', '3', '1', '4']
]
return table
if __name__ == "__main__":
start_game()
|
import random
def partition(Arr,p,r):
x = Arr[r]
i = p - 1
for j in range(p,r-1):
if Arr[j] <= x:
i += 1
t = Arr[i]
Arr[i] = Arr[j]
Arr[j] = t
t = Arr[i+1]
Arr[i+1] = Arr[r]
Arr[r] = t
return i+1
def randomizedPartition(Arr,p,r):
i = random.randint(p,r)
t = Arr[r]
Arr[r] = Arr[i]
Arr[i] = t
return partition(Arr,p,r)
def randomizedQuickSort(Arr,p,r):
if p < r:
q = randomizedPartition(Arr,p,r)
randomizedPartition(Arr,p,q-1)
randomizedPartition(Arr,q+1,r) |
import insertion
import mergesort
import linearsearch
import binarysearch
Arr1 = [-3,5,8,7,1,-2,4]
Arr2 = [5,8,-6,12,3,7,1,9,10]
Arr3 = [44,31,-61,12,3,71,1,19,56,-25]
print ("Unsorted array :")
print (Arr1)
print ("Unsorted array :")
print (Arr2)
insertion.insertionSort(Arr1)
print ("Sorted array :")
print (Arr1)
mergesort.mergeSort(Arr2,0,8)
print ("Sorted array :")
print (Arr2)
ind = linearsearch.linear(Arr3,12)
if ind != -1:
print ("Index of elemet ",ind)
else:
print ("Element don't exist ")
insertion.insertionSort(Arr3)
ind = binarysearch.binary(Arr3,71,0,len(Arr3)-1)
if ind != -1:
print ("Index of elemet ",ind)
else:
print ("Element don't exist ") |
import vertex_example
time = 0
class Graph:
def __init__(self,g = None,s = 0):
self.graph = g
self.size = s
def addVertexToGraph(self,vertex):
self.graph.append(vertex)
self.size += 1
def addVertexAdjacent(self,vertexNum,vertex):
(self.graph[vertexNum]).adjacency.append(vertex)
def printAdjacency(self,vertexNum):
print ("Vertex",(self.graph[vertexNum]).data1,"adjacency ")
for v in (self.graph[vertexNum]).adjacency:
v.printAdjacent()
def printGraphsVertexes(self):
num = 0
for v in self.graph:
print ("==========================================")
print ("Vertex num",v.data1)
print ("Vertex value",v.data2)
if v.color == vertex_example.VertexColor.WHITE:
print ("WHITE")
elif v.color == vertex_example.VertexColor.GRAY:
print ("GRAY")
else:
print ("BLACK")
self.printAdjacency(num)
num += 1
class QueueList:
def __init__(self,q = None,s = 0):
self.vertexQueue = q
self.size = s
def enqueue(self,vertex):
self.vertexQueue.insert(0,vertex)
self.size += 1
def dequeue(self):
self.size -= 1
return self.vertexQueue.pop()
def isEmpty(self):
if self.size == 0:
return True
else:
return False
def printQueue(self):
print ("Vertex queue")
for v in self.vertexQueue:
print ("==========================================")
print ("Vertex num",v.data1)
print ("Vertex value",v.data2)
if v.color == vertex_example.VertexColor.WHITE:
print ("WHITE")
elif v.color == vertex_example.VertexColor.GRAY:
print ("GRAY")
else:
print ("BLACK")
########################################################################################
def BFS(G,s):
for u in G.graph:
if u.data1 != s.data1:
u.color = vertex_example.VertexColor.WHITE
u.data2 = 500000000
u.preview = None
s.color = vertex_example.VertexColor.GRAY
s.data2 = 0
s.preview = None
queueList = []
queueV = QueueList(q = queueList)
queueV.enqueue(s)
while not queueV.isEmpty():
u = queueV.dequeue()
for v in u.adjacency:
if v.color == vertex_example.VertexColor.WHITE:
v.color = vertex_example.VertexColor.GRAY
v.data2 = u.data2 + 1
v.preview = u
queueV.enqueue(v)
u.color = vertex_example.VertexColor.BLACK
def printPath(G,s,v):
if v == s:
print ("==========================================")
print ("Vertex value",v.data2)
if v.color == vertex_example.VertexColor.WHITE:
print ("WHITE")
elif v.color == vertex_example.VertexColor.GRAY:
print ("GRAY")
else:
print ("BLACK")
elif v.preview == None:
print ("Path don't exist")
else:
printPath(G,s,v.preview)
########################################################################################
def DFS(G):
for u in G.graph:
u.color = vertex_example.VertexColor.WHITE
u.preview = None
global time
time = 0
for u in G.graph:
if u.color == vertex_example.VertexColor.WHITE:
DFSvisit(G,u)
def DFSvisit(G,u):
global time
time += 1
u.data1 = time
u.color = vertex_example.VertexColor.GRAY
for v in u.adjacency:
if v.color == vertex_example.VertexColor.WHITE:
v.preview = u
DFSvisit(G,v)
u.color = vertex_example.VertexColor.BLACK
time += 1
u.data2 = time
def printTime(G):
for v in G.graph:
print ("Start time ",v.data1)
print ("Finish time ",v.data2)
def printDistance(G):
for v in G.graph:
print ("Distance to ",v.data1,"is",v.data2)
########################################################################################
graphList = []
graph = Graph(g = graphList)
vertexList = []
########################################################################################
'''
vertexList.append(vertex_example.Vertex(c=vertex_example.VertexColor.WHITE, d1=1, d2=22))
vertexList.append(vertex_example.Vertex(c=vertex_example.VertexColor.WHITE, d1=2, d2=45))
vertexList.append(vertex_example.Vertex(c=vertex_example.VertexColor.WHITE, d1=3, d2=12))
vertexList.append(vertex_example.Vertex(c=vertex_example.VertexColor.WHITE, d1=4, d2=52))
vertexList.append(vertex_example.Vertex(c=vertex_example.VertexColor.WHITE, d1=5, d2=72))
for v in vertexList:
graph.addVertexToGraph(v)
graph.addVertexAdjacent(0,vertexList[1])
graph.addVertexAdjacent(0,vertexList[4])
graph.addVertexAdjacent(1,vertexList[0])
graph.addVertexAdjacent(1,vertexList[4])
graph.addVertexAdjacent(1,vertexList[2])
graph.addVertexAdjacent(1,vertexList[3])
graph.addVertexAdjacent(2,vertexList[1])
graph.addVertexAdjacent(2,vertexList[3])
graph.addVertexAdjacent(3,vertexList[1])
graph.addVertexAdjacent(3,vertexList[4])
graph.addVertexAdjacent(3,vertexList[2])
graph.addVertexAdjacent(4,vertexList[3])
graph.addVertexAdjacent(4,vertexList[0])
graph.addVertexAdjacent(4,vertexList[1])
print ("Undirected graph")
graph.printGraphsVertexes()
########################################################################################
graphList = []
graph = Graph(g = graphList)
vertexList = []
vertexList.append(vertex_example.Vertex(c=vertex_example.VertexColor.WHITE, d1=1, d2=22))
vertexList.append(vertex_example.Vertex(c=vertex_example.VertexColor.WHITE, d1=2, d2=45))
vertexList.append(vertex_example.Vertex(c=vertex_example.VertexColor.WHITE, d1=3, d2=12))
vertexList.append(vertex_example.Vertex(c=vertex_example.VertexColor.WHITE, d1=4, d2=52))
vertexList.append(vertex_example.Vertex(c=vertex_example.VertexColor.WHITE, d1=5, d2=72))
vertexList.append(vertex_example.Vertex(c=vertex_example.VertexColor.WHITE, d1=6, d2=28))
for v in vertexList:
graph.addVertexToGraph(v)
graph.addVertexAdjacent(0,vertexList[1])
graph.addVertexAdjacent(0,vertexList[3])
graph.addVertexAdjacent(1,vertexList[4])
graph.addVertexAdjacent(2,vertexList[5])
graph.addVertexAdjacent(2,vertexList[4])
graph.addVertexAdjacent(3,vertexList[1])
graph.addVertexAdjacent(4,vertexList[3])
graph.addVertexAdjacent(5,vertexList[5])
'''
'''
print ("Directed graph")
graph.printGraphsVertexes()
'''
########################################################################################
'''
queueList = []
queueV = QueueList(q = queueList)
queueV.enqueue(vertexList[0])
queueV.enqueue(vertexList[1])
queueV.printQueue()
queueV.dequeue()
queueV.printQueue()
'''
vertexList.append(vertex_example.Vertex(c=vertex_example.VertexColor.WHITE, d2=0, d1='v'))
vertexList.append(vertex_example.Vertex(c=vertex_example.VertexColor.WHITE, d2=1, d1='r'))
vertexList.append(vertex_example.Vertex(c=vertex_example.VertexColor.WHITE, d2=2, d1='s'))
vertexList.append(vertex_example.Vertex(c=vertex_example.VertexColor.WHITE, d2=3, d1='w'))
vertexList.append(vertex_example.Vertex(c=vertex_example.VertexColor.WHITE, d2=4, d1='t'))
vertexList.append(vertex_example.Vertex(c=vertex_example.VertexColor.WHITE, d2=5, d1='x'))
vertexList.append(vertex_example.Vertex(c=vertex_example.VertexColor.WHITE, d2=6, d1='u'))
vertexList.append(vertex_example.Vertex(c=vertex_example.VertexColor.WHITE, d2=7, d1='y'))
for v in vertexList:
graph.addVertexToGraph(v)
graph.addVertexAdjacent(0,vertexList[1])
graph.addVertexAdjacent(1,vertexList[0])
graph.addVertexAdjacent(1,vertexList[2])
graph.addVertexAdjacent(2,vertexList[1])
graph.addVertexAdjacent(2,vertexList[3])
graph.addVertexAdjacent(3,vertexList[2])
graph.addVertexAdjacent(3,vertexList[4])
graph.addVertexAdjacent(3,vertexList[5])
graph.addVertexAdjacent(4,vertexList[3])
graph.addVertexAdjacent(4,vertexList[5])
graph.addVertexAdjacent(4,vertexList[6])
graph.addVertexAdjacent(5,vertexList[3])
graph.addVertexAdjacent(5,vertexList[4])
graph.addVertexAdjacent(5,vertexList[6])
graph.addVertexAdjacent(5,vertexList[7])
graph.addVertexAdjacent(6,vertexList[4])
graph.addVertexAdjacent(6,vertexList[5])
graph.addVertexAdjacent(6,vertexList[7])
graph.addVertexAdjacent(7,vertexList[5])
graph.addVertexAdjacent(7,vertexList[6])
#graph.printGraphsVertexes()
BFS(graph,vertexList[2])
printDistance(graph)
#printPath(graph,vertexList[2],vertexList[4])
'''
vertexList.append(vertex_example.Vertex(c=vertex_example.VertexColor.WHITE, d2=0, d1='x'))
vertexList.append(vertex_example.Vertex(c=vertex_example.VertexColor.WHITE, d2=1, d1='u'))
vertexList.append(vertex_example.Vertex(c=vertex_example.VertexColor.WHITE, d2=2, d1='v'))
vertexList.append(vertex_example.Vertex(c=vertex_example.VertexColor.WHITE, d2=3, d1='y'))
vertexList.append(vertex_example.Vertex(c=vertex_example.VertexColor.WHITE, d2=4, d1='w'))
vertexList.append(vertex_example.Vertex(c=vertex_example.VertexColor.WHITE, d2=5, d1='z'))
for v in vertexList:
graph.addVertexToGraph(v)
graph.addVertexAdjacent(0,vertexList[2])
graph.addVertexAdjacent(1,vertexList[0])
graph.addVertexAdjacent(1,vertexList[2])
graph.addVertexAdjacent(2,vertexList[3])
graph.addVertexAdjacent(3,vertexList[0])
graph.addVertexAdjacent(4,vertexList[3])
graph.addVertexAdjacent(4,vertexList[5])
graph.addVertexAdjacent(5,vertexList[5])
#graph.printGraphsVertexes()
DFS(graph)
printTime(graph)
'''
|
import datetime
class Timer():
def __init__(self):
self.start_time = None
self.end_time = None
def start(self):
self.start_time = datetime.datetime.now()
def stop(self):
self.end_time = datetime.datetime.now()
print("Time taken: %s" % (self.end_time - self.start_time)) |
# Упражнение №4. Задачи посложнее.
# 1. Переставьте соседние элементы в списке. Задача решается в три строки.
A=[1,2,3,4,5]
for i in range(len(A)-1):
A.insert(i,A.pop(A[i]))
print(A)
|
# Упражнение №12
# В списке — нечетное число элементов, при этом все элементы различны. Найдите медиану списка: элемент,
# который стоял бы ровно посередине списка, если список отсортировать.
# При решении этой задачи нельзя модифицировать данный список (в том числе и сортировать его),
# использовать вспомогательные списки.
#
# Программа получает на вход нечетное число N, в следующей строке заданы N элементов списка через пробел.
# Программа должна вывести единственное число — значение медианного элемента в списке.
# Ввод Вывод
# 7 4
# 6 1 9 2 3 4 8
n=int(input())
A = list(map(int, input().split()))
# используем встречный поиск, каждый раз перемещаемся ближе к медиане с двух сторон
first=min(A)
last=max(A)
for i in range(n//2): # за n/2 обходов по списку найдем
f=last # начиная с дальнего конца найдем ближайшее большее first
l=first # начиная с дальнего конца найдем ближайшее меньшее last
for j in range(0, len(A)):
if A[j]>first:
f=min(f,A[j])
if A[j]<last:
l=max(l,A[j])
first=f
last=l
print(str(first))
# точно также можно вывести print(str(last)) - эти числа равны
|
# Упражнение №9
# Вывести список в следующем порядке: первое число, последнее, второе, предпоследнее и так далее все числа.
#Ввод Вывод
#1 2 3 4 5 1 5 2 4 3
#Ввод Вывод
#1 2 3 4 1 4 2 3
A=[1,2,3,4,5]
B=[]
while len(A)>0:
B.append(A.pop(0)) # вытаскиваем из списка первый элемент и добавляем в B
if len(A)>0:
B.append(A.pop()) # вытаскиваем из списка последний элемент и добавляем в B
print(B)
A=[1,2,3,4]
B=[]
while len(A)>0:
B.append(A.pop(0)) # вытаскиваем из списка (с потерей) первый элемент и добавляем в B
if len(A)>0:
B.append(A.pop()) # вытаскиваем из списка (с потерей) последний элемент и добавляем в B
print(B)
|
#to optimize the algorthim i have used fractions
#import fractions funtion
import fractions
#define a function with ar argument n
def smallestdivisble(n):
#set the intial value to 1
number = 1
#set the range
for i in range(1,n+1):
#mutiply the i value with cureent number value and divide it wilth gdc for i and current number value
number = (number*i)/fractions.gcd(number,i)
#return the number
return number
#print the smallest divsible value.Final Required Value.Change the Limit required at the end of the function
print ("Smallest Divisble Value by 1 to 20 is"+str(smallestdivisble(20))) |
#Copy lines 2 to 5 first and paste them to console.
import pandas as pd
cars = pd.read_csv('cars.csv')
print("First 5 rows:")
cars.loc[[0,1,2,3,4]]
#Now, copy lines 7 and 8 then paste them to console.
print("Last 5 rows:")
cars.loc[[27,28,29,30,31]]
#Copy and paste the lines of code below to console in order to display the answers to the subproblem b.
soln_b1 = cars.loc[[0,1,2,3,4]]
soln_b2 = cars.loc[[27,28,29,30,31]] |
from zipfile import ZipFile
import os
import wget
def downloader_file(download_link, destino): #, tipo_arquivo, nome):
"""
Função para fazer download de um arquivo a partir
de uma única URL. O download é feito para a pasta
/arquivos/.
"""
file = wget.download(download_link,out=destino)
# os.rename('download',nome+'.'+tipo_arquivo)
return 'download concluído com sucesso!'
def downloader_lista(download_link, destino):
"""
Função para fazer o download de arquivos a partir
de uma lista de URLs dentro de um arquivo. O download
é feito passando o arquivo que contém as URLs na
variável donwload_link. Arquivos são salvos na
pasta /arquivos/.
"""
prefixo = os.getcwd()
arquivos_urls = prefixo + download_link
print(arquivos_urls)
# for file in arquivos_urls:
f = open(arquivos_urls, 'r')
urls = f.read().split()
f.close()
for url in urls:
filename = wget.download(url,out=prefixo+destino)
return 'download concluído com sucesso'
def downloader(download_link, destino,lista=False):
"""
Função juntando ambas possibilidades de download.
"""
if lista == False:
downloader_file(download_link, destino)
else:
downloader_lista(download_link,destino)
def descompactando (caminho_do_arquivo, tipo_arquivo, destino):
"""
Função para a descompactação de todos arquivos ZIP de uma
pasta, salvando o resultado em outra pasta.
"""
path = os.getcwd()
files = os.listdir(path + caminho_do_arquivo)
for file in files:
if file.endswith(tipo_arquivo):
file_path = path + caminho_do_arquivo + file
with ZipFile(file_path) as zip_file:
zip_file.extract(member=file.strip('.zip'), path=path+destino)
return 'arquivos descompactados com sucesso' |
def read_file_info(file_name: str):
number_of_chars = 0
number_of_words = 0
number_of_lines = 0
with open(file_name, 'r') as file:
for lines in file:
words = lines.split()
number_of_lines += 1
number_of_words += len(words)
number_of_chars += len(lines)
print("Number of Lines: {}\nNumber of Words: {}\nNumber of Characters: {}".format(number_of_lines,
number_of_words,
number_of_chars))
|
MENU = {
"espresso": {
"ingredients": {
"water": 50,
"coffee": 18,
},
"cost": 1.5,
},
"latte": {
"ingredients": {
"water": 200,
"milk": 150,
"coffee": 24,
},
"cost": 2.5,
},
"cappuccino": {
"ingredients": {
"water": 250,
"milk": 100,
"coffee": 24,
},
"cost": 3.0,
}
}
resources = {
"water": 300,
"milk": 200,
"coffee": 100,
}
# TODO: 1.Print report of all coffeeMachine resources
def print_remaining_resources():
print(f"Water: {report_water}ml")
print(f"Coffee: {report_coffee}ml")
print(f"Milk: {report_milk}ml")
print(f"Money: ${round(report_money,2)}")
# TODO: 2.Check the coins - Process coins
def calculate_coins ():
print("Please insert coins.")
nr_quarters = float(input("how many quarters?: "))
nr_dimes = float(input("how many dimes?: "))
nr_nickels = float(input("how many nickels?: "))
nr_pennies = float(input("how many pennies?: "))
total_amount = round( (nr_quarters * 0.25) + (nr_dimes * 0.1)+ (nr_nickels * 0.05) + (nr_pennies * 0.01), 2)
# print(total_amount)
return total_amount
# TODO: 3.Check the inventory Check resources sufficient?
def check_inventory(product):
water_needed = MENU[product]["ingredients"]["water"]
coffee_needed = MENU[product]["ingredients"]["coffee"]
# other option is to add the key milk in the dictionnary for espresso with a value of 0
# MENU["espresso"]["ingredients"]["milk"] = 0
if product == "espresso":
milk_needed = 0
else:
milk_needed = MENU[product]["ingredients"]["milk"]
if water_needed > report_water:
print(f"Sorry there is not enough water.")
return False
elif coffee_needed > report_coffee:
print(f"Sorry there is not enough coffee.")
return False
elif milk_needed > report_milk:
print(f"Sorry there is not enough milk.")
return False
else:
return True
# TODO: 8.Check the payment
def check_payment(coins_amount, product):
money_needed = MENU[product]["cost"]
# print(money_needed)
change = round(coins_amount - money_needed, 2)
if change < 0:
# te weinig betaald, maw geen product
return change
else:
# teveel of genoeg betaald, maw product & refund
print(f" Here is $ {change} dollars in change.")
return change
# TODO Process the order
def process_order(revenue, product):
# increase revenue
global report_money
report_money += revenue
# reduce inventory
global report_water
global report_coffee
global report_milk
report_water -= MENU[product]["ingredients"]["water"]
report_coffee -= MENU[product]["ingredients"]["coffee"]
if product != "espresso":
report_milk -= MENU[product]["ingredients"]["milk"]
# print the order
print(f"Here is your {product}. Enjoy!")
# initialization
report_money = 0
report_water = resources["water"]
report_milk = resources['milk']
report_coffee = resources['coffee']
coffeeMachine_running = True
# TODO: 4.Prompt user by asking “ What would you like? (espresso/latte/cappuccino):
while coffeeMachine_running:
coffee_choice = input("What would you like? (espresso/latte/cappuccino): ")
if coffee_choice == "report":
print_remaining_resources()
elif (coffee_choice == "espresso") or (coffee_choice == "latte") or (coffee_choice == "cappuccino"):
# check the inventory
if check_inventory(coffee_choice):
coins_amount = calculate_coins()
# TODO: 6.Check transaction successful
if check_payment(coins_amount, coffee_choice) >= 0:
# genoeg betaald & genoeg voorraad
revenue = MENU[coffee_choice]["cost"]
# print_remaining_resources()
# TODO: 7.Make Coffee.
process_order(revenue, coffee_choice)
# print_remaining_resources()
else:
print("Sorry that's not enough money. Money refunded. ")
else:
check_inventory(coffee_choice)
# TODO: 5.turn off the Coffee Machine by entering “ off ” to the prompt.
elif coffee_choice == "off":
coffeeMachine_running = False
|
# part 1
def countdown(num):
result = []
for x in range(num, -1, -1):
result.append(x)
return result
print(countdown(12))
# part 2
def firstsecond(x):
print(x[0])
return(x[1])
x = firstsecond([1,2])
print(x)
# part 3
def first_plus_length(arr):
return arr[0] + len(arr)
total = first_plus_length([1,2,3,4,5,6])
print(total)
# part 4
def values_greater_than_second(a):
newList = []
count = 0
for i in range(0 , len(a), 1):
if (a[i] > a[1]):
newList.append(a[i])
count = count + 1
print(count)
if (len(newList) < 2):
return false
return newList
print(values_greater_than_second([10,2,3,6,1,5]))
# part 5
def this_length_that_value(size, value):
newList = []
for i in range(size):
newList.append(value)
return newList
print(this_length_that_value(10,2))
print(this_length_that_value(10, 5)) |
# -*-encoding:utf-8-*-
import os
KEYWORD_FILE_PATH = "./keyword.txt"
class Keyword:
def __init__(self):
if not os.path.exists(KEYWORD_FILE_PATH):
with open(KEYWORD_FILE_PATH, "w")as fw:
fw.write("# 关键词格式如下,由#分隔\n")
fw.write("关键词1#关键词2#关键词n#") # 每个关键词后面带#,这是标准格式
def GetKeyword(self):
keyword_list = []
keyword_file = open(KEYWORD_FILE_PATH, "r")
for line in keyword_file:
# Parse不是由#开头的第一行关键词
if not line.startswith("#"):
keyword_list = line.split("#")
break
return keyword_list
def SetKeyword(self, keyword):
try:
with open(KEYWORD_FILE_PATH, "a") as fw:
fw.write("{}#".format(keyword))
return True, "成功"
except:
return False, "无法打开keyword文件"
def RemoveKeyword(self, key):
keyword_file = open(KEYWORD_FILE_PATH, "r+")
line = ""
for line in keyword_file:
if not line.startswith("#"):
break
new_line = line.replace(key+'#', '')
if new_line != line:
keyword_file.seek(0)
keyword_file.truncate()
keyword_file.write(new_line)
keyword_file.close()
return True, "成功"
else:
keyword_file.close()
return False, "失败,列表中无此关键词"
def ClearKeyword(self):
try:
with open(KEYWORD_FILE_PATH, "w")as fw:
fw.write("")
return True, "清空关键词成功"
except:
return False, "清空关键词失败,无法打开keyword文件"
def ShowKeyword(self):
keyword_list = []
# Parse不是由#开头的第一行关键词
for line in open(KEYWORD_FILE_PATH, "r"):
if not line.startswith("#"):
keyword_list = line.split("#")
break
msg_send = "现有的关键词:\n"
for item in keyword_list:
if item:
msg_send += "{}\n".format(item)
return msg_send
|
for n in range(1,10):
for m in range(1,10):
print("%d*%d = %2d"%(m, n, n*m), end="\t")
print("\n")
|
# # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
#
# class Solution:
# def maxDepth(self, root: TreeNode) -> int:
# if root is None:
# return 0
# stack = [(1, root)]
# depth = 0
# while stack:
# cur_dep, node = stack.pop()
# depth = max(depth, cur_dep)
# if node.right:
# stack.append((cur_dep+1,node.right))
# if node.left:
# stack.append((cur_dep+1,node.left))
# return depth
# root=TreeNode([3,9,20,None,None,15,7])
# a=Solution()
# # root=[3,9,20,None,None,15,7]
# print(a.maxDepth(root))
# N=2
# dp = [0] * (N+1)
# print(dp)
'''
def isValid(s: str) -> bool:
dic = {')': '(', ']': '[', '}': '{'}
stack = []
for i in s:
stack.if
if stack and i in dic:
if stack[-1] == dic[i]:
stack.pop()
else:
return False
else:
stack.append(i)
return not stack
print(isValid('(){}[]'))
'''
# a=[1,2,3,41,1,12,2]
# a.sort()
# print(a)
'''
def findUnsortedSubarray( nums) -> int:
temp = nums[:]
nums.sort()
n = len(nums)
for i in range(n):
if temp[i] == nums[i]:
i += 1
else:
break
for j in range(n):
if temp[-(j + 1)] == nums[-(j + 1)]:
j += 1
else:
break
return (n - i - j)
print(findUnsortedSubarray([2,6,4,8,10,9,15]))
'''
# def lengthOfLongestSubstring(s) -> int:
# if not s:
# return 0
# length = []
# maxlength = 0
# for i in s:
# if i not in length:
# length.append(i)
# else:
#
# length[:] = length[length.index(i) + 1:]
# length.append(i)
# maxlength = max(maxlength, len(length))
# return maxlength
#
# dic = {1: 2, 3: 4 }
# a=1
# def isValid(s) -> bool:
# dic = {')': '(', ']': '[', '{': '}'}
# stack = []
# for i in s:
# if i in dic:
# if stack in dict:
# if stack[-1] == dic[i]:
# stack.pop()
# else:
# return False
# else:
# stack.append(i)
#
# return not stack
# isValid('{}(){}')
# b=2
# if b and a in dic:
# print(111)
# def findUnsortedSubarray( nums) -> int:
# bb = nums.sort()
# bb = sorted(nums)
# maxi = 0
# mini = 0
# flag = 1
# for i in range(len(nums)):
# if nums[i] != bb[i] and flag:
# mini = i
# flag -= 1
# if nums[i] != bb[i]:
# maxi = i
# return (maxi - mini + 1)
# print(findUnsortedSubarray([2,6,4,8,10,9,15]))
# def combinationSum2( candidates, target) :
# n = len(candidates)
# result = []
# candidates.sort()
# def back(idx,tmp_num,tmp_list):
# if tmp_num == target :
# result.append(tmp_list)
# return
# for i in range(idx,n):
# if tmp_num+candidates[i]>target:
# break
# back(i+1,tmp_num+candidates[i],tmp_list+[candidates[i]])
# back(0,0,[])
# return result
# print(combinationSum2([10,1,2,7,6,1,5],8))
# import sys
# sys.setrecursionlimit(100000)
# def coinChange(coins, amount) :
# n = len(coins)
# result = []
# coins.sort(reverse=True)
# aa = 0
#
# def back(idx, tmp_num, tmp_list):
# print(result)
# if tmp_num == amount:
# result.append(tmp_list)
# return
# for i in range(idx, n):
# # print(1)
# if tmp_num > amount:
# break
# back(i, tmp_num + coins[i], tmp_list + [coins[i]])
#
# back(0, 0, [])
# if not result:
# return -1
# return min([len(i) for i in result])
# def coinChange( coins, amount: int) -> int:
# dp = [float("inf")] * (amount + 1)
# dp[0] = 0
# for i in range(1, amount + 1):
# for coin in coins:
# if (i >= coin):
# dp[i] = min(dp[i], dp[i - coin] + 1)
# return dp[-1] if (dp[-1] != float("inf")) else -1
#
#
# print(coinChange([3,7,4,3],67))
# def maxSubArray( nums) -> int:
# size = len(nums)
#
# if size == 0:
# return 0
# dp = [0 for _ in range(size)]
#
# dp[0] = nums[0]
# for i in range(1, size):
# dp[i] = max(dp[i - 1] + nums[i], nums[i])
# print(dp)
# return max(dp)
# def lengthOfLIS( nums) -> int:
# n = len(nums)
# dp = [1] * n
# for i in range(1, n):
# for j in range(i):
# if nums[j] < nums[i]:
# dp[i] = max(dp[i], dp[j] + 1)
# print(dp)
# return max(dp or [0])
#
# print(lengthOfLIS([-2,1,-3,4,-1,2,1,-5,1]))
# def reverseLeftWords( s: str, n: int) -> str:
# s = list(s)
# for i in range(n):
# s.append(s[i])
# return s[n:]
#
#
# print(reverseLeftWords('abcdefg',5))
# def findContinuousSequence(target):
# aa = [i for i in range(1,int(target / 2) + 2)]
# bb = []
# for i in range(int(target / 2) ):
# result = 0
# j = i
# while (result < target):
# # print(i)
# result += aa[i]
# i += 1
# if result == target:
# bb.append(aa[j:i])
#
# return bb
import collections
#
# dic = collections.Counter([1,1,1,1,1,1,2,3,4,5,6,3])
# # print(dic)
# def twoSum( nums, target):
# adic = {}
# for i in nums:
# if i in adic:
# adic[i] += 1
# else:
# adic[i] = 1
# for i in nums:
# if (target - i) in adic and target != i * 2:
# return [i, target - i]
# print(twoSum([14,15,16,22,53,60]
# ,76))
#
# def exchange( nums) :
# a = 0
# for i in range(1,len(nums)):
# if nums[i] % 2 == 0:
# a+=1
# nums.append(nums[i])
# # nums.remove(nums[i])
# return nums[a:]
# print(exchange([2,16,3,5,13,1,16,1,12,18,11,8,11,11,5,1]))
# a=[1,2,3]
# a[0],a[2] = a[2],a[0]
# # a.pop(1)
# # print(list(range(5)))
# while True:
# for i in range(5):
# a=1
# if a ==1:
# break
# print(11)
# print(22)
# import sys
# K, N = map(int,sys.stdin.readline().strip().split())
# Num = list(map(int, input().strip().split()))
# # print(Num)
# result = 0
# count=0
# flag = 1
# f =1
# flag2=1
# flag3=1
# if K<Num[0]:
# for i in range(N):
# if result < K and flag == 1:
# result = result + Num[i]
# abs(result)
# else:
# result = result - Num[i]
# # abs(result)
# if result > K or abs(result) != result:
# count += 1
# result = abs(result)
# result = result % K
# flag -= 1
# if result == K:
# print(i)
# f -= 1
# print('paradox')
# if sum(Num) < K:
# print(K - result, count)
# flag2 -= 1
# if f and flag2 == 1:
# print(result, count)
# for i in range(N):
# if count==0 or result<K and flag==1 :
# result= result+Num[i]
# abs(result)
# else:
# result=result-Num[i]
# # abs(result)
# if result>K or abs(result)!=result :
# count+=1
# result=abs(result)
# result= result%K
# flag-=1
# if result==K:
# print(i)
# f-=1
# print('paradox')
# if sum(Num)<K:
# print(K-result, count)
# flag2-=1
# if f and flag2==1:
# print(result,count)
# print(abs(-1))
# print(n,m)
# import sys
# land = []
# for i in range(6):
# line = sys.stdin.readline().strip()
# values = list( line.split())
# land.append(values)
# print(land)
# def findNumberIn2DArray( matrix, target: int) -> bool:
# m, n = len(matrix) - 1, 0
# # for i in range(m): 不知道循环次数 用while
# while m >=0 and n < len(matrix[0]):
# print(m,n)
# if matrix[m][n] > target:
# m -= 1
# elif matrix[m][n] < target:
# n += 1
# else:
# return True
# return False
# print(findNumberIn2DArray([[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]]
# ,20))
# def maxValue( grid) -> int:
# m, n = len(grid[0]), len(grid)
# dp = [[0] * m for i in range(n)]
# for i in range(m):
# for j in range(n):
# if i == 0 and j == 0:
# dp[j][i] = grid[0][0]
# elif i == 0 and j != 0:
# dp[j][i] = dp[j - 1][i] + dp[j][i]
# elif i != 0 and j == 0:
# dp[j][i] = dp[j][i - 1] + dp[j][i]
# else:
# dp[j][i] = max(dp[j - 1][i], dp[j][i - 1]) + dp[j][i]
# return dp[-1][-1]
# def maxProfit( prices) -> int:
# minprice = float('+inf')
# maxprofit = 0
# for i in range(len(prices)):
# minprice = min(minprice, prices[i])
# maxprofit = max(prices[i] - minprice, maxprofit)
# return maxprofit
# print(maxProfit([7,1,5,3,6,4]))
# a= list(range(5))
# print(a[1:3])
# Num = list(map(int, input().strip().split()))
# # print(Num)
# res=[]
# while True:
# try:
# s =input()
# res.append(list(map(int,s.split(' '))))
# except:
# break
# def calc_area(rect1, rect2):
# xl1, yb1, xr1, yt1 = rect1
# xl2, yb2, xr2, yt2 = rect2
# xmin = max(xl1, xl2)
# ymin = max(yb1, yb2)
# xmax = min(xr1, xr2)
# ymax = min(yt1, yt2)
# width = xmax - xmin
# height = ymax - ymin
# if width <= 0 or height <= 0:
# return 0
# cross_square = width * height
# return cross_square
# def cal_area(rec):
# x1,y1,x2,y2=rec
# area=abs(x2-x1)*abs(y2-y1)
# return area
# for i in res:
# rect1 =i[0:4]
# rect2 = i[4:8]
# cross=calc_area(rect1,rect2)
# area1 = cal_area(rect1)
# area2 = cal_area(rect2)
# print(area1+area2-cross)
# res=[]
# for line in input():
# res.append(line.split())
# print(res)
# class Diycontextor:
# def __init__(self, name, mode):
# self.name = name
# self.mode = mode
#
# def __enter__(self):
# print("Hi enter here!!")
# self.filehander = open(self.name, self.mode)
# return self.filehander
#
# def __exit__(self, *para):
# print( "Hi exit here")
# self.filehander.close()
#
#
# with Diycontextor('py_ana.py', 'a+') as f:
# for i in f:
# print(i)
# res=[]
# for i in range(2):
# Num = list(map(str, input().strip().split()))
# res.append(Num)
# tem1 = dict()
# tem2 = dict()
# for item in res[0][0]:
# tem1[item] =0 if (item not in tem1) else tem1[item]+1
# for item in res[1][0]:
# tem2[item] =0 if (item not in tem2) else tem2[item]+1
# if tem1==tem2:
# print(1)
# else:
# print(0)
# n= int(input().strip())
# n= int(input().strip())
# # def count_prime(n):
# # if n<7:
# # return 0
# # isPrime =list(range(n))
# # isPrime[0]=isPrime[1]=0
# # for i in range(2,int(n**0.5)+1):
# # if isPrime[i]:
# # isPrime[i*i:n:i] = [0]*((n-1-i*i)//i+1)
# # isPrime=filter(lambda x:x!=0,isPrime)
# # p=list(isPrime)
# #
# # i ,j ,res =0,1,[]
# # while p[j] <= n//2+1:
# # cur_sum =sum(p[i:j+1])
# # if cur_sum < n:
# # j+=1
# # elif cur_sum>n:
# # i+=1
# # else:
# # res.append(p[i:j+1])
# # j+=1
# # flag =1
# # for i in range(2, n):
# # if n % i == 0:
# # break
# # else:
# # flag-=1
# # if flag==0:
# # return len(res)+1
# # else:
# # return len(res)
# # print(count_prime(n))
# list = [1,2,3,4]
# print(next(iter(list)))
# for i in iter(list):
# print(i)
#
# import csv
#
# with open('/Users/andy/Desktop/aic_origin_result.csv') as f:
#
# f_csv = csv.reader(f)
#
# headers = next(f_csv)
#
# print(headers)
#
# for row in f_csv:
#
# print(row)# type:list
# for i in range(5):
# print(i)
# if i == 3:
# break
# print(11111)
# s = input().strip()
# print(s)
# dic = {}
# for i in s:
# if i in dic:
# dic[i]+=1
# else:
# dic[i]=1
# #
# # print(dic['o'])
# n = len(s)
# ls = []
# for i in range(n):
# if s[i] == 'G':
# ls.append(s[i])
# for j in range(i,n):
# s[j]
# t = input().strip()
# s = 'Good'
# n,m = len(s),len(t)
# inx = 999999
# flag = 1
# while inx >= m-1:
# if flag ==1:
# inx=-1
# flag-=1
# for i in range(n):
# for j in range(inx+1,m):
# if t[j] == s[i]:
# inx = j
# if inx ==m:
# break
# print(inx)
# break
# else:
# print(0)
# print(1)
# #
# a,b = [int(i) for i in input().split()]
# ls=[]
# for i in range(a):
# Num = list(map(int, input().strip().split()))
# ls.append(Num)
# if not ls:
# print(0)
# x = len(ls)
# y = len(ls[0])
# dp = [[1 for _ in range(y)]for _ in range(x)]
# numsSort = sorted(sum([[(ls[i][j],i,j) for j in range(y)]for i in range(x)],[]))
# for i,j,k in numsSort:
# dp[j][k] = 1+max(
# dp[j-1][k] if j and ls[j-1][k]<i else 0,
# dp[j][k-1] if k and ls[j][k-1] < i else 0,
# dp[j + 1][k] if j!=x-1 and ls[j + 1][k] < i else 0,
# dp[j ][k+1] if k!=y-1 and ls[j][k+1] < i else 0
# )
# print(max(sum(dp,[])))
# # # n = int(sys.stdin.readline().strip())
# # ans = 0
# for i in range(a):
# # 读取每一行
# line = sys.stdin.readline().strip()
# # 把每一行的数字分隔后转化成int列表
# values = list(map(int, line.split()))
# for v in values:
# ans += v
# print(ans)
# import sys
# n = int(sys.stdin.readline().strip())
# ans = 0
# for i in range(n):
# # 读取每一行
# line = sys.stdin.readline().strip()
# # 把每一行的数字分隔后转化成int列表
# values = list(map(int, line.split()))
# for v in values:
# ans += v
# print(ans)
# print(7//2)
# s = input().strip()
# ans = 0
# ans2=0
# count = 0
# count2=0
# for i in s:
# if i =='(' or i ==')':
# if i == '(':
# ans+=1
# else:
# ans-=1
# if ans<0:
# count+=1
# ans+=1
# count+=ans
# # print(count)
# for i in s:
# if i =='[' or i ==']':
# if i == '[':
# ans2+=1
# else:
# ans2-=1
# if ans2<0:
# count2+=1
# ans2+=1
# count2+=ans2
# #
# print(count+count2)
num = input().strip()
num = int(num)
ls =[]
def de(f,C,D):
unit = (D-C)/10000
s=0
for i in range(10000):
s+= f(C+unit*i)*unit
return s
for i in range(num):
Num = list(map(int, input().strip().split()))
A,B,C,D= Num
def f(x):
return A*x**2+x+B
# f = lambda x:A*x**2+x+B
result=de(f,C,D)
ls.append(result)
for i in range(len(ls)):
print(ls[i])
# num = input().strip()
# num = int(num)
# if num<1 or num>10**9:
# print(0)
# print((num*(2**(num-1)))%(10**9+7))
#
# s = input().strip()
# if not s:
# print(0)
# else:
# ans = 0
# ans2=0
# count = 0
# count2=0
# for i in s:
# if i =='(' or i ==')':
# if i == '(':
# ans+=1
# else:
# ans-=1
# if ans<0:
# count+=1
# ans+=1
# count+=ans
# for i in s:
# if i =='[' or i ==']':
# if i == '[':
# ans2+=1
# else:
# ans2-=1
# if ans2<0:
# count2+=1
# ans2+=1
# count2+=ans2
# print(count+count2)
# import
# num = input().strip()
# num = int(num)
|
'''message = "Hello , How are you?"
print(message)
'''
simple_math_string = f"2+3 is equal to {2+3} "
print(simple_math_string)
s = "Hi"
print(s[1])
print(len(s))
print(s + ' there')
|
# A list is a collection which is ordered and changeable. Allows duplicate members
# Create a list
numbers = [1, 2, 3, 4, 5]
fruits = ['Apples', 'Oranges', 'Grapes', 'Pears']
# Use a constructor
# numbers2 = list((1, 2, 3, 4, 5))
# print(numbers, numbers2)
# Get a value
print(fruits[1])
# Get length
print(len(fruits))
# Append to the list
fruits.append('Guava')
# Print
print(fruits)
# Remove from the list
fruits.remove('Grapes')
print(fruits)
# Insert into position
fruits.insert(2, 'Strawberries')
print(fruits)
# Change values
fruits[0] = 'Blueberries'
print(fruits)
# Remove with pop
fruits.pop(2)
# Reverse list
fruits.reverse()
print(fruits)
# Sort list
fruits.sort()
print(fruits)
# Reverse sort
fruits.sort(reverse=True)
print(fruits)
|
import numpy as np
import math
class Spherical(object):
'''
(x - a)^2 + (y - b)^2 = r^2
so circles have a centerpoint (a,b) and a radius (r)
'''
def __init__(self, focal_length, depth, height):
self.height = height
self.r = abs(self.focal_length_to_radius(focal_length))
self.fl = focal_length
self.a = None
self.b = 0
self.depth = depth
def set_x_offset(self, x_offset):
if self.fl < 0: # We wanna bounce off the right side of the circle
self.a = x_offset - self.r
else: # we wanna bounce off the left side?
self.a = x_offset + self.r
print "SETTING OFFSET"
print "offset, radius, a:", x_offset, self.r, self.a
def prop(self, eqns):
a = self.a
# b = self.b
r = self.r
result_ms = []
result_bs = []
result_xs = []
result_ys = []
result_freqs = []
result_colors = []
for eq in eqns:
m, b, old_x, old_y, freq = eq
if m == 0:
'''
The special case is super easy
(x - a)^2 + (y - b)^2 = r^2
(x - a) = sqrt(r^2 - (y - b)^2)
x = sqrt(r^2 - (y - b)^2) + a
x = sqrt(r^2 - y^2) + a
'''
y0 = b
x0 = math.sqrt(self.r * self.r - y0 * y0) + self.a
else:
# Newton's Method
# y0 = b
# for i in xrange(1):
# fy = a * y0 * y0 - (1.0 / m) * y0 + c + b / m
# fydot = 2 * a * y0 - (1.0 / m)
# y1 = y0 - fy / fydot
# y0 = y1
# x0 = a * y0 * y0 + c
x0 = self.a + self.r
for i in xrange(10):
# fx = (-m * m - 1) * x0 * x0 + (2 * a + 2 * b * m) * x0 + b * b - a * a + r * r
# fxdot = 2 * (-m * m - 1) * x0 + (2 * a + 2 * b * m)
fx = (m * m + 1) * x0 * x0 + (2 * b * m - 2 * a) * x0 + b * b + a * a - r * r
fxdot = 2 * (m * m + 1) * x0 + (2 * b * m - 2 * a)
x1 = x0 - fx / fxdot
if x1 - x0 == 0:
break
x0 = x1
y0 = m * x0 + b
# Okay we've found the intercept, let's reflect.
# First step is to find the slope of the reflected line
slope_inverse = -y0 / math.sqrt(self.r * self.r - y0 * y0)
# print "SI", x0, y0, slope_inverse
if slope_inverse == 0:
# Another special case: the parabola is perfectly vertical here
# All we gotta do is reflect off a vertical line, which amounts
# to flipping the sign of the slope
final_m = -m
else:
M1 = 1 / slope_inverse
M2 = m
M3 = (M1 * M1 * M2 + 2 * M1 - M2) / (1 + 2 * M1 * M2 - M1 * M1)
final_m = M3
# Great, just plug in the slope and a know point on the line
# To find the y intercept
final_b = y0 - final_m * x0
result_ms.append(final_m)
result_bs.append(final_b)
result_xs.append(x0)
result_ys.append(y0)
result_freqs.append(freq)
return np.array(zip(
result_ms, result_bs, result_xs, result_ys, result_freqs))
def focal_length_to_radius(self, focal_length):
return focal_length * 2
def __str__(self):
return "Spherical: x = Math.sqrt(Math.pow({}, 2) - Math.pow(y, 2)) + {} : {}".format(self.r, self.a, self.height)
|
import random
def repeat():
print("To play again, type PLAY")
response = input("> ")
if response == "PLAY":
game()
def game():
rand = random.randint(1, 10)
guesses = 0
guessed = 0;
print("Welcome to the Number Guessing Game.")
while guessed != rand:
if guesses == 5:
print("You ran out of guesses! The number was {}.".format(rand))
break
print("Guesses remaining: {}".format(5 - guesses))
guessed = input("Please guess a whole number from 1 to 10: ")
guessed = int(guessed)
if guessed == rand:
print("Congratulations! {} is the right number!".format(guessed))
break
if guessed > rand:
print("The random number is lower!")
guesses = guesses + 1
continue
if guessed < rand:
print("The random number is higher!")
guesses = guesses + 1
continue
game()
repeat()
|
#!/usr/bin/env python
#
# ===============================================================
# ADVENT OF CODE
# ===============================================================
# DAY 12 FERRY LOGO
#
# A: Manhattan distance between start and end points
# B:
# ===============================================================
INPUTFILE = "day12.input"
def main():
input = open(INPUTFILE, 'r')
pos = [0, 0]
waypoint = [10, 1]
direction = 90
# PART A
# read values
for line in input:
line = line.rstrip()
cmd = line[0]
val = int(line.rstrip()[1:])
x = 0
y = 0
if(cmd == "F"):
if(direction == 0):
cmd = "N"
elif(direction == 90):
cmd = "E"
elif(direction == 180):
cmd = "S"
elif(direction == 270):
cmd = "W"
else:
print("DIRECTION {} not recognized.".format(direction))
exit(1)
if(cmd == "S"):
y = val * -1
if(cmd == "N"):
y = val
if(cmd == "E"):
x = val
if(cmd == "W"):
x = val * -1
if(cmd == "R"):
direction = (direction + val) % 360
if(cmd == "L"):
direction -= val
if(direction < 0):
direction += 360
pos = [pos[0] + x, pos[1] + y]
print("PART A: Manhattan distance: {} ({})".format(abs(pos[0])+abs(pos[1]), pos))
# PART B
input.seek(0)
pos = [0, 0]
# read values
for line in input:
line = line.rstrip()
cmd = line[0]
val = int(line.rstrip()[1:])
x = 0
y = 0
if(cmd == "F"):
for i in range(val):
pos = [pos[0] + waypoint[0], pos[1] + waypoint[1]]
if(cmd == "S"):
waypoint = [waypoint[0], waypoint[1] - val]
if(cmd == "N"):
waypoint = [waypoint[0], waypoint[1] + val]
if(cmd == "E"):
waypoint = [waypoint[0] + val, waypoint[1]]
if(cmd == "W"):
waypoint = [waypoint[0] - val, waypoint[1]]
# should be some geometry here, but we cheat because
# directions are modulo 90 (E/W/N/S 90/270/0/180)
if(cmd == "R"):
direction = val
if(cmd == "L"):
direction = 360 - val
if(cmd == "R" or cmd == "L"):
# rotate the waypoint around the ship
if(direction == 90):
waypoint = [waypoint[1], -waypoint[0]]
elif(direction == 270):
waypoint = [-waypoint[1], waypoint[0]]
elif(direction == 180):
waypoint = [-waypoint[0], -waypoint[1]]
waypoint = [waypoint[0] + x, waypoint[1] + y]
# print(cmd, val, " : waypoint:", waypoint)
# print(cmd, val, " : pos:", pos)
print("PART B: Manhattan distance: {} ({})".format(abs(pos[0])+abs(pos[1]), pos))
# print("PART B: sum of memory: {}".format(total_b))
if __name__ == "__main__":
main() |
courses = [ 'bch310' , 'bch311' , 'bch312' , 'bch313' , 'bch315' , 'pbb313' , 'chm311' , 'ced300' ]
grades = {
'A':5,
'B':4,
'C':3,
'D':2,
'F':0
}
courses_credits = {
'bch310' : 5,
'bch311' : 2,
'bch312' : 4,
'bch313' : 4,
'bch315' : 2,
'pbb313': 3,
'chm311': 4,
'ced300' : 2,
'bch321' : 6
}
total_array_grade =[]
total_array_credits = sum(courses_credits.values())
print("Hello I am your friendly GPA calculator")
print()
while True:
grade_bch310= input("Enter the grade for BCH310 ").upper()
grade_bch311= input("Enter the grade for BCH311 ").upper()
grade_bch312= input("Enter the grade for BCH312 ").upper()
grade_bch313= input("Enter the grade for BCH313 ").upper()
grade_bch315= input("Enter the grade for BCH315 ").upper()
grade_pbb313= input("Enter the grade for PBB313 ").upper()
grade_chm311= input("Enter the grade for CHM311 ").upper()
grade_ced300= input("Enter the grade for CED300 ").upper()
grade_bch321= input("Enter the grade for BCH321 ").upper()
break
total_array_grade.append({
'BCH310' : grade_bch310,
'BCH311' : grade_bch311,
'BCH312' : grade_bch312,
'BCH313' : grade_bch313,
'BCH315' : grade_bch315,
'PBB313' : grade_pbb313,
'CHM311' : grade_chm311,
'CED300' : grade_ced300,
'BCH321' : grade_bch321
})
def arraygrade():
for grade in total_array_grade:
try:
context ={
'bch310' : grade["BCH310"],
'bch311' : grade["BCH311"],
'bch312' : grade["BCH312"],
'bch313' : grade["BCH313"],
'bch315' : grade["BCH315"],
'pbb313' : grade["PBB313"],
'chm311' : grade["CHM311"],
'bch321' : grade["BCH321"],
'ced300' : grade["CED300"]
}
except Exception as e:
pass
return context
def calculate(variable):
context=arraygrade()
if context[variable] == "A":
credit_weight = 5 * courses_credits[variable]
return credit_weight
elif context[variable] == "B":
credit_weight = 4 * courses_credits[variable]
return credit_weight
elif context[variable] == "C":
credit_weight = 3 * courses_credits[variable]
return credit_weight
elif context[variable] == "D":
credit_weight = 2 * courses_credits[variable]
return credit_weight
elif context[variable] == "F":
credit_weight = 0 * courses_credits[variable]
return credit_weight
bch310 = "bch310"
bch311 = "bch311"
bch312 = "bch312"
bch313 = "bch313"
bch315 = "bch315"
pbb313 = "pbb313"
ced300 = "ced300"
bch321 = "bch321"
chm311 = "chm311"
def results():
#result = []
points = {
'bch310' :0 ,
'bch311' :0 ,
'bch312' :0,
'bch313' : 0,
'bch315' : 0,
'pbb313' : 0,
'chm311' :0,
'ced300' : 0,
'bch321' : 0,
}
bch310_points = calculate(bch310)
bch311_points = calculate(bch311)
bch312_points = calculate(bch312)
bch313_points = calculate(bch313)
bch315_points = calculate(bch315)
pbb313_points = calculate(pbb313)
ced300_points = calculate(ced300)
bch321_points = calculate(bch321)
chm311_points = calculate(chm311)
try:
points["bch310"] = bch310_points
points["bch311"] = bch311_points
points["bch313"] = bch313_points
points["bch315"] = bch315_points
points["bch312"] = bch312_points
points["pbb313"] = pbb313_points
points["chm311"] = chm311_points
points["ced300"] = ced300_points
points["bch321"] = bch321_points
except:
pass
try:
gpa_result_total = sum(points.values())
gpa_300_level = gpa_result_total / total_array_credits
print()
print()
print(f"Your 300 level GPA is {gpa_300_level} ")
print()
except Exception as e:
print("Something went wrong somewhere , check your inputs and try again")
results()
|
n = int(input())
res = []
for _ in range(n):
i = int(input())
if not res or i != res[-1]:
res.append(i)
for i in res:
print(i)
# METHOD 2
#n = int(input())
#res = []
#
#for _ in range(n):
# i = int(input())
# if i not in res:
# res.append(i)
#
#for i in res:
# print(i)
# METHOD 3
#n = int(input())
#buf = None
#res = []
#
#for _ in range(n):
# i = int(input())
# if buf:
# if i > buf:
# res.append(i)
# buf = i
# else:
# res.append(i)
# buf = i
#
#for i in res:
# print(i)
|
def is_parent(dic, child, parent):
if child == parent:
return True
for e in dic[child]:
if is_parent(dic, e, parent):
return True
return False
n = int(input())
parents = {}
for _ in range(n):
a = input().split()
parents[a[0]] = [] if len(a) == 1 else a[2:]
m = int(input())
exceptions = []
for _ in range(m):
e = input()
for e_parent in exceptions:
if is_parent(parents, e, e_parent):
print(e)
break
exceptions.append(e)
|
''' Combines sentences from wikipedia articles '''
from bs4 import BeautifulSoup
from nltk import pos_tag, word_tokenize
import re
import requests
import sys
def get_page(page=None):
''' load and parse a wikipedia page '''
if page and page != 'http://en.wikipedia.org/wiki/':
r = requests.get(page)
else:
r = requests.get('http://en.wikipedia.org/wiki/Special:Random')
soup = BeautifulSoup(r.text)
page_topic = soup.find('h1').text
page_content = soup.find('div', {'id': 'mw-content-text'})
paragraphs = page_content.findChildren('p')
# skip lists
if re.match(r'^List[s]? ', page_topic) and not page:
return get_page()
# skip disambiguation pages
match = re.search(r'[can|may] refer to', paragraphs[0].text)
if match and not page:
return get_page()
sentences = []
for paragraph in paragraphs:
paragraph = paragraph.text
# remove citation footnotes: [1]
paragraph = re.sub(r'\[[0-9].?\]', '', paragraph)
paragraph = re.sub(r'[\s]+', ' ', paragraph)
# remove parentheticals: (whateva)
paragraph = re.sub(r' \(.*\)', '', paragraph)
sentences += paragraph.split('. ')
for sentence in sentences:
if sentence == '' or re.match(r'^\s$', sentence):
sentences.remove(sentence)
sentence = sentence.strip()
return {'topic': page_topic, 'text': sentences}
def get_pos_tags(sentences):
''' uses nltk to tag part of speech for each sentence '''
tagged = []
for sentence in sentences:
tags = pos_tag(word_tokenize(sentence))
# throw out sentenes with no verb
verbs = [word for word in tags if word[1].startswith('VB')]
if len(verbs):
tagged.append(tags)
return tagged
def merge_sentences(primary, secondary):
''' combines two pos tagged sentences '''
joined_sentence = []
for word in primary:
if word[1][:2] == 'VB':
break
else:
joined_sentence.append(word[0])
isAddable = False
for word in secondary:
if word[1][:2] == 'VB':
isAddable = True
if isAddable:
joined_sentence.append(word[0])
return ' '.join(joined_sentence)
if __name__ == '__main__':
wiki_url = 'http://en.wikipedia.org/wiki/'
primary_page = wiki_url + sys.argv[1] if len(sys.argv) >= 2 else None
secondary_page = wiki_url + sys.argv[2] if len(sys.argv) >= 3 else None
content = [get_page(primary_page), get_page(secondary_page)]
for item in content:
item['tagged'] = get_pos_tags(item['text'][:20])
facts = []
while len(content[0]['tagged']) and len(content[1]['tagged']):
facts.append(merge_sentences(content[0]['tagged'].pop(0),
content[1]['tagged'].pop(0)))
# display the results
print '%s + %s' % (content[0]['topic'], content[1]['topic'])
for fact in facts:
fact = re.sub(r' \.', '.', fact)
fact = re.sub(r' ,', ',', fact)
fact = re.sub(r' \'', '\'', fact)
fact = re.sub(r'`` ', '\"', fact)
fact = re.sub(r'\'\'', '\"', fact)
print fact
|
#coding=utf-8
'''
下面已a = 10 ,b = 20 为例进行计算
运算符 描述 实例
+ 加 两个对象相加a+b 输出结果为30
- 减 得到负数或是减去一个数 a-b 输出结果为-10
* 乘 两个数相乘或是返回一个被重复若干次的字符窜 a*b输出结果为200
/ 除 X除以Y b/a 输出结果为2
// 取整除 返回商的整数部分 9//2 输出结果为4,9.0//2.0 输出结果为4.0
% 取余 返回除法的余数 b%a 输出结果为0
** 幂 返回x的y次幂 a**b 为10的20次方,输出结果为100000000000000000000
'''
#如果对象*数值则返回多个对象,例如:
name = input('请输入你的名字:')
print('='*50)
print('你的名字:%s'%name)
print('='*50)
|
#coding=utf-8
#三个条件,皮肤白/有钱/美
color = int(input('请问你的皮肤白吗?1.白 2.不白'))
rich = int(input('请问你的财富总额有多少?'))
beutiful = int(input('请问你漂亮吗?1.是 2.不是'))
if color==1 and rich>100000 and beutiful==1:
print('你好白富美....')
elif color==1 and rich<100000 and beutiful==1:
print('你好美女')
elif color==2 and rich>100000 and beutiful==1:
print('你可能需要去漂白了~')
elif color==1 and rich>100000 and beutiful==2:
print('你需要去整容了')
elif color==2 and rich<10000 and beutiful==2:
print('请你努力读书造福社会~')
|
#-----------------------------------------------------------
# Implementation of classic arcade game Pong
#
# Additional Functions for abit of fun:
# - The players can add there names
# - A single player option which sincs both paddles with
# the Up and Down arrows
#-----------------------------------------------------------
# Date Ver Comments
# ---------- ----- ----------------------------------------
# 18/10/2014 1.00 Initial code to test source.
#-----------------------------------------------------------
import simplegui
import random
# initialize globals - pos and vel encode vertical info for paddles
WIDTH = 600
HEIGHT = 400
BALL_RADIUS = 20
PAD_WIDTH = 8
PAD_HEIGHT = 80
HALF_PAD_WIDTH = PAD_WIDTH / 2
HALF_PAD_HEIGHT = PAD_HEIGHT / 2
LEFT = False
ball_pos = [WIDTH / 2, HEIGHT / 2]
paddle1_x = PAD_WIDTH / 2
paddle2_x = WIDTH - (PAD_WIDTH / 2)
ball_vel = [0, 0]
font_size = 30
starting = True
score1 = 0
score2 = 0
player1_name = "Player 1"
player2_name = "Player 2"
sinc_paddles = False
# initialize ball_pos and ball_vel for new bal in middle of table
def spawn_ball():
global paddle1_pos, paddle2_pos, paddle1_vel, paddle2_vel # these are numbers
global ball_pos, ball_vel # these are vectors stored as lists
global LEFT
global score1, score2, starting
# Replace the ball in the centre
ball_pos = [WIDTH / 2, HEIGHT / 2]
# Calculate the new randow direction to move
# Not sure if '/60' is corrext, but I get the speeds I was after
x = random.randrange(120,240)/60
y = random.randrange(60,180)/60
# if LEFT is True, then the ball's velocity is upper left
# if LEFT is False, then the ball's velocity is upper right
# increment the score for the winner of the last game
if LEFT == True:
ball_vel[0] = - x
score1 += 1
else:
ball_vel[0] = x
score2 += 1
# set the ball movement upward
ball_vel[1] = - y
# new game initialisation for paddles and scores
if starting == True:
paddle1_pos = (HEIGHT / 2)
paddle1_vel = 0
paddle2_pos = (HEIGHT / 2)
paddle2_vel = 0
score1 = 0
score2 = 0
starting = False
# define event handlers
def new_game():
global starting
# Set the new game indicator for the spawn process
starting = True
# Update the game controls as new game
spawn_ball()
def draw(canvas):
global score1, score2
global paddle1_pos, paddle2_pos, ball_pos, ball_vel
global paddle1_vel, paddle2_vel
global LEFT, font_size
global player1_name, player2_name
# draw mid line and gutters
canvas.draw_line([WIDTH / 2, 0],[WIDTH / 2, HEIGHT], 1, "White")
canvas.draw_line([PAD_WIDTH, 0],[PAD_WIDTH, HEIGHT], 1, "White")
canvas.draw_line([WIDTH - PAD_WIDTH, 0],[WIDTH - PAD_WIDTH, HEIGHT], 1, "White")
# update ball - horizontal position
ball_pos[0] += ball_vel[0]
# check if the ball has reached the gutter
if ball_pos[0] <= 0 + PAD_WIDTH + BALL_RADIUS:
# set the direction for the new ball if not paddled
LEFT = False
# Check if the ball hit the Left paddle
if ball_pos[1] >= paddle1_pos - HALF_PAD_HEIGHT:
if ball_pos[1] <= paddle1_pos + HALF_PAD_HEIGHT:
# Paddle hit and ball velocity increased by 10%
ball_vel[0] = - ball_vel[0]
ball_vel[0] = ball_vel[0] * 1.1
else:
# Missed Paddle - spawn new ball
spawn_ball()
else:
# Missed Paddle - spawn new ball
spawn_ball()
if ball_pos[0] >= WIDTH - PAD_WIDTH - BALL_RADIUS:
# set the direction for the new ball if not paddled
LEFT = True
# Check if the ball hit the Right paddle
if ball_pos[1] >= paddle2_pos - HALF_PAD_HEIGHT:
if ball_pos[1] <= paddle2_pos + HALF_PAD_HEIGHT:
# Paddle hit and ball velocity increased by 10%
ball_vel[0] = - ball_vel[0]
ball_vel[0] = ball_vel[0] * 1.1
else:
# Missed Paddle - spawn new ball
spawn_ball()
else:
# Missed Paddle - spawn new ball
spawn_ball()
# update ball vertical position
ball_pos[1] += ball_vel[1]
# bounce ball of top or bottom borders
if ball_pos[1] <= BALL_RADIUS:
ball_vel[1] = - ball_vel[1]
if ball_pos[1] >= HEIGHT - BALL_RADIUS:
ball_vel[1] = - ball_vel[1]
# draw ball
canvas.draw_circle(ball_pos, BALL_RADIUS, 1, 'Yellow', 'Orange')
# update paddle's vertical position, keep paddle on the screen
paddle1_pos += paddle1_vel
paddle2_pos += paddle2_vel
# stop Left paddle movement of the boundary edge has been reached
if paddle1_pos < HALF_PAD_HEIGHT:
paddle1_vel = 0
elif paddle1_pos > HEIGHT - HALF_PAD_HEIGHT:
paddle1_vel = 0
# stop Right paddle movement of the boundary edge has been reached
if paddle2_pos < HALF_PAD_HEIGHT:
paddle2_vel = 0
elif paddle2_pos > HEIGHT - HALF_PAD_HEIGHT:
paddle2_vel = 0
# draw paddles
canvas.draw_line([paddle1_x, paddle1_pos - HALF_PAD_HEIGHT], [paddle1_x, paddle1_pos + HALF_PAD_HEIGHT], PAD_WIDTH , "White")
canvas.draw_line([paddle2_x, paddle2_pos - HALF_PAD_HEIGHT], [paddle2_x, paddle2_pos + HALF_PAD_HEIGHT], PAD_WIDTH , "White")
# draw players name centred on each side
len1 = frame.get_canvas_textwidth(player1_name, font_size)
canvas.draw_text(player1_name,[(1.0*WIDTH/4) - (len1/2.0),font_size],font_size,"Red")
len2 = frame.get_canvas_textwidth(player2_name, font_size)
canvas.draw_text(player2_name,[(3.0*WIDTH/4) - (len2/2.0),font_size],font_size,"Blue")
# draw scores
canvas.draw_text(str(score1),[(1.0*WIDTH/4),font_size*2],font_size,"White")
canvas.draw_text(str(score2),[(3.0*WIDTH/4),font_size*2],font_size,"White")
def keydown(key):
global paddle1_vel, paddle2_vel, ball_vel
global sinc_paddle
# move paddles up or down while keys pressed
if sinc_paddles == False:
if key == simplegui.KEY_MAP["up"]:
paddle2_vel = -3
if key == simplegui.KEY_MAP["down"]:
paddle2_vel = 3
if chr(key) == "W":
paddle1_vel = -3
if chr(key) == "S":
paddle1_vel = 3
else:
# move both paddles up or down while keys pressed
if key == simplegui.KEY_MAP["up"]:
paddle1_vel = -3
paddle2_vel = -3
if key == simplegui.KEY_MAP["down"]:
paddle1_vel = 3
paddle2_vel = 3
def keyup(key):
global paddle1_vel, paddle2_vel
# stop paddle movement when key is released
if sinc_paddles == False:
if key == simplegui.KEY_MAP["up"]:
paddle2_vel = 0
if key == simplegui.KEY_MAP["down"]:
paddle2_vel = 0
if chr(key) == "W":
paddle1_vel = 0
if chr(key) == "S":
paddle1_vel = 0
else:
# stop both paddles movement when key is released
if key == simplegui.KEY_MAP["up"]:
paddle1_vel = 0
paddle2_vel = 0
if key == simplegui.KEY_MAP["down"]:
paddle1_vel = 0
paddle2_vel = 0
def player1(name):
global player1_name
#set player 1's name on the board
player1_name = name
def player2(name):
global player2_name
#set player 2's name on the board
player2_name = name
def lock_paddles():
global sinc_paddles, paddle1_pos, paddle2_pos
if lock.get_text() == "Single Player - Up Down Arrows Only.":
sinc_paddles = True
paddle1_pos = paddle2_pos
lock.set_text("Two Player - 'W' 'S' keys activate")
else:
sinc_paddles = False
lock.set_text("Single Player - Up Down Arrows Only.")
# create frame
frame = simplegui.create_frame("Pong", WIDTH, HEIGHT)
frame.set_draw_handler(draw)
frame.set_keydown_handler(keydown)
frame.set_keyup_handler(keyup)
# Game Reset button
frame.add_button("Reset", new_game)
# Players name input
inp1 = frame.add_input("Player 1 - Name", player1, 200)
inp1.set_text(player1_name)
inp2 = frame.add_input("Player 2 - Name", player2, 200)
inp2.set_text(player2_name)
# Single Player and Paddle sinc lock button
lock = frame.add_button("Single Player - Up Down Arrows Only.", lock_paddles)
# start frame
new_game()
frame.start()
|
'''
Quicksort is a quick and efficient sorting algorithm.
It recursively sorts by selecting a pivot and sending all elements smaller than the pivot to the left of it, and the elements larger than it to the right.
The array is now divided into sub-arrays separated by the pivot picked. The process repeats itself recursively; pivotal exchanges, smaller sub-arrays, until all elements in the prime array are sorted.
Time complexity:
Worst-case performance: O(n2)
Best-case performance: O(n log(n))
Average performance: O(n log(n))
'''
import random
def Quicksort(array):
if len(array) <= 1: # base case
return array
else:
left = []
right = []
pivot = array[0]
for i in range(1, len(array)):
if array[i] >= pivot:
right.append(array[i])
else:
left.append(array[i])
return Quicksort(left) + [pivot] + Quicksort(right)
arr = [random.randint(1,100) for i in range(10)]
print(arr)
print(Quicksort(arr))
|
"""
A Singly-Linked List is a sequence of objects that point to the next item in
the list but have no back references to previous items in the list.
"""
class ListElement:
def __init__(self, data):
self.next_item = None
self.data = data
def append(self, data):
self.last().next_item = ListElement(data)
def last(self):
if not self.next_item:
return self
else:
return self.next_item.last()
|
import tensorflow as tf
from tensorflow import keras
from nn import activations
# %%
class NeuralNet(object):
"""
A neural network model
Attributes
----------
trainable_params : itarable
contains all trainable parameters.
layers : iterable
ordered collection of network layers.
Methods
-------
add(layer) -> self
append layer to network.
backprop() -> gradinents
Backpropagete gdatient of the loss through the network.
"""
def __init__(self, layers=[]):
"""
Parameters
----------
layers : iterable
layers of the network
"""
layers_built = all([layer.built for layer in layers])
if layers_built:
for layer_l, layer_r in zip(layers[:-1], layers[1:]):
assert layer_l.units == layer_r.kernel.shape[0]
else:
pass
self.layers = layers[:]
self.trainable_weights = []
self.built = layers_built
def __call__(self, inputs):
"""
Given inputs predict correct outputs
Parameters
----------
inputs : tf.Tensor
inupt features. shape=(sample size, number of features)
Returns
-------
activations : tf.Tensor
activations of last layer on network.
shape=(sample size, output dimmentions)
"""
if not self.built:
self.build(inputs.shape)
else:
pass
activations = inputs
for layer in self.layers:
activations = layer(activations)
return activations
def add(self, layer):
"""
Apend leayer to network
Layer input dimmentions must be same as output dimmentions
of network.
Parameters
----------
layer : Layer
instance of Layer.
Returns
-------
self
network with added layer
"""
if layer.built:
# layer.kernel only exisits after layer.buid() call.
assert self.layers[-1].units == layer.kernel.shape[0]
else:
self.built = False
self.layers.append(layer)
return self
def build(self, input_shape):
"""
Create variables for all layers in the network.
Parameters
----------
input_shape : Collection
shape of a single input.
Returns
-------
None.
"""
input_dim = input_shape[1]
for layer in self.layers:
if not layer.built:
layer.build(input_shape=(1, input_dim))
else:
pass
input_dim = layer.units
self.trainable_weights += layer.trainable_weights
self.built = True
def backprop(self, dY):
"""
Backpropagete gratient of the loss through the network.
Parameters
----------
dY : tf.Tensor
gradien of the loss with respect to output of the network.
Returns
-------
gradients : iterable
collection of the gradients of the loss with respect to all trainable
parametrs. (Same order as trainable_weights)
"""
gradients = []
dA = dY
for layer in reversed(self.layers):
dA, trainable = layer.backprop(dA)
gradients = [*trainable, *gradients]
return gradients
# %%
class Layer(object):
"""
A single generic layer of neural network.
Attributes
---------
kernel : tf.Tensor
weihts matrix. Availbale only after Layer.bulid() was called.
bias : tf.Tensor
bias vector. Available only after Layer.build() and only if Layer.use_bias is
set to True.
trainable_weights : iterable
trainable weights of layer:
W - weights associated with layer inputs. shape=(input, output)
B - biases associated with layer inputs. shape=(1, outputs) (if use_bias=True)
use_bias : bool
indicator of whether to use bias term for computing pre-activations.
activation : function
activation of the layer.
built : bool
indicator of whether layer variables have been initialized.
units : int
number of unint is the layer.
input_shape: int
number of inputs to a unit.
kernel_reguralizer : func
returns loss term for weight regularization.
Methods
-------
backprop(dA) -> gradinents
Compute backpropagation step.
build(input_shape) -> None
Create variables for the layer.
"""
def __init__(
self,
units,
activation=activations.Linear(),
kernel_initializer=keras.initializers.GlorotUniform(),
bias_initializer=tf.zeros,
input_shape=None,
use_bias=True,
kernel_reguralizer=None,
):
"""
Parameters
----------
units_num : int
number of unint is the layer.
activation : func
ativation function for layer.
kernel_initializer : func
given shape return tensor inintialized acording to initialization scheme.
bias_initializer : func
given shape return tensor inintialized acording to initialization scheme.
input_num : int, optional
number of inputs to a unit. The default is None
use_bias : bool, optional
wheter to use bias term when computing preactivation. The default is True.
kernel_reguralizer : func
returns loss term for weight regularization.
Returns
-------
None.
"""
self.units = units
self.activation = activation
self.kernel_initializer = kernel_initializer
self.bias_initializer = bias_initializer
self.input_shape = input_shape
self.use_bias = use_bias
self.kernel_reguralizer = kernel_reguralizer
self.built = False
def __call__(self, inputs):
"""
Given inpust compute actiovations of the layer.
Parameters
----------
inputs : tf.Tensor
inputs to layer
shape=(sample size, input dimention)
Returns
-------
activation : tf.Tensor
activations of the layer
shape=(sample size, number of units in the layer)
"""
if not self.built:
self.built(inputs.shape)
else:
pass
self.inputs = inputs
Z = inputs @ self.kernel
if self.use_bias:
Z += self.bias
else:
pass
self.Z = Z
activations = self.activation(Z)
return activations
def backprop(self, dA):
"""
Compute backpropagation step.
Parameters
----------
dA : tf.Tensor
gradient of loss with respect to activations of the layer
Returns
-------
gradients : iterable
collection of the form:
[dA, [d-trainable]]
where:
dA - gradient with respect to inputs.
[d-trainable] - gradients with respect to all trainable parameters.
"""
dZ = tf.reshape(
dA[:, tf.newaxis, :] @ self.activation.get_jacobian(self.Z), shape=dA.shape
)
dB = tf.math.reduce_sum(dZ, axis=0, keepdims=True)
dW = tf.matmul(self.inputs, dZ, transpose_a=True)
dX = tf.matmul(dZ, self.kernel, transpose_b=True)
return [dX, [dW, dB]]
def build(self, input_shape):
"""
Create variables for the layer.
Parameters
----------
input_shape : Collection
shape of an input.
Returns
-------
None.
"""
input_dim = input_shape[1]
trainable_weights = []
self.kernel = tf.Variable(
self.kernel_initializer(shape=(input_dim, self.units))
)
trainable_weights.append(self.kernel)
if self.use_bias:
self.bias = tf.Variable(self.bias_initializer(shape=(1, self.units)))
trainable_weights.append(self.bias)
else:
pass
self.built = True
self.trainable_weights = trainable_weights
# %%
class Dropout:
"""
Dropout regulariozation layer.
Attributes
----------
keep_prob : float
probability of retraining unit
0 < keep_prob < 1
"""
def __init__(self, keep_prob):
pass
def __call__(self, activations):
"""
Apply dropout regularization to the activataions.
Rescales activations to have uncahnged expectaions.
Parameters
----------
activations : tf.Tensor
activations of the layer
Returns
-------
reguralized_activation : tf.Tensor
reguralized activations of the layer
"""
reguralized_activations = None
return reguralized_activations
# %%
class BatchNormalization(object):
"""
TODO
"""
|
import time
# 1.使用全局函数来装饰类方法
# 2.使用类方法来装饰类方法
# 3.使用类内置方法来装饰实例方法
# def a_(fun):
# class A(object):
# def __init__(self):
# self.a_ = 100
# @a_ #使用全局函数装饰
# def func(self, num):
# def b_(fun):
# @b_ #使用类内方法装饰
# def func1(self, num):
# c = A()
# c_ = c.func(100)
# print(c_) #200
# c_1 = c.func1(102)
# print(c_1) #202
#--------------------------
# def a_(fun):
# def inner(*args,**kwargs):
# c = fun(*args,**kwargs)
# return c
# return inner
# class A(object):
# def __init__(self):
# self.a = 100
# @a_#使用全局函数装饰
# def func(self, num):
# return num + 100
# c = A()
# c_ = c.func(100)
# print(c_) # 200
# #------------------------
# class A(object):
# def __init__(self):
# self.a = 100
# def b_(fun):
# ******
# @b_#使用类内方法装饰
# def func1(self, num):
# ******
# c_1 = c .func1(102)
# print(c_1) # 202
# #-------------------------
# class B(object):
# def __init__(self):
# ******
# def __***__()
# ******
# @B#使用类来装饰
# def cc(num,num1):
# return num+num1
# d = cc (11,22) # 33
# print(d)
#-------------------------
class A(object):
def __init__(self,func):
self.a = 100
self.func = func
def __call__(self, *args, **kwargs):
print(time.time())
c = self.func(self,*args,**kwargs)
print(c,'这是c')
print(time.time())
return c
class B:
def __init__(self):
self.a = 200
@A
def func(self,num):
return num+self.a
b = B()
c = b.func(100)
print(c) |
import sys
import re
import numpy as np
comparisons = 0
FIRST = 0
LAST = 1
MIDDLE = 2
def swap( arr, a, b ):
keep = arr[ a ]
arr[ a ] = arr[ b ]
arr[ b ] = keep
return
def find_pivot( el ):
if len( el ) % 2 == 0:
middle_index = int( len( el ) / 2 - 1 )
else:
middle_index = len( el ) // 2
if el[ 0 ] < el[ middle_index ] < el[ -1 ] or el[ -1 ] < el[ middle_index ] < el[ 0 ]:
pivot = middle_index
elif el[ 0 ] < el[ -1 ] < el[ middle_index ] or el[ middle_index ] < el[ -1 ] < el[ 0 ]:
pivot = -1
else:
pivot = 0
return pivot
def quick_sort( el, pivot_meth = FIRST ):
global comparisons
# output of quicksort moves pivot point into location such that
# [ L........; P; R........... ]
# all elements in L are < P and all elements in R are > P
# determine pivot point value to use
if pivot_meth == FIRST:
new_pivot_index = 0
elif pivot_meth == LAST:
new_pivot_index = -1
elif pivot_meth == MIDDLE:
new_pivot_index = find_pivot( el )
# algo always uses el[ 0 ] as pivot; swap new pivot val to this loc
pivot_point = 0
swap( el, new_pivot_index, pivot_point )
# i indicates the left-most element in the R array
i = 1;
# track number of comparisons
comparisons += ( len( el ) - 1 )
# print( 'total = {:d}, new = {:d}'.format( comparisons, len(el)-1 ) )
for j in range( 1, len( el ) ):
if el[ j ] < el[ pivot_point ]:
swap( el, j, i )
i += 1
# upon completion, put pivot point in correct place
swap( el, pivot_point, i - 1 )
# recurse, if necessary
leftLength = i - 1
left = el[ 0:leftLength ]
if leftLength > 0:
quick_sort( left, pivot_meth )
rightLength = len( el ) - i
right = el[ i:len( el ) ]
if rightLength > 0:
quick_sort( right, pivot_meth )
return
def main():
global comparisons
comparisons = 0
genTestFile = False
genFileName = ''
elements = []
pivot = FIRST
# check for pivot point
for switch in sys.argv:
if re.match( '-last', switch ):
pivot = LAST
sys.argv.remove( switch )
elif re.match( '-first', switch ):
pivot = FIRST
sys.argv.remove( switch )
elif re.match( '-middle', switch ):
pivot = MIDDLE
sys.argv.remove( switch )
if len( sys.argv ) > 1:
if re.match( '-h', sys.argv[ 1 ] ):
print( 'Usage -- with or without commas:' )
print( 'my_prompt> python3 quicksort.py 1 6 3 2 4 5' )
print( 'my_prompt> python3 quicksort.py 1, 6, 3, 2, 4, 5' )
print( 'The next example writes the input values from the command line to a file, one per line.' )
print( 'my_prompt> python3 quicksort.py -g outputfile.txt 1, 6, 3, 2, 4, 5' )
print( 'The next examples expects input values, one per line, in the associated file' )
print( 'my_prompt> python3 quicksort.py -f inputfile.txt' )
return
# generates output files for test
if re.match( '-g', sys.argv[ 1 ] ):
genTestFile = True
genFileName = sys.argv[ 2 ]
del sys.argv[ 1:3 ]
# gets values from file
if re.match( '-file', sys.argv[ 1 ] ):
inputFileName = sys.argv[ 2 ]
with open( inputFileName, 'rt' ) as fin:
while True:
line = fin.readline()
if not line:
break
elements.append( int( line ) )
else:
# getting values from command line
elements = [ int( re.sub( ',', '', x ) ) for x in sys.argv[ 1: ] ]
if genTestFile:
with open( genFileName, 'wt' ) as fout:
for num in elements:
print( num, file = fout )
print( 'original array: {}'.format( elements ) )
# call the sort function
npArray = np.array( elements )
quick_sort( npArray, pivot )
print( 'sorted array: {}'.format( npArray ) )
print( 'number of comparisons: {:,d}'.format( comparisons ) )
return
# if no command line arguments
comparisons = 0
elements = np.array( [ 87, 16, 2, 0, 12, 25, 26, 27, 63, 75, 28, 50, 2, 5, 41, 39 ] )
quick_sort( elements )
print( elements )
print( 'number of comparisons: {:d}'.format( comparisons ) )
comparisons = 0
elements = np.array( [ 98, 97, 96, 90, 73, 72, 71, 70, 43, 42, 41, 40, 25, 24, 23, 22 ] )
quick_sort( elements )
print( elements )
print( 'number of comparisons: {:d}'.format( comparisons ) )
comparisons = 0
elements = np.array( [ 5, 4, 3, 2, 1 ] )
quick_sort( elements )
print( elements )
print( 'number of comparisons: {:d}'.format( comparisons ) )
comparisons = 0
elements = np.array( [ 6, 5, 4, 3, 2, 1 ] )
quick_sort( elements )
print( elements )
print( 'number of comparisons: {:d}'.format( comparisons ) )
comparisons = 0
elements = np.array( [ 23, 27, 82, 69, 1, 4, 2, 100, 1023, 1000, 83, 41, 14, 19, 37, 18, 8 ] )
quick_sort( elements )
print( elements )
print( 'number of comparisons: {:d}'.format( comparisons ) )
comparisons = 0
elements = np.array( [ 1, 2, 3, 4, 5, 6, 7, 8 ] )
quick_sort( elements )
print( elements )
print( 'number of comparisons: {:d}'.format( comparisons ) )
comparisons = 0
elements = np.array( [ 6, 2, 3, 8, 4, 1, 7, 5 ] )
quick_sort( elements )
print( elements )
print( 'number of comparisons: {:d}'.format( comparisons ) )
comparisons = 0
elements = np.array( [ 3, 9, 8, 4, 6, 10, 2, 5, 7, 1 ] )
quick_sort( elements )
print( elements )
print( 'number of comparisons: {:d}'.format( comparisons ) )
if __name__ == '__main__':
main()
|
def CompareLists(headA, headB):
while (headA != None and headB !=None):
if (headA.data != headB.data):
return 0
headA = headA.next
headB = headB.next
if (headA == None and headB == None):
return 1
else:
return 0 |
#!/bin/python
def print_list(ar):
print(' '.join(map(str, ar)))
def insertionSort(ar):
if len(ar) == 1:
print_list(ar)
return(ar)
else:
for j in range(1, len(ar)):
for i in reversed(range(j)):
if ar[i + 1] < ar[i]:
ar[i], ar[i + 1] = ar[i + 1], ar[i]
else:
break
print_list(ar)
return(ar)
m = input()
ar = [int(i) for i in raw_input().strip().split()]
insertionSort(ar)
|
N = int(raw_input())
X = [int(x) for x in raw_input().split(" ")]
F = [int(x) for x in raw_input().split(" ")]
def unravel_input(X, F, N):
S = []
for i in range(0,N):
temp = [X[i]]*F[i]
S = S + temp
return S
def quartile(X):
N = len(X)
middle = N/2
if(len(X) % 2 != 0):
middle = middle + 1
A = sorted(X)
lower = A[0:N/2]
upper = A[middle:]
return median(lower), median(A), median(upper)
def median(numbers):
numbers = sorted(numbers)
center = len(numbers) / 2
if len(numbers) % 2 == 0:
return int(sum(numbers[center - 1:center + 1]) / 2.0)
else:
return int(numbers[center])
S = unravel_input(X, F, N)
q1, q2, q3 = quartile(S)
print float(q3 - q1)
|
# program to get all the numerical set in a string
# helper_function
def is_alpha(a):
a = a.lower()
if a >= 'a' and a <= "z":
return True
return False
def get_numerical_set(str):
str = str.replace(" ", "")
numerical_num = ""
for i in range(0, len(str)):
if not is_alpha(str[i]):
numerical_num += str[i]
return int(numerical_num)
print(get_numerical_set("i am 3846surendra 14 years36472 old "))
# program to count total number of words in a string
def count_strings(str):
count = 0
str2 = str.split(" ")
return len(str2)
print(count_strings("i am surendra i am coding"))
# program to check given string is palindrom or not
def is_palindrom(str):
temp = str[::-1]
if(str == temp):
return "palindrom"
return "not palindrom"
print(is_palindrom("kayak"))
|
# program to find second largest number in the array
arr=[34,213,45,213,63]
def find_max(arr):
max = 0
index = None
for i in range(0, len(arr)):
if(max < arr[i]):
index = i
max = arr[i]
return index
# print(find_max(arr))
def second_max(arr):
arr.pop(find_max(arr))
new_arr = arr
second_largest = find_max(new_arr)
return arr[second_largest]
print(second_max(arr))
# program to find second smallest element in an array
def find_min(arr):
index = 0
min = arr[0]
for i in range(0, len(arr)):
if(min > arr[i]):
index = i
min = arr[i]
return index
def second_min(arr):
arr.pop(find_min(arr))
new_arr=arr
second_smallest=find_min(new_arr)
return arr[second_smallest]
print(second_min(arr)) |
# program to find max number in an array
# using buidin-function
def max_num(arr):
return max(arr)
print(max_num([3,2,4,6]))
# using logic
def max_num2(arr):
maxnum=0
for i in range(0,len(arr)):
if arr[i]>maxnum:
maxnum=arr[i]
return maxnum
print(max_num2([45,3,38,23]))
# program to find smallest number
# using buidin_function
def min_num(arr):
return min(arr)
# using logical method
def min_num2(arr):
minnum=arr[0]
for i in range(0,len(arr)):
if arr[i]<minnum:
minnum=arr[i]
return minnum
print(min_num([342,232,34]),min_num2([634,432,222]))
|
# single linked list implementaion in python and also
# implementaion of helper function used in linked list
# Creating Node
class node:
def __init__(self, data):
self.data = data
self.next = None
# Creating linkedList
class linkedList:
def __init__(self):
self.head = None
# ----------------------------insertion operations on linkedList----------------------------------------
# Method to insert a node at head postion
def insertAtHead(self, newnode):
current_node = self.head
if(current_node == None):
self.head = newnode
return
self.head = newnode
self.head.next = current_node
# Method to insert newnode at end of the list
def insertAtEnd(self, newnode):
current_node = self.head
if(current_node == None):
self.head = newnode
return
while(current_node.next != None):
current_node = current_node.next
current_node.next = newnode
# Method to insert newnode at given postion
def insertAtPos(self, newnode, pos):
if(pos < 0 or pos > self.listLength()):
print("{ pos } is Invalid postion")
return
if(pos == self.listLength()):
self.insertAtEnd(newnode)
return
if(pos == 0):
self.insertAtHead(newnode)
return
current_node = self.head
current_pos = 0
previous_node = None
while(current_pos != pos):
previous_node = current_node
current_node = current_node.next
current_pos += 1
previous_node.next = newnode
newnode.next = current_node
# ---------------------------Deletion Operation on linkedList-------------------------------------------
# Method to delete head node from the linkedList
def deleteAtHead(self):
current_node = self.head
self.head = current_node.next
del current_node
# Method to delete a node at the end of the linkedList
def deleteAtEnd(self):
current_node = self.head
previous_node = None
while(current_node.next != None):
previous_node = current_node
current_node = current_node.next
previous_node.next = None
del current_node
# Method to delete a node at a given postion
def deleteAtPos(self, pos):
if(pos < 0 or pos > self.listLength()):
print("{ pos } is Invalid postion")
return
if(pos == self.listLength()):
self.deleteAtEnd()
return
if(pos == 0):
self.deleteAtHead()
return
current_node = self.head
previous_node = None
current_pos = 0
while(pos != current_pos):
previous_node = current_node
current_node = current_node.next
current_pos += 1
previous_node.next = current_node.next
del current_node
# -------------------Helper function used on linkedList operations----------------------------------------
# Method to return length of the linked list
def listLength(self):
current_node = self.head
length = 0
while(current_node != None):
length += 1
current_node = current_node.next
return length
# Method to print the whole list data
def printList(self):
current_node = self.head
if(current_node == None):
print("List is empty !")
return
while(current_node != None):
print(current_node.data)
current_node = current_node.next
# Method to reverse a given linked list
def reverseList(self):
current_node = self.head
previous_pointer = None
while(current_node != None):
next = current_node.next
current_node.next = previous_pointer
previous_pointer = current_node
current_node = next
self.head = previous_pointer
# Method to search an element in the following linked list
def searchElement(self, ele):
current_node = self.head
index = 0
noMatch = True
while(current_node != None):
index += 1
if(current_node.data == ele):
print(f"The element {ele} is found at {index} node")
noMatch = False
return
current_node = current_node.next
if(noMatch):
print(f"The element {ele} is not found in following location")
# ------------------------- Creating instance of the linekd list-----------------------------------------
linked = linkedList()
linked.insertAtHead(node(1))
linked.insertAtEnd(node(2))
linked.insertAtEnd(node(3))
linked.insertAtEnd(node(4))
linked.insertAtEnd(node(5))
linked.insertAtPos(node(0), 0)
linked.printList()
linked.deleteAtHead()
print("after head node deletion")
linked.printList()
linked.deleteAtEnd()
print("after end node deletion")
linked.printList()
pos = linked.listLength()
linked.deleteAtPos(pos)
print(f"after deleting {pos} node")
linked.printList()
linked.searchElement(2)
print("\n")
print("After reversing the linkedList")
linked.reverseList()
linked.printList()
|
# program to find the median of an array
# helper function to merge two arrays
def merge_arrays(arr1, arr2):
arr3 = arr1+arr2
return sorted(arr3)
arr1 = [5, 4, 3, 2, 1]
arr2 = [11, 10, 9, 8, 7]
def find_median(arr1, arr2):
arr3 = merge_arrays(arr1, arr2)
array_len = len(arr3)-1
array_mid = int(array_len/2)
median = arr3[array_mid]+arr3[array_mid+1]
return int(median/2)
# print(find_median(arr1, arr2))
# program to rotate array elements towards left
def rotateLeft(arr):
i = 0
j = len(arr)-1
while(i != j):
temp = arr[j]
arr[j] = arr[i]
arr[i] = temp
i += 1
j -= 1
return arr
arr = [45, 34, 56, 23, 64]
print(rotateLeft(arr))
# program to move elements fowards left on given range
# helper function to move elements one by one
def move_elements(arr):
j = len(arr)-1
temp = arr[0]
i = 0
while(i != j):
arr[i] = arr[i+1]
i += 1
arr[j] = temp
def loop_Elements(arr, index_Limit):
if len(arr)-1 > index_Limit:
for i in range(0, index_Limit+1):
move_elements(arr)
return arr
return "Limit Overflow"
arr3 = [5, 4, 3, 2, 1]
print(loop_Elements(arr3, 10))
# program to print the elements that are matched with the index of that element
def match_index_print(arr):
no_index_match = True
for i in range(0, len(arr)):
if(i == arr[i]):
print(arr[i])
no_index_match = False
if(no_index_match):
print("No match index found")
match_index_print([2, 5, 9, 5, 7, 9]) # case 1
match_index_print([2, 5, 2, 5, 4, 9]) # case 2
|
#!/usr/bin/env python
#-*- coding:utf-8 -*-
"""
bubble sort implementation, basic concepts:
promote the minimum item one by one, from end to beginning.
"""
def BubbleSort(alist):
for i in range(0, len(alist)):
for j in range(len(alist)-1, i, -1):
if alist[j] < alist[j-1]:
alist[j], alist[j-1] = alist[j-1], alist[j]
return True
if __name__ == "__main__":
arr = [99, 82, 107, 16, 2, 8, 104, 33, 24, 32, 64]
BubbleSort(arr)
for item in arr:
print item,
|
import sqlite3
import json
DB_FILENAME = "Database/Data/database.db"
class SqlInterface:
def __init__(self):
self.connection = sqlite3.connect(DB_FILENAME)
self.connection.execute("""
CREATE TABLE IF NOT EXISTS user (
username TEXT,
password TEXT,
email TEXT,
data JSON
)
""")
self.connection.commit()
""" Returns record from database
@:param ret - str value, it is name of column from which return value will be retrieved
@:param user - str value that specifies record to return
"""
def select(self,
ret,
user):
# print(self.print_all())
res = self.connection.execute("SELECT " + ret + " FROM user WHERE username='" + user + "'")
if res.arraysize is not 1:
print("Sommething went wrong in SqlInterface.select()!")
return None
else:
return res
""" Inserts to database new values
@:param name - str value that sepcufies new username
@:param password - str value that specifies new password
"""
def insert(self,
name,
password,
email=None,
data=None):
json_data = json.dumps(data)
self.connection.execute("""
INSERT INTO user (username, password, email, data)
VALUES (?, ?, ?, ?)
""", (name, password, email, json_data))
self.connection.commit()
""" Updates record in user table
@param value - dict object that represents updates to user table, e.g {column: new_value, column2: new_value2...}
All those updates are applied to user with username equal to username parameter
@param name - str that specifies user record that will be updated
"""
def update(self,
value,
name):
val, querry = self.prepare_update_querry(value, name)
self.connection.execute("""""" + querry + """""", val)
self.connection.commit()
# self.print_all()
def delete(self,
name):
# print(name)
self.connection.execute("""
DELETE FROM user WHERE username = ?
""", (name,))
self.connection.commit()
# print(self.print_all())
def prepare_update_querry(self,
update,
name):
querry = "UPDATE user SET username = ?"
values = [name]
for up in update:
querry += ", " + up + " = ?"
# print(str(up))
values.append(update[up])
querry += " WHERE username is ?"
values.append(name)
# print(values)
# print(querry)
return values, querry
def print_all(self):
for row in self.connection.execute("SELECT * FROM user"):
print(row)
|
#%% #creates separate cell to execute
from keras.datasets import mnist #import MNIST dataset
from keras.models import Sequential #import the type of model
from keras.layers.core import Dense, Dropout, Activation, Flatten #import layers
from keras.layers.convolutional import Convolution2D, MaxPooling2D #import convolution layers
from keras.utils import np_utils
import matplotlib #to plot import matplotlib
import matplotlib.pyplot as plt
#%% #in this cell we define our parameters
batch_size = 128 #batch size to train
nb_classes = 10 #number of output classes
nb_epoch = 12 #number of epochs to train
img_rows, img_cols = 28, 28 #input image dimensions
nb_filters = 32 #number of convolutional filters to use in each layer
nb_pool = 2 #size of pooling area for max pooling, 2x2
nb_conv = 3 #convolution kernel size, 3x3
#%%
# the data, shuffle and split between train and test sets
# X_train and X_test are pixels, y_train and y_test are levels from 0 to 9
# you can see what is inside by typing X_test.shape and y_test shape commands
# X_train are 60000 pictures, 1 channel, 28x28 pixels
# y_train are 60000 labels for them
# X_test are 10000 pictires, 1 channel, 28x28 pixels
# y_test are 10000 labels for them
(X_train, y_train), (X_test, y_test) = mnist.load_data()
# reshape the data
# X_train.shape[0] - number of samples,
# 1 - channel, img_rows - image rows, img_cols - image columns
X_train = X_train.reshape(X_train.shape[0], 1, img_rows, img_cols)
X_test = X_test.reshape(X_test.shape[0], 1, img_rows, img_cols)
#convert X_train and X_test data to 'float32' format
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
#then we normalize the data, dividing it by 255, the highest intensity
X_train /= 255
X_test /= 255
# Print the shape of training and testing data
print('X_train shape:', X_train.shape)
# Print how many samples you have
print(X_train.shape[0], 'train samples')
print(X_test.shape[0], 'test samples')
# convert class vectors to binary class matrices,
# for example from "2" to "[0 0 1 0 0 0 0 0 0 0]
Y_train = np_utils.to_categorical(y_train, nb_classes)
Y_test = np_utils.to_categorical(y_test, nb_classes)
#now let's plot X_train example #4606
i = 4606
plt.imshow(X_train[i, 0], interpolation = 'nearest')
print("label :", Y_train[i,:])
#%% in this cell we define a model of neural network
model = Sequential() # we will use sequential type of model
# we add first layer to neural network, type of the layer is Convolution 2D,
# with 32 convolutional filters, kernel size 3x3
model.add(Convolution2D(nb_filters, nb_conv, nb_conv,
border_mode = 'valid',
input_shape = (1, img_rows, img_cols))) # number of channels 1, 28x28 pixels
# now we add activation function to convolutional neurons of the 1st layer,
# it will be "Rectified Linear Unit" function, RELU
convout1 = Activation('relu')
# we add activation function to model to visualize the data
model.add(convout1)
# we add second convolutional layer
model.add(Convolution2D(nb_filters, nb_conv, nb_conv))
# and add to 2nd layer the activation function
convout2 = Activation('relu')
model.add(convout2) # add this one to visualize data later
# we add 3rd layer, type maxpooling, pooling area 2x2
model.add(MaxPooling2D(pool_size = (nb_pool, nb_pool)))
# we add 4th layer, type dropout, which works as a regularizer
model.add(Dropout(0.25))
model.add(Flatten())
#we add 5th layer, consisting of 128 neurons
model.add(Dense(128))
model.add(Activation('relu')) # activation function for them is RELU as well
#add 6th dropout layer
model.add(Dropout(0.5))
#last 7th layer will consist of 10 neurons, same as number of classes for output
model.add(Dense(nb_classes))
model.add(Activation('softmax')) # for last layer we use SoftMax activation function
# and define optimizer and a loss function for a model
model.compile(optimizer='adadelta', loss='categorical_crossentropy',
metrics=['accuracy'])
#%% in this cell we will train the neural network model
model.fit(X_train, Y_train, batch_size = batch_size, nb_epoch = nb_epoch,
show_accuracy=True, verbose=1, validation_data = (X_test, Y_test))
model.fit(X_train, Y_train, batch_size = batch_size, nb_epoch = nb_epoch,
show_accuracy = True, verbose = 1, validation_split = 0.2)
#%% in this cell we evaluate the model we trained
score = model.evaluate(X_test, Y_test, show_accuracy = True, verbose = 0)
print('Test score:', score[0])
print('Test accuracy:', score[1])
# here we will predict what is six elements of data we have in X_test
# to see how neural network model works and recognize the numbers
print(model.predict_classes(X_test[1:7]))
#and let's see what labels these images have
print(Y_test[1:7])
# this neural network model can recognize 20000 numbers in 1 minute, using CPU
|
"""
[][][][][][x][][]
K
N other players numbered 1 to N. Chef can choose who to play against.
so player i is found at positions l*p[i] where l is an integer.
Does it jump over positions?
if player moves pawn to square with Chef's pawn chef's pawn is
captured and loses the game.
Idea
Find the shortest distance to chef from any position
- means it is reachable and the time it takes to reach that position - i.e K%p[i] and K > p[i] then K-p[i]/p[i] else inf
"""
def shortest_distance(chef_position, pawn_position):
if chef_position % pawn_position != 0:
return float('inf'), -1
if chef_position < pawn_position:
return float('inf'), -1
return (chef_position - pawn_position)//pawn_position, pawn_position
def shortest_distance_to_chef_any_position(pawn_positions, chef_position):
return min(
(
shortest_distance(chef_position, pawn_position)
for pawn_position in pawn_positions
), key=lambda x:x[0]
)[1]
if __name__ == '__main__':
T = int(input())
for _ in range(T):
_, chef_position = map(int, input().split())
pawn_positions = list(map(int, input().split()))
print(
shortest_distance_to_chef_any_position(
pawn_positions,
chef_position,
)
)
|
def generate_cake(firstColour, secondColour, width, breadth):
resArr = [[0 for j in range(width)] for i in range(breadth)]
for i in range(breadth):
for j in range(width):
if (i+j)%2 == 0:
resArr[i][j] = firstColour
else:
resArr[i][j] = secondColour
return ["".join(row) for row in resArr]
def compare(arr1, arr2):
assert len(arr1)==len(arr2)
assert len(arr1[0])==len(arr2[0])
n = len(arr1)
m = len(arr1[0])
ans = 0
for i in range(n):
for j in range(m):
if arr1[i][j]=='R' and arr2[i][j]=='G':
ans += 5 # replacing red with green is 5
elif arr1[i][j]=='G' and arr2[i][j]=='R':
ans += 3 # replacing green with red is 3
return ans
T = int(input())
for _ in range(T):
n, m = list(map(int, input().split()))
arr = []
for j in range(n):
arr.append(input().strip())
redCake = generate_cake(firstColour='R', secondColour='G', width=m, breadth=n)
greenCake = generate_cake(firstColour='G', secondColour='R', width=m, breadth=n)
print(min(compare(arr1=arr, arr2=redCake), compare(arr1=arr, arr2=greenCake)))
|
fDic ={}
fDic[1]=1
fDic[2]=2
fDic[3]=4
fDic[4]=8
def f(n):
if n in fDic:
return fDic[n]
else:
fDic[n]= f(n-1)+f(n-2)+f(n-3)+f(n-4)
return fDic[n]
print f(50) |
#!/bin/python
# Enter your code here. Read input from STDIN. Print output to STDOUT
import sys
sys.setrecursionlimit(1000000)
def palindrome(A, a, b, c, d):
pal = xorsum[a][b] ^ xorsum[c][d] ^ xorsum[a][d] ^ xorsum[c][b]
nzero = nzeroes[c][d] - nzeroes[a][d] - nzeroes[c][b] + nzeroes[a][b]
if (pal & (pal - 1)) == 0 and nzero < (c - a) * (d - b) - 1:
return True
else:
return False
cachePal = {}
def isPalindrome(A, n, m):
if (n, m) in cachePal:
return cachePal[(n, m)]
N = len(A)
M = len(A[0])
if n == 1 and m == 1:
return 0, 0, 0, 0
for a in range(N - n + 1):
for b in range(M - m + 1):
if palindrome(A, a, b, a + n, b + m):
cachePal[(n, m)] = (a, b, a + n - 1, b + m - 1)
return a, b, a + n - 1, b + m - 1
cachePal[(n, m)] = False
return
cache = {}
def largestBeautiful(A, a, b, n, m):
"""returns the largest beautiful A of size less than or equal to n*m"""
# print n, m
if n < 1 or m < 1:
return ((0, 0, 0, 0), 1)
if n * len(A[0]) + m in cache:
return cache[n * len(A[0]) + m]
if palindrome(A, a, b, a+n, b+m):
return ((a, b, a+n, b+m), n*m)
else:
N = len(A)
M = len(A[0])
if n == 1 and m == 1:
c = 0, 0, 0, 0
maxval = 1
for a in range(N - n + 1):
for b in range(M - m + 1):
c, d = a+n, b+m
nzero = nzeroes[c][d] - nzeroes[a][d] - nzeroes[c][b] + nzeroes[a][b]
if nzero >= (c - a) * (d - b) - 1:
palindrome(A, a, b, c, d)
c = isPalindrome(A, n, m) # is there a beautiful rect of size n, m
if c: # there is a valid coordinate of size n*m
cache[n * len(A[0]) + m] = (c, n * m)
return (c, n * m)
else:
c1, area1 = largestBeautiful(A, n - 1, m)
c2, area2 = largestBeautiful(A, n, m - 1)
if area1 > area2:
cache[n * len(A[0]) + m] = (c1, area1)
return c1, area1
else:
cache[n * len(A[0]) + m] = (c2, area2)
return c2, area2
n, m = raw_input().strip().split(' ')
n, m = [int(n), int(m)]
table = []
for table_i in range(n):
table_temp = (map(int, raw_input().strip().split(' ')))
table.append(table_temp)
#print (table, type(table))
xorsum = [[0 for j in range(m + 1)] for i in range(n + 1)]
nzeroes = [[0 for j in range(m + 1)] for i in range(n + 1)]
for i in range(1, n + 1):
xorsum[i][0] = 0
nzeroes[i][0] = 0
s = 0
col = 0
for j in range(1, m + 1): # columns
col = col ^ (1 << table[i - 1][j - 1])
xorsum[i][j] = xorsum[i - 1][j] ^ (col)
s += int(table[i - 1][j - 1] == 0)
# print s,
nzeroes[i][j] = nzeroes[i - 1][j] + s
if nzeroes[n][m] >= (n * m - 1):
ans = ((0, 0, 0, 0), 1)
ans = largestBeautiful(table, n, m)
print (ans[1])
print ('%d %d %d %d ' % ans[0])
else:
ans = largestBeautiful(table, n, m)
print (ans[1])
print ('%d %d %d %d ' % ans[0])
|
"""
Link to (question)[https://www.codechef.com/SEPT20B/problems/CRDGAME2]
The key idea here is that the maximum never changes the pile it belongs to
while every other number will change the pile it belongs to and reduce by 1
So we can focus on the number of maximum values.
if the number of maximum values is odd, it doesn't matter
how the distribution is made, there will always be a winner since the numbers
less than the maximum will reduce to zero and the sum of piles that contain
just the maximum will always be different i.e a winner exist.
the only case where they could be a draw is when the maximum occurs an
even number of times. So we just need to compute the number of possible ways
this could happen.
That is combinations(n_max, n_max//2)*2**(len(cards) - n_max)
So to find the distributions that cant end in draws we substract this
from 2**len(card)
"""
from collections import Counter
MOD = 1_000_000_007
factorial = [1 for _ in range(100001)]
for i in range(1, 100001):
factorial[i] = (factorial[i-1] * i) % MOD
def inverse(x):
return pow(x, MOD-2, MOD)
def combination(n, r):
return (factorial[n] * inverse(factorial[r]) ** 2) % MOD
def number_of_distributions_with_winner(cards):
max_value = max(cards)
counter = Counter(cards)
if counter[max_value] % 2 == 1:
return pow(2, len(cards), MOD)
else:
return pow(2, len(cards), MOD) - combination(
counter[max_value], counter[max_value] // 2
) * pow(2, len(cards) - counter[max_value], MOD)
T = int(input())
for _ in range(T):
N = int(input())
cards = list(map(int, input().strip().split()))
print(number_of_distributions_with_winner(cards) % MOD)
|
#!/bin/python
import sys
from math import ceil
def lowestTriangle(base, area):
# Complete this function
return int(ceil(area / float(base) * 2))
base, area = raw_input().strip().split(' ')
base, area = [int(base), int(area)]
height = lowestTriangle(base, area)
print(height)
|
""" Project Euler 152"""
import fractions
f = [fractions.Fraction(1,i*i) for i in xrange(2,101)]
f = [1.0/float(i*i) for i in xrange(2,101)]
#print f
#You are given N and D. result should be the number of ways of writing 1/D as a sum of square fractions less than N+1
#use a backtracking algorithm
Solution = []
def backtrackDFS(goal,possibleChoices,pathSoFar,selected):
print goal,possibleChoices,pathSoFar,selected
if abs(pathSoFar-goal)<10e-6:
#print pathSoFar, goal, selected
#print 'here2'
print selected
Solution.append(set(selected))
return
else:
if sum(possibleChoices)<(goal-pathSoFar):
#print 'here'
return
for element in possibleChoices:
#print 'element',element,possibleChoices
pathSoFar+=element
if pathSoFar>goal:
pathSoFar-=element
continue
possibleChoices.remove(element)
selected.add(element)
#print pathSoFar,selected
backtrackDFS(goal,possibleChoices,pathSoFar,selected)
possibleChoices.add(element)
selected.remove(element)
print f[:44]
backtrackDFS(0.5,set(f[:44]),0,set())
print Solution |
def atm(x , y):
'''This function take tow argument balance and requested money '''
if x > y:
hundre = y /100
print "give100\n" * hundre
gived = hundre*100
rest1 = y - gived
fifteen = rest1 /50
print "give50\n" * fifteen
gived2 = fifteen * 50
rest2 = y - (gived + gived2 )
ten = rest2 / 10
print "give 10\n" * ten
gived3 = ten * 10
rest3 = y - (gived + gived2 + gived3)
one = rest3 / 1
print "give 1\n" * one
else:
print " no Balance"
atm(520 , 600) |
# 문제16 : 로꾸거
# 문장이 입력되면 거꾸로 출력하는 프로그램을 만들어 봅시다.
# >> 입력
# 거꾸로
# >> 출력
# 로꾸거
data = input("단어를 입력 : ")
print(data[::-1]) |
# 문제14 : 3의 배수 인가요?
# 영희는 친구와 게임을 하고 있습니다. 서로 돌아가며 랜덤으로 숫자를 하나 말하고 그게 3의 배수이면 박수를 치고 아니면 그 숫자를 그대로 말하는 게임입니다.
# 입력으로 랜덤한 숫자 n이 주어집니다.
# 만약 그 수가 **3의 배수라면 '짝'이라는 글자를, 3의 배수가 아니라면 n을 그대로 출력**해 주세요.
# >> 입력
# 3
# 짝
# 2
# 2
data = int(input("숫자를 입력: "))
if data % 3 == 0:
print("짝")
else:
print(data) |
#!/usr/bin/env python3
def get_best_savings_rate(starting_annual_salary, r=0.04, total_cost=1000000, portion_down_payment=0.25, semi_annual_raise=0.07):
months = 36
threshold = 100
amount_to_save = total_cost*portion_down_payment
savings = 0
num_guesses = 0
low = 0
high = 10000
guess = (high + low)/2
while abs(amount_to_save - savings) > 100:
if low == high:
return []
savings = 0
annual_salary = starting_annual_salary
portion_saved = guess/10000.0
for i in range(1, months+1):
if i % 6 == 0:
annual_salary += annual_salary * semi_annual_raise
savings += portion_saved*annual_salary/12.0 + savings*r/12.0
if savings < amount_to_save:
low = round(guess)
else:
high = round(guess)
guess = (high + low)/2
num_guesses += 1
print("Guesses:",num_guesses,"Low:",low,"High:",high,"Portion saved:",portion_saved,"Savings:",savings)
return [portion_saved, num_guesses]
if __name__ == '__main__':
annual_salary = float(input("What is your starting annual salary?\n"))
search_data = get_best_savings_rate(annual_salary)
if len(search_data) > 0:
print("Best savings rate:", search_data[0])
print("Number of guesses:", search_data[1])
else:
print("It is not possible to pay the down payment in three years.")
|
# Goal:To get all the city name in website lianjia
# Purpose: practise beautifulsoup
# Sophia 20190914
# filename: citys.py
# coding: utf-8
import sys
import csv
from urllib.request import urlopen
from bs4 import BeautifulSoup
url = "https://www.lianjia.com"
# get html page
html = urlopen(url).read()
# get BeautifulSoup subjective,
# pip install lxml
bsobj = BeautifulSoup(html, "lxml")
# get all <a> tag under div class="fc-main clear"
city_tags = bsobj.find("div", {"class":"fc-main clear"}).findChildren("a")
# save every data in the file "citys.csv"
with open("./cityslian.csv", "w") as f:
writ = csv.writer(f)
for city_tag in city_tags:
# get the href link of <a> tag
city_url = city_tag.get("href").encode("utf-8")
# get the names of <a> tag
city_name = city_tag.get_text()
print(city_name)
print(city_url)
writ.writerow((city_name, city_url))
|
#title-factorial of a no
#Nilay Pedram
#M-45
def factorial(n): #defining the fun
f=1
if n<0: #if-elif statement
print('enter positive no.')
elif n==0 or n==1:
print('1')
else:
while n>1:
f=f*n
n=n-1 #refreshing the value of n after every one loop until its 1
print(f)
n=int(input("enter a no.")) #user input
result=factorial(n)
print(result)
|
# 寫一個打印菜單的函數
def show_menu():
print('+--------------------------------+')
print('| 1) 添加學生信息 |')
print('| 2) 查看所有學生信息 |')
print('| 3) 修改學生的成績 |')
print('| 4) 刪除學生信息 |')
print('| 5) 按成績從高至低打印學生信息 |')
print('| 6) 按成績從低至高打印學生信息 |')
print('| 7) 按年齡從大到小打印學生信息 |')
print('| 8) 按年齡從小到大打印學生信息 |')
print('| 9) 保存信息到文件(si.txt) |')
print('| 10)從文件中读取数据(si.txt) |')
print('| q) 退出 |')
print('+--------------------------------+')
|
list_elementos=['piedra','papel','tijeras','lagarto','holk']
while(True):
juegos= int(input("Ingrese la cantidad de veces a jugar:"))
for i in list(range(0, juegos)):
print("\n","Caso #",i+1,":")
Caso= str(input("Ingrese respuestas de los jugadores:")).lower().replace("roca","piedra")
if len(Caso.split(" "))!=2:
print("Respuesta no valida")
elif Caso.split(" ")[0] in list_elementos and Caso.split(" ")[1] in list_elementos:
Brayan= Caso.split(" ")[0]
Brigitte= Caso.split(" ")[1]
if (Brayan == 'tijeras' and Brigitte =='papel') or (Brayan == 'papel' and Brigitte =='piedra') or (Brayan == 'piedra' and Brigitte == 'lagarto') or (Brayan == 'lagarto' and Brigitte =='holk'):
|
#!/usr/bin/python2.7
import pygame
from pygame.locals import *
def main():
#Initialize Screen
pygame.init()
screen = pygame.display.set_mode((150,150))
pygame.display.set_caption("Basic Pygame Program")
#Fill Background
background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((250,250,250))
# Display some text
font = pygame.font.Font(None, 36)
text = font.render("Hello World", 1, (10,10,10))
textpos = text.get_rect()
textpos.centerx = background.get_rect().centerx
background.blit(text,textpos)
# Blit everything to the screen
screen.blit(background, (0,0))
pygame.display.flip()
#Event Loop
while 1:
for event in pygame.event.get():
print event.key
if event.type == QUIT:
return
screen.blit(background, (0,0))
pygame.display.flip()
if __name__ == "__main__":
main()
|
def recurv(n):
if n<=1:
return n
else:
return n + recurv(n-1)
if num < 0:
print("print +ve number")
else:
print("sum is",recurv(num))
|
import time
# my function of is_prime
def is_prime(n):
if n == 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3,int(n**0.5)+1):
if n % i == 0:
return False
return True
t1 = time.clock()
for n in range(1,150000):
is_prime(n)
t2 = time.clock()
print("{} seconds.".format(t2-t1))
# it calls my is_prime function
# from 1 to 150000
# the output in my computer is
# 0.627116 seconds.
# which is faster than sympy module function
|
# -*- coding: utf-8 -*-
import sys
"""
In mathematics, the Fibonacci numbers are the numbers in the following integer sequence, called the Fibonacci sequence,
and characterized by the fact that every number after the first two is the sum of the two preceding ones
https://en.wikipedia.org/wiki/Fibonacci_number
"""
def fib(n):
if n <= 1:
return 1
else:
return fib(n - 1) + fib(n - 2)
def main():
print('Enter a number : ')
num = int(sys.stdin.readline())
print(fib(num))
if __name__ == '__main__':
main()
|
#This script is used for try/except block
def divideBy(num):
try:
return (42/num)
except ZeroDivisionError:
print("you are trying to divide a number by zero")
print(divideBy(2))
print(divideBy(12))
print(divideBy(0))
print(divideBy(1))
|
def divideBy(num):
return (42/num)
try:
print(divideBy(2))
print(divideBy(12))
print(divideBy(0))
print(divideBy(1))
except ZeroDivisionError:
print('You are trying to divide by ZERO which is not right')
|
# This is use For loop
##for i in range(10): # this will start from 0 until 9 and excluding 10
## print(i)
##
##for i in range(1,10): # this will start from 1 until 9
## print(i)
##for i in range(1,10,2): #This will pring from 1-9 with jump of 2 numbers
## print(i)
for i in range(20,10,-2): #This will print from 20-10 and with a substraction of 2
print(i)
|
# Rakin Uddin
import unittest
from heaps import *
class TestHeapMethods(unittest.TestCase):
def test_init(self):
# Check if the heap is initialized properly
test_heap = Heap([1, 2, 3, 4])
self.assertEqual(test_heap._heap, [4, 3, 2, 1])
# Heap is empty when initializing it with an input list
# Heap incorrectly adding items to list
def test_insert(self):
# Check if .insert method is adding objects properly to heap
test_heap = Heap([])
test_heap._heap = [4, 2, 1, 3]
test_heap.insert(5)
self.assertEqual(test_heap._heap, [5, 4, 1, 3, 2])
# .insert is concatenating an int with a list
def test_bubble_up_middle_index(self):
# Check if ._bubble_up method is properly percolating values at indices
# that are not 0 or (len(list) - 1)
test_heap = Heap([1, 4, 2, 3])
test_heap._bubble_up(2)
self.assertEqual(test_heap._heap, [4, 3, 2, 1])
# Index of parent is not an int
def test_remove_top_empty(self):
# Check that an exception is being raised if the heap is empty
test_heap = Heap([])
with self.assertRaises(HeapEmptyError):
test_heap.remove_top()
# remove_top does not raise an error
# Exception is named incorrectly
def test_is_empty(self):
# See if is_empty is correctly returning True for an empty list and
# vice versa
test_heap = Heap([])
self.assertTrue(test_heap.is_empty())
test_heap = Heap([1, 2, 3, 4])
self.assertFalse(test_heap.is_empty())
# is_empty returning NoneType instead of bool
def test_violates_no_children(self):
# Check if a tree has no children, .violates returns True
test_heap = Heap([1])
self.assertFalse(test_heap._violates(0))
# Comparing differing types (int vs list)
def test_bubble_down_one_child(self):
# Check if heap is properly bubbled down with root > left child
test_heap = Heap([1, 2])
test_heap._bubble_down(0)
self.assertEqual(test_heap._heap, [2, 1])
# Goes into endless recursion by bubbling down from same position, not
# recursively decomposing properly
def test_remove_top_full_list(self):
# See if heap.remove_top removes the first element in a list and
# properly bubbles down the last element after replacing the removed
# element
test_heap = Heap([])
test_heap._heap = [4, 2, 3, 1]
test_heap.remove_top()
self.assertEqual(test_heap._heap, [3, 2, 1])
def test_bubble_up_first(self):
# Bubbling up the first element should not change the list
test_heap = Heap([])
test_heap._heap = [1, 4, 2, 3]
test_heap._bubble_up(0)
self.assertEqual(test_heap._heap, [1, 4, 2, 3])
def test_bubble_up_last(self):
# Test to see if last element is bubbled up properly
test_heap = Heap([])
test_heap._heap = [1, 3, 2, 4]
test_heap._bubble_up(3)
self.assertEqual(test_heap._heap, [4, 1, 2, 3])
# Bubble up was percolating the child node instead of the parent node
if(__name__ == '__main__'):
unittest.main(exit=False)
|
# lesson 03, chapt 2, challenge 4
'''
Write a Car Salesman program where the user enters the base price of a car.
The program should add on extra fees such as tax, license, dealer prep,
and destination charge. Make tax and license a percent of the base price.
The other fees should be set values.
Display the actual price of the car once all the extras are applied.'''
# variables
base = 0.0; # base price of car, float
total = 0.0; # total price of car
tax = .08; # 8% tax
licenseFee = .05; # 5% license fee
dealerPrep = 100.00; # dealer prep fee
destinationCharge = 150.00; # destination charge fee
# user input
base = float(input("Enter the base price of the car: \n"));
# calcs
total = base + base*(tax + licenseFee) + dealerPrep + destinationCharge;
# display
print("The total price of the car is: $", end="");
print("{0:0.2f}".format(total));
|
# lesson 11
'''
function scoping/global variables, passing parameters
'''
# function scoping---
# namespaces follow LEGB-hierarchy: Local, Enclosed, Global, Built-In
# scope directly related to level of block indentation
# local scope: x is defined in the function
def f1():
x = 11
print("inside f1: x = ", x)
return
x = 1
f1()
print("outside f1: x = ",x)
# global scope: x is defined outside the function, so python goes global
def f1():
print("inside f1: x = ", x)
return
x = 2
f1()
print("outside f1: x = ",x)
# global keyword tells python to define var on global level
def f1():
print("inside f1, x = ", x)
print("inside f1, y = ", y)
return
def main():
global x # global keyword
x = 2
f1()
return
y = 5 # global var implicitly defined
main()
# built-in scope functions
# locals() - call inside a function
print("z" in locals())
# globals()
print("z" in globals())
def f1():
print("In f1: 'z' in locals()? ", 'z' in locals()); # False
print("In f1: 'z' in globals()? ", 'z' in globals()); # False
return;
def main():
z = 9;
f1();
print("In main: 'z' in locals()? ", 'z' in locals()); # True
print("In main: 'z' in globals()? ", 'z' in globals()); # False
return;
main();
# enclosed example- function w/in function
def f1():
def f1a():
print("Inside f1a: x = ", x); # 2
print("locals: ", x in locals()); # False
print("globals: ", x in globals()); # False
return;
x = 2;
f1a()
return;
def main():
f1();
return;
main();
# modifying scope variables
# can read local variables, but can't modify
''' example
def f1():
print(x); # Can read contents of x
x += 1; # Trying to modify x -> ERROR
return;
x = 1; # x is in local scope
f1();
=> UnboundLocalError: local variable 'x' referenced before assignment
'''
# global declaration outside f1() and trying to modify inside f1()
'''
def f1():
print(x); # Can read contents of x
x += 1; # Trying to modify x -> ERROR
return;
global x; # x is declared global at Enclosed level
x = 1; # x is assigned
f1();
=> UnboundLocalError: local variable 'x' referenced before assignment
'''
# global declaration inside function - not recommended
def f1():
global x; # x is declared global at Local level for modification
print(x); # Can read contents of x
x += 1; # Modifying x
return;
x = 1; # x in Global scope
f1();
print("Outside f1: x = ", x); # Outside f1: x = 2
# passing parameters---
# pass by value - make copy in memory of actual value; immutable args
# pass by reference - copy of address of actual parameter is stored
|
# lesson 04
'''
importing modules, conditions, conditional branching, code blocks
'''
# python modules---
# module is a file w/ python code, can define functions, classes, vars
# import statement: import modulename;
# from...import statement: from modulename import name1
# usage syntax: modulename.methodname(params)
# list of available modules: help("modules");
'''
from os import system;
system("python -m pip install --upgrade pip"); # install latest pip
system("pip install openpyxl"); # install excel module
system("pip uninstall openpyxl"); # Un-install excel module
'''
import random;
rand_nbr = random.randint(1, 6); print(rand_nbr); # randint 1-6 inclusive
rand_nbr = random.randrange(6); print(rand_nbr); # randrange 0-5
from random import randint, randrange;
rand_nbr = randint(1, 6); print(rand_nbr); # randint 1-6 inclusive
rand_nbr = randrange(6); print(rand_nbr); # randrange 0-5
# conditions, branching---
# non-zero AND non-null -> True
# zero OR null -> False
''' syntax:
if condition:
code
---------------
if condition:
code
else:
code
---------------
if condition:
code
elif condition:
code
elif condition:
code
else: recommend using else as error check
code
'''
a = 1; b = 2;
if a != b:
print(a, b);
if a == b:
print(a, b);
else:
print("a does not equal b");
i = 60;
if i >= 80:
print(i, "first option");
elif i >=60:
print(i, "second option");
elif i < 60:
print(i, "third option");
else:
print(i, "not possible");
# code blocks---
# one or more consecutive lines indented by same amount
count = 2;
if (count == 3):
count += 10;
print("Count = ", count); # Count is not printed since count not equal 3
# different result if print outside of indentation
if (count == 3):
count += 10;
print("Count = ", count);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.