text stringlengths 37 1.41M |
|---|
if __name__ == '__main__':
while True:
print("开始?0/1")
c=input()
if c==0:
break
else:
s = input("请输入字符串,我帮你看看哪个重复了:")
d = set()
for i in s:
d.add(i)
for i in d:
num = s.count(i)
if num >= 2:
print("重复的是{0},重复的次数为:{1}".format(i, num))
#第二题
|
#随机生成两个分别包含10和15个整数的列表,并计算输出两个列表的并集
import random
# 并集就是把两个列表相加去重
def suiji():
nlist = [random.randint(1, 21) for i in range(0, 15)]
mlist = [random.randint(1, 31) for i in range(0, 10)]
slist = mlist + nlist
ulist = {i for i in slist}
print("第一个随机列表为:{0}".format(nlist))
print("第二个随机列表为:{0}".format(mlist))
print("两列表的并集为:{0}".format(ulist))
'''交集:intersection。
差集:difference。
并集:union。
子集校验:issubset。
父集校验:issupperset。注意!只适用于set集合
''' |
#!/usr/bin/env python2.7
# encoding: utf-8
"""
@brief:
@author: icejoywoo
@date: 15/12/6
"""
import re
import perf
s = ("Note that there is a significant advantage in Python to adding a number "
"to itself instead of multiplying it by two or shifting it left by one bit. "
"In C on all modern computer architectures, each of the three arithmetic "
"operations are translated into a single machine instruction which executes "
"in one cycle, so it doesn't really matter which one you choose.")
words = re.split(r'\W', s)
def string_add():
r = ''
for w in words:
r += w + ' '
return r
def string_join():
return ' '.join(words)
if __name__ == '__main__':
print perf.perf(string_add)
print perf.perf(string_join)
|
x=int(input())
if x%2==0:
print("it is Even")
else:
print("it is Odd")
|
#primenumber......ajith
x=int(input("enter a value"))
if x<=1000:
if(x>1):
for i in range(2,x):
if(x%i==0):
print("it is not a prime number")
break
else:
print("it is a prime number")
else:
print("not a prime number")
else:
print(" value should be less than 1000")
|
from os import path
def print_paths_parts(file, number):
"""
This method outputs print b amount of parts of input path to file
in correct order.
Amount of parts also an input argument
Works on with all common type of path : Unix and Win
:parameters:
path : string - path to be sliced
number : int - amount of last lines of file
:returns :
None
"""
number = int(number)
if not path.isfile(file):
print('Sorry - path to file doesn`t exist.Please provide another path')
elif number <= 0:
print('Please provide number more than 0')
else:
with open(file, 'r') as file:
file_lines = file.readlines()
max_number = len(file_lines)
if number > max_number:
print("Sorry, amount of number is bigger than amount of lines.\
Amount in provided file is {}".format(max_number))
else:
for i in reversed(range(1, number+1)):
# Print last N lines of file in correct order
print(file_lines[-i])
|
# PB1 ABHISHEK WAHANE
# Unification Algorithm
class Variable:
def __init__(self, value):
self.value = value
def __eq__(self, other):
return self.value == other.value
class Constant:
def __init__(self, value):
self.value = value
def __eq__(self, other):
return self.value == other.value
class Relation:
def __init__(self, name, args):
self.name = name
self.value = str(self.name) + str([i.value for i in args])
self.args = args
def unification(L1, L2, testset):
if (isinstance(L1, Variable) or isinstance(L2, Variable) or isinstance(L1, Constant) or isinstance(L2, Constant)):
if L1 == L2:
return None
elif isinstance(L1, Variable):
if isinstance(L2, Variable):
print('Mismatching variables!')
return False
else:
if L1.value not in testset.values():
return [L2, L1]
else:
print('Ambiguous Variable.')
return False
elif isinstance(L2, Variable):
if isinstance(L1, Variable):
print('Mismatching Variables!')
return False
else:
if L2.value not in testset.values():
return [L1, L2]
else:
print('Ambiguous Variable')
return False
else:
print('Mismatch!!')
return False
elif L1.name != L2.name:
print('Relation does not match')
return False
elif len(L1.args) != len(L2.args):
print('Number of Arguments do not match')
return False
subset = {}
for i in range(len(L1.args)):
s = unification(L1.args[i], L2.args[i], subset)
if s == False:
return False
if s != None:
subset[s[0].value] = s[1].value
return subset
print('Unification:\n')
print(unification(Relation('Knows', [Constant('John'), Variable('X')]), Relation(
'Knows', [Variable('Y'), Relation("Brother", [Variable("Y")])]), {}))
print(unification(Relation("Knows", [Constant("Ram"), Variable("X")]), Relation(
"Knows", [Variable("Y"), Constant("Shyam")]), {}))
"""
OUTPUT:
Unification:
{'John': 'Y', "Brother['Y']": 'X'}
{'Ram': 'Y', 'Shyam': 'X'}
"""
|
"""
lambda는 함수명이 존재하지 않으며 재활용성을 고려한 함수보다는
1회성으로 잠깐 사용하는 속성 함수라고 볼 수 있음
"""
answer = lambda x: x**3
print(answer(5))
power = list(map(lambda x: x**2, (range(1,6))))
print(power) |
foods = ["bacon", "beef", "spam", "tomato", "tuna"]
# for food in foods[3:]:
# print(food)
# print(len(food))
# for number in range(5):
# print(number)
# for number in range(1,10,2):
# print(number)
# for number in range(10):
# print(str(number) + " Hello World")
times = 5
while times < 10:
print(times)
times += 1 |
str="HI! my name is vaishnav!. what is yours?"
print(str)
print('Split string =')
print('HI!\n My name is vaishnavi\n What is yours?\n')
|
a=input("enter the words in string to be reversed")
a=a.split()
b=a[-1::-1]
revstr=' '.join(b)
print(b)
|
#learned a little bit about csv files and the csv library while making this program. Also have a pretty cool way to search for popular drake songs!
import csv
from string import *
# convert_num: converts things like "1M" or "2.4K" to 1000000 and 2400
# converts input string to a list of chars, manipulates that list, then remakes the string and casts to int
def convert_num(n): # returns 0 if a songs is n/a, -1 if unreleased
listn = [char for char in str(n)]
newlistn = []
for char in listn:
if char == '.':
pass
elif char == 'K':
for i in range(2):
newlistn.append('0')
elif char == 'M':
for i in range(5):
newlistn.append('0')
else:
newlistn.append(char)
newstringn = ''.join(newlistn)
newintn = 0
if newstringn:
if newstringn == '(Unreleased)':
newintn = -1
else:
newintn = int(newstringn)
return newintn
# function that finds all drake songs with # of genius hits between the bounds
def find_drake(lower, upper): #n will be the minimum number of genius hits the returned songs got
with open("drake_data.csv", encoding = 'utf8') as drake_data:
csv_reader = csv.reader(drake_data, delimiter = ',') #csv reader makes an iterator over the rows of the csv
first_line = True
for row in csv_reader:
if first_line:
#print(f"Column names are {', '.join(row)}")
first_line = False
else:
if (convert_num(row[4]) >= lower) and (convert_num(row[4]) <= upper): #if this song's hits are between the bounds
print(f"{row[0]}, {row[1][:-7]}, {row[4]}") #print the album title, song title, and the number of hits
#main function, run at the end of the file
def main():
print("Welcome to DrakeSearch.")
print()
print("This program allows you to search for Drake songs by")
print("the amount of hits his songs have on Genius.")
print()
while(1):
lower = input("Enter a lower bound: (type 'q' or 'quit' to quit, or 'h' for help) ")
if lower.lower() == "q" or lower.lower() == "quit": break
if lower.lower() == "h":
print("\nINSTRUCTIONS:\n")
print("When prompted to enter the bounds, enter only integers.\n")
print("The bounds determine what songs are returned. Only songs that")
print("have been visited MORE than <lower bound> number of times and ")
print("LESS than <upper bound> number of times will be returned.\n")
continue
try:
lowern = int(lower)
except ValueError as e:
print("That is not a number. Please only enter integers.\n")
continue
upper = input("Enter an upper bound: ")
try:
uppern = int(upper)
except ValueError as e:
print("That is not a number. Please only enter integers.\n")
continue
print("SEARCH RESULTS:\n")
find_drake(lowern, uppern)
main()
|
import numpy as np
import matplotlib.pyplot as plt
import pickle
import random
##opening of the file
f = open('data2_new.pkl','rb')
data = pickle.load(f)
f.close()
da = np.asarray(data)
X = da[:,0]
Y = da[:,1]
#initialisation of variables
cnt = 0
best_fit = 0
slope = 0
intercept = 0
iterations = 1
variance = 0
inlier = 0
outlier = 0
l = len(da)
p = 0.9
while iterations > cnt :
xyrand1 = random.choice(da) ## generation of random variables
xyrand2 = random.choice(da)
rand_data = np.array( (xyrand1, xyrand2) )
##line fitting and calculation of slope/intercept
m = (rand_data[1,1] - rand_data[0,1])/(rand_data[1,0]-rand_data[0,0])
c = rand_data[1,1] - (m*rand_data[1,0])
distance = []
inlier = 0 #outlier and inlier initialisation at each iteration in order to compare with prev value
outlier = 0
for i in range(len(da)) :
#calculation of distance of a point from the fitted line
D = ( c - Y[i] + (m*X[i]) )/(np.sqrt( (m**2)+1) )
#distance array is used to compute the distance of each point from the fitted line. It is done by first computing the variance of the distane array in order to know how the gradient occurs for a particular pair of chosen points. This variance is used to compute the required threshold for outlier rejection.
distance = np.append(distance, D)
variance = np.var(distance)
thres = np.sqrt(3.84*variance)
for i in range(l) :
if(distance[i] < thres) : #inilier is identified if the points distance is less than the threshold given.
inlier += 1
else :
outlier+= 1
e = (1 - (float(inlier))/l)
iterations = int(np.log10(1-p))/(np.log10(1-((1-e)**2)))
cnt+=1
if (best_fit < inlier) :
#the variable best_fit is used to identify whether the chosen set of points in the current iteration generate the best line that has the maximum number of inlier to outlier ratio. The best_fit variable stores the previous inlier value and is compared to the previous value. If the current inliers are more then it means the current model is more efficient than the prev one.
best_fit = inlier
intercept = c
slope = m
else :
intercept = intercept
best_fit = best_fit
slope = slope
y_predict = (slope*X) + intercept
plt.figure(1)
#plt.subplot(132)
plt.plot(X,Y,'ro')
plt.plot(X, y_predict, color = 'k', linewidth = 2)
plt.axis([-150,150,-100,100])
plt.show()
|
from collections import deque
element="hello"
print(element[0])
print(element[-1])
print(element[4])
print(element[-5])
# [2:4] the element at 4 is excluded
print(element[2:4])
print(element[2:9])
print(element[77:99])
#List Implementation
print("\n\nLIST IMPLEMENTATION")
sampleList=[0,1,2,3,4,5,6,7]
print("This is the sample list {0}".format(sampleList))
#Slicing returns new list
childList=sampleList[2:4]
print("this is the child List {0}".format(childList))
childList[0]=10
print("the New parent list is {0}".format(sampleList))
print("Modified child list {0}".format(childList))
sampleList[4:]=[]
print("emptying 4,5,6,7 {0}".format(sampleList))
#slicing can also be used to append the list
sampleList[4:]=[4,5,6,7,8,9,10,11,12,13,14]
lenghtOfsample=len(sampleList)
sampleList[lenghtOfsample:]=[15,16,17,18,19,20]
print("assinging 4,5, {0}".format(sampleList))
sampleList.append([1,2,3,4])
sampleList.extend([0,8,6,[3,4,5,6,7]])
print("List after useing append and extend :: {0}".format(sampleList))
#Multiple assinggments
print("\n\nMultiple Assignments implementation")
a, b=0,1
print("Values of a and b are ::{0}, {1}".format(a,b))
#Evaluation on right hand side is done before any assingments and the evaluation is from left to right
a,b=b,a+b
print("Values of a and b after further computations :: {0},{1}".format(a,b))
#For Loop
#This loop can be used to iterate over lists
print("\n\n For loop Implementation")
words=["apple","orange","beautiful"]
# dummy list is created using slicing to stop infinite looping
for item in words[:] :
if len(item)>6 :
print(item)
words.insert(0,"extraElementInList")
break
#Else clause of loop runs only when loop exits, it also doesn't get called when break statement is used inside for.
else :
#pass statement does nothing it can be used to define a dummy function where u syntactically need an statement but don't want any code to execute
pass
print("The loop condition over")
print("The loop is over and the list is {0}".format(words))
#MORE ON FUNCTIONS
#DEFAULT ARGUMENT VALUES
#The default argument values are initialized only once
def dummyFunction(arg1="hello",arg2=None) :
if arg2==None :
arg2=[]
arg2.append(arg1)
print(arg2)
dummyFunction("hi")
dummyFunction("hello")
dummyFunction("how are you")
dummyFunction("kiss",["i","hate","you"])
dummyString="dfklkfd"
#LISTS IN PYTHON
#LISTS AS QUEUES
dummy_queue=deque(["harry","tom","keil"])
dummy_queue.append("bala")
print(dummy_queue)
print(dummy_queue.popleft())
print(dummy_queue)
dummy_queue=list(dummy_queue)
print(dummy_queue)
dummy_queue="hello hai brother"
print(dummy_queue)
#TUPLES
tuple_element=("naveen","mohana","hari","muthu")
#unpacking of tuple done
nave, moh, har, muth =tuple_element
print(nave , moh , har, muth)
#item assignments is not possible for tuples
#Tuples are immutable
#sets
set_element=set()
set_element.add("hello")
set_element.add("hanuman")
print(set_element)
set_element.add('mano')
print(set_element)
#str() and repr()
str_dummy="hlllo dude \n"
print(str(str_dummy))
print(repr(str_dummy))
x = 10 * 3.25
y = 200 * 200
s = 'The value of x is ' + str(x) + ', and y is ' + str(y) + '...'
rr = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...'
print(s)
print(rr)
var1="hello {} i amd the {dude}".format('red','lese',dude="hari")
print(var1)
jack_detail="hello {0:10} am the {1:10d} ".format("01234569604jdkd",32434950934504534534)
print(jack_detail)
#File Reading
print("\n\nFile Operations")
file_sample=open('quickWorkouts.py')
# print(file_sample.read())
line_from_file=file_sample.readline()
while line_from_file!="\n" :
print(repr(line_from_file))
line_from_file=file_sample.readline()
print("\nThis is after while loop\n")
for line in file_sample :
print(line,end='')
print()
file_sample.close()
with open("quickWorkouts.py","r") as f :
read_sample=f.read()
print(read_sample.index("print"))
print (f.closed)
with open("quickWorkouts.py","a") as f :
print("inside loop")
f.write("print(\"How is every-thing going ? \")")
with open("quickWorkouts.py","r") as f :
print("\n\n ",f.read())
print(f)
#Exception handling
# IT is similar to other languages, there can be multiple except classess when there are both base class and derived classes in the except the class which is matched first will called irrespective of the original exception class.
# There is an else segment in the exception handling which gets called when no exception is raised.
# raise exception is similar to throw exception
try :
raise Exception("arg1","arg2")
except Exception as inst :
print(inst.args)
x,y=inst.args
print(x,y) |
element=["1","2","3"]
print(element)
element[1]="7"
print(element)print("How is every-thing going ? ")print("How is every-thing going ? ")print("How is every-thing going ? ")print("How is every-thing going ? ")print("How is every-thing going ? ")print("How is every-thing going ? ")print("How is every-thing going ? ")print("How is every-thing going ? ")print("How is every-thing going ? ")print("How is every-thing going ? ")print("How is every-thing going ? ")print("How is every-thing going ? ")print("How is every-thing going ? ") |
import sys
def driver_testcases():
no_of_cases = int(input())
for i in range(1, no_of_cases+1):
length = int(input())
arr = [int(x) for x in input().split()]
print(f"Case #{i}: {Reversort(arr)}")
def main():
Reversort(L)
def Reversort(L):
cost = 0
l = len(L)
for i in range(0, l-1):
j = get_smallest(L,i)
reverse_array(L,i,j)
cost += j-i +1
return cost
def get_smallest(array, start):
smallest = array[start]
index = start
for i in range(start+1, len(array)):
if array[i] <= smallest:
smallest = array[i]
index = i
return index
## Correct
def reverse_array(array, start, end):
while start < end:
temp = array[start]
array[start] = array[end]
array[end] = temp
start+=1
end-=1
return array
if __name__ == "__main__":
driver_testcases()
# print(reverse_array([5,6,7,8,3,5, 9], 2,5))
# print(get_smallest([5,6,7,8,3,5, 9],2))
|
from electronicDie import ElectronicDie
from sense_hat import SenseHat
import time
import csv
import os.path
from os import path
from datetime import datetime
#Creating an object pointing to the SenseHat class
sense = SenseHat()
#Creating an object pointing to the ElectronicDie class
electronicDieObj = ElectronicDie()
class Game:
player1 = 0
player2 = 0
playerTurn = True
#Constructor for the class
#The two parameters are the starting score for the two players
def __init__(self, player1, player2):
self.player1 = player1
self.player2 = player2
#This function records the winner score to the winner.csv file
def recordResult(self, player, score, date, time):
#To check if the winner.csv file exists
if path.exists("winner.csv") == True:
#If the file exists append result to existing file
with open('winner.csv', 'a') as file:
writer = csv.writer(file)
writer.writerow([player, score, date, time])
#If file does not exists create the file and append the result
else:
with open('winner.csv', 'w') as file:
writer = csv.writer(file)
writer.writerow([player, score, date, time])
#This function gets the accelorometer values from the sensehat
def getAccelerometer(self):
#Gets the values of 3 diffrent axis from the sensehat
a, b, c = sense.get_accelerometer_raw().values()
a = abs(a)
b = abs(b)
c = abs(c)
return a,b,c
#This function is a wait for user input function
#The following code will wait until user shakes the PI before continueing the code
def wait_until(self):
#Calls the getAccelerometer() function
x = self.getAccelerometer()
#Check if user shakes the PI
if x[0] > 1.4 or x[1] > 1.4 or x[2] > 1.4:
return True
else:
return False
#This function is to display instructions through the sense hat before starting the game
def displayInstructions(self):
sense.show_message("Welcome!")
sense.show_message("This is a simple two player electronic die-based game created for the Raspberry Pi")
sense.show_message("Each player will take turns rolling the die by shaking the Raspberry Pi")
sense.show_message("Whoever reaches a total score of 30 or above wins")
sense.show_message("Are you ready? Shake to start!!!")
#Wait for the user to shake the PI before continueing
while not self.wait_until():
time.sleep(0.01)
#This function contains the code for the game
def gameLogic(self):
#While both of the player's score is below 30 keep looping
while self.player1 < 30 and self.player2 < 30:
#Check for which player's turn
#Player 1 = True, Player 2 = False
if self.playerTurn == True:
#Telling the user is Player 1's turn
sense.show_message("Player 1's Turn!!!")
#Wait for the user to shake the PI before continueing
while not self.wait_until():
time.sleep(0.01)
#Updates player's total score after shaking the dice
self.player1 = self.player1 + electronicDieObj.roll_dice()
#Display player's current total score on the console
print "Player 1's Current Score:",self.player1
time.sleep(2)
sense.clear()
#Assign turn to player 2
self.playerTurn = False
#Check if its player 2's turn
elif self.playerTurn == False:
#Telling the user is Player 2's turn
sense.show_message("Player 2's Turn!!!")
#Wait for the user to shake the PI before continueing
while not self.wait_until():
time.sleep(0.01)
#Updates player's total score after shaking the dice
self.player2 = self.player2 + electronicDieObj.roll_dice()
#Display player's current total score on the console
print "Player 2's Current Score:",self.player2
time.sleep(2)
sense.clear()
#Assign turn to player 1
self.playerTurn = True
#If either one of the players has reached a total score of 30 display game over
sense.show_message("Game Over!")
#Record the winner's score, time and date to the winner.csv file
#Check which player won
if self.player1 >= 30:
#Display message if player 1 wins
sense.show_message("Player 1 Wins!!!")
#Record the results
self.recordResult("Player 1", self.player1, datetime.date(datetime.now()), datetime.time(datetime.now()))
else:
#Display message if player 2 wins
sense.show_message("Player 2 Wins!!!")
#Record the results
self.recordResult("Player 2", self.player2, datetime.date(datetime.now()), datetime.time(datetime.now()))
|
import curses
class ViewController(object):
""" A ViewController is essentially the entry point
to the UI. It is responsible for initializing the screen,
moving between main views, and waiting in the main
event loop. """
def __init__(self, views=None):
""" Create a new ViewController.
:param list View views: a view stack to initialize with. """
self.views = views or []
self.initialized = False
def _present(self, screen=None):
if screen:
screen = self.initialize_screen(screen)
self.screen = screen or self.screen
self.screen.erase()
self.active_view.screen = self.screen
self.active_view.draw()
self.active_view.refresh()
# Begin the main event loop
self.event_loop()
def present(self):
""" Take control of the terminal, initialize the
curses screen, and render views. """
if not self.initialized:
curses.wrapper(self._present)
self.initalized = True
else:
self._present()
def event_loop(self):
""" The main event loop. When a keypress is received,
the key is sent to the active view. It is up to the active
view to forward this signal to any subviews that require
notification of this event. """
while True:
key = self.screen.getch()
self.active_view.key_pressed(key)
self.active_view.refresh()
def push_view(self, view):
""" Push a view to the top of the controller's view stack.
After pushing, calling present() will render the new view.
:param View view: the view to add to top of view stack """
view.controller = self
self.views.append(view)
def pop_view(self, *args, **kwargs):
""" Pop a view from the top of the controller's view stack.
After poping, calling present() will render view on the
stack underneath the one that was just popped. """
del self.views[-1]
@property
def active_view(self):
""" Returns view at the top of the stack. This *should*
corresponds to the currently displayed view. """
return self.views[len(self.views) - 1]
def initialize_screen(self, screen):
""" Initialize the curses screen. This method defines
a sensible set of defaults. To customize, override this
method in a subclass. """
curses.noecho()
curses.curs_set(0)
curses.cbreak()
screen.keypad(1)
curses.start_color()
curses.use_default_colors()
return screen
class View(object):
""" Views are objects that know how
to draw themselves on the screen. """
screen = None
subviews = []
action_keys = {}
def draw_text(self, x, y, message, *args, **kwargs):
""" Writes the given message at row x, column y. """
self.screen.addstr(x, y, message)
def refresh(self):
""" Refresh the screen to pick up any changes since the
last time the screen has been refreshed. """
self.screen.refresh()
def add_subview(self, view):
""" Add a subview to this view. Subviews are views
that are rendered when this view's draw() method is
invoked. """
view.parent = self
self.subviews.append(view)
def add_subviews(self, *views):
""" Same as add_subview, except it accepts multiple
view objects. """
for view in views:
view.parent = self
view.screen = self.screen
self.subviews.append(view)
def draw(self):
""" Render this view. By default, this method just
calls draw() on each of its subviews. Override this
method to customize behavior. """
for view in self.subviews:
view.screen = self.screen
view.draw()
def add_action_key(self, key, func):
""" Add a function to be executed when key
is pressed. For simplicity, the functions are
called with no arguments, so any state needed must
be stored on the View object itself.
"""
self.action_keys[ord(key)] = func
def key_pressed(self, key):
""" This is a callback that is invoked by this view's
controller when a keydown event happens. """
if ord(key) in self.action_keys:
self.action_keys[ord(key)]()
self.refresh()
|
from abc import ABC,abstractmethod
class shape(ABC):
def __init__(self,hight,base):
self.hight=hight
self.base=base
@abstractmethod
def area(self):
pass
class Triangle(shape):
def area(self):
area=.5* self.base * self.hight
print("area of triangle:",area)
class Rectangle(shape):
def area(self):
area=self.base * self.hight
print("area of rectangle:",area)
t=Triangle(20,30)
t.area()
r=Rectangle(20,30)
r.area() |
#!/usr/bin/python3
"""Module to display the first 10 hot posts"""
import requests
def top_ten(subreddit):
""" Function that will take the first 10 hot posts
from a subreddit """
response = requests.get('https://www.reddit.com/r/{}/hot.json'
.format(subreddit),
headers={'User-Agent': 'Camilo@holberton.com'},
allow_redirects=False, params={'limit': 10})
if response.status_code == 200:
response = response.json()
data = response.get('data')
children = data.get('children')
if data and children:
for post in children:
post_data = post.get('data')
title = post_data.get('title')
print(title)
else:
print(None)
|
"""
Various functions useful for saving and loading arrays of results
"""
import os, json, logging
import numpy as np
def save_json(folder_name, base_name, output_data):
"""
Serialize a structure of output data to JSON file in specified location
:param folder_name:
:param base_name:
:param output_data: Nested dictionary structure that can be serialized with JSON
"""
# TODO: most notable required error handling would be if incompatible data struc or non-ASCII
# chars specified.
if not os.path.isdir(folder_name):
os.makedirs(folder_name)
out_fn = os.path.join(folder_name, base_name + ".json")
with open(out_fn, 'w') as f:
json.dump(output_data, f)
logging.debug("Saved JSON results to {}".format(out_fn))
def save_array(folder_name, base_name, data_array):
"""
Save numpy array data
"""
if not os.path.isdir(folder_name):
os.makedirs(folder_name)
out_fn = os.path.join(folder_name, base_name + ".npy")
np.save(out_fn, data_array)
logging.debug("Saved array data to {}".format(out_fn))
def save_multi_array(folder_name, base_name, dict_of_arrays):
"""
Use np.savez to store multiple arrays in a single file.
:param folder_name:
:param base_name:
:param dict_of_arrays:
"""
if not os.path.isdir(folder_name):
os.makedirs(folder_name)
out_fn = os.path.join(folder_name, base_name + ".npz")
np.savez(out_fn, **dict_of_arrays)
logging.debug("Saved array data to {}".format(out_fn))
def load_array(folder_name, base_name, multi_array=False):
"""
Load in an array with results. Sets the extension based on whether the file contains one
array (from np.save) or multiple arrays (from np.savez).
"""
ext = ".npz" if multi_array else ".npy"
inp_fn = os.path.join(folder_name, base_name + ext)
d = np.load(inp_fn)
logging.debug("Loaded array data from {}".format(inp_fn))
if multi_array:
# np.load seems to return a file object for npz files; i/o can be slow as specific
# desired arrays are only called in sequence. Get all the data and ensure the file is
# correctly closed.
arr_dict = {k: v.copy() for k, v in d.items()}
d.close()
return arr_dict
else:
return d |
""" Provide geometric transformations and other utilities. """
from math import sin, cos, sqrt
import numpy as np
from lxml import etree
def rotation_about_vector(vec, t, mat=None):
"""
Return a transform matrix to rotate ``t`` radians around unit vector ``vec``.
"""
l = vec[0]
m = vec[1]
n = vec[2]
st = sin(t)
ct = cos(t)
if mat is not None:
## Use the supplied array to hold the result instead of making a new one
mat[0] = l*l*(1-ct)+ct, m*l*(1-ct)-n*st, n*l*(1-ct)+m*st, 0
mat[1] = l*m*(1-ct)+n*st, m*m*(1-ct)+ct, n*m*(1-ct)-l*st, 0
mat[2] = l*n*(1-ct)-m*st, m*n*(1-ct)+l*st, n*n*(1-ct)+ct, 0
mat[3] = 0,0,0,1
return mat
return np.array([[l*l*(1-ct)+ct, m*l*(1-ct)-n*st, n*l*(1-ct)+m*st, 0],
[l*m*(1-ct)+n*st, m*m*(1-ct)+ct, n*m*(1-ct)-l*st, 0],
[l*n*(1-ct)-m*st, m*n*(1-ct)+l*st, n*n*(1-ct)+ct, 0],
[0,0,0,1]])
def translate(vec):
"""
Return a transform matrix to translate by vector ``vec``.
"""
l = vec[0]
m = vec[1]
n = vec[2]
return np.array([[1.0, 0, 0, l],
[0, 1.0, 0, m],
[0, 0, 1.0, n],
[0, 0, 0, 1.0]])
origin = np.array([0, 0, 0, 1.0])
def get_translation(*args):
"""
Return the translation component of a translation matrix or sequence of translation matricies.
"""
arg_org = list(args)
arg_org.append(origin)
return mul(*arg_org)[:3]
def mul(*args):
"""
Return the resultant translation matrix from multiplying a supplied sequence of matricies.
"""
return reduce(np.dot, args)
pos_x = np.array([1, 0, 0])
pos_y = np.array([0, 1, 0])
pos_z = np.array([0, 0, 1])
def normalize(vec, degen=pos_x):
"""
Return a new vector representing ``vec`` with a length of 1.
If ``vec`` is degenerate (length < 1e-10) returns ``degen`` instead.
"""
abs_n_vec = sqrt(np.dot(vec, vec))
return degen if abs_n_vec < 1e-10 else vec / abs_n_vec
def matrix_from_nx_ny_ro(n_x, n_y, r_o):
"""
Return a transform matrix that moves to r_o and aligns the local x, y with n_x, n_y
Doesn't use n_x and n_y directly because they may not be perfectly perpendicular. The
disadvantage is 2 cross products are needed instead of 1.
"""
e_x = normalize(n_x, pos_x)
e_z = normalize(np.cross(e_x, n_y), pos_z)
mat = np.eye(4)
mat[0, :3] = e_x
mat[1, :3] = np.cross(e_z, e_x)
mat[2, :3] = e_z
mat = mat.T
mat[0, 3] = r_o[0]
mat[1, 3] = r_o[1]
mat[2, 3] = r_o[2]
return mat
def trans_mat_from_xml(elem):
"""
Take an xml element that represents a Coord_System_Definition and return a trans matrix.
"""
r_o = np.array([float(f) for f in elem.xpath(r"./*[@name = 'position']//@value")])
n_x = np.array([float(f) for f in elem.xpath(r"./*[@name = 'local_x']//@value")])
n_y = np.array([float(f) for f in elem.xpath(r"./*[@name = 'local_y']//@value")])
return matrix_from_nx_ny_ro(n_x, n_y, r_o)
xpath_val = etree.XPath(r".//*[@Name = $n]/Value/ValueExpression/Value")
def trans_mat_from_avm_xml(elem):
"""
Take an xml element that represents a Coord_System_Definition and return a trans matrix.
"""
r_o = np.array([float(f) for f in xpath_val(elem, n="position")[0].text[1:-1].split(",")])
n_x = np.array([float(f) for f in xpath_val(elem, n="local_x")[0].text[1:-1].split(",")])
n_y = np.array([float(f) for f in xpath_val(elem, n="local_y")[0].text[1:-1].split(",")])
return matrix_from_nx_ny_ro(n_x, n_y, r_o)
def ray_sphere_intersection(ray_o, ray_t, cen, rad):
"""
Calculate the intersection point of a ray with a sphere.
"""
d = normalize(ray_t - ray_o, pos_x)
offset = ray_o - cen
A = np.dot(d, d)
B = np.dot(2 * offset, d)
C = np.dot(offset, offset) - rad * rad
discr = B * B - 4 * A * C
if discr < 0.0:
return None
## Only ever need the far point
t_1 = (-B + sqrt(discr)) / (2 * A)
return ray_o + d * t_1
def ray_plane_intersection(ray_o, ray_t, plane_normal, point_on_plane):
"""
Return the intersection point of a ray with a plane.
Returns ``None`` if no intersection is found.
"""
plane_d = -np.dot(plane_normal, point_on_plane)
V = normalize(ray_t - ray_o, pos_x)
t = -(np.dot(ray_o, plane_normal) + plane_d) / ( np.dot(V, plane_normal))
if t > 0.0:
return ray_o + t * V
|
from sympy.combinatorics.permutations import Permutation
from sympy.utilities.iterables import variations, rotate_left
from sympy.core.symbol import symbols
from sympy.matrices import Matrix
def symmetric(n):
"""
Generates the symmetric group of order n, Sn.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> Permutation.print_cyclic = True
>>> from sympy.combinatorics.generators import symmetric
>>> list(symmetric(3))
[Permutation(2), Permutation(1, 2), Permutation(2)(0, 1),
Permutation(0, 1, 2), Permutation(0, 2, 1), Permutation(0, 2)]
"""
for perm in variations(range(n), n):
yield Permutation(perm)
def cyclic(n):
"""
Generates the cyclic group of order n, Cn.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> Permutation.print_cyclic = True
>>> from sympy.combinatorics.generators import cyclic
>>> list(cyclic(5))
[Permutation(4), Permutation(0, 1, 2, 3, 4), Permutation(0, 2, 4, 1, 3),
Permutation(0, 3, 1, 4, 2), Permutation(0, 4, 3, 2, 1)]
See Also
========
dihedral
"""
gen = range(n)
for i in xrange(n):
yield Permutation(gen)
gen = rotate_left(gen, 1)
def alternating(n):
"""
Generates the alternating group of order n, An.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> Permutation.print_cyclic = True
>>> from sympy.combinatorics.generators import alternating
>>> list(alternating(3))
[Permutation(2), Permutation(0, 1, 2), Permutation(0, 2, 1)]
"""
for perm in variations(range(n), n):
p = Permutation(perm)
if p.is_even:
yield p
def dihedral(n):
"""
Generates the dihedral group of order 2n, Dn.
The result is given as a subgroup of Sn, except for the special cases n=1
(the group S2) and n=2 (the Klein 4-group) where that's not possible
and embeddings in S2 and S4 respectively are given.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> Permutation.print_cyclic = True
>>> from sympy.combinatorics.generators import dihedral
>>> list(dihedral(3))
[Permutation(2), Permutation(0, 2), Permutation(0, 1, 2), Permutation(1, 2),
Permutation(0, 2, 1), Permutation(2)(0, 1)]
See Also
========
cyclic
"""
if n == 1:
yield Permutation([0, 1])
yield Permutation([1, 0])
elif n == 2:
yield Permutation([0, 1, 2, 3])
yield Permutation([1, 0, 3, 2])
yield Permutation([2, 3, 0, 1])
yield Permutation([3, 2, 1, 0])
else:
gen = range(n)
for i in xrange(n):
yield Permutation(gen)
yield Permutation(gen[::-1])
gen = rotate_left(gen, 1)
def rubik_cube_generators():
"""Return the permutations of the 3x3 Rubik's cube, see
http://www.gap-system.org/Doc/Examples/rubik.html
"""
a = [[(1,3,8,6),(2,5,7,4),(9,33,25,17),(10,34,26,18),(11,35,27,19)],
[(9,11,16,14),(10,13,15,12),(1,17,41,40),(4,20,44,37),(6,22,46,35)],
[(17,19,24,22),(18,21,23,20),(6,25,43,16),(7,28,42,13),(8,30,41,11)],
[(25,27,32,30),(26,29,31,28),(3,38,43,19),(5,36,45,21),(8,33,48,24)],
[(33,35,40,38),(34,37,39,36),(3,9,46,32),(2,12,47,29),(1,14,48,27)],
[(41,43,48,46),(42,45,47,44),(14,22,30,38),(15,23,31,39),(16,24,32,40)]]
return [Permutation([[i - 1 for i in xi] for xi in x], size=48) for x in a]
def rubik(n):
"""Return permutations for an nxn Rubik's cube.
Permutations returned are for rotation of each of the slice
from the face up to the last face for each of the 3 sides (in this order):
front, right and bottom. Hence, the first n - 1 permutations are for the
slices from the front.
"""
if n < 2:
raise ValueError('dimension of cube must be > 1')
# 1-based reference to rows and columns in Matrix
def getr(f, i):
return faces[f].col(n - i)
def getl(f, i):
return faces[f].col(i - 1)
def getu(f, i):
return faces[f].row(i - 1)
def getd(f, i):
return faces[f].row(n - i)
def setr(f, i, s):
faces[f][:,n - i] = Matrix(n, 1, s)
def setl(f, i, s):
faces[f][:,i - 1] = Matrix(n, 1, s)
def setu(f, i, s):
faces[f][i - 1,:] = Matrix(1, n, s)
def setd(f, i, s):
faces[f][n - i,:] = Matrix(1, n, s)
# motion of a single face
def cw(F, r=1):
for _ in range(r):
face = faces[F]
rv = []
for c in range(n):
for r in range(n - 1, -1, -1):
rv.append(face[r, c])
faces[F] = Matrix(n, n, rv)
def ccw(F):
cw(F, 3)
# motion of plane i from the F side;
# fcw(0) moves the F face, fcw(1) moves the plane
# just behind the front face, etc...
def fcw(i, r=1):
for _ in range(r):
if i == 0:
cw(F)
i += 1
temp = getr(L, i)
setr(L, i, list((getu(D, i))))
setu(D, i, list(reversed(getl(R, i))))
setl(R, i, list((getd(U, i))))
setd(U, i, list(reversed(temp)))
i -= 1
def fccw(i):
fcw(i, 3)
# motion of the entire cube from the F side
def FCW(r=1):
for _ in range(r):
cw(F)
ccw(B)
cw(U)
t = faces[U]
cw(L)
faces[U] = faces[L]
cw(D)
faces[L] = faces[D]
cw(R)
faces[D] = faces[R]
faces[R] = t
def FCCW():
FCW(3)
# motion of the entire cube from the U side
def UCW(r=1):
for _ in range(r):
cw(U)
ccw(D)
t = faces[F]
faces[F] = faces[R]
faces[R] = faces[B]
faces[B] = faces[L]
faces[L] = t
def UCCW():
UCW(3)
# defining the permutations for the cube
U, F, R, B, L, D = names = symbols('U, F, R, B, L, D')
# the faces are represented by nxn matrices
faces = {}
count = 0
for fi in range(6):
f = []
for a in range(n**2):
f.append(count)
count += 1
faces[names[fi]] = Matrix(n, n, f)
# this will either return the value of the current permutation
# (show != 1) or else append the permutation to the group, g
def perm(show=0):
# add perm to the list of perms
p = []
for f in names:
p.extend(faces[f])
if show:
return p
g.append(Permutation(p))
g = [] # container for the group's permutations
I = range(6*n**2) # the identity permutation used for checking
# define permutations corresonding to cw rotations of the planes
# up TO the last plane from that direction; by not including the
# last plane, the orientation of the cube is maintained.
# F slices
for i in range(n-1):
fcw(i)
perm()
fccw(i) # restore
assert perm(1) == I
# R slices
# bring R to front
UCW()
for i in range(n-1):
fcw(i)
# put it back in place
UCCW()
# record
perm()
# restore
# bring face to fron
UCW()
fccw(i)
# restore
UCCW()
assert perm(1) == I
# D slices
# bring up bottom
FCW()
UCCW()
FCCW()
for i in range(n-1):
# turn strip
fcw(i)
# put bottom back on the bottom
FCW()
UCW()
FCCW()
# record
perm()
# restore
# bring up bottom
FCW()
UCCW()
FCCW()
# turn strip
fccw(i)
# put bottom back on the bottom
FCW()
UCW()
FCCW()
assert perm(1) == I
return g
|
import sys
import os
import webbrowser
def webview(outfile):
"""pop up a web browser for the given file"""
if sys.platform == 'darwin':
os.system('open %s' % outfile)
else:
webbrowser.get().open(outfile)
def webview_argv():
"""This is tied to a console script called webview. It just provides
a convenient way to pop up a browser to view a specified html file(s).
"""
for name in sys.argv[1:]:
if os.path.isfile(name):
webview(name)
|
quantidade_de_valores = True
conta_par = 0
cont = 0
print("Digite um numero diferente de -1: ")
while quantidade_de_valores:
num = int(input("Digite um numero: "))
if(num < 0):
break
cont = cont + 1
if num % 2 == 0:
conta_par = conta_par + 1
print(conta_par, "numeros pares")
|
# ---- Global variables -------------------------------------------------------
N = int(input("\nEnter square size N: ")) # N - lenght of side
LIST = []
NUMBER_LENGTH = len(str(N*N)) # Check how many digits the largest number has
# ---- Class for colours ------------------------------------------------------
class bcolors:
GREEN = '\033[92m'
YELLOW = '\033[93m'
# ---- Functtions ----- -------------------------------------------------------
def count_rooms():
# Find edge rooms in a given square of size N. Code complexity: 4x4 = 16.
for i in range(1, N) :
run_script(i+1) # top side
run_script(N+N*i) # right side
run_script(1 + (i-1)*N) # left side
run_script(N*(N-1)+i) # bottom side
def run_script(number):
# Output to screen and append to a list
#print(number)
LIST.append(number)
def print_image():
# visualize the results
print("Initial list:")
print(LIST)
LIST.sort()
print("Sorted list:")
print(LIST)
print()
string = ""
for i in range(N):
# top side
number_block = blokify_number(LIST[i])
string += bcolors.GREEN + number_block
string += "\n"
for i in range(N-2):
# right & left sides
number_block = blokify_number(LIST[N+(i*2)]) # right side
string += number_block
string += " " + bcolors.YELLOW # offset by 1 space
for n in range((N-2)*(NUMBER_LENGTH+1)-1): # block_size = NUMBER_LENGTH + 1; and offset by -1
string += "#" # square filling
number_block = blokify_number(LIST[N+(i*2)+1]) # left side
string += bcolors.GREEN + number_block
string += "\n"
for i in range(N):
number_block = blokify_number(LIST[len(LIST)-N+i]) # bottom side
string += number_block
print(string)
def blokify_number(number):
# Create blocks of numbers by appending required amount of empty space in front
number = str(number)
block = " "
for n in range(NUMBER_LENGTH - len(number)):
block += " "
number = block + number
return(number)
# ---- Main -------------------------------------------------------------------
if __name__ == '__main__':
print("Maximum number length is: %d\nBlock size is: %d\n" % (NUMBER_LENGTH, NUMBER_LENGTH+1))
count_rooms()
print_image()
|
# задание№1
# Поработайте с переменными, создайте несколько, выведите на
# экран. Запросите у пользователя некоторые числа и строки и
# сохраните в переменные, затем выведите на экран.
name = input('Введите Ваше имя: ')
surname = input('Введите Вашу фамилию: ')
age = int(input('Введите Ваш возраст: '))
year_birth = 2021 - age
print(f'Добрый день {name} {surname}, Вы родились в {year_birth} году и Вам {age} лет')
|
# Declaring aa class
class Time:
second = 0
hour = 0
minute = 0
# Providing Inputs to variables of class
time = Time()
time.hour = 1 # 1 hour = 3600 seconds
time.minute = 10 # 10 minutes = 600 seconds
time.second = 20
# Function to convert Time in H:M:S format in to Seconds
def time_to_int(time):
minutes = time.hour * 60 + time.minute
seconds = minutes * 60 + time.second
print("Time converted in to seconds:", seconds)
int_to_time(seconds)
return(seconds)
# Function to convert Seconds in H:M:S Time format
def int_to_time(seconds):
time = Time()
minutes, time.second = divmod(seconds, 60)
time.hour, time.minute = divmod(minutes, 60)
print(time.hour, time.minute, time.second)
return(time)
time_to_int(time)
|
import sys
def cumulative_sum(num):
empty_list = []
length = len(num)
temp = 0
print("length of the list:", length)
for i in range(0, length):
temp = temp + num[i]
empty_list.append(temp)
# print(i)
return(empty_list)
# Program2
num = [10, 2, 3]
new_list = cumulative_sum(num)
print('List with Cumulative Sum', new_list)
# cumulative_sum_user_input()
|
import requests
import sys
import os
import re
def get_vendor_info():
"""Making request to Linux usb information database to retrieve devices information
: Input: None
: Output: List of devices and their ids"""
# Making request to linux usb database
try:
print("[+] Retrieving information from database...")
req = requests.get("http://www.linux-usb.org/usb.ids")
except:
print("[-] Could not establish connection! Please try again later!")
sys.exit(1)
# Store plaintext data in a string
usb_data = req.text
device_info = []
for line in usb_data.splitlines():
# Filter results
# Break if reach other contents list
if line == "# List of known device classes, subclasses and protocols":
break
# Ignore comment lines
elif line.startswith("#") or line == "":
continue
device_info.append(line)
return device_info
def parse_database_info():
"""Parsing device information on the website to a dictionary
: Input: None (data is parse from the get_vendor_info() function)
: Output: A dictionary with vendor ID as the keys and its product as the value"""
device_info = get_vendor_info()
vendor_dict = {}
for info in device_info:
# Extract id and name information from the device information data
id_info = info.split(" ")[0]
name_info = info.split(" ")[1]
# If the information is not tabed -> vendor information
if not info.startswith("\t"):
vendor_dict[id_info] = {}
vendor_dict[id_info]["name"] = name_info
vendor_dict[id_info]["products"] = {}
# Store current vendor id to a parameter
current_vendor = id_info
# Process product information
else:
# Use the current vendor key to identify which product belong to which vendor
vendor_dict[current_vendor]["products"][id_info.replace(
"\t", "")] = name_info
return vendor_dict
def usb_lookup(vendor_id, product_id, vendor_dict):
"""Lookup USB information using its vendor ID and product ID
: Input: vendor id, product id and vendor dictionary to lookup
: Output: vendor name and product name"""
# Lookup the vendor using vendor_id
try:
vendor = vendor_dict[vendor_id]["name"]
except:
vendor = "Vendor name not found!"
# Look up the product using product_id
try:
product = vendor_dict[vendor_id]["products"][product_id]
except:
product = "Product name not found!"
return vendor, product
def process_device_info(device_dict):
"""Using regular expression to segregate parameter from the device string
: Input: Devices dictionary with device string as the key
: Output: A list of devices information"""
devices = []
# for device in device_dict.keys():
for device, date in device_dict.items():
# Pre-declare parameters
vid = ""
pid = ""
rev = ""
uid = ""
# Compile regex to capture desired information
# (?:) Use to ignore group capture
# Capture vendor info
vendor_capture = re.compile(r"(?:(?:ven)|(?:vid))_(.*?)&")
vendor_id = vendor_capture.search(device)
if vendor_id:
vid = vendor_id.group(1)
# Capture product info
product_capture = re.compile(
r"(?:(?:pid)|(?:dev)|(?:prod))_(.*?)(&|\\)")
product_id = product_capture.search(device)
if product_id:
pid = product_id.group(1)
# Capture revision info
revision_capture = re.compile(r"(?:(?:mi)|(?:rev))_(.*?)(\\|,)")
revision_id = revision_capture.search(device)
if revision_id:
rev = revision_id.group(1)
# Capture uid info
uid = device.split("\\")[2]
if vid != "" or pid != "":
devices.append({"Vendor ID": vid, "Product ID": pid,
"Revision": rev, "UID": uid, "First Installation Date": date})
return devices
def parse_device_from_log(log_file):
"""Parsing the api log file for important data
: Input: Path to the api log file
: Output: A dictionary contain the device information string and its install date"""
# Start declare a dictionary for storing result
device_dict = {}
with open(log_file, "r") as api_log:
for line in api_log:
# Search for string that indicate installation of new devices
if "device install (hardware initiated)" in line.lower() and ("ven" in line.lower() or "vid" in line.lower()):
# Extract information from the line with indicator and the next line which contains the install date
device_info = line.split(
"-")[1].lower().replace("]", "").strip()
date_install = next(api_log).split(
"start")[1].strip().lower()
# Only add the records that start with "usb" for usb information
if device_info.startswith("usb"):
device_dict[device_info] = date_install
return device_dict
def parse_device_winxp(log_file):
"""Parsing the api log file from Windows XP for important data
: Input: Path to the api log file (Windows XP)
: Output: A dictionary contain the device information string and its install date"""
# Initialize device dictionary
device_dict = {}
with open(log_file, "r") as api_log:
for line in api_log:
# Search for string that indicate installation of new devices
if "driver install]" in line.lower():
# Extract the install date and the string after that which indicate the hardware that is installed
date_install = " ".join(line.split(" ")[
:3]).replace("[", "").strip()
device_info = next(api_log).split(" ")[-1].strip()
# Only extract the devices that start with "usb"
if device_info.startswith("usb"):
device_dict[device_info] = date_install
return device_dict
def main():
"""The main function
: This function is going to parse the information from log file then look up on the USB database to display informative output"""
# As user for the log file location
log_file = input("Enter the path to your log file: ")
# Check to see if file exist
if not os.path.isfile(log_file):
print("[-] Error! File does not exist!")
sys.exit(1)
# Prompting users for log type
win_version = input("Is the log file from Windows XP? (y/n) ")
while win_version.lower() != ("y" or "n"):
print("[-] Invalid option! Only (y/n) is allow")
win_version = input("Is the log file from Windows XP? (y/n) ")
# Use WinXP parser if the log is from Windows XP system
if win_version.lower() == "y":
devices_dict = parse_device_winxp(log_file)
# Else (From Windows 7 or higher) -> Parse it normally
else:
# Parsing device infromation from log file
devices_dict = parse_device_from_log(log_file)
# Escape if no entry for USB is found
if not devices_dict:
print("[-] Could not find any entry for USB! Exiting...")
sys.exit(1)
# Parsing information from the web page and process the information
vendor_dict = parse_database_info()
devices = process_device_info(devices_dict)
for device in devices:
# Print banner to separate results
print("{:=^50}".format(""))
# Lookup the Vendor ID and Product ID to get their names
vendor, product = usb_lookup(
device["Vendor ID"], device["Product ID"], vendor_dict)
print("Vendor Name: {}".format(vendor))
print("Product Name: {}".format(product))
# Print out the data received from device string
for info, data in device.items():
print("{}: {}".format(info, data))
print("{:=^50}".format(""))
if __name__ == "__main__":
main()
|
def solution(n):
answer = 0
if n == 2:
answer = 1
else :
answer = 1
for i in range(3, n + 1) :
is_prime_num = True
for j in range(2, i) :
if i%j == 0 :
is_prime_num = False
break
if is_prime_num == True :
answer = answer + 1
return answer
|
A = int(input())
for i in range(A):
print(" "*i, end = "")
print("*"*(2*A - 1 - 2*i))
for i in range(A - 1, 0, -1):
print(" "* (i-1), end = "")
print("*"*(2*A - 1 - 2*(i - 1)))
|
def palindrome(s):
l = len(s)
dp = [[0 for i in range(l)] for j in range(l)]
for i in range(len(s)-1,-1,-1):
for j in range(i,len(s)):
if i==j: dp[i][j] = 1
elif j-1==i and s[i]==s[j]: dp[i][j] = 1
elif dp[i+1][j-1]==1 and s[i]==s[j]: dp[i][j] = 1
index = 0
for i in range(len(s)):
if dp[i][len(s)-1]==1:
index = i
break
answer = len(s) + index
return (answer)
def get_data():
data_list = []
N = int(input())
for _ in range(N):
d = input()
data_list.append(d)
return (data_list)
def main():
data = get_data()
ans_list = []
for d in data:
palin_len = palindrome(d)
ans_list.append(palin_len)
print (ans_list)
if __name__ == "__main__":
main()
|
# 최대 구간 합 문제 (maximum subarray problem)
def read_data():
array = [int(v) for v in input().split()]
return array
def max_sum(array):
l = len(array)
m = int(l/2)
if l == 1:
return sum(array)
array_l = array[:m]
array_r = array[m:]
answer = 1e-100
# 이곳에 문제 3에 대한 코드를 작성하세요.
m_l = max_sum(array_l)
m_r = max_sum(array_r)
m_m = in_between(array)
answer = max(m_l, m_r, m_m)
return answer
def in_between(array):
l = len(array)
m = int(l/2)
array_l = array[:m][::-1]
array_r = array[m:]
m_l = stretch_array(array_l)
m_r = stretch_array(array_r)
return m_l + m_r
def stretch_array(array):
cumsum = -1e100
# 이곳에 문제 2에 대한 코드를 작성하세요.
cumsum = -1e100
for i in range(1, len(array) + 1):
s = sum(array[:i])
if s > cumsum:
cumsum = s
return cumsum
def main():
array = read_data()
print(in_between(array))
if __name__ == '__main__':
main() |
def numDivisor(n):
'''
n의 약수의 개수를 반환하는 함수를 작성하세요.
'''
sum_divisor = 0
for i in range(1, n+1):
if 0 == n % i:
sum_divisor += 1
return sum_divisor
def main():
'''
Do not change this code
'''
number = int(input())
print(numDivisor(number))
if __name__ == "__main__":
main()
|
import math
def get_data():
N = int(input())
data_list = []
for _ in range(N):
num = int(input())
data_list.append(num)
return data_list
def sorting_number(numbers):
s = 0
# 여기에 문제 1에 대한 코드를 작성하세요.
while len(numbers) != 1:
sorted_numbers = sorted(numbers)
current_s = sum(sorted_numbers[:2])
s += current_s
sorted_numbers = sorted_numbers[2:]
sorted_numbers.append(current_s)
numbers = sorted_numbers
return s
def main():
numbers = get_data()
print (sorting_number_heap(numbers))
if __name__ == '__main__':
main()
|
def push(heap, x) :
heap.append(x)
index = len(heap)-1
while index != 1 :
if heap[index//2] > heap[index] :
tmp = heap[index//2]
heap[index//2] = heap[index]
heap[index] = tmp
index = index // 2
else :
return
def pop(heap) :
return_value = heap[1]
heap[1] = heap[-1]
heap.pop()
index = 1
while index < len(heap) :
minIdx = -1
if index*2 >= len(heap) :
break
elif index*2+1 >= len(heap) :
minIdx = index*2
else :
if heap[index*2] > heap[index*2+1] :
minIdx = index*2+1
else :
minIdx = index*2
if heap[index] <= heap[minIdx] :
break
else :
tmp = heap[index]
heap[index] = heap[minIdx]
heap[minIdx] = tmp
index = minIdx
return return_value
def heapSort(items) :
heap = [0]
result = []
for i in items :
push(heap, i)
for i in range(len(items)) :
result.append(pop(heap))
return result
def main():
'''
Do not change this code
'''
line = [int(x) for x in input().split()]
print(heapSort(line))
if __name__ == "__main__":
main()
|
def get_parent_child_rel():
p_c_rel = dict()
all_childs = set()
no_rels = int(input())
for _ in range(no_rels):
tmp = [int(v) for v in input().split()]
p_c_rel[tmp[0]] = {'left' : tmp[1], 'right' : tmp[2]}
for child in tmp[1:]:
if child != -1:
all_childs.add(child)
root_node = list(set(range(1, no_rels + 1)) - all_childs )[0]
return p_c_rel, root_node
def inorder_traverse(rel, target_node, order_list, node_level):
if target_node == -1: return
current_rel = rel[target_node]
current_level = node_level[target_node]
if current_rel['left'] != -1: node_level[current_rel['left']] = current_level + 1
if current_rel['right'] != -1: node_level[current_rel['right']] = current_level + 1
# 이곳에 문제 1에 대한 코드를 작성하세요.
inorder_traverse(rel, current_rel['left'], order_list, node_level)
order_list.append(target_node)
inorder_traverse(rel, current_rel['right'], order_list, node_level)
return [order_list, node_level]
def main():
rel, root_node = get_parent_child_rel()
order_list, node_level = inorder_traverse(rel, root_node, [], {root_node : 1})
level_node = dict()
for k, v in node_level.items():
if v in level_node:
level_node[v].append(k)
else:
level_node[v] = [k]
print (get_max_width(order_list, level_node))
if __name__ == '__main__':
main() |
import math
def get_data():
N = int(input())
data_list = []
for _ in range(N):
num = int(input())
data_list.append(num)
return data_list
def construct_heap(numbers):
heap = []
while len(numbers) != 0:
number_ = numbers.pop()
heap.append(number_)
heap = move_up(heap)
return heap
def move_up(heap):
child_idx = len(heap) - 1
# 이곳에 문제 2에서 작성했던 코드를 붙여넣기 하세요.
while True:
parent_idx = int(math.floor((child_idx - 1) / 2))
if heap[parent_idx] > heap[child_idx]:
heap[parent_idx], heap[child_idx] = heap[child_idx], heap[parent_idx]
child_idx = parent_idx
if child_idx == 0:
break
else:
break
return heap
def move_down(heap):
parent_idx = 0
# 이곳에 문제 3의 코드를 작성하세요.
while True:
child_idx1 = 2 * parent_idx + 1; child_idx2 = 2 * parent_idx + 2
if child_idx1 > len(heap) - 1:
break
elif child_idx1 == len(heap) - 1:
if heap[parent_idx] > heap[child_idx1]:
heap[parent_idx], heap[child_idx1] = heap[child_idx1], heap[parent_idx]
break
else:
child_val1 = heap[child_idx1]
child_val2 = heap[child_idx2]
if heap[parent_idx] > min([child_val1, child_val2]):
if child_val1 < child_val2:
heap[parent_idx], heap[child_idx1] = heap[child_idx1], heap[parent_idx]
parent_idx = child_idx1
else:
heap[parent_idx], heap[child_idx2] = heap[child_idx2], heap[parent_idx]
parent_idx = child_idx2
else:
break
return heap
def sorting_number_heap(numbers):
heap = construct_heap(numbers)
s = 0
while (len(heap) > 2):
s1 = heap.pop(0)
popped = heap.pop()
heap.insert(0, popped)
heap = move_down(heap)
s2 = heap.pop(0)
popped = heap.pop()
heap.insert(0, popped)
heap = move_down(heap)
ss = s1 + s2
heap.append(ss)
heap = move_up(heap)
s += ss
s += sum(heap)
return s
def main():
numbers = get_data()
print (sorting_number_heap(numbers))
if __name__ == '__main__':
main()
|
input_file=raw_input("input file name?")
def print_all(f):
print f.read()
def rewind(f):
f.seek(0)
def print_a_line(line_count,f):
print line_count,f.readline(),
input_file=open(input_file,'r')
print"let us first print the whole file\n"
print_all(input_file)
print "let's now rewind kind of a tape"
rewind(input_file)
print "let's print three lines"
current_line=1
print_a_line(current_line,input_file)
current_line=current_line+1
print_a_line(current_line,input_file)
current_line=current_line+1
print_a_line(current_line,input_file)
|
people = 20
cats = 40
dogs = 5
if people < cats:
print "too many cats world is doomed"
if people > cats:
print "not many cats world is saved"
if people < dogs:
print"the world is drooled on"
if people > dogs:
print"the world is dry"
dogs += 5
if people >= dogs:
print"people are greater than or equal to dogs"
if people <= dogs:
print"people are less than equal to dogs"
if people == dogs:
print "people are dogs"
|
import math;
class BasicObject:
animationIdCount = 0
def __init__(self, points, color):
self.points = points
self.color = color
self.old_animation_positions = {} # this is used during the animation rendering procces inorder to keep track of the last position and lerp from there for example in lerp
self.lastAnimationTime = 0;
self.recalculate_position_from_points()# if after a wierd roation there is a shape we can average out the x and y from the points
self.running_positions = {"color": color} ## this is strore certain things inorder to allow the user to do thing like translate before the rendering procces
""" This helper function adds a function to be run with parameters given in an array in a certain index."""
def insert_animation_into_frame(self, function, parameters, i):
while len(self.scene.frames) <= i:
self.scene.frames.append([])
self.scene.frames[i].append([function, parameters]);
""" Returns an objects current position, can be used for rotating around other object. """
def get_position(self):
return Point(self.running_positions["x"], self.running_positions["y"]);
"""
Give a starting time and duration retuns the frame number of the first and last frame in a tuple (first_frame_number, last_fram\e_number)
"""
def get_anim_frames(self, time, starting_time):
startingFrame = starting_time * self.scene.FRAME_RATE
totalFrames = startingFrame + time * self.scene.FRAME_RATE;
return (int(round(startingFrame)), int(round(totalFrames)))
""" Can be used to check how far along certain animation we are, used for fade in and outs """
def get_prog(self,index, startingFrame, lastFrame):
if(index >= startingFrame):
pass
#return 1
return float((index-int(startingFrame))/(int(lastFrame)-int(startingFrame)))
""" Called by the animation frame runner """
def anim_set_color(self, color):
starting_color = color;
self.color = color
def fadeOut(self, duration=0.5, starting_time="not_set", blocking=True):
if starting_time == "not_set":
starting_time = self.lastAnimationTime;
startingFrame, lastFrame = self.get_anim_frames(duration, starting_time);
starting_color = self.running_positions["color"]
for i in range(startingFrame, lastFrame+1):
alpha = 1-self.get_prog(i, startingFrame, lastFrame)
starting_color.a = alpha;
self.insert_animation_into_frame(self.anim_set_color, [Color(starting_color.r, starting_color.g, starting_color.b, starting_color.a)], i );
self.running_positions["color"] = starting_color;
if blocking:
self.lastAnimationTime = starting_time + duration;
return self
def fadeIn(self, duration=0.5, starting_time="not_set", blocking=True):
if starting_time == "not_set":
starting_time = self.lastAnimationTime;
startingFrame, lastFrame = self.get_anim_frames(duration, starting_time);
starting_color = self.running_positions["color"]
for i in range(startingFrame, lastFrame+1):
alpha = self.get_prog(i, startingFrame, lastFrame)
starting_color.a = alpha
self.insert_animation_into_frame(self.anim_set_color, [Color(starting_color.r, starting_color.g, starting_color.b, starting_color.a)], i );
self.running_positions["color"] = starting_color;
if blocking:
self.lastAnimationTime = starting_time + duration;
return self
def rotate(self, angle, duration=0.5, starting_time="not_set", blocking=True, around="not_set", pi_mode=False):
if not pi_mode:
angle = (angle /180)*math.pi;
self.recalculate_position_from_points()
#print(f"around: {around.x} {around.y}, self: {self.x} {self.y}");
if starting_time == "not_set":
starting_time = self.lastAnimationTime;
starting_frame, last_frame = self.get_anim_frames(duration, starting_time);
subAngle = angle/(last_frame-starting_frame+1);
for i in range(starting_frame, last_frame+1):
self.insert_animation_into_frame( self.rotate_object_by_angle, [subAngle, around], i);
self.insert_animation_into_frame( self.recalculate_position_from_points, [], last_frame);
if blocking:
self.lastAnimationTime = starting_time + duration;
return self;
def wait(self, duration=0.5):
self.lastAnimationTime = self.lastAnimationTime + duration;
return self
""" Averages out new x y coordinates from the points, used inorder to fix irregualar shapes and wonky rotations """
def recalculate_position_from_points(self):
newx = 0
newy = 0
counter = 0
for point in self.points:
newx += point.x
newy += point.y
counter+= 1
self.x = newx/counter
self.y = newy/counter
""" Helper functio used during rendering of animation """
def rotate_object_by_angle(self, angle, around="not_set"):
if around == "not_set":
around = Point(self.x, self.y);
for i, point in enumerate(self.points):
self.points[i] = BasicObject.rotate_point_by_angle(point, angle, around);
def rotate_point_by_angle(point, angle, around):
point = Point(point.x - around.x, point.y - around.y) # change the orgin so we rotate around ourselves instead of the real origin
newx = around.x + (point.x*math.cos(angle)- point.y*math.sin(angle));
newy = around.y + (point.y*math.cos(angle) + point.x*math.sin(angle));
#print(f"new x: {newx} y: {newy} angle: {angle} cos: {math.cos(angle)} px {point.x} py {point.y}");
return Point(newx, newy);
def lin_interpolate(x1, y1, x2, y2, x3):
return y1 + (x3 - x1) * ((y2-y1)/(x2-x1))
class Shape(BasicObject):
def translate(self, x=0, y=0, duration=0.5, starting_time="not_set"):
self.move_to(Point(self.running_positions["x"] + x, self.running_positions["y"] + y), duration=duration, starting_time=starting_time);
return self
def set_color(self, color, duration=0.5, starting_time="not_set", blocking=True):
if starting_time == "not_set":
starting_time = self.lastAnimationTime
startingFrame, lastFrame = self.get_anim_frames(duration, starting_time);
starting_color = self.running_positions["color"];
for i in range(startingFrame, lastFrame+1):
self.insert_animation_into_frame(self.lerp_to_color, [color, startingFrame, lastFrame, i, starting_color], i );
self.running_positions["color"] = color;
if blocking:
self.lastAnimationTime = starting_time + duration
return self
def move_to(self, point, duration=0.5, starting_time="not_set"):
self.running_positions["x"] = point.x;
self.running_positions["y"] = point.y;
if starting_time == "not_set":
starting_time = self.lastAnimationTime
startingFrame, lastFrame = self.get_anim_frames(duration, starting_time);
for i in range(startingFrame, lastFrame+1):
self.insert_animation_into_frame(self.lerp_to, [point, startingFrame, lastFrame,i, BasicObject.animationIdCount], i );
BasicObject.animationIdCount += 1;
self.lastAnimationTime = starting_time+duration;
return self
def lerp_to_color(self, color, first_frame, last_frame, current_frame_index, starting_color):
lerped_r = lin_interpolate(first_frame, starting_color.r, last_frame, color.r, current_frame_index) ## we dont want current position, we want intial posisiton
lerped_g = lin_interpolate(first_frame, starting_color.g, last_frame, color.g, current_frame_index) ## we dont want current position, we want intial posisiton
lerped_b = lin_interpolate(first_frame, starting_color.b, last_frame, color.b, current_frame_index) ## we dont want current position, we want intial posisiton
self.color = Color.RGB(lerped_r, lerped_g, lerped_b);
def lerp_to(self, final_point, first_frame, last_frame, current_frame_index, animation_id):
starting_x = 0;
starting_y = 0;
#print(f" last {last_frame} current : {current_frame_index}")
if animation_id in self.old_animation_positions:
starting_x, starting_y = self.old_animation_positions[animation_id];
else:
starting_x = self.x;
starting_y = self.y;
self.old_animation_positions[animation_id] = (self.x, self.y);
lerped_x = lin_interpolate(first_frame, starting_x, last_frame, final_point.x, current_frame_index) ## we dont want current position, we want intial posisiton
lerped_y = lin_interpolate(first_frame, starting_y, last_frame, final_point.y, current_frame_index)
self.change_coord(Point(lerped_x, lerped_y));
#print(f"final point = {final_point.x} {final_point.y} current pos = {self.x} {self.y}" )
#print(f"moving to {lerped_x} y {lerped_y}");
def change_coord(self, point):
self.setX(point.x);
self.setY(point.y);
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
class Color:
def RGB(r,g,b,a=255):
return Color(r/255, g/255,b/255, a/255);
def __init__(self, r, g, b, a=1):
self.r = r
self.g = g
self.b = b
self.a = a
class Rectangle(Shape):
def __init__(self, x, y, width, height, color=Color(0,0,0)):
self.x = x;
self.y = y;
self.width = width;
self.height = height;
super().__init__( self.calcPoints(), color);
self.running_positions["x"] = x;
self.running_positions["y"] = y;
def calcPoints(self):
width = self.width
height = self.height
return [Point(self.x-width/2,self.y-height/2), Point(self.x+width/2, self.y-height/2), Point(self.x+self.width/2, self.y+self.height/2), Point(self.x-width/2,self.y+self.height/2)]
def setY(self, y):
self.y = y;
self.points = self.calcPoints();
def setX(self, x):
self.x = x;
self.points = self.calcPoints();
|
#coding=gbk
'''
Created on 2014319
@author: bling
'''
#
dic = {'tom':11,'sam':56,'jun':20,'jun':19}
print dic,type(dic)
print dic['jun']
dic['jun']=30
print dic
dic={}
print dic
dic['yangml']=10
print dic
#ʵԪصѭ
dic = {'tom':11,'sam':56,'jun':20,'jun':19}
for key in dic:
print dic[key],type(dic[key])
#ʵij÷
print dic.keys()
print dic.values()
print dic.items()
dic.clear()
print dic
dic = {'tom':11,'sam':56,'jun':20,'jun':19}
del dic['tom']
print dic,len(dic) |
import math
import string
import random
# Writ a function which generates a six digit random_user_id.
# print(random())
# print(randint(3,9))
def random_user_id(stringLength = 6):
letters = string.ascii_lowercase
return ''.join(random.choice(letters) for i in range(stringLength))
print(random_user_id())
multiple_variable = lambda a, b, c: a ** 2 - 3 * b + 4 * c
print(multiple_variable(5, 5, 3)) |
it_companies = {'Facebook', 'Google', 'Microsoft', 'Apple', 'IBM', 'Oracle', 'Amazon'}
A = {19, 22, 24, 20, 25, 26}
B = {19, 22, 20, 25, 26, 24, 28, 27}
age = [22, 19, 24, 25, 26, 24, 25, 24]
# Find the length of the set, it_companies
print(len(it_companies))
# Add 'Twitter' to it companies
it_companies.add('Twitter')
print(it_companies)
# Insert multiple it companies at once to the set, it_companies
multiple_it_companies = {'ujiigroceries', 'ujiilearn'}
it_companies.update(multiple_it_companies)
print(it_companies)
# Remove one of the companies from the set, it_companies
it_companies.remove('Facebook')
print(it_companies)
# What is the difference between remove and discard
# The difference between remove and discard is that remove method raises an error the item you want to remove is not found in the set,
# while discard method does not raise any error even when the item is not found in the set.
# Join A and B
set_union = A.union(B)
print(set_union)
# Find A intersection B
inter_section = A.intersection(B)
print(inter_section)
# Is A subset of B
A.issubset(B)
# Are A and B disjoint sets
A.isdisjoint(B)
# Join A with B and B with A
join_C = A.update(B)
print(join_C)
join_D = B.union(A)
print(join_D)
# What is the symmetric difference between A and B
symmetric_diff = A.symmetric_difference(B)
# Delete the sets completely
del A
del B
# Convert the ages to set and compare the length of the list and the set, which is larger ?
ages = set(age)
print(ages)
# Explain the difference among the following data types: string, list, tuple and set
# I am a teacher and I love to inspire and teach people. How many unique words have been used in the sentence. |
# Concatenate the string 'Thirty', 'Days', 'Of', 'Python' to a single string, 'Thirty Days Of Python'
concatunate = ['Thirty', 'Days', 'Of', 'Python']
full_sentence = ' '.join(concatunate)
print(full_sentence)
# Concatenate the string 'Coding', 'For' , 'All' to a single string, 'Coding For All'
string = ['Coding', 'For', 'All']
string_sentence = ' '.join(string)
print(string)
# Declare a variable name company and assign it to an initial value "Coding For All.
company = 'Coding For All'
# Print company using print()
print(company)
# Print the length of the company string using len() method and print()
print(len(company))
# Change all the characters to capital letters using upper() method
print(company.upper())
# Change all the characters to lowercase letters using lower() method
print(company.lower())
# Use capitalize(), title(), swapcase() methods to format the value the string Coding For All.
print(company.capitalize())
print(company.swapcase())
print(company.title())
# Cut(slice) out the first word of Coding For All string
remove_coding = company[7:15]
print(remove_coding)
# Check if Coding For All string contains a word Coding using the method index, find or other methods.
print(company.index('Coding'))
print(company.find('Coding'))
# Replace the word coding in the string 'Coding For All' to Python.
print(company.replace('Coding', 'Python'))
# Change Python for Everyone to Python for All using the replace method or other methods
sentense = 'Python for Everyone'
print(company.replace('Everyone', 'All'))
# Split the string 'Coding For All' at the space using split() method
print(company.split())
# "Facebook, Google, Microsoft, Apple, IBM, Oracle, Amazon" split the string at the comma
# What is character at index 0 in the string Coding For All.
first_letter = company[0]
print(first_letter)
# What is the last index of the string Coding For All
lastLetter = company[-1]
print(lastLetter)
# What character is at index 10 in "Coding For All" string.
tenth_index = company[10]
print(tenth_index)
# Create an acronym or an abbreviation for the name 'Python For Everyone'
print(''.join(w[0] for w in sentense.split()))
# Create an acronym or an abbreviation for the name 'Coding For All'
print(''.join(x[0] for x in company.split()))
# Use index to determine the position of the first occurrence of C in Coding For All.
print(company.index('C'))
# Use index to determine the position of the first occurrence of F in Coding For All
print(company.index('F'))
# Use rfind to determine the position of the last occurrence of l in Coding For All People.
last_l = 'l'
print(company.find(last_l, 13))
# Use index or find to find the position of the first occurrence of the word because in the following sentence:'You cannot end a sentence with because because because is a conjunction'
text = 'You cannot end a sentence with because because because is a conjunction'
first_because = 'because'
print(text.find(first_because))
# Use rindex to find the position of the last occurrence of the word because in the following sentence:'You cannot end a sentence with because because because is a conjunction'
last_because = 'because'
print(text.find(last_because, 56))
# Slice outr the phrase because because because in the following sentence:'You cannot end a sentence with because because because is a conjunction'
print(text[31:54])
# Find the position of the first occurrence of the word because in the following sentence:'You cannot end a sentence with because because because is a conjunction'
ferst_because = 'because'
print(text.find(ferst_because))
# Slice out the phase because because because in the following sentence:'You cannot end a sentence with because because because is a conjunction'
because = text[31:54]
print(because)
# Does Coding For All starts with a substring Coding?
print(company.startswith('Coding'))
# Does Coding For All ends with a substring coding?
print(company.endswith('Coding'))
# ' Coding For All ' , remove the left and right trailing spaces in the given string.
trailing = ' Coding For All '
print(trailing.strip())
# Which one of the following variable return True when we use the method isidentifier()30DaysOfPython, thirty_days_of_python
correct_id = 'thirty_days_of_python'
incorrect_id = '30daysofpython'
print(correct_id.isidentifier())
print(incorrect_id.isidentifier())
# The following are some of python libraries list: ['Django', 'Flask', 'Bottle', 'Pyramid', 'Falcon']. Join the list with a hash with space string.
python_libraries = ['Django', 'Flask', 'Bottle', 'Pyramid', 'Falcon']
print('#, '.join(python_libraries))
# Use new line escape sequence to writ the following sentence.
# I am enjoying this challenge.
# I just wonder what is next.
print('I am enjoying this challenge.\nI just wonder what is next.')
# Use a tab escape sequence to writ the following sentence.
# Name Age Country
# Asabeneh 250 Finland
print('Name\tAge\tCountry\nFelix\t45\tNigeria')
# Use string formatting method to display the following:
# radius = 10
# area = 3.14 * radius ** 2
# The area of radius 10 is 314 meters squares.
radius = 10
area = 3.14 * radius ** 2
result = 'he area of the radius {} is {:.3f}.'.format(radius, area)
# Make the following using string formatting methods:
num1 = 8
num2 = 6
print(f'{num1} + {num2} = {num1 + num2}')
print(f'{num1} - {num2} = {num1 - num2}')
print(f'{num1} * {num2} = {num1 * num2}')
print(f'{num1} / {num2} = {num1 / num2}')
print(f'{num1} % {num2} = {num1 % num2}')
print(f'{num1} // {num2} = {num1 // num2}')
print(f'{num1} ** {num2} = {num1 ** num2}')
|
# -*- coding:utf-8 -*-
data={"name":"walker","age":33}
try:
data["weight"]
except (KeyError,IndexError) as e: #这样一次只能捕获一个错误;如果对两种错误的处理方式一样,可以用这种方式进行处理
print("字典不存在",e)
print("----------")
list1=["sadfasd","sadfsadf",333]
# list1[5]
try:
list1[5]
except IndexError as e:
print(e)
print("------------")
m=6666
try:
data["weight"]
print("字典不存在",e)
print(m[9])
except IndexError as e:
print(e)
except Exception as e: #抓住所有的错误;不建议一开始就是用使用
print("未知错误")
else:
print("一切正常")
finally:
print("finally 是有错没错都执行")
print("-------\n自定义异常")
class mysqlerror(Exception):
def __init__(self,msg):
self.msg="23333333"
def __str__(self):
return "asdf"
try:
raise mysqlerror("数据库连不上出错了吧哈哈") #raise触发自己编写的异常;自定义异常时不要覆盖已有的异常
except mysqlerror as e:
print(e)
|
#! -*- coding:utf-8 -*-
# https://www.cnblogs.com/zpzcy/p/7668765.html
"""
需求:
启动程序后,让用户输入工资,然后打印商品列表
允许用户根据商品编号购买商品
用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
可随时退出,退出时,打印已购买商品和余额
"""
product_list = [
('Iphone', 5800),
('Mac Pro', 9800),
('Bike', 800),
('Watch', 10600),
('Coffee', 31),
('Alex Python', 120),
]
# product_list.a
salary = input("what is your salary")
shopping = []
# shopping_number = input("the number of whtat you want buy")
# print(type(product_list[int(shopping_number)]))
# print(product_list[int(shopping_number)][0])
# shopping_market = shopping.append(product_list[int(shopping_number)][0])
if salary.isdigit():
salary = int(salary) # 控制台输入的都是字符串
while True:
for index, item in enumerate(product_list):
print(index, item)
use_choice = input("选择要买商品的number")
if user_choice.isdigit():
user_choice = int(user_choice)
if user_choice < len(product_list) and use_choice > 0:
p_item=product_list[user_choice]
|
#! -*- coding:utf-8 -*-
"""
len() ,len(list)方法返回列表元素个数,list -- 要计算元素个数的列表,返回值,返回列表元素个数
元组与列表是非常类似的,区别在于元组的元素值不能修改,元组是放在括号中,列表是放于方括号中。
list( seq ) 方法用于将元组或字符串转换为列表,返回值,返回列表
#可以直接del list[2] 删除列表中的元素
#列表对 + 和 * 的操作符与字符串相似。+ 号用于组合列表,* 号用于重复列表
列表可以嵌套列表
序列中的每个元素都分配一个数字 - 它的位置,或索引,第一个索引是0,第二个索引是1,依此类推
"""
list = ["name", "age", "height", "age", "1"]
list.append("333") # 向列表最后添加,该方法无返回值,但是会修改原来的列表
a = list.index("age") # 该方法返回查找对象的索引位置,如果没有找到对象则抛出异常
b = list.count("age") # 返回列表中字符出现的次数,返回值:返回元素在列表中出现的次数
list.remove("age") # 删除指定字符,若有重合删除索引小的,该方法没有返回值但是会移除两种中的某个值的第一个匹配项
print(list)
list.insert(2, "second") # 在列表指定位置插入数据,该方法没有返回值,但会在列表指定位置插入对象
c = list.sort() # 将列表排序,若列表中包含int类型则报错,需要改为string类型
list.reverse() # 该方法没有返回值,但是会对列表的元素进行反向排序。
print(list)
list.pop() # 默认删除列表最后一个,若是指定索引,则删除所在索引位置的字符串
list.clear() # 清空列表,该方法没有返回值。
d = ["1", 2, 3, 3]
f = [6, 7, 8, 9]
d.extend(f) # 函数用于在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表),该方法没有返回值,但会在已存在的列表中添加新的列表内容
print(d)
list.copy()
g = f.copy() # copy() 则顾名思义,复制一个副本,原值和新复制的变量互不影响,
# 使用=直接赋值,是引用赋值,更改一个,另一个同样会变
f.append("3333")
print(g)
print(f)
|
import io
n = int(input())
# all subsets of {1,2,3, ... , n}
def printSubstring(arr):
f = io.StringIO()
f.write('{')
# Flag to check if an extra comma is present at the end
extraComma = False
for elem in a:
f.write('{},'.format(elem))
extraComma = True
if extraComma:
# Pop comma after last element
lastPos = f.tell()
f.truncate(lastPos - 1)
f.write('}')
print(f.getvalue())
return
a = []
def backtrack(a,k):
# check if the current configuration is a solution and process it.
if k == n:
printSubstring(a)
else:
# Extend the current partial solution to find a valid solution
k += 1
# Enumerates all subsets where k is present
a.append(k)
backtrack(a,k)
# Enumerates all subsets where k is not present
a.pop()
backtrack(a,k)
backtrack(a,0)
|
animals = ['cat', 'dog', 'monkey', 'lion', 'zebra', 'giraffe']
#animals = ['cat', 'monkey', 'dog']
COUNT = 2
# all combinations of animals of size 2.
n = len(animals)
a = [[],[]]
def backtrack(a,k):
# check if the current configuration is a solution and process it.
if k == n:
print(a)
else:
# Extend the current partial solution to find a valid solution
curr = animals[k]
k += 1
a[0].append(curr)
# all combinations with curr in the first set.
backtrack(a,k)
a[0].pop()
a[1].append(curr)
# all combinations with curr in the second set.
backtrack(a,k)
a[1].pop()
return
backtrack(a,0)
|
import random
import matplotlib.pyplot as plt
import collections
seed = random.randint(1, 10000000)
random.seed(seed)
size_list = [18] * 60
size_list_hubs = [50] * 60
min_distance = 110
connection_distance = min_distance + 80
class Hub:
def __init__(self, name, x, y):
self.name = name
self.x = x
self.y = y
def distance_from_me(self, new_x, new_y):
# manhattan distance from me to a new point
return int(abs(self.x - new_x) + abs(self.y - new_y))
def validate_new_point(self, new_x, new_y):
manhattan_dist = self.distance_from_me(new_x, new_y)
return manhattan_dist >= min_distance
class Station:
def __init__(self, name, x, y):
self.name = name
self.x = x
self.y = y
self.size = 1
def distance_from_me(self, new_x, new_y):
# manhattan distance from me to a new point
return int(abs(self.x - new_x) + abs(self.y - new_y))
def validate_new_point(self, new_x, new_y):
manhattan_dist = self.distance_from_me(new_x, new_y)
return manhattan_dist >= min_distance
def __str__(self):
return "Name: {} Coordinate: ({:4}, {:4}) \t size {}".format(str(self.name), str(self.x), str(self.y),
self.size)
class Points:
def __init__(self, num_stations, num_hubs):
self.stations = []
self.hubs = []
self.num_stations = num_stations
self.num_hubs = num_hubs
self.connections = collections.OrderedDict()
# {My name1 : {connected's name1: distance1, connected's name2: distance2 ...}, My name2 : {...}, ...}
self.x_values = []
self.y_values = []
self.hub_x_values = []
self.hub_y_values = []
self.num_freight = 15
self.num_passenger = 5
self.freight_schedule = collections.OrderedDict()
# Stores {Name: [Home Hub, destination and start time]}
self.passenger_schedule = collections.OrderedDict()
# stores {Name: [Home Hub, destination and departure times]} Home Hub and destinations
self.fail_max = 1000000
def validate_point(self, new_x, new_y):
if not self.stations:
return True
for station in self.stations:
if not station.validate_new_point(new_x, new_y):
return False
for hub in self.hubs:
if not hub.validate_new_point(new_x, new_y):
return False
return True
def generate_points(self):
self.hubs = []
self.stations = []
fails = 0
name_stations = 1
name_hubs = 1 # Iterates and increases by 1
n = 0 # Counter for how many successful point placements. Stop When num stations is met
while n < self.num_stations:
x = random.randint(1, 1000)
y = random.randint(1, 1000)
if self.validate_point(x, y):
self.stations.append(Station(name_stations, x, y))
n += 1
name_stations += 1
elif fails > self.fail_max:
print("Failed placing points more than {} times. Consider lower min dist".format(self.fail_max))
return True, fails
else:
fails += 1
n = 0
while n < self.num_hubs:
x = random.randint(1, 1000)
y = random.randint(1, 1000)
if self.validate_point(x, y):
self.hubs.append(Hub("H" + str(name_hubs), x, y))
n += 1
name_hubs += 1
elif fails > self.fail_max:
print("Failed placing points more than {} times. Consider lower min dist".format(self.fail_max))
return True, fails
else:
fails += 1
return False, fails
def connect_stations(self):
for start_station in self.stations:
connection_dict = {}
smallest = None
min_man_dist = 999999999
for station in self.stations:
manhattan_dist = abs(start_station.x - station.x) + abs(start_station.y - station.y)
if manhattan_dist != 0 and manhattan_dist < connection_distance:
connection_dict[station] = manhattan_dist
if manhattan_dist != 0 and manhattan_dist < min_man_dist:
min_man_dist = manhattan_dist
smallest = station
if not connection_dict:
connection_dict[smallest] = min_man_dist
self.connections[start_station] = connection_dict
def connect_hubs(self):
for hub in self.hubs:
connection_dict = {}
stations_distances = []
smallest = None
min_man_dist = 999999999
for station in self.stations:
manhattan_dist = abs(hub.x - station.x) + abs(hub.y - station.y)
stations_distances.append(manhattan_dist)
# Find smallest manhattan distance station
if smallest is None or manhattan_dist < min_man_dist:
smallest = station
min_man_dist = manhattan_dist
connection_dict[smallest] = min_man_dist
self.connections[smallest][hub] = min_man_dist
self.connections[hub] = connection_dict
def connect_points(self):
for point, connections in self.connections.items():
x_1 = point.x
y_1 = point.y
for external, distance in connections.items():
x_2 = external.x
y_2 = external.y
# distance placed at the midpoint of line
plt.plot([x_1, x_2], [y_1, y_2], c="00")
def print_station_stats(self, fails):
print("Statistics\n\nCoordinates")
coordinates_stations = list(zip(self.x_values, self.y_values))
coordinates_hubs = list(zip(self.hub_x_values, self.hub_y_values))
for i, k in enumerate(coordinates_stations):
print(i + 1, k)
for i, k in enumerate(coordinates_hubs):
print("H" + str(i + 1), k)
print("#" * 60, "\n\t Below are connections to other stations")
statement = ""
for point, connections in self.connections.items():
statement += "{:2} connects to: ".format(point.name)
for external, distance in connections.items():
statement += "({}, {}) ".format(external.name, distance)
statement += "\n"
print(statement)
print("Num Fails: {}".format(fails))
print("Fails Refers to the number of points that were attempted, but too close to another point")
def create_trains_schedules(self):
for freight in range(self.num_freight):
home_hub = random.randint(1, 5)
destination = random.randint(1, 60)
start_time = None
if random.randint(1, 2) == 1:
start_time = random.randint(1, 1440/2)
# NOTE: Freight trains must start before half day is up. 1440 minutes...
self.freight_schedule[freight + 1] = [home_hub, destination, start_time]
# print(self.freight_schedule)
for passenger in range(self.num_passenger):
home_hub = random.randint(1, 5)
num_destinations = random.randint(5, 10)
destinations = []
departure_times = []
cur_time = 100
while num_destinations != 0:
destinations.append(random.randint(1, 60))
departure_times.append(random.randint(cur_time, cur_time+100))
cur_time += 100
num_destinations -= 1
self.passenger_schedule[passenger + 1] = [home_hub, destinations, departure_times]
# print(self.passenger_schedule)
def set_coordinates(self):
for station in self.stations:
self.x_values.append(station.x)
self.y_values.append(station.y)
# print(station)
for hub in self.hubs:
self.hub_x_values.append(hub.x)
self.hub_y_values.append(hub.y)
def make_map(self):
fig, ax = plt.subplots()
ax.scatter(self.x_values, self.y_values, size_list, c="00")
ax.scatter(self.hub_x_values, self.hub_y_values, size_list_hubs, c="C3")
names = range(60)
names_hubs = ["H1", "H2", "H3", "H4", "H5"]
for i, txt in enumerate(names):
ax.annotate(str(txt + 1), (self.x_values[int(i)] - 15, self.y_values[int(i)] + 20))
for i, txt in enumerate(names_hubs):
ax.annotate(str(txt), (self.hub_x_values[int(i)] - 15, self.hub_y_values[int(i)] + 20))
self.connect_points()
plt.show()
def create_input_files(self):
f = open("Input1.txt", "w+")
for station in self.stations:
f.write("{}: ({}, {})\n".format(station.name, station.x, station.y))
f.close()
g = open("Input2.txt", "w+")
# g.write("format: station ## connects to: (station ##:distance)")
statement = ""
for point, connections in self.connections.items():
statement += "{:2} connects to: ".format(point.name)
for external, distance in connections.items():
statement += "({}, {}) ".format(external.name, distance)
statement += "\n"
g.write(str(statement))
g.close()
self.create_trains_schedules()
h = open("Input3.txt", "w+")
statement = ""
for name, details in self.freight_schedule.items():
if details[2] is not None:
statement += "Freight {:1}, Home_Hub: {:1}," \
" Destination: {:2}, Start_Time: {:4}\n".format(name, details[0], details[1], details[2])
else:
statement += "Freight {}, Home_Hub: {:1}," \
" Destination: {:2}, Start_Time: \n".format(name, details[0], details[1])
h.write(statement)
statement = ""
for name, details in self.passenger_schedule.items():
dest_string = ""
dep_string = ""
for destination in details[1]:
dest_string += "{:2} ".format(str(destination))
for departure_time in details[2]:
dep_string += "{:4} ".format(str(departure_time))
statement += "Passenger No. {}, Home_Hub: {}," \
" Destinations: {}, Departure_Times: {}\n".format(name, details[0], dest_string, dep_string)
h.write(statement)
h.close()
j = open("seed.txt", "w+")
j.write("seed: {}".format(seed))
j.close()
def run(self):
failed, fails = self.generate_points()
if not failed:
self.set_coordinates()
self.connect_stations()
self.connect_hubs()
# Uncomment the statement below to see all statistics posted to output files
# self.print_station_stats(fails)
self.create_input_files()
self.make_map()
if __name__ == "__main__":
S = Points(60, 5)
S.run()
|
import re
from datetime import datetime
def map_str_to_datetime(date_string):
regex_year = '^\d{4}$'
regex_month = regex_year[:-1] + '-\d{2}$'
regex_day = regex_month[:-1] + '-\d{2}$'
regey_daytime = regex_day[:-1] + ' \d{2}:\d{2}:\d{2}$'
if re.match(regex_year, date_string):
return datetime.strptime(date_string, '%Y')
elif re.match(regex_month, date_string):
return datetime.strptime(date_string, '%Y-%m')
elif re.match(regex_day, date_string):
return datetime.strptime(date_string, '%Y-%m-%d')
elif re.match(regey_daytime, date_string):
return datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S')
else:
raise ValueError('date_string is not formatted correctly!') |
import string
class Solution:
# def isPalindrome(self, s: str) -> bool:
def isPalindrome(self, s):
# s = s.lower()
ptr_pos = 0
ptr_neg = len(s) - 1
while ptr_pos<=ptr_neg:
if s[ptr_pos].lower() == s[ptr_neg].lower():
ptr_pos += 1
ptr_neg -= 1
elif not s[ptr_pos].isalnum() :
ptr_pos += 1
elif not s[ptr_neg].isalnum():
ptr_neg -= 1
else:
return False
return True
#-----------improved-----------
def isPalindrome(self, s):
ss = [k.lower() for k in s if k.islnum()]
return ss == s[::-1] |
import time
from collections import deque
from Queue import Queue
number = 100000
start = time.time()
a = list()
for i in range(number):
a.append((i))
for _ in range(number):
a.pop()
print('time for built-in list is {}'.format(time.time()-start))
start = time.time()
a = deque()
for i in range(number):
a.append((i))
for _ in range(number):
a.pop()
print('time for deque is {}'.format(time.time()-start))
start = time.time()
a = Queue()
for i in range(number):
a.put((i))
for _ in range(number):
a.get()
print('time for deque is {}'.format(time.time()-start)) |
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
mid = len(nums) // 2
if nums[mid] == target:
return mid
if nums[mid] < nums[-1]: # head on the left
if nums[mid] < target and nums[mid] < target[-1]:
return mid + self.search(nums[mid + 1:], target)
else:
return self.search(nums[:mid], target)
else: # head on the right
if nums[mid] > target and nums[0] > target:
return mid + self.search(nums[mid + 1:], target)
else:
return self.search(nums[:mid], target)
|
# linked list
# need a head that points to the next item in list, last item in list will point to None
# adding is easiest to head, because will have the head pointer
class Node:
def __init__(self, data):
self.data = data
self.next = none
def getData(self):
return self.data
def getNext(self):
return self.next
def setData(self, new_data):
self.data = new_data
def setNext(self, new_next):
self.next = new_next
class LinkedList:
def __init__(self):
self.head = None
def is_empty(self):
return self.head == None
def size(self):
length = 0
current = self.head
while current.next:
length += 1
self.
return length
def add(self, item):
new_node = Node(item)
self.next = setNext(new_node)
self.head = self.new_node
def remove(self, item) |
# all recursive algorithms must obey three important laws:
# A recursive algorithm must have a base case.
# A recursive algorithm must change its state and move toward the base case.
# A recursive algorithm must call itself, recursively.
def sum_list_recursively(num_list):
"""Sum numbers in a list using recursion
>>> print sum_list_recursively([1, 3, 5, 7, 9])
25
"""
if len(num_list) == 1:
return num_list[0]
else:
return num_list[0] + sum_list_recursively(num_list[1:])
# takeaways: remember the len list 1 base case w/ passing in rest of list model
def factorial(n):
"""Return the factorial of a non-negative integer using recursion.
>>> factorial(6)
720
"""
if n <= 1:
return 1
else:
return n * factorial(n - 1)
# def factorial(n):
# """return factorial of n not using recursion"""
# num = 1
# for i in range(1, n+1):
# num *= i
# return num
def reverse_string(string):
""" reverse string recursively
>>> reverse_string('hello')
'olleh'
"""
if len(string) < 2:
return string
else:
return string[-1] + reverse_string(string[:-1])
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print "recursion master!" |
"""Reverse a string using recursion.
For example::
>>> rev_string("")
''
>>> rev_string("a")
'a'
>>> rev_string("porcupine")
'enipucrop'
"""
def rev_string(s):
"""Return reverse of string using recursion.
You may NOT use the reversed() function!
"""
# can put new_string as default funct, but then it doesn't reset the var once
# the function is done. Leaky.
# new_string = ''
# if astring == '':
# return ''
# elif astring is not None:
# new_string += astring[-1]
# rev_string(astring[:-1])
# return new_string
# # return ''.join(new_string)
# return new_string
# Problem - initializing list/string overwrites it each time instead of adds to,
# so I end up with only the last element, not all of them
if len(s) < 2:
return s
return s[-1] + rev_string(s[:-1])
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print "\n*** ALL TESTS PASSED. !KROW DOOG\n"
# new_string = rev_string(new_string[-2::-1])
|
def string_validator(s):
"""Return t/f for if s contains lowers, uppers, digits, etc"""
t = type(s)
for method in [t.isalnum, t.isalpha, t.isdigit, t.islower, t.isupper]:
print any(method(char) for char in s) |
# anagram puzzle
# doesn't quite work this way because of examples like 'baab'
# def is_anagram_of_palindrome(word):
# """
# >>> is_anagram_of_palindrome("a")
# True
# >>> is_anagram_of_palindrome("ab")
# False
# >>> is_anagram_of_palindrome("aab")
# True
# >>> is_anagram_of_palindrome("baab")
# True
# >>> is_anagram_of_palindrome("arceace")
# True
# >>> is_anagram_of_palindrome("arceaceb")
# False
# >>> is_anagram_of_palindrome("aaac")
# False
# >>> is_anagram_of_palindrome("aaacaaa")
# True
# >>> is_anagram_of_palindrome("aaaacaaa")
# False
# """
# lword = list(word)
# sword = set(lword)
# if len(sword) == 2 and len(lword) % 2 == 0:
# return False
# if (len(sword) * 2) - len(lword) <= 1:
# return True
# return False
def is_anagram_of_pal(word):
"""
>>> is_anagram_of_pal("a")
True
>>> is_anagram_of_pal("ab")
False
>>> is_anagram_of_pal("aab")
True
>>> is_anagram_of_pal("baab")
True
>>> is_anagram_of_pal("arceace")
True
>>> is_anagram_of_pal("arceaceb")
False
>>> is_anagram_of_pal("aaac")
False
>>> is_anagram_of_pal("aaacaaa")
True
>>> is_anagram_of_pal("aaaacaaa")
False
"""
d = {}
for char in word:
if char not in d:
d[char] = 1
else:
d[char] += 1
check = 0
for amt in d.values():
if amt % 2 != 0:
check += 1
if check > 1:
return False
return True
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print "\n*** ALL TEST PASSED. AWESOMESAUCE!\n"
|
def calculateScore(text, prefixString, suffixString):
"""
>>> calculateScore('nothing', 'bruno', 'ingenious')
"""
pass
def calculate_prefix_score(string1, string2):
"""
>>> calculate_prefix_score('nothing', 'bruno')
2
"""
prefix = ''
prefix_start = string1[0]
start_pre_match = string2.find(prefix_start)
if start_pre_match != -1:
prefix = string2[start_pre_match:]
# add check for making sure the 'fixes' match
return len(prefix)
def calculate_suffix_score(string1, string2):
"""
>>> calculate_suffix_score('nothing', 'ingenious')
3
"""
suffix = ''
suffix_start = string1[0]
start_pre_match = string2.find(prefix_start)
if start_pre_match != -1:
prefix = string2[start_pre_match:]
if __name__ == "__main__":
import doctest
if doctest.testmod().failed == 0:
print "\n Tests passed - yahooo string masta!" |
# def array_sum(lst):
# for i in xrange(len(lst)):
# if sum(lst[:i]) == sum(lst[i+1:]):
# return "YES"
# else:
# # print sum(lst[:i]), sum(lst[i+1:])
# continue
# return "NO"
# above solution times out on HR
# better solution:
def equal_sums_on_sides_of_index(lst):
total = sum(lst)
left_side = 0
for i in xrange(len(lst)):
current = lst[i]
total -= current
if left_side == total:
return "YES"
left_side += current
return "NO"
# O(n) runtime
|
class Digraph:
class RandomizedQueue():
def __init__(self):
self.RandomizedQueue = []
self.size = 0
def isEmpty(self):
return self.RandomizedQueue == []
def enqueue(self, item):
self.RandomizedQueue.append(item)
self.size += 1
def sample(self):
if not self.isEmpty():
return self.RandomizedQueue[random.randint(0,self.size)]
else:
return False
def dequeue(self):
if not self.isEmpty():
self.size -= 1
return self.RandomizedQueue.pop(random.randint(0,self.size))
else:
return "Empty queue"
def iterator(self):
return RandomizedQueue.RandomArrayIterator(self)
class RandomArrayIterator():
def __init__(self, RQ):
self.RQ = RQ
self.i = 0
self.randomIndexes = random.sample(range(0,RQ.size), RQ.size)
def hasNext(self):
if self.i < self.RQ.size:
return True
else:
return False
def next(self):
oldIndex = self.randomIndexes[self.i]
self.i += 1
return self.RQ.RandomizedQueue[oldIndex]
def __init__(self, V):
self.V = V
self.adj = [None]*V
v = 0
while v < V:
self.adj[v] = Digraph.RandomizedQueue()
v += 1
def addEdge(self, v, w):
self.adj[v].enqueue(w)
def adjacent(self, v):
return self.adj[v] |
class Shell():
@staticmethod
def sort(a):
N = len(a)
h = 1
while h <= N/3:
h = 3*h + 1
while h >= 1:
i = h
while i < N:
j = i
while j >= h and Shell.less(a[j], a[j-h]):
Shell.exch(a, j, j-h)
j -= h
i += 1
h = h//3
return
@staticmethod
def less(v,w):
if v < w:
return -1 < 0
elif v > w:
return 1 < 0
else:
return 0 < 0
@staticmethod
def exch(a, i, j):
swap = a[i]
a[i] = a[j]
a[j] = swap
@staticmethod
def isSorted(a):
i = 1
while i < len(a):
if Selection.less(a[i], a[i-1]):
return False
i += 1
return True
a = [5,2,3,1]
Shell.sort(a)
print(a) |
import random
class Shuffle():
@staticmethod
def shuffle(a):
N = len(a)
i = 0
while i < len(a):
r = random.randint(0,i)
Shuffle.exch(a, i, r)
i += 1
@staticmethod
def exch(a, i, j):
swap = a[i]
a[i] = a[j]
a[j] = swap
a = [1,2,3,4,5]
Shuffle.shuffle(a)
print(a) |
from sklearn.datasets import load_digits
from sklearn.svm import SVC
from sklearn.model_selection import validation_curve,train_test_split
from sklearn.model_selection import learning_curve
from sklearn.neighbors import KNeighborsClassifier
from sklearn.externals import joblib
import matplotlib.pyplot as plt
import numpy as np
####switch####
model=0 #KNN = 0, SVC=1
Ex1=0 #Ex1: Split data to train the model.
#After training, calculate the accurracy by test data.
#Show the wrong-prediction results.
Ex2=0 #Ex2: Cross_validation
#Use cross validation method to score the model.
#Find the parameter value with best performance
Ex3=0 #Ex3: Learning curve
#See the procession of learning.
#We can observe if there is the overfiting.
Ex4=0 #Use the model which has been trained and saved.
Ex5=1 #Compare SVC and KNN models in learning curve.
##############
#Load data
digits = load_digits() #This data is for the number by handwriting.
X = digits.data
Y = digits.target
images = digits.images
if (Ex1==1):
#Ex1: Split data to train the model.
#After training, calculate the accurracy by test data.
#Show the wrong-prediction results.
#Split data to train the model. Train_data:Test_data = 8:2
x_train, x_test, y_train, y_test, i_train, i_test = train_test_split(X, Y, images,test_size=0.2)
if (model == 0 ):#KNN
KNN = KNeighborsClassifier(n_neighbors=2)
KNN.fit(x_train, y_train)
title='KNN'
print ("The prediction for the test data:",KNN.predict(x_test[:10]))
print ("The target for the test data: ",y_test[:10])
num_success = sum(KNN.predict(x_test) == y_test)
accuracy = num_success/len(y_test)
num_failed=len(y_test)-num_success
print ("accuracy=",accuracy)
joblib.dump(KNN, 'save/KNN_digit.pkl') # Save
fig = plt.figure(figsize=(num_failed, 1))# 調整子圖形
fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)
j=0
for i in range(0,len(y_test)):
if(KNN.predict([x_test[i]]) != y_test[i]):
# 在 1 x num_failed 的網格中第 i + 1 個位置繪製子圖形,並且關掉座標軸刻度
ax = fig.add_subplot(1, num_failed, j + 1, xticks = [], yticks = [])
# 顯示圖形,色彩選擇灰階
ax.imshow(i_test[i], cmap = plt.cm.binary)
# 在左下角標示目標值
ax.text(0, 7, str(y_test[i]))
ax.text(0, 5, str(KNN.predict([x_test[i]])))
j=j+1
plt.show()
else: #SVC
svc=SVC(gamma=0.001)
svc.fit(x_train, y_train)
title='SVC'
print ("The prediction for the test data:",svc.predict(x_test[:10]))
print ("The target for the test data: ",y_test[:10])
num_success = sum(svc.predict(x_test) == y_test)
accuracy = num_success/len(y_test)
num_failed=len(y_test)-num_success
print ("accuracy=",accuracy)
joblib.dump(svc, 'save/SVC_digit.pkl') # Save
fig = plt.figure(figsize=(num_failed, 1))# 調整子圖形
fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)
j=0
for i in range(0,len(y_test)):
if(svc.predict([x_test[i]]) != y_test[i]):
# 在 1 x num_failed 的網格中第 i + 1 個位置繪製子圖形,並且關掉座標軸刻度
ax = fig.add_subplot(1, num_failed, j + 1, xticks = [], yticks = [])
# 顯示圖形,色彩選擇灰階
ax.imshow(i_test[i], cmap = plt.cm.binary)
# 在左下角標示目標值
ax.text(0, 7, str(y_test[i]))
ax.text(0, 5, str(svc.predict([x_test[i]])))
j=j+1
plt.show()
if (Ex2==1):
#The method 2:
#Use cross_validation KNeighborsClassifier model to find the best parameter
if (model == 0 ):
param_range = range(1, 10)
train_score, test_score = validation_curve(
KNeighborsClassifier(), X, Y, param_name='n_neighbors', param_range=param_range, cv=5,
scoring='accuracy')
xlabel="Number of neighbor"
title='KNN for digits data with different n_neighbor'
else:
param_range = np.logspace(-6, -2.3, 15)
train_score, test_score = validation_curve(
SVC(), X, Y, param_name='gamma', param_range=param_range, cv=5,
scoring='accuracy')
xlabel="gamma"
title='SVC model for digits data with different gamma'
train_score_mean = np.mean(train_score, axis=1)
test_score_mean = np.mean(test_score, axis=1)
plt.plot(param_range, train_score_mean, 'o-', color="r",
label="Training")
plt.plot(param_range, test_score_mean, 'o-', color="g",
label="Cross-validation")
plt.title(title)
plt.xlabel(xlabel)
plt.ylabel("score")
plt.legend(loc="best")
plt.show()
if (Ex3==1):
#The method 3:
#Use learning curve to see if there is overfit phenomena,
if (model == 0 ):
train_sizes, train_score, test_score= learning_curve(
KNeighborsClassifier(n_neighbors=2), X, Y, cv=6, scoring='accuracy',
train_sizes=[0.2, 0.4, 0.6, 0.8, 1])
else:
train_sizes, train_score, test_score= learning_curve(
SVC(gamma=0.01), X, Y, cv=6, scoring='accuracy',
train_sizes=[0.2, 0.4, 0.6, 0.8, 1])
train_score_mean = np.mean(train_score, axis=1)
test_score_mean = np.mean(test_score, axis=1)
plt.plot(train_sizes, train_score_mean, 'o-', color="r",
label="Training")
plt.plot(train_sizes, test_score_mean, 'o-', color="g",
label="Cross-validation")
plt.xlabel("Training examples")
plt.ylabel("score")
plt.legend(loc="best")
plt.show()
if (Ex4==1):
KNN2 = joblib.load('save/KNN_digit.pkl')
svc2 = joblib.load('save/SVC_digit.pkl')
xtrain, xtest, ytrain, ytest = train_test_split(X, Y, test_size=0.1)
print("The KNN prediction for the test data:",KNN2.predict(xtest[:10]))
print("The SVC prediction for the test data:",svc2.predict(xtest[:10]))
print("The target for the test data: ",ytest[:10])
if (Ex5==1):
train_sizes1, train_score1, test_score1= learning_curve(
KNeighborsClassifier(n_neighbors=2), X, Y, cv=6, scoring='accuracy',
train_sizes=[0.2, 0.4, 0.6, 0.8, 1])
train_sizes2, train_score2, test_score2= learning_curve(
SVC(gamma=0.001), X, Y, cv=6, scoring='accuracy',
train_sizes=[0.2, 0.4, 0.6, 0.8, 1])
train_score_mean1 = np.mean(train_score1, axis=1)
test_score_mean1 = np.mean(test_score1, axis=1)
train_score_mean2 = np.mean(train_score2, axis=1)
test_score_mean2 = np.mean(test_score2, axis=1)
plt.plot(train_sizes1, test_score_mean1, 'o-', color="r",
label="KNN")
plt.plot(train_sizes2, test_score_mean2, 'o-', color="g",
label="SVC")
plt.xlabel("Training examples")
plt.ylabel("score")
plt.legend(loc="best")
plt.show()
|
ficha = []
temp = []
while True:
nome = str(input(' Nome : ')).strip().capitalize()
n = int(input('Quantas notas deseja cadastrar :'))
nota = media = s =0
for i in range(0,n):
nota = float(input(f' Digite a {i+1}ª nota : '))
s += nota
temp.append(nota)
media = s/n
ficha.append([nome, temp[:], media])
temp.clear()
resp = str(input(' Quer continuar ? [S]sim[N]não'))[0].strip().upper()
if resp in 'N':
break
print('- -'*30)
print(f'{"Nº :":<8}{"NOME :":<10}{"MÉDIA":>8}')
print('- -'*26)
for i, a in enumerate(ficha):
print(f'{i:<8}{a[0]:<10}{a[2]:>8.1f}')
while True:
print('- -'*30)
opc = int(input("Mostrar notal de qual aluno :[0] interrompe"))
if opc == 999:
break
if opc <= len(ficha)-1:
print(f'Notas de {ficha[opc][0]} são {ficha[opc][1]}')
print('Fim do Programa')
|
#contador de vogais em tupla
palavras = ('PANDEMIA', 'CORONA', 'VIRUS',
'BRASIL', 'PRESIDENTE', 'DESGOVERNO',
'MORTES', 'CRISE', 'ECONOMIA')
for p in palavras:
print(f'Na palavra {p} temos as vogais . . . . . ',end=' ')
for letra in p:
if letra in 'AEIOU':
print(f'{letra}',end=' ')
print()
|
from pip._vendor.distlib.compat import raw_input
from random import randint
escola = [[],[],[]]
aluno = {}
notas = {}
def cadastro_aluno():
print('-'*30)
aluno['matrícula'] = randint(1, 1000)
aluno['nome'] = raw_input("Nome : ")
aluno['idade'] = int(input("Idade : "))
aluno['ano'] = int(input('ano: '))
if aluno['ano'] == 1:
escola[0].append(aluno.copy())
if aluno['ano'] == 2:
escola[1].append(aluno.copy())
if aluno['ano'] == 3:
escola[2].append(aluno.copy())
def cadastro_notas():
indice = -1
nota = []
print('-' * 30)
ano = int(input('Para qual ano deseja inserir a nota :'))
for i in escola[ano-1]:
print('-'*30)
for k, v in i.items():
if k == 'matrícula':
print(f'{k} : {v}', end=' ')
if k == 'nome':
print(f'{k} : {v}')
print('-'*30)
matricula = int(input('Para qual matrícula deseja vincular a nota :'))
local = False
for k, v in aluno.items():
if v == matricula:
local = True
if local:
notas['matéria'] = raw_input('Digite o nome da matéria :')
qtd = int(input('Digite Quantas notas deseja cadastrar :'))
for i in range(0, qtd):
notas[f'nota{i+1}'] = float(input(f' - Digite a {i+1}ª nota : '))
while True:
cadastro_aluno()
cadastro_notas()
print(escola)
|
"""
'button.py' module.
Used in the creation of all the buttons in the program.
"""
from .constants import pg, FONT_SMALL_PLUS, WHITE, HOVER_SOUND
class Button:
"""Button instance class implementation."""
def __init__(self, rect_size, color, text):
"""
Button instance constructor.
:param rect_size: size of the button rectangle
:param color: color of the button rectangle
:param text: button text string
"""
self.rect = pg.Rect(rect_size)
self.color = color
self.font = FONT_SMALL_PLUS
self.text_string = text
self.text = self.font.render(text, True, WHITE)
self.hovered = False
self.image = pg.image.load("assets/frames/Table_01.png")
self.active_image = pg.image.load("assets/frames/Table_01_active.png")
def on_click(self, event):
"""
Check for a button click.
:param event: program event
:return: True if the button is clicked and False otherwise
"""
if self.rect.collidepoint(event.pos):
return True
return False
def check_hover(self):
"""Play a sound if the mouse is hovering over a button."""
if self.rect.collidepoint(pg.mouse.get_pos()):
if not self.hovered:
self.hovered = True
pg.mixer.Sound(HOVER_SOUND).play()
else:
self.hovered = False
def wh_text(self):
"""
Get the width and height of the text rectangle.
:return: text rectangle width and height tuple
"""
text_rect = self.text.get_rect()
return text_rect.width, text_rect.height
def update(self, surface):
"""
Update button text position and image.
:param surface: screen surface
"""
self.check_hover()
if self.hovered: # Switch to active image of the button when hovered over
surface.blit(self.active_image, (self.rect.x, self.rect.y))
else:
surface.blit(self.image, (self.rect.x, self.rect.y))
# Update button text position
text_width, text_height = self.wh_text()
surface.blit(self.text, (self.rect.centerx - (text_width / 2), self.rect.centery + 5))
|
"""
'missile.py' module.
Used in creating the cannon missile body and shape.
"""
from math import pi, pow, degrees
import pymunk as pm
from pymunk.vec2d import Vec2d
from .constants import MISSILE_DRAG_CONSTANT
from .sprite_class import Sprite
class Missile(Sprite):
"""Missile Sprite subclass implementation."""
def __init__(self):
"""Virtually private constructor which initializes the missile Sprite."""
super().__init__('assets/frames/missile_small.gif') # call Sprite initializer
self.body, self.shape = None, None # Pymunk body and shape of the missile
self.launched = False # Boolean to check if the missile has been launched
self.collided = True # Boolean to check if the missile has collided with another object
def create(self, position):
"""
Create new missile body and shape at specified location.
:param position: new body and shape position coordinates
"""
vs = [(-30, 0), (0, 3), (10, 0), (0, -3)] # Polygon point coordinates
mass = 0.5
moment = pm.moment_for_poly(mass, vs)
self.body = pm.Body(mass, moment) # Create the body
self.body.position = position # Position the body
self.shape = pm.Poly(self.body, vs) # Create the shape
self.shape.color = (115.0, 148.0, 107.0, 100.0)
self.shape.friction = .5 # Set the shape friction with other objects
self.shape.collision_type = 3
self.shape.filter = pm.ShapeFilter(group=1)
def prepare_for_launch(self, cannon_body, cannon_shape):
"""
Position the missile for launch (at anti-spacecraft cannon location)
:param cannon_body: anti-spacecraft cannon body
:param cannon_shape: anti-spacecraft cannon shape
"""
self.body.position = cannon_body.position + Vec2d(cannon_shape.radius - 30, 0).rotated(cannon_body.angle)
self.body.angle = cannon_body.angle + pi
def apply_gravity(self):
"""Apply gravitational effects to the launched missile."""
pointing_direction = Vec2d(1, 0).rotated(self.body.angle)
flight_direction = Vec2d(self.body.velocity)
flight_speed = flight_direction.normalize_return_length()
dot = flight_direction.dot(pointing_direction)
# Calculate (roughly) the air resistance effect force on the missile
drag_force_magnitude = (1 - abs(dot)) * pow(flight_speed, 2) * MISSILE_DRAG_CONSTANT * self.body.mass
# Apply impulse to the missile body
self.body.apply_impulse_at_world_point(drag_force_magnitude * -flight_direction, self.body.position)
# Rotate missile simulating (roughly) air resistance
if 90 <= degrees(self.body.angle) < 270:
self.body.angular_velocity += .025
elif 90 > degrees(self.body.angle) >= -90:
self.body.angular_velocity -= .025
else:
self.body.angular_velocity = 0
def launch(self, difference):
"""
Calculate impulse strength and launch the missile.
:param difference: the time between the 'shoot' key press and its release
"""
power = max(min(difference, 1000), 10)
impulse = power * Vec2d(1, 0)
impulse.rotate(self.body.angle)
# Apply force to the missile (launch the missile)
self.body.apply_impulse_at_world_point(impulse, self.body.position)
self.launched = True
def ready_to_blit(self):
"""
Check if the missile is ready to be shown on the screen
:return True if the missile is launched and has not collided with another shape
"""
return self.launched and not self.collided
def remove_from_space(self, space):
"""
Remove the body and shape of the missile and reset its attributes.
:param space: Pymunk object space
"""
space.remove(self.body)
space.remove(self.shape)
self.launched = False
self.collided = True
|
import matplotlib.pyplot as plt
class Pie:
def __init__(self, labels, data, title):
self.labels = labels
self.data = data
self.title = title
def make_pie(self, out_path, name):
fig1, ax1 = plt.subplots()
ax1.pie(self.data, labels=self.labels, autopct='%1.1f%%',
shadow=True, startangle=90)
ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
plt.title(self.title)
plt.savefig(f"{out_path}/{name}.png")
|
class Matrix(object):
def __init__(self,num_rows = 2,num_cols = 2):
'''
initilaizes rows, columns, and array
'''
self.num_rows = num_rows
self.num_cols = num_cols
try:
if type(num_rows) == int and type(num_cols) == int:#check if rows and column are integers
if num_rows >= 1 and num_cols >= 1: #checks for positivity
self.array = [ [ 0 for i in range(num_cols) ] for j in range(num_rows) ] #initaize zero for each row,column
return None
except ValueError:
raise ValueError("Matrix: Error, the dimensions must be positive integers!")
def __str__(self):
'''
Returns a string representation of the matrix
'''
result = "" #empty string to keep reult as a string
for i in range(self.num_rows):
for j in range(self.num_cols):
if i== 0 and j == 0:
result += "[[{}".format(self.array[i][j])
elif j == 0:
result += " [{}".format(self.array[i][j])
elif j == self.num_cols - 1 :
if i == self.num_rows - 1:
result += " {}]]".format(self.array[i][j])
else:
result += " {}]\n".format(self.array[i][j])
else:
result += " {}".format(self.array[i][j])
return result
def __repr__(self):
'''
Returns the same matrix string as __str__
'''
return(self.__str__())
def __getitem__(self, iijj):
'''
Gets the values from the matrix, given indexes
'''
if type(iijj) == tuple: #checks if indexes is tuple
for i in iijj: #iterates through indexes and checks for each index is integer
if not type(i) == int:
raise ValueError("Matrix: Error, the indices must be a positive integer or a tuple of integers!")
if 0 < iijj[0] < self.num_rows and 0 < iijj[1] < self.num_cols: #checks if indexing is positive
return self.array[iijj[0] -1][iijj[1] - 1]
else:
if 0 >= iijj[0] or 0 >= iijj[1]: #raise error if negative
raise IndexError("Matrix: Error, bad indexing!")
else:
raise IndexError("Matrix: Error, index out of range!")
elif type(iijj) == int: #checks if indexes is integer
if 0 < iijj < self.num_rows : #checks if indexing is positive
return self.array [iijj - 1]
else:
if 0 > iijj:
raise IndexError("Matrix: Error, index out of range!")
else:
raise IndexError("Matrix: Error, index out of range!")
else:
raise ValueError("Matrix: Error, the indices must be a positive integer or a tuple of integers!")
def __setitem__(self, iijj, value):
'''
Set the values from the matrix, given indexes and value
'''
if type(value) != int: #checks if value is integer
if type(value) != float: #checks if value is integer
raise ValueError("Matrix: Error, You can only assign a float or int to a matrix!")
if type(iijj) == tuple:#checks indexes is tuple
for i in iijj: #loops through tuple and check if all values are int
if type(i) != int:
raise ValueError("Matrix: Error, the indices must be a tuple of integers!")
if 0 < iijj[0] <= self.num_rows and 0 < iijj[1] <= self.num_cols: #checks if indexing is positive
self.array[iijj[0] - 1][iijj[1] - 1 ] = value #sets value
else:
if 0 >= iijj[0] or 0 >= iijj[1]:
raise IndexError("Matrix: Error, bad indexing!")
else:
raise IndexError("Matrix: Error, index out of range!")
else:
raise ValueError("Matrix: Error, the indices must be a tuple of integers!")
def __add__(self, B):
'''
performs a matrix addition
'''
if B:
if type(B) != Matrix: #checks if matrix
raise ValueError("Matrix: Error, you can only add a matrix to another matrix!")
if not (self.num_cols == B.num_cols and self.num_rows == B.num_rows ) :#checks same dimension
raise ValueError("Matrix: Error, matrices dimensions must agree in addition!")
else:
D = Matrix(self.num_rows,self.num_cols) #creates a new matrix
for i in range(self.num_rows): #loops through rows
for j in range(B.num_cols): #oops through columns
D.array[i][j] = self.array[i][j] + B.array[i][j] #adds values and equate to new matrix
return D
else:
raise ValueError("Matrix: Error, you can only add a matrix to another matrix!")
def dot_product(self,L1,L2):
'''
Returns the dot product of two given lists of numbers
'''
dot_product = 0 #to add multiplacation value
if not len(L1) == len(L2): #checks for same length
raise ValueError("Dot Product: must be same length")
else:
for iijj in range(len(L1)):
dot_product += ( L1[iijj] * L2[iijj] ) #multiply values of lists
return dot_product
def __mul__(self,B):
'''
Performs multiplication of two matrices, using dot product function
'''
if not type(B) == Matrix: #checks if matrix
raise ValueError("Matrix: Error, you can only multiply a matrix to another matrix!")
if not self.num_cols == B.num_rows : #checks dimension
raise ValueError("Matrix: Error, matrices dimensions must agree in multiplication!")
else:
C = Matrix(self.num_rows , B.num_cols) #creates a new matrix
for i in range(C.num_rows):
for j in range(C.num_cols):
j_list = [] #to append values from j
for i_s in B.array: #loops through B_rows
j_list.append(i_s[j]) #appends values from j
C.array[i][j] = Matrix.dot_product(self, self.array[i], j_list) #set value in matrix to dot_product of i and j
return C
def transpose(self):
'''
Returns the transpose of the matrix
'''
T = Matrix(self.num_cols, self.num_rows) #creates a new matrix
for i in range(T.num_rows): #loops through rows
for j in range(T.num_cols):#loops through colums
T[i + 1, j+ 1] = self.array[j][i] #switches rows and colums to transpose, equate to new matrix
return T
def __eq__(self,B):
'''
Checks if corresponding values of matrices are equal , returns boolean
'''
if B:
if type(B) != Matrix: #checks if matrix B is a matrix
return False
if not (self.num_cols == B.num_cols and self.num_rows == B.num_rows ) : #checks equal dimension
return False
else:
for i in range(self.num_rows): #loops through rows
for j in range(B.num_cols): #loops through rows
if i == j : #check if values are equal
continue
return True
else:
return False
def __rmul__(self,num):
'''
Performs a scalar multiplication , given integer
'''
R = Matrix(self.num_rows, self.num_cols) #creates a new matrix
if type(num) != int: #checks for num validity
raise ValueError("Matrix Error: scaler must be an int." )
else:
for i in range(0, self.num_rows ):
for j in range(0 , self.num_cols):
R.array[i][j] = self.array[i][j] * num #gets value and makes multiplication
return R
|
class Privileges:
"""A simple attempt to model a privileges for an admin."""
def __init__(self, privileges=['can add post', 'can delete post', 'can ban user']):
"""Initialize the battery's attributes."""
self.privileges = privileges
def show_privileges(self):
"""Show all privileges"""
for privilege in self.privileges:
print(privilege)
|
def print_models(unprinted_desing, completed_models):
"""
Simulate printing each design, until none are left.
Move each design to completed_models after printing.
"""
while unprinted_desing:
current_design = unprinted_desing.pop()
print(f"Printing model: {current_design}")
completed_models.append(current_design)
def show_completed_models(completed_models):
"""Show all the models that were printed."""
print("\nThe following models have been printed:")
for completed_model in completed_models:
print(completed_model)
# Start with some designs that need to be printed.
unprinted_desing = ['phone case', 'robot pendant', 'dodecahedron']
completed_models = []
print_models(unprinted_desing[:], completed_models)
show_completed_models(completed_models)
print(unprinted_desing)
|
# A named tuple type has a few attributes in addition to those inherited from tuple .
# Example 2-10 shows the most useful: the _fields class attribute, the class method
# _make(iterable) and the _asdict() instance method.
from collections import namedtuple
City = namedtuple('City', 'name country population coordinates')
Latlong = namedtuple('Latlong', 'lat long')
delhi_dat = ('Delhi NCR', 'IN', 21.935, Latlong(28.613889, 77.208889))
delhi = City._make(delhi_dat)
print(delhi._asdict())
for key, value in delhi._asdict().items():
print(f"{key}: {value}")
# _fields is a tuple with the field names of the class.
# _make() lets you instantiate a named tuple from an iterable; City(*delhi_da
# ta) would do the same.
# _asdict() returns a collections.OrderedDict built from the named tuple
# instance. That can be used to produce a nice display of city data. |
symbols = '$¢£¥€¤'
# using list comprehension
beyond_ascii = [ord(code) for code in symbols if ord(code) > 127]
print(beyond_ascii)
# using filter and map
beyond_ascii = list(filter(lambda x: x > 127, map(ord, symbols)))
print(beyond_ascii) |
items = ['laptop', 'mobile', 'computer', 'hony', 'rabbi', 'piash', 'borna']
print('The first three item in the list are:')
for item in items[:3]:
print(item)
print('The items from the middle of the list are:')
for item in items[2:]:
print(item)
print('The last three items in the list are:')
for item in items[-3:]:
print(item) |
alien_0 = {'color': 'green', 'point': 5}
print(alien_0['color'])
print(alien_0['point'])
print(alien_0)
# alien_0 = {'color': 'red'}
# print(alien_0)
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
print(f"The alien is {alien_0['color']}")
alien_0['color'] = 'yellow'
print(f"The alien is now {alien_0['color']}")
alien_1 = {'x_position': 0, 'y_position': 25, 'speed': 'medium'}
print(f"Original position {alien_1['x_position']}")
# Move the alien to the right.
# Determine how far to move the alien based on its current speed.
if alien_1['speed'] == 'slow':
x_increament = 1
elif alien_1['speed'] == 'medium':
x_increament = 2
else:
x_increament = 3
# The new position is the old position plus the increment.
alien_1['x_position'] = alien_1['x_position'] + x_increament
print(f"New position {alien_1['x_position']}")
del alien_0['point']
print(alien_0) |
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]
my_foods.append('canoli')
friend_foods.append('ice cream')
print('My favorite foods are:')
print(my_foods)
print('\nMy frieds favorite foods are:')
print(friend_foods)
s_foods = my_foods
s_foods.append('jalkd')
print(my_foods)
print(s_foods) |
def show_messages(messages):
"""Show all messages is in list"""
for message in messages:
print(message)
def send_messages(messages, sent_messages):
"""Display all send message and add every message in new list"""
while messages:
current_message = messages.pop()
print(f"Send successfully message: {current_message}")
sent_messages.append(current_message)
def arrived_messages(sent_messages):
"""Display all arrived messages"""
for sent_message in sent_messages:
print(sent_message)
messages = ['hi', 'hello', 'rabbi', 'piash']
sent_messages = []
show_messages(messages)
send_messages(messages[:],sent_messages)
arrived_messages(sent_messages)
|
def cipher(direction , shift, message):
if direction == "encode":
shift_text =""
for char in message:
value = alphabets.index(char)
shift_num = value+shift
shift_text = shift_text + alphabets[shift_num]
print(shift_text)
elif direction =="decode":
char_text = ""
for char in message :
char_num=alphabets.index(char)
char_total = char_num - shift
char_text = char_text + alphabets[char_total]
print(char_text)
from art import logo
print(logo)
alphabets = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
play = True
while play:
direction = input("Enter encode for encoding and decode for decoding:")
message = input("Enter the message : ")
shift = int(input("Enter the shift value : "))
cipher(direction,shift, message)
user = input("Do you want to covert again: ")
if user=="no"or user=="n":
play=False
print("good bye") |
class A:
def __init__(self,a):
self.a=a
# print a
def __str__(self):
return str(self.a)
def s(self):
return self.a**2
def __del__(self):
pass
b=A(10)
print b
print b.s()
del b
#print b
|
import json
class Matrix:
def __init__(self,array):
self.array=array
def __add__(self,other):
if len(self.array)==len(other.array):
new_matrix=[]
for i in range(2):
row=[]
for j in range(2):
row.append(self.array[i][j] + other.array[i][j])
new_matrix.append(row)
return Matrix(new_matrix)
# print new_matrix
def __sub__(self,other):
new_matrix=[]
for i in range(2):
row=[]
for j in range(2):
row.append(self.array[i][j] - other.array[i][j])
new_matrix.append(row)
return Matrix(new_matrix)
def __str__(self):
return str(self.array)
# # return json.dumps(self.array,indent=4)
l1=[]
for i in range(2):
l2=[]
for j in range(2):
var=input("enter")
l2.append(var)
l1.append(l2)
l3=[]
for i in range(2):
l4=[]
for j in range(2):
var=input("enter")
l4.append(var)
l3.append(l4)
a=Matrix(l1)
b=Matrix(l3)
print a
print b
print a+b
print a-b
|
var=raw_input("enter the month")
my_dict={'jan':[31,23],'feb':28,'mar':31,'apr':30,'may':31,'jun':30,'jul':31,'aug':31,'sep':30,'oct':31,'nov':30,'dec':31}
print my_dict[var]
|
import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
#As we know, a Cube has 8 vertices and 12 edges
"""All we have to do, is define the basic structure of an
object and feed it to OpenGL, which will create the appropriate
3D Model for it
"""
#8 Vertices. Each vertex is a tuple
verticies = (
(1, -1, -1),
(1, 1, -1),
(-1, 1, -1),
(-1, -1, -1),
(1, -1, 1),
(1, 1, 1),
(-1, -1, 1),
(-1, 1, 1)
)
#Each node has 3 edges in a cube
#12 edges. Each tuple is an edge.
edges = (
(0,1),
(0,3),
(0,4),
(2,1),
(2,3),
(2,7),
(6,3),
(6,4),
(6,7),
(5,1),
(5,4),
(5,7)
)
#6 Faces in a Cube
faces = (
(0,1,2,3),
(3,2,7,6),
(6,7,5,4),
(4,5,1,0),
(1,5,7,2),
(4,0,3,6),
)
colors = (
(255, 0, 255),
(255, 0, 0),
(0, 255, 0),
(0, 0, 255),
(0, 255, 255),
(255, 255, 0),
)
def Cube():
glBegin(GL_QUADS)
x = 0
for face in faces:
glColor3fv(colors[x]) #Setting up the color
x += 1
x %= len(colors)
for vertex in face:
glVertex3fv(verticies[vertex])
glEnd()
glBegin(GL_LINES) #Since our 3d Model is just a bunch of lines
for edge in edges:
for vertex in edge:
glVertex3fv(verticies[vertex])
glEnd()
def main():
pygame.init()
display = (800,600)
pygame.display.set_mode(display,DOUBLEBUF|OPENGL)
gluPerspective(45, (display[0]/display[1]), 0.1, 50.0) #First : Field of view, Second : Aspect Ratio : width/height(Both have already been set in the display),
# 3rd : Clipping Plane, #4th : A large number
glTranslatef(0.0,0.0,-5) #If this was 0,0,0 then we would be fully zoomed in to the cube.This function is zooming out in the z axis by 5 units
glRotatef(0,0,0,0) #Angle of rotation, x,y,z coordinates of a vector
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
glRotatef(2, 4, 3, 1)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
Cube()
pygame.display.flip()
pygame.time.wait(10)
main()
|
def make_album(artist_name, album_title, num_tracks = ''):
album = {'name' : artist_name, 'title' : album_title}
if num_tracks:
album['tracks'] = num_tracks
return album
while (True):
artist_name = input("\nInput the artist name ('q' to quit): ")
if (artist_name == 'q'):
break;
album_title = input("\nInput the album title ('q' to quit): ")
if (album_title == 'q'):
break;
num_tracks = input("\nInput the number of tracks ('q' to quit): ")
if (num_tracks == 'q'):
break;
album = make_album(artist_name, album_title, num_tracks)
print(album)
|
class Restaurant():
"""A simply attempt to model a restaurant."""
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.number_served = 0
def describe_restaurant(self):
print("The name of the restaurant is " + self.restaurant_name.title() + ".")
print("The cuisine type of the restaurant is " + self.cuisine_type.title() + ".")
def open_restaurant(self):
print("The restaurant " + self.restaurant_name.title() + " is now open!!")
def set_number_served(self, number_served):
self.number_served = number_served
def increment_number_served(self, number_served_one_day):
self.number_served += number_served_one_day
my_restaurant = Restaurant("Old Code Seller", "Chinese Canadian")
my_restaurant.describe_restaurant()
my_restaurant.open_restaurant()
print("Number of customers have been served: " + str(my_restaurant.number_served))
my_restaurant.number_served = 12
print("Number of customers have been served: " + str(my_restaurant.number_served))
my_restaurant.set_number_served(1001)
print("Number of customers have been served: " + str(my_restaurant.number_served))
my_restaurant.increment_number_served(100)
print("Number of customers have been served: " + str(my_restaurant.number_served))
|
friends = ["Yanbai", "Wanggang", "Chenhongyun"]
message1 = "How are you, " +friends[0] + "?"
print(message1)
message2 = "在四川过好吗, " +friends[1] + "?"
print(message2)
message3 = "How is the house price in Shanghai, " +friends[-1] + "?"
print(message3)
|
def make_sandwich(size, *fillings):
"""Summarize the sandwich we are about to make."""
print("\nMaking a " + size +
"-size sandwich with the following fillings:")
for filling in fillings:
print("- " + filling)
make_sandwich('large', 'Beef')
make_sandwich('small', 'Pork', 'Onion', 'Potato')
|
transportation = ["Car", "Helicopter", "Ship"]
message1 = "I like traveling by " +transportation[0] + "."
print(message1)
message2 = "However,my wife like traverling by " +transportation[-1] + "."
print(message2)
message3 = "We dream that some day we could by our own " + transportation[-2] + "."
print(message3)
|
""" This is The Internship Program Developer Exam 2019 """
import xmltodict, json, os
def main():
""" This is MAin Function """
print("Please input name of file XML: ", end="")
name = input()
for filename in os.listdir(): #loop to find file.XML in path directoy
if filename.endswith(name+".xml"):
f = open(filename) #Open file
XML_content = f.read() #read XML file
filename = filename.replace('.xml', '') #Tranform file name
output_file = open(filename + '.json', 'w')
#parse the content of each file using xmltodict
x = xmltodict.parse(XML_content, attr_prefix='')
j = json.dumps(x,indent=4)
output_file.write(j)
print("-- Convert XML to JSON Finished --")
main() |
'''
Arithmetic
Addition +
Substraction -
Multiplication *
Devision /
Floor devision //
Modulus %
Exponential **
#trying on int
data1 = 100
data2 = 2
print(data1 + data2)
print(data1 - data2)
print(data1 * data2)
print(data1 / data2)
print(data1 // data2)
print(data1 % data2)
print(data1 ** data2)
'''
'''
#trying on string
data1 = "nirmal"
data2 = "vatsyayan"
print("length of string is ",len(data1))
print("value at 0th index of data1 ",data1[0])
print("string contatenation using + ",data1 + data2)
print("printing strig separated by comma ",data1, data2)
'''
'''
#trying on boolean
data1 = True
data2 = True
print(data1 + data2)
print(data1 - data2)
print(data1 * data2)
print(data1 / data2) # will give error is data2 = False
print(data1 // data2) # will give error is data2 = False
print(data1 % data2) # will give error is data2 = False
print(data1 ** data2)
'''
'''
#Comparison operators
#< <= > >= == !=
print(2 > 3)
print(2 >= 3)
print(2 < 3)
print(2 <= 3)
print(2 == 3)
print(2 != 3)
'''
'''
name = "nirmal"
title = "vatsyayan"
print(id(name), " ",id(title))
print(name>title)
print(name>=title)
'''
#string are immutable
#now address of title is similar to name
#title = "nirmal"
#print(id(name), " ",id(title))
#print(name > title)
#print(name >= title)
#value1 = 1
#value2 = "ok"
'''
'''
#this will not work
#print(value1>value2)
'''
#expression conjunction operators
#and or not
'''
print(True and True)
print(True and False)
print(False and True)
print(False and False)
print(True or True)
print(True or False)
print(False or True)
print(False or False)
print(not True)
print(not False)
|
value = 100
denominator = 10
d = {}
try:
div = value/ denominator
print(div)
try:
raise IOError
except:
print("nested except")
print(d[1])
except ZeroDivisionError as e:
denominator = denominator + 1
div = value/ denominator
print("Congrats !! your code have a ZeroDivisionError :)")
print("recanculated value is ", div)
except IOError as e:
print("its an awesome error !!")
print("Congrats !! your code have a IOError :)")
except KeyError as e:
print("Congrats !! your code have a KeyError :)")
except:
print("Congrats !! your code have a bug :)")
print("hello world !!")
|
var1 = 'Hello World!'
#reverse a string
#string[::-1]
#string[start:stop:step]
print("var1[0]: ", var1[0])
print("var1[1:5]: ", var1[1:5])
#capitalize - first alphabet to upper
print(var1.capitalize())
#length of string
print(len(var1))
#check end of string
suffix = "d!";
print(var1.endswith(suffix))
#find string in another string
search = "ll"
print(var1.find(search))
#check if string is alphanumeric
print(var1.isalnum())
#check if string consists only alphabets
print(var1.isalpha())
#check if string consists only digits
data = '1111'
print(data.isdigit())
print(data.isnumeric())
#all alphabets in lower
data = "bc"
print(data.islower())
#convert to lower & upper
data = "OK"
print(data.lower())
data = 'ok'
print(data.upper())
#strip string
val = ' abc'
print(val)
print(val.lstrip())
print(val.rstrip())
print(val.strip())
#split string
val = 'abc,abc,abc,abc'
print(val.split(','))
#max and min value in string
val = "thisisastring"
print(max(val))
print(min(val))
paragraph = '''this is a long string
a paragraph example
long string'''
print(paragraph)
|
'''
Iterables
When you create a list,
you can read its items one by one.
Reading its items one by one is called iteration:
Generators are iterators
but you can only iterate over them once.
Its because they do not store all the values in memory,
they generate the values on the fly
Yield is a keyword that is used like return,
except the function will return a generator.
'''
def fibonacci(n):
a, b, counter = 0, 1, 0
while True:
if (counter >= n):
return
yield a
a, b = b, a + b
counter += 1
f = fibonacci(10)
'''
print(next(f))
print(next(f))
print(next(f))
print(next(f))
print(next(f))
'''
for x in f:
# no linefeed is enforced by end="":
#asked in class by nisar
print(x, " ", end="") #
print()
'''
def getelement():
abc = [1,2,3,4]
for val in abc:
yield val
g = getelement()
print(g)
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
'''
'''
def cityGenerator():
yield "delhi"
yield "MUMBAI"
yield "hyderabad"
yield "indore"
yield "gr noida"
yield "gurgaon"
yield "york"
g = cityGenerator()
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
''' |
data = [1, 2, True,"Nirmal Vatsyayan", 2.4, ["ok"]]
print(type(data))
for value in data:
print(value," type is ",type(value))
data = []
#append a value in list
data.append(1)
print(data)
#extending a list by adding all value from another list
new_data = [1000,111,1]
data.extend(new_data)
print(data)
#insert in a list at given position
data.insert(0, 100)
print(data)
#remove 1st occurence of item from list with value similar to argument
data.remove(1)
print(data)
#returns min/max value from list
list1, list2 = ['xyz', 'lmn', 'abc'], [456, 700, 200]
print("Max value element : ", max(list1))
print("Max value element : ", max(list2))
print("Min value element : ", min(list1))
print("Min value element : ", min(list2))
#reverse a list
list1.reverse()
print(list1)
#sort a list
list2.sort()
print(list2)
#find index of element in list, if not present it will give error
#print(list2.index('a')) # error
print(list2.index(200))
#pop element from list
print(list2)
print(list2.pop()) # by default last element
print(list2.pop(1)) # index can also be passed
|
'''operator overloading error example, file doc'''
class Student(object):
'''this is an awesome student class'''
def __init__(self, name, roll_number):
self.name = name
self.roll_number = roll_number
def message(self):
'''this is comment for message function'''
print(self.name, " is awesome !!")
def __le__(self, other):
if self.roll_number <= other.roll_number:
return True
else:
return False
def __lt__(self, other):
if self.roll_number < other.roll_number:
return True
else:
return False
def __gt__(self, other):
return True
def __ge__(self, other):
return True
def __ne__(self, other):
return True
def __eq__(self, other):
return True
linga = Student("linga", 1)
joshua = Student("Joshua", 2)
print(linga <= joshua)
print(linga < joshua)
print(linga > joshua)
print(linga >= joshua)
print(linga == joshua)
print(linga != joshua)
#BIF
#print(dir())
#prints file name
#print(__file__)
#print __main__
#print(__name__)
#prints module level docs
#print(__doc__)
#print(__builtins__)
#print(__loader__)
#print(__spec__)
#print(__package__)
|
import numpy as np
a = np.array([1, 2])
b = np.array([2, 1])
print(a*b)
print(np.sum(a*b))
print((a*b).sum())
print(np.dot(a, b))
#dot function is also instance method
print(a.dot(b))
print(b.dot(a))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.