text
stringlengths 37
1.41M
|
---|
import string #importing stringle module to get string constant
import random #module implements pseudo-random number generators for various distributions
import pickle #The pickle module implements binary protocols for serializing and de-serializing
info={} #creating a empty dictionary
# with open("game.p","br") as readfile: #opening the file in read mode
# info = pickle.load(readfile)
if __name__ == "__main__":
s1 = string.ascii_lowercase #Give lower ascii which is in format abcd....
s2 = string.ascii_uppercase #Give upper ascii which is in format ABCD....
s3 = string.digits #Give digit '0123456789'
s4 = string.punctuation #Give punctuation '!@#$^*..'
len_password = int(input("Enter password length:\n")) #take the length from the user
s = [] #creating a blank list
s.extend(list(s1)) #concatenating the string s1 and converting into list
s.extend(list(s2)) #concatenating the string s2 and converting into list
s.extend(list(s3)) #concatenating the string s3 and converting into list
s.extend(list(s4)) #concatenating the string s4 and converting into list
print("Your password is: ")
password=("".join(random.sample(s,len_password))) #taking the random sample from s
print(password)
Answer=input("would you like to keep this password:") # taking the input user
if("yes" in Answer): #checking the condition
account_name = input("Enter the account name:")
info[account_name]=password
with open("game.p","bw") as filewrite: #opening the file and writing in it
pickle.dump(info,filewrite,protocol=2)
else:
print("OK")
|
import tensorflow as tf
def create_feature_columns(dataframe,lable_column_name):
'''
Creates Tensorflow Feature_column and returns the feature_columns from the Datafram dataset
'''
NUMERICAL_COLUMN_NAMES = ['age','fare']
CATECORICAL_COLUMN_NAMES =list(dataframe.columns.unique())
CATECORICAL_COLUMN_NAMES = [x for x in CATECORICAL_COLUMN_NAMES if x not in NUMERICAL_COLUMN_NAMES]
CATECORICAL_COLUMN_NAMES.remove(lable_column_name)
feature_columns = []
# Bucketized-column of a Numeric_column 'Age'
age = tf.feature_column.numeric_column(NUMERICAL_COLUMN_NAMES.pop(0))
age_bucketized = tf.feature_column.bucketized_column(age,boundaries=[20,25,40,55,80,100])
feature_columns.append(age_bucketized)
# Numerica Features Column
for feature_name in NUMERICAL_COLUMN_NAMES:
feature_columns.append(tf.feature_column.numeric_column(feature_name,dtype=tf.float32))
# Categorical Features Column with Vocabulary
for feature_name in CATECORICAL_COLUMN_NAMES:
feature_vocabulary_list = dataframe[feature_name].unique()
cat_feature_column_with_vocab = tf.feature_column.categorical_column_with_vocabulary_list(feature_name,feature_vocabulary_list)
## Wrap the caltegorical column with Embeding_column in case of having larg vocabulary list
## Finding the best value for 'dimention' is a challange here and it depends on the data itself
# feature_columns.append(tf.feature_column.embedding_column(tf.feature_column.categorical_column_with_hash_bucket(feature_name,10),dimension=1))
## Wrap the categorical column with Indicator_column in case of having alimitted vocabulary list
feature_columns.append(tf.feature_column.indicator_column(cat_feature_column_with_vocab))
# Cross feature of 'age' and 'sex'
sex = tf.feature_column.categorical_column_with_vocabulary_list('sex',['male','female'])
age_sex_cross_feature = tf.feature_column.crossed_column([age_bucketized,sex],hash_bucket_size=3)
age_sex_cross_feature_column = tf.feature_column.indicator_column(age_sex_cross_feature)
return feature_columns
|
# Python Software Foundation
# https://docs.python.org/2.7/tutorial/inputoutput.html
7.2.1. Methods of File Objects
# The rest of the examples in this section will assume that a file object
# called f has already been created.
# To read a file’s contents, call f.read(size), which reads some quantity
# of data and returns it as a string. size is an optional numeric argument.
# When size is omitted or negative, the entire contents of the file will be
# read and returned; it’s your problem if the file is twice as large as your
# machine’s memory. Otherwise, at most size bytes are read and returned.
# If the end of the file has been reached, f.read() will return an empty
# string ("").
>>>
>>> f.read()
'This is the entire file.\n'
>>> f.read()
''
# f.readline() reads a single line from the file; a newline character (\n)
# is left at the end of the string, and is only omitted on the last line of
# the file if the file doesn’t end in a newline. This makes the return value
# unambiguous; if f.readline() returns an empty string, the end of the file
# has been reached, while a blank line is represented by '\n', a string
# containing only a single newline.
>>>
>>> f.readline()
'This is the first line of the file.\n'
>>> f.readline()
'Second line of the file\n'
>>> f.readline()
''
# For reading lines from a file, you can loop over the file object. This is
# memory efficient, fast, and leads to simple code:
>>>
>>> for line in f:
print line,
This is the first line of the file.
Second line of the file
# If you want to read all the lines of a file in a list you can also use
# list(f) or f.readlines().
# f.write(string) writes the contents of string to the file, returning None.
>>>
>>> f.write('This is a test\n')
# To write something other than a string, it needs to be converted to a string
# first:
>>>
>>> value = ('the answer', 42)
>>> s = str(value)
>>> f.write(s)
# f.tell() returns an integer giving the file object’s current position in
# the file, measured in bytes from the beginning of the file. To change
# the file object’s position, use f.seek(offset, from_what). The position is
# computed from adding offset to a reference point; the reference point is
# selected by the from_what argument. A from_what value of 0 measures from
# the beginning of the file, 1 uses the current file position, and 2 uses
# the end of the file as the reference point. from_what can be omitted and
# defaults to 0, using the beginning of the file as the reference point.
>>>
>>> f = open('workfile', 'r+')
>>> f.write('0123456789abcdef')
>>> f.seek(5) # Go to the 6th byte in the file
>>> f.read(1)
'5'
>>> f.seek(-3, 2) # Go to the 3rd byte before the end
>>> f.read(1)
'd'
# When you’re done with a file, call f.close() to close it and free up any
# system resources taken up by the open file. After calling f.close(), attempts
# to use the file object will automatically fail.
>>>
>>> f.close()
>>> f.read()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: I/O operation on closed file
#It is good practice to use the with keyword when dealing with file objects.
# This has the advantage that the file is properly closed after its suite
# finishes, even if an exception is raised on the way. It is also much shorter
# than writing equivalent try-finally blocks:
>>>
>>> with open('workfile', 'r') as f:
... read_data = f.read()
>>> f.closed
True
# File objects have some additional methods, such as isatty() and truncate()
# which are less frequently used; consult the Library Reference for a complete
# guide to file objects.
|
# Functions can also be called using keyword arguments of the form kwarg=value.
print "if you put", voltage, "volts through it."
print "-- Lovely plumage, the", type
print "-- It's", state, "!"
# accepts one required argument (voltage) and three optional arguments
# (state, action, and type).
parrot(1000) # 1 positional argument
parrot(voltage=1000) # 1 keyword argument
parrot(voltage=1000000, action='VOOOOOM') # 2 keyword arguments
parrot(action='VOOOOOM', voltage=1000000) # 2 keyword arguments
parrot('a million', 'bereft of life', 'jump') # 3 positional arguments
parrot('a thousand', state='pushing up the daisies') # 1 positional, 1 keyword
# but all the following calls would be invalid:
parrot() # required argument missing
parrot(voltage=5.0, 'dead') # non-keyword argument after a keyword argument
parrot(110, voltage=220) # duplicate value for the same argument
parrot(actor='John Cleese') # unknown keyword argument
# In a function call, keyword arguments must follow positional arguments.
# All the keyword arguments passed must match one of the arguments accepted by
# the function (e.g. actor is not a valid argument for the parrot function),
# and their order is not important. This also includes non-optional arguments
# (e.g. parrot(voltage=1000) is valid too). No argument may receive a value more
# than once. Here’s an example that fails due to this restriction:
>>> def function(a):
... pass
...
>>> function(0, a=0)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: function() got multiple values for keyword argument 'a'
# When a final formal parameter of the form **name is present, it receives a
# dictionary (see Mapping Types — dict) containing all keyword arguments except
# for those corresponding to a formal parameter. This may be combined with a
# formal parameter of the form *name (described in the next subsection) which
# receives a tuple containing the positional arguments beyond the formal
# parameter list. (*name must occur before **name.) For example, if we define
# a function like this:
def cheeseshop(kind, *arguments, **keywords):
print "-- Do you have any", kind, "?"
print "-- I'm sorry, we're all out of", kind
for arg in arguments:
print arg
print "-" * 40
keys = sorted(keywords.keys())
for kw in keys:
print kw, ":", keywords[kw]
# It could be called like this:
cheeseshop("Limburger", "It's very runny, sir.",
"It's really very, VERY runny, sir.",
shopkeeper='Michael Palin',
client="John Cleese",
sketch="Cheese Shop Sketch")
# and of course it would print:
# -- Do you have any Limburger ?
# -- I'm sorry, we're all out of Limburger
# It's very runny, sir.
# It's really very, VERY runny, sir.
----------------------------------------
client : John Cleese
shopkeeper : Michael Palin
sketch : Cheese Shop Sketch
# Note that the list of keyword argument names is created by sorting the
# result of the keywords dictionary’s keys() method before printing its contents;
# if this is not done, the order in which the arguments are printed is undefined.
|
"""
Задание 2.
Предложите фундаментальные варианты оптимизации памяти
и доказать (наглядно, кодом, если получится) их эффективность
Например, один из вариантов, использование генераторов
"""
from memory_profiler import profile
from memory_profiler import memory_usage
import timeit
def work_with_indexes():
array = [i for i in range(10000)]
res = []
if len(array) == 0:
return 0
for i in range(len(array)):
if i % 2 == 0:
res.append(array[i])
return sum(res) * array[-1]
def work_with_indexes_time():
array = [i for i in range(10000)]
res = []
if len(array) == 0:
return 0
for i in range(len(array)):
if i % 2 == 0:
res.append(array[i])
return sum(res) * array[-1]
def work_with_indexes_2():
array = [i for i in range(10000)]
return sum(array[0::2]) * array[-1] if 0 < len(array) else 0
def work_with_indexes_2_time():
array = [i for i in range(10000)]
return sum(array[0::2]) * array[-1] if 0 < len(array) else 0
def work_with_indexes_3():
array = [i for i in range(10000)]
res = []
if len(array) == 0:
return 0
for i in range(len(array)):
if i % 2 == 0:
res.append(array[i])
yield sum(res) * array[-1]
def work_with_indexes_3_time_check():
array = [i for i in range(10000)]
res = []
if len(array) == 0:
return 0
for i in range(len(array)):
if i % 2 == 0:
res.append(array[i])
yield sum(res) * array[-1]
print(timeit.timeit("work_with_indexes_time()", setup="from __main__ import work_with_indexes_time", number=1000))
print(timeit.timeit("work_with_indexes_2_time()", setup="from __main__ import work_with_indexes_2_time", number=1000))
print(timeit.timeit("work_with_indexes_3_time_check()", setup="from __main__ import work_with_indexes_3_time_check",
number=1000))
work_with_indexes()
work_with_indexes_2()
def memory_check(func):
m1 = memory_usage()
func()
m2 = memory_usage()
return print(m2[0] - m1[0])
memory_check(work_with_indexes)
memory_check(work_with_indexes_2)
memory_check(work_with_indexes_3)
# вывод я исп вначале я сравнил 2 варианта решения задачи, один с помозью создания новго списка,
# второй при помощи list coprehansion и среза, результат был очевиден -
# первый вариант очень сильно отличается по времени( в полтора раза медленне)
# однако этот малоэффектифный код превратился в очень быстрый, как только
# я поменял return на yield, это доказывет что генератор очень эффективен в использовании
|
class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def size(self):
return len(self.items)
def reverse(string):
my_stack = Stack()
for char in string:
my_stack.push(char)
out = ""
while not my_stack.is_empty():
out += my_stack.pop()
return out
if __name__ =="__main__":
print(reverse("joel"))
|
"""
CODE CHALLENGE: LOOPS
Delete Starting Even Numbers
delete_starting_evens(lst)
"""
#Write your function here
def delete_starting_evens(lst):
i = 0
while i < len(lst):
if lst[i] % 2 != 0:
return lst[i:]
else:
i += 1
continue
return []
#Uncomment the lines below when your function is done
#print(delete_starting_evens([4, 8, 10, 11, 12, 15]))
#print(delete_starting_evens([4, 8, 10]))
|
"""
Given an unsorted integer array, find the smallest missing positive integer.
Example 1:
Input: [1,2,0]
Output: 3
Example 2:
Input: [3,4,-1,1]
Output: 2
Example 3:
Input: [7,8,9,11,12]
Output: 1
Note:
Your algorithm should run in O(n) time and uses constant extra space.
"""
class Solution:
def firstMissingPositive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
set_nums = set(nums)
i = 1
while i in set_nums:
i += 1
return i
|
"""
insert number x in the List(ordered) with appropriate index (ordered)
"""
def solution(L, x):
for i in range(0,len(L)):
if x < L[i]:
L.insert(i,x)
return L
else:
continue
L.insert(len(L),x)
return L
|
# checks to see if a given system is satisfies the additive property of linear systems
# Algorithm
# given an input signal x1[n], the output response produced is y1[n] and
# given an input signal x2[n], the output response produced is y2[n],
# then for an input signal x3[n] = x1[n] + x2[n], the output response y3[n] = y1[n] + y2[n]
from math import *
# import matplotlib.pyplot as plt
# parameter: system function, input x1, input x2, interval from, interval to
def linear(f, x1, x2, n_from: int, n_to: int):
# define n
n = [i for i in range(n_from, n_to + 1)]
# define x1[n]
x_1 = [x1(i) for i in n]
# define x2[n]
x_2 = [x2(i) for i in n]
# output response produced by input x1
y_1 = [f(i) for i in x_1]
# output response produced by input x2
y_2 = [f(i) for i in x_2]
# sum of two output y1 and y2
y_1_2 = [y_1[i] + y_2[i] for i in range(len(y_1))]
# define x3[n] = A*x1[n] + B*x2[n]
# for simplicity make A = B = 1
x_3 = [(x_1[i] + x_2[i]) for i in range(len(x_1))]
# define output response y_3
y_3 = [f(i) for i in x_3]
isEqual = False
for i in range(len(y_3)):
if (y_3[i] == y_1_2[i]):
isEqual = True
else:
isEqual = False
if isEqual:
print('Outputs are consistent with a linear system')
else:
print('System is not linear')
# ploting stuffs
# fig, axs = plt.subplots(ncols=2,
# nrows=1,
# constrained_layout=True,
# sharey=True)
# axs[0].stem(n, y_1_2)
# axs[0].set(xlabel='n', ylabel='Output responses', title='y1[n] + y2[n]')
# axs[1].stem(n, y_3)
# axs[1].set(xlabel='n', title='y3[n]')
# fig.suptitle('Stem plots of the responses')
# plt.show()
return [n, y_1_2, y_3]
|
import random as r
guess_count = 0
result = 'false'
def easy():
even = []
for num in range(1, 20):
if num % 2 == 0:
even.append(num)
even_gen = r.choice(even)
return even_gen
def intermediate():
odd = []
for num in range(1, 20):
if num % 2 != 0:
odd.append(num)
odd_gen = r.choice(odd)
return odd_gen
def hard():
prime = []
for num in range(1, 20, + 1):
if num > 1:
for x in range(2, num):
if num % x == 0:
break
else:
prime.append(num)
prime_gen = r.choice(prime)
return prime_gen
def start():
new_guess = input(''' Ready to start? \n Please enter Y for YES and N for No: ''')
if new_guess in ('n', 'y'):
if new_guess.upper() == 'Y':
print('''
Game begins now....
''')
else:
print('Thanks for stopping by. Exiting.......')
else:
print('Value entered is invalid, want to try again?')
start()
|
#A tic - tac -toe game (using minimax algorithm)
#import clear screen function
from special_func import clear,sleep
#setup
steps_win = 3;
number_rows = 3;
number_columns = 3;
AI_player = "X";
hu_player = "O";
#global var
list_spots_origin = [];
######################
def Start(number_rows,number_columns):
#Print a board(AxB)
global list_spots_origin;
list_spots_origin = [];
for i in range(0, number_rows * number_columns):
list_spots_origin.append(i);
if (i % number_columns == 0 ) :
print("\n",end="");
print("|\t",end="");
print(i,end="\t|\t");
print("\n");
def GetAns():
#Get the step that player want
global list_spots_origin;
x = "";
while 1 == 1:
x = int(input("Nhap vi tri ban muon danh dau: "));
if x in list_spots_origin:
print("Vi tri nay da duoc danh dau!");
else:
continue;
return x;
def TakeAnsFromPlayer():
#Take the spot that player want
print("Player turn :",end="");
ans = GetAns();
return ans;
def CheckVer(kind,position):
#Check vertically
global list_spots_origin;
x = position + number_columns * (steps_win - 1);
if (x > (len(list_spots_origin) - 1)):
return False;
else:
for i in range(1,steps_win):
k = position + number_columns * i ; # k is step which we need to check
if (str(list_spots_origin[k]) != kind):
return False;
return True;
def CheckHor(kind,position):
#Check horizontal
x = position + steps_win - 1;
if (x > number_columns):
return False;
else:
for i in range(1,steps_win):
k = position + i ; # k is step which we need to check
if (str(list_spots_origin[k]) != kind):
return False;
return True;
def CheckCrsR(kind,position):
#Check cross right
x = position + (number_columns + 1) * (steps_win - 1);
if (x > (len(list_spots_origin) - 1)):
return False;
else:
for i in range(1,steps_win):
k = position + (number_columns + 1) * i ; # k is step which we need to check
if (str(list_spots_origin[k]) != kind):
return False;
return True;
def CheckCrsL(kind,position):
#Check cross left
x = position + number_rows * (steps_win - 1);
if (x > (len(list_spots_origin) - 1)):
return False;
else:
for i in range(1,steps_win):
k = position + number_rows * i ; # k is step which we need to check
if (str(list_spots_origin[k]) != kind):
return False;
return True;
def FindAvaiSpots():
#Search and put all available spots 'index
list_avai_spots = [];
for i in list_spots_origin:
if i in range(0,number_rows * number_columns + 1):
list_avai_spots.append(i)
return list_avai_spots;
def CheckWin(player):
#Check win or lose
global list_spots_origin;
flag = 1;
for i in list_spots_origin:
if (i == "X") or (i == "O"):
#vertical
if (CheckVer(i,list_spots_origin.index(i)) == True):
flag = 0;
continue;
#horizontal
if (CheckHor(i,list_spots_origin.index(i)) == True):
flag = 0;
continue;
#cross (right)
if (CheckCrsR(i,list_spots_origin.index(i)) == True):
flag = 0;
continue;
#cross (left)
if (CheckCrsL(i,list_spots_origin.index(i)) == True):
flag = 0;
continue;
if flag == 1 :
return True;
else:
return False;
def Exit():
#Game exit (RETRY?)
x = input("Do you want to try again (Y/N):");
x.upper();
if x == "Y" :
Start(number_rows,number_columns);
Process();
else:
print("Goodbye!");
sleep(2);
#some code to wait and exit :))
def AnnounceWinner(player,state):
#tell The Winner
if state == 1 :
print("{} is the winner".format(player));
Exit();
else :
print("Tie!");
Exit();
def GetMax(list_max):
Max = 0;
for i in list_max:
if list_max.index(i) % 2 == 0:
if i > Max :
Max = i;
best_index = list_max.index(i) - 1;
return best_index;
def GetMax(list_min):
Min = 20;
for i in list_min:
if list_min.index(i) % 2 == 0:
if i < Min :
Min = i;
best_index = list_min.index(i) - 1;
return best_index;
def minimax(new_board,player):
#Choose the best option to win over the hu_player
list_avai_spots = FindAvaiSpots();
moves = [];
best_move = 0;
if len(list_avai_spots) > 0 :
i = 1;
if list_avai_spots[i] not in moves:
index = list_avai_spots[1];
new_board[index] = player;
moves.append(index);
else:
++i;
flag = 1;
# if ai wins then score 10
# if human wins then score -10
# if no one wins then score 0
if CheckWin(AI_player) == True :
value = 10;
flag = 0;
else:
if CheckWin(hu_player) == True :
value = -10;
flag = 0;
else:
if (len(list_avai_spots) == 0):
value = 0;
flag = 0;
if flag == 0:
moves.append(value);
else:
moves.append(0);
if player == AI_player:
minimax(new_board,hu_player);
else :
if player == hu_player:
minimax(new_board,AI_player);
def ShowBoard(number_rows,number_columns):
#Print a board(AxB)
global list_spots_origin;
for i in range(0, number_rows * number_columns):
if (i % number_columns == 0 ) :
print("\n",end="");
print("|\t",end="");
print(list_spots_origin[i],end="\t|\t");
print("\n");
def Process():
#Call functions in order
#Change player
global list_spots_origin;
#ChangePlayer();
clear();
ShowBoard(number_rows,number_columns);
|
class Pocket:
def __init__(self, balance):
self.balance = balance
def __str__(self):
return ("Account balance : %d" % self.balance)
def deposit(self, amount):
if (type(amount) == float and amount > 0):
self.balance += amount
return True
else:
return False
def withdraw(self, amount):
if (type(amount) == float and amount > 0):
if self.balance - amount >= 0:
self.balance -= amount
return True
else:
return False
|
x = input("What is your name?\t")
print( "Hello" + " " + ( str (x) ) + " " + ( str ( len (x) ) ) )
|
# coding=utf8
import json
class MyDict(dict):
"""
A **Python** _dict_ subclass which tries to act like **JavaScript** objects, so you can use the **dot notation** (.) to access members of the object. If the member doesn't exist yet then it's created when you assign something to it. Brackets notation (d['foo']) is also possible.
"""
def __init__(self, dict_source=None, **kw):
if dict_source and isinstance(dict_source, (dict, MyDict)):
for k, v in dict_source.items():
self[k] = self._transform(v)
for key, value in kw.items():
self[key] = self._transform(value)
def _transform(self, source):
if isinstance(source, (dict, MyDict)):
return MyDict(source)
elif isinstance(source, list):
return [item for item in map(self._transform, source)]
elif isinstance(source, tuple):
result = None
for item in source:
if not result:
result = (self._transform(item),)
else:
result = result + (self._transform(item),)
return result
else:
# no need for transformation (int, float, str, set, ...)
return source
def __getattr__(self, name):
"""
Get a field "name" from the object in the form:
obj.name
"""
if name in self:
return self[name]
def __setattr__(self, name, value):
"""
Sets a field into the object in the form:
obj.name = value
"""
self[name] = self._transform(value)
def __getitem__(self, name):
"""
Get a field "key" value from the object in the form:
obj[name]
"""
return self.get(name)
def has_path(self, key):
"""
Check existence of "path" in the tree.
d = MyDict({'foo': {'bar': 'baz'}})
d.has_path('foo.bar') == True
**It only supports "dot-notation" (d.foo.bar)
"""
if super(MyDict, self).__contains__(key):
return True
else:
parts = str(key).split('.')
if len(parts) > 1:
k = '.'.join(parts[:1])
return self[k].has_path('.'.join(parts[1:]))
else:
return super(MyDict, self).__contains__(key)
def get(self, key, default=None):
if key in self:
return super(MyDict, self).get(key, default)
else:
parts = str(key).split('.')
if len(parts) > 1:
try:
return self.get(parts[0]).get('.'.join(parts[1:]))
except Exception:
return None
else:
return super(MyDict, self).get(key, default)
def to_json(self):
"""Returns a JSON-like string representin this instance"""
return json.dumps(self.get_dict())
def get_dict(self):
"""Returns a <dict> of the <MyDict> object"""
# d_ = {}
def _get_dict(member):
if isinstance(member, (dict, MyDict)):
d = {}
for k, v in member.items():
d[k] = _get_dict(v)
return d
elif isinstance(member, (list,)):
lst = []
for a in member:
lst.append(_get_dict(a))
return lst
elif isinstance(member, (tuple,)):
tpl = tuple()
for a in member:
tpl = tpl + (_get_dict(a),)
return tpl
elif isinstance(member, (set,)):
st = set([])
for a in member:
st.add(_get_dict(a))
return st
else:
return member
# d_.update(**self)
# return d_
return _get_dict(self)
@staticmethod
def from_json(json_source):
"""
Returns a "MyDict" instance from a:
JSON string
<file>-like containing a JSON string
"""
if isinstance(json_source, (str, bytes)):
# decode bytes to str
if isinstance(json_source, bytes):
json_source = json_source.decode('utf8')
load_method = 'loads'
elif hasattr(json_source, 'read'):
json_source.seek(0)
load_method = 'load'
# json_obj = json.load(json_source)
# json_obj = json.loads(json_source)
json_obj = getattr(json, load_method)(json_source)
return MyDict(json_obj)
|
#encoding=utf-8
class Solution:
'''
@param integer[] nums
@return integer
'''
# del nums[i] is o(n) 时间复杂度
def removeDuplicates1(self, nums):
i = 0
while i < (len(nums) - 1):
if nums[i] is nums[i+1]:
del nums[i]
else:
i += 1
return len(nums)
def removeDuplicates(self, nums):
if not nums:
return 0
tail = 0
for i in range(1, len(nums)):
if nums[tail] != nums[i]:
tail += 1
nums[tail] = nums[i]
return tail + 1
s = Solution()
print("Len of unduplicated nums is %d" %s.removeDuplicates([]))
|
#encoding=utf-8
"""
# Author: Acer
# Created Time: 星期二 6/ 2 23:20:05 2015
# File Name: 061-RotateList.py
# Description:
# @param:
# @return:
"""
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def rotateList(self, head, k):
if not head or k == 0:
return head
# 1.计算链表长度
# 2.找到队尾指针
p = head
lenOfList = 0
while p.next:
lenOfList += 1
p = p.next
tail = p
lenOfList += 1
k %= lenOfList
if k == 0:
return head
# 寻找新的首尾节点
newTail = head
for i in range(lenOfList - k - 1):
newTail = newTail.next
newHead = newTail.next
# 旋转的节点指向空,队尾节点指向newHead
tail.next = head
newTail.next = None
head = newHead
return head
n = ListNode(1)
n2 = ListNode(2)
n.next = n2
s = Solution()
print(s.rotateList(n, 1).val)
|
import numpy as np
import sympy as sp
def mprint(A):
for i in A:
print(i)
print('\n')
# Dot product function from scratch
def dprod(v1, v2):
return sum((a * b for a, b in zip(v1, v2)))
# Write a function to do matrix vector multiplication from scratch:
def mvprod(M, v):
result = []
for row in M:
element = sum((a * b for a, b in zip(row, v)))
result.append(element)
return result
# Write a function that multiplies matrices
def mprod(M, N):
mrows = len(M)
ncols = len(N[0])
result = [[] for i in range(mrows)]
for i in range(mrows):
for j in range(ncols):
row = M[i]
col = [nrow[j] for nrow in N]
element = sum((r * c for r, c in zip(row, col)))
result[i].append(element)
return result
# transpose a matrix:
def transpose(M):
cols = len(M[0])
result = []
for i in range(cols):
tcol = [row[i] for row in M]
result.append(tcol)
return result
# Rotate a matrix 90 degrees clockwise (using numpy)
def rot90cw(M):
nM = np.array(M)
return np.flip(nM, 0).T
# Rotate a matrix 90 degrees ccw
def rot90ccw(M):
numcols = len(M[0])
temp = []
final = []
for i in range(numcols):
temp.append([row[i] for row in M])
numrows = len(temp)
for j in range(numrows):
final.append(temp[numrows - 1 - j])
return final
# element wise sum of two vectors
# element wise difference of two vectors.
if __name__ == '__main__':
# create a new ndarray from a nested list
A = [[1, 2, 3],
[2, 4, 6],
[1, 1, 1]]
B = [[1, 2],
[1, 1],
[1, 3]]
x = [1, 2]
y = [1, 2, 3]
z = [1, 1, 1]
print("dot product using numpy and my function: ")
print(dprod(y, z))
print(np.dot(y, z), '\n')
print("Matrix vector multiplication: ")
mprint(mvprod(B, x))
print(np.array(B) @ np.array(x), '\n')
print("Matrix multiplication :")
mprint(mprod(A, B))
print(np.array(A) @ np.array(B), '\n')
print("Transpose with numpy and my function:")
mprint(transpose(B))
print(np.transpose(np.array(B)), '\n')
print("rotate matrix 90 degrees clockwise: ")
mprint(B)
mprint(rot90cw(B))
# counter clock-wise
print("rotate matrix 90 degrees counter-clockwise: ")
mprint(B)
mprint(rot90ccw(B))
# matrix creation with numpy (random, zeros, ones, reshape)
print("practice with ndarray creation using random, zeros, ones and reshape")
C = np.random.randint(1, 3, 4).reshape(2, 2)
mprint(C)
D = np.zeros((4, 4))
mprint(D)
# show that numpy.reshape and ndarray.reshape both return reshaped references to the original object, not a copy.
E = D.reshape((2, 8))
print(E, '\n')
E[0, 0] = 1
print(E, '\n')
print(D, '\n')
F = np.reshape(E, (2, 8))
print(F, '\n')
F[0, 0] = 2
print(D, '\n')
# finding maximum and minimum elements:
X = np.random.randint(1, 11, 25).reshape(5, 5)
print(X)
print("The maximum value of any element in X is {}, and occurs at index {}.".format(np.max(X), np.argmax(X)))
print("find the maximum sum along rows and columns")
rowsums = np.array([sum(row) for row in X])
colsums = np.array([sum(X[:, i]) for i in range(len(X[0]))])
print("max row sum: {}".format(np.max(rowsums)))
print("max col sum: {} \n".format(np.max(colsums)))
print("practice appending rows and columns, using the sums above")
print(X.shape)
print(colsums.shape)
print(rowsums.shape)
colsums = colsums.reshape(1, 5)
rowsums = rowsums.reshape(5, 1)
# all_data = np.append(X, rowsums, axis=1)
all_data = np.append(X, colsums, axis=0)
print("X with sums appended as an additional row or column:")
print(all_data, '\n')
# Matrix Powers
print("X^2= \n", np.linalg.matrix_power(X, 2), '\n')
# practice slicing lists (1-D) (works the same for Numpy ndarrays)
list1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
sublist = list1[0:5]
# slicing lists in 2-D (must use list comprehension, as 2-D slicing is unavailable for lists)
list2 = [list1, list1, list1]
list3 = [row[0:3] for row in list2]
print(list3, '\n')
# practice slicing 2-D with Numpy ndarrays (recreate list3 but with better slicing capabilities)
list4 = np.array(list2)
list3 = list4[0:2, 0:3]
print(list3, '\n')
# ***NOTE*** that using slicing in numpy returns a view of the original ndarray. Any changes made to the slice
# will be reflected in the original. In order to avoid this, you must make a copy.
# finding eigenvalues and vectors with numpy
A = np.array([[-2, -9],
[1, 4]])
print(A)
vals, vecs = np.linalg.eig(A)
print("numpy eigenvalues: {}".format(vals))
print("numpy eigenvects: {} \n".format(vecs))
A = sp.Matrix(A)
print(type(A))
vals = A.eigenvals() # dictionary of key value {pairs eigenvalue:algebraic multiplicity}
vects = A.eigenvects() # list of tuples of form (egenvalue, algebraic multiplicity, [eigenvectors]
print(vals)
print(vects)
print("eigenvector: \n ", vects[0][2])
|
#pascal naming convention
class Point:
#constructor
def __init__(self, x, y):
self.x = x
self.y = y
def move(self):
print('move')
def draw(self):
print('draw')
#creating object
point1 = Point(10,20)
#point1.x = 10;
print(point1.x)
point1.draw()
|
numbers = [5, 2, 1, 9, 8, 9]
uniques = []
for number in numbers:
if number not in uniques:
uniques.append(number)
print(uniques)
# numbers = [5, 2, 1, 9, 8, 9]
# numbers.sort()
# ctr =1
# for i in numbers:
# if numbers[ctr] == i:
# numbers.remove(i)
# ctr += 1
# print(numbers)
|
"""
checkout the decorators function and syntax "at @"
"""
example_user = {'username': "randomuser", "access_level": "admin"}
"""
Example 1 approching decorators secure password
"""
# def get_admin_password():
# return 12345
# def secure_function(secure_func):
# if example_user["access_level"] == 'admin':
# return secure_func
# now set get_admin_password = get_admin_password(secure_function)
# get_admin_password = secure_function(get_admin_password)
# print(get_admin_password) # return Noun, now we are safe and good to go
# if not it will run simply to get get_admin_password(), basically just print out
# print(get_admin_password()) # return 12345
"""
Example 2 apprched securing password
"""
# def get_admin_password():
# return 12345
# def make_secure(secure_func):
# def secure_function():
# if example_user["access_level"] == 'admin':
# return secure_func()
# else:
# return f'No admin permission for {example_user["username"]!r}.'
# return secure_function
# get_admin_password = make_secure(get_admin_password)
# print(get_admin_password())
"""
Example 3 refactored example 2
if we have make_secure() function first we can use @make_secure to get_admin_password()
and we are no longer needed "get_admin_password = make_secure(get_admin_password)"
"""
import functools
def make_secure(secure_func):
#wrapper to call get_admin_password.__name__ == get_admin_password, and != secure_function
@functools.wraps(secure_func)
def secure_function(*args, **kwargs): # option for decorators with parameters taking an argument
if example_user["access_level"] == 'admin':
return secure_func(*args, **kwargs)
else:
return f'No admin permission for {example_user["username"]!r}.'
return secure_function
#decorator
@make_secure
def get_admin_password(panel):
# return 12345 # original
#added
if panel == "admin":
return 12345
#added
elif panel == "testering":
return "super_dooper_secure_password"
print(get_admin_password('testering'))
|
# Library System - a small library system to describe and keep track of books using dictionaries.
# Name: Ruarai Kirk
# Student ID: D17125381
# Course: DT265A
# Below are the specific functions of the Library System:
# A Python function that prints details about all the books in the library.
def print_all(dict):
print("There are", len(dict),"titles in stock.")
print("The stock available is as follows:")
for key, val in dict.items():
print("ISBN:", key, "Title:", val[0], "Author:", val[1], "Quantity in stock:", val[2])
return
# A Python function that adds a book to the library
def add_stock(key,details,quantity,dict):
# The function takes the book isbn, details (as a list) and quantity purchased, as well as the library dictionary name
if len(key) != 13: # If ISBN number is not 13 digits, send error message and exit
print("ISBN invalid!")
return
else: # Otherwise, enter if-else loop
if key in dict: # If ISBN already in the library, just update the quantity
dict[key][2] += quantity
else: # Else add book to the library as a new item in the dictionary
dict[key] = details
return
# A Python function that checks out a book for loaning
def check_out(key, dict):
# The function takes the book isbn and the library dictionary name
if len(key) != 13: # If ISBN number is not 13 digits, send error message and exit
print("ISBN invalid!")
return
else:
if key in dict and dict[key][2] != 0: # If ISBN valid, and there are titles in stock
dict[key][2] -= 1 # Decrement quantity value and return message, stating success of operation and stock remaining
print("Book checked out! There are ", dict[key][2], " copies of this title left in stock.")
elif key not in dict: # If book ISBN not valid/does not exist, return error message
print("Book not valid...")
elif dict[key][2] == 0: # If book out of stock, return message
print("This book is out of stock...")
else:
return
# A Python function that searches the library for a book by the book "title" and returns the book’s ISBN
def title_search(title, dict):
for key in dict.keys():
if dict[key][0] == title:
print("The ISBN for book titled", title, "is", key)
break
#elif dict[key][0] != title:
# continue
#else:
# return
# Library
# The library is implemented as a dictionary, with the keys being the book ISBN (13-digits) and the values being the
# details (such as title, author and quantity) implemented in a list
library = {
"9780132805575" : ["The Practice of Computing Using Python", "William Punch", 0],
"9780132737968" : ["Digital Fundamentals", "Thomas Floyd", 1],
"9781118063330" : ["Operating System Concepts", "Abraham Silberschatz", 1]
}
# User interface presented as a list of options
print("""
Library System Options:
-----------------------------
1: View details of all books in library
2: Add new stock or update quantity
3: Check out a book on loan
4: Search the library for a title and retrieve title ISBN
5: Exit Program
""")
option = int(input("Enter an option: ")) # Ask for user input
while option != 0: # While loop which process option input
if option == 1: # Run 'view all details' function
print_all(library)
elif option == 2: # Run add stock (or update quantity)' function
in1 = input("To add book, please enter the book 13-digit ISBN: ")
in2 = str(input("Please enter book title: "))
in3 = str(input("Please enter author: "))
in4 = int(input("Please enter quantity purchased: "))
details = [in2, in3, in4]
add_stock(in1, details, in4, library)
print_all(library)
elif option == 3: # Run 'check out for loan' function
in1 = input("To search for a book and borrow 1 copy, please enter the book's 13-digit ISBN: ")
check_out(in1, library)
elif option == 4: # Run 'search the library for a title and retrieve title ISBN' function
in1 = input("To search for a book and retrieve it's ISBN, please enter the book's title: ")
title_search(in1, library)
elif option == 5: # Terminate program
break
elif option != 0: # If input invalid return error message and ask for input again
print("You did not enter a valid number.")
option = int(input("Enter an option: "))
# Notes for further improvement:
# 1. When searching for a book's isbn using the title, the title has to be inputted exactly (case sensitive etc.)
# To improve this, I would implement an all lower case value in the library, and strip the user input of case using the
# ascii 'lowercase method.
# 2. The title search function only returns a value when successful. This should be amended to return a message with a
# negative value or error message if required.
# 3. At present, the above library system only records number of books 'in stock', and not total quantity. The above
# should be amended to show this by including another value in the value list.
|
filename = "input.txt"
data = []
data_part2 = []
filehandle = open(filename, 'r')
while True:
line = filehandle.readline()
if not line:
break
line = line.strip()
parts = line.split(":")
constraints = parts[0].split(" ")
occurence_counts = constraints[0].split("-")
min_count = int(occurence_counts[0], base=10)
max_count = int(occurence_counts[1], base=10)
letter = constraints[1].strip()
password = parts[1].strip()
policy = {
"letter": letter,
"min_count": min_count,
"max_count": max_count,
"password": password
}
policy_2 = {
"letter": letter,
"position_1": min_count,
"position_2": max_count,
"password": password
}
data.append(policy)
data_part2.append(policy_2)
def is_valid_password(policy):
password = policy["password"]
letter = policy["letter"]
min_count = policy["min_count"]
max_count = policy["max_count"]
count = password.count(letter)
return count >= min_count and count <= max_count
def is_valid_password_v2(policy):
password = policy["password"]
letter = policy["letter"]
position_1 = policy["position_1"] - 1
position_2 = policy["position_2"] - 1
chars = list(password)
return (chars[position_1] == letter and chars[position_2] != letter) or (chars[position_1] != letter and chars[position_2] == letter)
num_valid = 0
for policy in data:
is_valid = is_valid_password(policy)
if is_valid:
num_valid = num_valid + 1
print("part 1: ")
print("number of valid passwords: ", num_valid)
print()
num_valid = 0
for policy in data_part2:
is_valid = is_valid_password_v2(policy)
if is_valid:
num_valid = num_valid + 1
print("part 2: ")
print("number of valid passwords: ", num_valid)
|
""" loop2 """
N = 2
while N <= 10:
print(N)
N = N + 2
print("Goodbye!")
|
class Student:
def __init__(self,roll,name):
self.roll=roll
self.age="16"
self.name=name
def printdetails(self):
print("student name "+self.name)
print("student age "+self.age)
print("student roll no. "+self.roll)
S1 = Student("28","Simar")
S1.printdetails()
S2 = Student("41","Zoyaa")
S2.printdetails()
|
print "How old are you?",
age = raw_input(34)
print "How tall are you?",
height = raw_input("6'2") #add '6\'2"' to make feet and inces show
print "How much do you weigh?",
weight = raw_input(185)
print "So, you're %r old, %r tall, and %r heavy." % (34, "6'2", 185) #why can't I list the height like before??
|
def get_length(dna):
""" (str) -> int
Return the length of the DNA sequence dna.
>>> get_length('ATCGAT')
6
>>> get_length('ATCG')
4
"""
return len(dna)
def is_longer(dna1, dna2):
""" (str, str) -> bool
Return True if and only if DNA sequence dna1 is longer than DNA sequence
dna2.
>>> is_longer('ATCG', 'AT')
True
>>> is_longer('ATCG', 'ATCGGA')
False
"""
return len(dna1) > len(dna2)
def count_nucleotides(dna, nucleotide):
""" (str, str) -> int
Return the number of occurrences of nucleotide in the DNA sequence dna.
>>> count_nucleotides('ATCGGC', 'G')
2
>>> count_nucleotides('ATCTA', 'G')
0
"""
num_nucleotides = 0
for char in dna:
if char in nucleotide:
num_nucleotides = num_nucleotides + 1
return num_nucleotides
def contains_sequence(dna1, dna2):
""" (str, str) -> bool
Return True if and only if DNA sequence dna2 occurs in the DNA sequence
dna1.
>>> contains_sequence('ATCGGC', 'GG')
True
>>> contains_sequence('ATCGGC', 'GT')
False
"""
return dna2 in dna1
def is_valid_sequence(dna):
""" (str) -> bool
Return True if and only if the DNA sequence is valid (i.e. contains no characters other than 'A', 'T', 'C', 'G'.
>>> is_valid_sequence('ATTCG')
True
>>> is_valid_sequence('ABCG')
False
"""
valid = True
for char in dna:
if not char in 'ATCG':
valid = False
return valid
def is_valid_sequence(dna):
""" (str) -> bool
Return True if and only if the DNA sequence is valid (i.e. contains no characters other than 'A', 'T', 'C', 'G'.
>>> is_valid_sequence('ATTCG')
True
>>> is_valid_sequence('ABCG')
False
"""
valid = True
for char in dna:
if not char in 'ATCG':
valid = False
return valid
def insert_sequence(dna1, dna2, index):
""" (str, str, int) -> str
Return the DNA sequence obtained by inserting the second DNA sequence into the first DNA sequence at the given index.
>>> insert_sequence('ATCG', 'ATCG', 2)
'ATATCGCG'
>>> insert_sequence('ATCG', 'ATCG', -1)
'ATCATCGG'
"""
new_sequence = dna1[:index] + dna2[:] + dna1[index:]
return new_sequence
def get_complement(nucleotide):
""" (str) -> str
Return the nucleotide's complement. (i.e. A complements T, C complements G, and vice versa).
>>> get_complement('A')
'T'
>>> get_complement('G')
'C'
"""
if nucleotide in 'A':
print ('T')
elif nucleotide in 'T':
print ('A')
elif nucleotide in 'C':
print ('G')
elif nucleotide in 'G':
print ('C')
def get_complementary_sequence(dna):
""" (str) -> str
Return the complementary nucleotides for the DNA sequence. (i.e. A complements T, C complements G, and vice versa).
>>> get_complementary_sequence('ATCG')
'TAGC'
>>> get_complementary_sequence('GCTA')
'CGAT'
"""
new_sequence = ''
for char in dna:
if char in 'A':
new_sequence = new_sequence + 'T'
if char in 'T':
new_sequence = new_sequence + 'A'
if char in 'C':
new_sequence = new_sequence + 'G'
if char in 'G':
new_sequence = new_sequence + 'C'
return new_sequence
|
#!/usr/bin/python3
class Me():
def __init__(self, first, last, height, weight, age):
self.first = first
self.last = last
self.height = height
self.weight = weight
self.age = age
# def __str__(self):
def loose_weight(self):
return self.weight - 5
new_me = Me("Michael", "Lennerblom", "5.6", 150, 43)
print(new_me.loose_weight())
|
# encoding=utf-8
import random
import matplotlib.pyplot as plt
import numpy as np
import math
SAMPLING_NUM = 10000
CANDIDATE_NUM = 20
def check_success(candidates, stop_time):
max_in_observation = max(candidates[:stop_time])
chosen = 0
for i in range(stop_time, len(candidates)):
if candidates[i] > max_in_observation:
chosen = candidates[i]
break
max_in_all = max(candidates)
if math.isclose(chosen, max_in_all):
return True
return False
def main():
lifes = [[random.uniform(0, 1) for i in range(CANDIDATE_NUM)] for j in range(SAMPLING_NUM)]
success_count = [0] * CANDIDATE_NUM
for stop_time in range(1, CANDIDATE_NUM):
for life in lifes:
if check_success(life, stop_time):
success_count[stop_time] += 1
cherry = np.argmax(success_count) + 1
print('choose between the %d and %d candidates after %d life simulation' % (cherry, CANDIDATE_NUM, SAMPLING_NUM))
print('standard answer is:', int(CANDIDATE_NUM / math.e) + 1)
plt.plot(range(1, CANDIDATE_NUM), success_count[1:CANDIDATE_NUM], 'ro-', linewidth=2.0)
plt.show() # Could not display in Linux
if __name__ == '__main__':
main()
|
#!/usr/bin/python
'''
(1) as an exercise, take a list of random integers and sort them into ascending
order using your own code
if you cannot think of a way to sort the list into order using python that
you know, do an internet search for "bubble sort algorithm"
the code below gets you started with a list of random unsorted numbers
(2) make a copy of the unsorted list and sort it using the builtin .sort() function
then write code to compare element by element to check that the two lists are identical
(3) run the script several times to check that:
(a) the starting random numbers list produced by the randint function is
different each time and
(b) your sorting method always produces the same order as the built in .sort method
'''
#exercise: sort a list of random integers by swapping elements
import random
#this creates a list of random integers
unsorted = [random.randint(0,10) for x in range(100)]
print unsorted
|
#!/usr/bin/python
'''
read in every line from a csv file into a list
calculate the sum of each column
'''
import sys
inp = sys.argv[1]
data = []
f = open(inp)
#read in column headings
header = f.readline().strip().split(',')
for line in f:
#split into columns
cols = line.strip().split(',')
#convert data into floats
for i,val in enumerate(cols):
cols[i] = float(val)
#append to list of data
data.append(cols)
f.close()
data[row_number][col_number]
total = [0.0] * len(header)
for row in data:
for i,val in enumerate(row):
total[i] += val
for i,x in enumerate(total):
print header[i],total[i],total[i]/len(data)
#calculate the sum of each column and display it
for i,col_name in enumerate(header):
total = 0.0
for row in data:
total += row[i]
print col_name,total,total/len(data)
|
# Faça um programa que percorre uma lista com o seguinte formato:
# [['Brasil', 'Italia', [10, 9]], ['Brasil', 'Espanha', [5, 7]], ['Italia', 'Espanha', [7,8]]].
# Essa lista indica o número de faltas que cada time fez em cada jogo. Na lista acima, no jogo entre
# Brasil e Itália, o Brasil fez 10 faltas e a Itália fez 9.
# O programa deve imprimir na tela:
# a) o total de faltas do campeonato
# b) o time que fez mais faltas
# c) o time que fez menos faltas
lista = [['Brasil', 'Italia', [10, 9]], [
'Brasil', 'Espanha', [5, 7]], ['Italia', 'Espanha', [7, 8]]]
faltasBrasil = int(lista[0][2][0]) + int(lista[1][2][0])
faltasItalia = int(lista[0][2][1]) + int(lista[2][2][0])
faltasEspanha = int(lista[2][2][1]) + int(lista[1][2][1])
def totalFaltas():
faltaJogo1 = int(lista[0][2][0]) + int(lista[0][2][1])
faltaJogo2 = int(lista[1][2][0]) + int(lista[1][2][1])
faltaJogo3 = int(lista[2][2][0]) + int(lista[2][2][1])
totalJogos = faltaJogo1 + faltaJogo2 + faltaJogo3
print(f'O total de faltas dos 3 jogos é {totalJogos}')
def maisFaltas():
if faltasBrasil > faltasItalia and faltasBrasil > faltasEspanha:
print(
f'O Brasil é o país com mais faltas, tendo um total de {faltasBrasil}')
elif faltasItalia > faltasEspanha and faltasItalia > faltasBrasil:
print(
f'A Italia é o país com mais faltas, tendo um total de {faltasItalia}')
elif faltasEspanha > faltasBrasil and faltasEspanha > faltasItalia:
print(
f'A Espanha é o país com mais faltas, tendo um total de {faltasEspanha}')
elif faltasBrasil == faltasItalia:
print(
f'O número de faltas entre Itália e Brasil é o mesmo: um total de {faltasBrasil}')
elif faltasBrasil == faltasEspanha:
print(
f'O número de faltas entre Espanha e Brasil é o mesmo: um total de {faltasBrasil}')
elif faltasEspanha == faltasItalia:
print(
f'O número de faltas entre Itália e Espanha é o mesmo: um total de {faltasEspanha}')
def menosFaltas():
if faltasBrasil < faltasItalia and faltasBrasil < faltasEspanha:
print(
f'O Brasil é o país com menos faltas, tendo um total de {faltasBrasil}')
elif faltasItalia < faltasEspanha and faltasItalia < faltasBrasil:
print(
f'A Italia é o país com mais faltas, tendo um total de {faltasItalia}')
elif faltasEspanha < faltasBrasil and faltasEspanha < faltasItalia:
print(
f'A Espanha é o país com mais faltas, tendo um total de {faltasEspanha}')
elif faltasBrasil == faltasItalia:
print(
f'O número de faltas entre Itália e Brasil é o mesmo: um total de {faltasBrasil}')
elif faltasBrasil == faltasEspanha:
print(
f'O número de faltas entre Espanha e Brasil é o mesmo: um total de {faltasBrasil}')
elif faltasEspanha == faltasItalia:
print(
f'O número de faltas entre Itália e Espanha é o mesmo: um total de {faltasEspanha}')
totalFaltas()
maisFaltas()
menosFaltas()
|
# Define a procedure, biggest, that takes three
# numbers as inputs and returns the largest of
# those three numbers.
# 1 method
def bigger(a,b):
if a>b:
return a
return b
def biggest(a,b,c):
return bigger(bigger(a,b),c)
# 2 method
### return max(a,b,c)
# 3 method
''' if b<a or c<a:
if c>b:
if a>c:
return a
else:
return c
else:
if a>b:
return a
else:
return b
else:
if b>c:
return b
else:
return c'''
print biggest(3, 6, 9)
print biggest(6, 9, 3)
print biggest(9, 3, 6)
print biggest(3, 3, 9)
print biggest(9, 3, 9)
|
import numpy as np
# Manejo de arrays con numpy
# Arreglo desde el 5 hasta el 19 con salto de 3
arreglo_uno = np.arange(5, 20, 3)
print("Arreglo general de salto de 3:\n {}\n\n".format(arreglo_uno))
# Matriz de ceros 10x2
matriz_ceros = np.zeros(shape=(10, 2))
print("Arreglo ceros 10x2:\n {}\n\n".format(matriz_ceros))
# Matriz de unos de 5x4
matriz_unos = np.ones(shape=(5, 4))
print("Matriz unos 5x4:\n {}\n\n".format(matriz_unos))
# Números aleatorios, 50 número entre 0 y 99
vector_aleatorios = np.random.randint(0, 100, 50)
print("50 npumeros aleatorios:\n {}\n\n".format(vector_aleatorios))
# Posición del valor máximo del arreglo
print("Posición del valor máximo del arreglo: \n{}\n\n".format(
vector_aleatorios.argmax()))
# Valor máximo del arreglo
print("Número mayor del arreglo: \n{}\n\n".format(vector_aleatorios.max()))
# Posición del valor mínimo del arreglo
print("Posición del valor mínimo del arreglo: \n{}\n\n".format(
vector_aleatorios.argmin()))
# Valor mínimo del arreglo
print("Número menor del arreglo: \n{}\n\n".format(vector_aleatorios.min()))
# Forma del arreglo
print("Forma del arreglo: \t{}\n\n".format(vector_aleatorios.shape))
# Transformar forma del arreglo
matriz_aleatorios = vector_aleatorios.reshape(10, 5)
print("Transformación forma del arreglo:\n{}\n\n".format(matriz_aleatorios))
# Acceder a un elemento del arreglo
print("Acceder a un elemento del arreglo:\n{}".format(matriz_aleatorios[0,1]))
print("{}\n\n".format(matriz_aleatorios[0][3]))
|
def make_incrementor(n):
return lambda x: x + n
x = int(raw_input("Please enter an integer: "))
f = make_incrementor(x)
print f(0)
print f(1)
|
from contextlib import ExitStack
from itertools import chain, zip_longest
from typing import Generator, List
def merge_sorted_files(file_list: List) -> Generator[int, None, None]:
"""Generator that merge two lists"""
with ExitStack() as stack:
files = [stack.enter_context(open(fname)) for fname in file_list]
file1, file2 = files[0].readlines(), files[1].readlines()
try:
for element in (
element for element in chain(*zip_longest(file1, file2)) if element
):
yield int(element.strip())
except ValueError:
print("Files should have only integers")
|
import turtle as t
from random import randint as rint
t.shape("turtle")
t.pensize(5)
t.colormode(255)
t.bgcolor("black")
t.tracer(False)
for x in range(700):
t.color(rint(0,255),rint(0,255),rint(0,255))
t.circle(2*(1+x/4),5)
t.speed(20)
t.tracer(True)
|
""""
Module 07 - My Web Scraping learning example
"""
import requests
from bs4 import BeautifulSoup
class WebScrap:
""" This example parses Quotes from http://quotes.toscrape.com/ """
def __init__(self, arg_url):
self.url = arg_url
self.bs_html = BeautifulSoup(requests.get(self.url).text, 'lxml')
def get_pretty_soup(self):
print(self.bs_html.prettify())
def get_by_tag(self):
# Get by using tag-to-tag method (first entry of tag)
print('Get by tag-to-tag:\t', self.bs_html.div.div.a.text)
# Get a child by index from list of elements
print('Get by index:\t\t', self.bs_html.head.contents[3].text)
def find_div(self):
print('Get by find(tag):\t', self.bs_html.find('div').div.a.text)
def get_by_class(self):
# header = self.bs_html.find_all('div', class_='col-md-8')
print('Get by find(class):\t', self.bs_html.find(class_="col-md-8").a.text)
def get_quotes(self):
""" Get all quotes Method from http://quotes.toscrape.com/"""
for quote in self.bs_html.find_all('span', class_='text'):
print('\t', quote.text)
def get_quotes_list(self):
lst_quotes = [quote.text for quote in self.bs_html.find_all('span', class_='text')]
return lst_quotes
if __name__ == "__main__":
# print("Hello Gold")
cls_scrap = WebScrap('http://quotes.toscrape.com/')
# cls_scrap.get_pretty_soup()
cls_scrap.get_by_tag()
cls_scrap.find_div()
cls_scrap.get_by_class()
cls_scrap.get_quotes()
print('Print from list:', cls_scrap.get_quotes_list()[0])
|
str_var='MyString'
int_var = 1
fl_var = 12.5
print('Variable name: "{0}", value: "{1}", type:{2}'.format('str_var', str_var, type(str_var)))
print('Variable name: "{0}", value: "{1}", type:{2}'.format('int_var', int_var, type(int_var)))
print('Variable name: "{0}", value: "{1}", type:{2}'.format('fl_var', fl_var, type(fl_var)))
print(f'Variable name: "str_var", value: "{str_var}", type: "{type(str_var)}"')
|
"""
LEGB
Local, Enclosing, Global, Built-In
Decoration Demonstration from lesson
"""
from datetime import datetime
from functools import wraps
from time import sleep
#### Example 1
print('========= Example 1')
def my_decorator(func):
print('Come to decor=', func)
@wraps(func)
def wrapper(*args, **kwargs):
print('Params came to wrapper()=', args, kwargs)
print("This executed before function: {}".format(func.__name__))
result_of_execution = func(*args, **kwargs)
print('Result of func exec=', result_of_execution)
print("This executed after function: {}".format(func.__name__))
return result_of_execution
return wrapper
@my_decorator
def my_f(a, b):
print('Func begin:')
print('', a)
print('', b)
return 'Function execute complete'
my_f("A", "B")
#### Example 2
print()
print('========= Example 2')
def my_timer(msg):
# Executed only in @decorator init before function
print('## Begin my_timer Decorator creator')
print(' Come to Decor creator arg: msg=', msg)
def decorator(func):
print(' Come to decorator arg=', func)
def wrapper(*args, **kwargs):
print('#### Begin wrapper')
print(' Params came to wrapper, *args, **kwarg=', args, kwargs)
t1 = datetime.now()
res = func(*args, **kwargs)
print("{} {}".format(msg, datetime.now() - t1))
return res
return wrapper
print(' Decorator created, return decorator=', decorator)
return decorator
@my_timer("Execution took: ")
def test_2(msg):
"""This function returns Hello world"""
sleep(1)
return msg
@my_timer("BlaBlaBla: ")
def test(msg):
"""This function returns Hello world"""
sleep(1)
return msg
test("Function: test")
test_2("Function: test_2")
|
isbn = [9, 7, 8, 0, 9, 2, 1, 4, 1, 8]
loop_count = 0
while loop_count < 3:
num = int(input())
isbn.append(num)
loop_count += 1
count = 0
for x in range(0, len(isbn)):
if count % 2 == 1:
isbn[x] *= 3
count += 1
isbn_val = 0
for x in range(0, len(isbn)):
isbn_val += isbn[x]
print("The 1-3-sum is " + str(isbn_val))
|
def snakes_ladders():
pos = 0
while pos != 100:
roll = int(input())
pos += roll
if roll == 0:
return "You Quit!"
if pos == 54:
pos = 19
if pos == 90:
pos = 48
if pos == 99:
pos = 77
if pos == 9:
pos = 34
if pos == 40:
pos = 64
if pos == 67:
pos = 86
if pos > 100:
pos -= roll
print("You are now on square {sqr}".format(sqr=pos))
if pos == 100:
return "You win"
print(snakes_ladders())
|
def sum_to_ten():
die1 = int(input())
die2 = int(input())
if die1 > 9:
die1 = 9
if die2 > 9:
die2 = 9
correct = 0
for x in range(1, die1 + 1):
for i in range(1, die2 + 1):
if x + i == 10:
correct += 1
total = "There are " + str(correct) + " ways to get the sum 10."
if correct == 1:
total = "There is 1 way to get the sum 10."
return total
print(sum_to_ten())
|
'''Convert file sizes to human-readable form.
Available functions:
approximate_size(size, a_kilobyte_is_1024_bytes)
takes a file size and returns a human-readable string
Examples:
>>> approximate_size(1024)
'1.0 KiB'
>>> approximate_size(1000, False)
'1.0 KB'
'''
SUFFIXES = {1000: ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
1024: ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']}
def approximate_size(size, a_kilobyte_is_1024_bytes=True, newsuffix=None, withsuffix=True):
'''Convert a file size to human-readable form.
Keyword arguments:
size -- file size in bytes
a_kilobyte_is_1024_bytes -- if True (default), use multiples of 1024
if False, use multiples of 1000
Returns: string
'''
if size < 0:
raise ValueError('number must be non-negative')
if newsuffix:
return approximate_size_specific(size, newsuffix, withsuffix)
multiple = 1024 if a_kilobyte_is_1024_bytes else 1000
for suffix in SUFFIXES[multiple]:
size /= multiple
if size < multiple:
if withsuffix:
return '{0:.2f} {1}'.format(size, suffix)
else:
return size
raise ValueError('number too large')
def approximate_size_specific(size, newsuffix, withsuffix=True):
"""
converts a size in bytes to a specific suffix (like GB, TB, TiB)
"""
for multiple in SUFFIXES:
for suffix in SUFFIXES[multiple]:
if suffix.lower() == newsuffix.lower():
power = SUFFIXES[multiple].index(suffix)
newsizeint = float(size) / (multiple ** float(power+1))
if withsuffix:
return '{0:.2f} {1}'.format(newsizeint, suffix)
else:
return newsizeint
return -1
def convert_size(dsize, newsuffix, withsuffix=True):
'''Convert a file size like 8TB to another size
Keyword arguments:
size -- file size in bytes
newsuffix -- the suffix to change it to
withsuffix -- return size with new suffix, otherwise returns just
the number
Returns: a new size
'''
newsize = 0
foundmult = 0
power = 0
foundsuffix = 0
for multiple in SUFFIXES:
for suffix in SUFFIXES[multiple]:
if suffix in dsize:
foundmult = multiple
foundsuffix = suffix
power = SUFFIXES[multiple].index(suffix) + 1
size = dsize.replace(foundsuffix, "").strip()
size = float(size)
newsize = size * (foundmult ** power)
newsizes = approximate_size_specific(newsize, newsuffix)
if withsuffix:
return newsizes
else:
return float(newsizes.replace(newsuffix, ""))
#if newsize > 0:
#print "Old Size: %s" % dsize
#print "Num Size: %d" % size
#print "New Size: %d" % newsize
#print "New Size: %s" % newsizes
#print "Converted back: %s" % approximate_size(newsize, True if foundmult == 1024 else False)
if __name__ == '__main__':
print(approximate_size(1000000000000, False))
print(approximate_size(1000000000000))
# Copyright (c) 2009, Mark Pilgrim, All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS'
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
|
from matplotlib import pyplot as plt
for i in range(0,10):
plt.plot([0,i+1],[10-i,0])
for i in xrange(0,-10,-1):
plt.plot([0,i-1],[10+i,0])
for i in range(0,10):
plt.plot([0,i+1],[-10+i,0])
for i in range(0,10):
plt.plot([0,-i-1],[-10+i,0])
plt.plot([0,0],[-10,10])
plt.plot([-10,10],[0,0])
plt.ylabel('some numbers')
plt.show()
|
STOCK_PORTFOLIO = {}
STOCKS_WATCHLIST = ['SNAP', 'UBER', 'MSFT', 'ABNB', 'AAPL']; STOCKS_WATCHLIST.sort()
MAX_STOCK_QTY = 2 #the max amount of shares willing to hold per stock
MAX_UNIT_PRICE = 100.0 #the max unit price willing to buy per share
PREV_STOCK_PRICES = {}
def main(stock_prices):
"""
Strategy: tit for tat strategy, if a stock just increased in price, buy and if a stock just decreased, sell
param <dict<float>> stock_prices: the stock prices
return <dict<list<tuple>>> order: the quantity of stocks to buy and sell ex {"Buy": [(SNAP, 2)], "Sell": [(UBER, 1)]}
"""
#if it is the first run, set previous stock prices to current prices and return an empty order
if not PREV_STOCK_PRICES:
for ticker in stock_prices:
PREV_STOCK_PRICES[ticker] = stock_prices[ticker]
return {"Buy": [], "Sell": []}
#use tit for tat strategy
order = execute_order(stock_prices)
#save old prices so they can be used to compare with new prices
for ticker in stock_prices:
PREV_STOCK_PRICES[ticker] = stock_prices[ticker]
return order
def execute_order(stock_prices):
"""
Determine which stocks to sell and buy based on strategy
param <dict<float>> stock_prices: the stock prices
return <dict<list<tuple>>> order: the quantity of stocks to buy and sell ex {"Buy": [(SNAP, 2)], "Sell": [(UBER, 1)]}
"""
order = {"Buy": [], "Sell": []}
for ticker in STOCKS_WATCHLIST:
if stock_prices[ticker] > PREV_STOCK_PRICES[ticker]: #rising
#buy
if ticker not in STOCK_PORTFOLIO:
order["Buy"].append((ticker, MAX_STOCK_QTY))
STOCK_PORTFOLIO[ticker] = MAX_STOCK_QTY
continue
if stock_prices[ticker] < PREV_STOCK_PRICES[ticker]: #going down
#sell
if ticker in STOCK_PORTFOLIO:
order["Sell"].append((ticker, MAX_STOCK_QTY))
del STOCK_PORTFOLIO[ticker]
return order
|
class ProbableTournamentTree():
"""
the probable tournament tree details the likely winners of games from the round of 16 on
"""
MAX_LEVEL = 4
class Node():
def __init__(self, left, right, winner=None):
self.left = left
self.right = right
self.winner = winner
def children_winner(self):
"""
:return: ``Team`` instance. The winner of this ``Node``'s left and right children
"""
left_winning_prob = self.left.winner.winning_probabilities[self.right.winner.country]
return self.left.winner if left_winning_prob >= .5 else self.right.winner
def __init__(self, tournament):
self.tournament = tournament
self.groups = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
self.group_pointer = 0
self.group_subpointer = 0
self.root = self.build_tree(self.Node(None, None))
def _search_subtree(self, subtree, team):
"""
:param subtree: ``Node`` instance, the subtree to search
:param team: ``Team`` instance, the team to search ``subtree`` for
:return: ``True`` if ``team`` in ``subtree``. ``False`` o/w
"""
if subtree.winner.country == team.country:
return True
elif subtree.left is None or subtree.right is None:
return False
else:
return self._search_subtree(subtree.left, team) or self._search_subtree(subtree.right, team)
def build_tree(self, node, cur_level=MAX_LEVEL):
"""
:param node: the current root of the tree being built
:return: ``Node`` the original node fed into the method completely built into a tree
"""
if cur_level == 0:
node.left = None
node.right = None
# the leafs value should be the winner of the group pointed to by self.group_pointer
group = self.groups[self.group_pointer % len(self.groups)]
group_winners = self.tournament.get_group_winners(group)
# 1st place from group should play 2nd place from sibling group
node.winner = group_winners[self.group_subpointer]
self.group_pointer += 1
# make sure that we invert the order of choosing 1st place / 2nd place after traversing all groups once
self.group_subpointer = 1 if self.group_subpointer == 0 or self.group_pointer == len(self.groups) else 0
else:
node.left = self.build_tree(self.Node(None, None), cur_level=cur_level - 1)
node.right = self.build_tree(self.Node(None, None), cur_level=cur_level - 1)
node.winner = node.children_winner()
return node
def get_opponent_at_stage(self, team, stage):
"""
:param team: ``Team`` instance to get the probable opponent for
:param stage: ``int`` the stage to get the probable opponent for ``team`` at. (Stage should always be between
0 inclusive and 3 exclusive)
:return: ``Team`` instance the ``team``'s likely opponent at ``stage``
This method has two distinct paths depending on whether ``team`` is a part of the probability tree or not.
If not, it means it's likely they won't make it out of group, so to get their likely opponent at ``stage``,
we emulate the team in their group who came in second and find that team's opponent at ``stage``. If ``team`` is
already in the tree, the method is more straightforward.
"""
def _helper(node, t=None, cur_level=self.MAX_LEVEL):
deeper_level = cur_level - 1
if deeper_level < 0:
return None
elif deeper_level == stage:
# if the next level is the one that we're looking for, then get the subtree (left or right) that the
# team we're searching for is in and return the direct child from the opposite subtree, this is their
# opponent
if self._search_subtree(node.left, t):
return node.right.winner
elif self._search_subtree(node.right, t):
return node.left.winner
else:
return None
else:
return _helper(node.left, t=t, cur_level=deeper_level) or _helper(node.right, t=t, cur_level=deeper_level)
group_winners = self.tournament.get_group_winners(team.group)
return _helper(self.root, t=team if team in group_winners else group_winners[1])
def print_tree(self):
"""
print this tree to STDOUT
"""
levels = {}
def _helper(node, cur_depth=0):
vals_at_level = levels.get(cur_depth, [])
vals_at_level.append(node.winner.country)
levels[cur_depth] = vals_at_level
if node.left is None or node.right is None:
return
else:
_helper(node.right, cur_depth=cur_depth + 1)
_helper(node.left, cur_depth=cur_depth + 1)
_helper(self.root)
for level in levels.keys():
print "\t".join(levels[level])
print "\n"
|
def strsort(a_string):
return ''.join(sorted(a_string))
# print(strsort('python'))
def even_odd_sum(sequence):
my_list = []
sum_odd = 0
sum_even = 0
for nr in sequence:
if sequence.index(nr) % 2 == 0:
sum_odd += nr
else:
sum_even += nr
my_list.append(sum_odd)
my_list.append(sum_even)
return my_list
print(even_odd_sum([10, 20, 30, 40, 50, 60]))
def plus_minus(sequence):
result = 0
for nr in sequence:
if sequence.index(nr) % 2 != 0:
result += nr
else:
result -= nr
return result
print(plus_minus([10, 20, 30, 40, 50, 60]))
def convert_to_int(my_num):
return int(my_num)
def my_input_list():
my_list = [my_in for my_in in input("Gime me some numbers: ").split(",")]
my_int_list = []
for nr in my_list:
try:
my_nr = int(nr)
my_int_list.append(my_nr)
except ValueError:
print(f'Not valid for conversion {nr} to int')
return my_int_list
def plus_minus():
my_list = my_input_list()
my_sum = my_list[0]
for nr in my_list[1:]:
if my_list.index(nr) % 2 != 0:
my_sum += nr
else:
my_sum -= nr
return my_sum
print(plus_minus())
|
import string
def gematria_dict():
return {char: index
for index, char
in enumerate(string.ascii_lowercase,1)}
GEMATRIA = gematria_dict()
def gematria_for(word):
return sum(GEMATRIA.get(one_char, 0)
for one_char in word)
def gematria_equal_words(input_word):
our_score = gematria_for(input_word.lower())
return [one_word.strip()
for one_word in open("test_text.txt")
if gematria_for(one_word.lower()) == our_score]
print(gematria_equal_words(''))
|
import time
def word_count(filename):
counts = {
'characters': 0,
'words': 0,
'lines': 0
}
unique_words = set()
for one_line in open(filename):
counts['lines'] += 1
counts['characters'] += len(one_line)
counts['words'] += len(one_line.split())
unique_words.update(one_line.split())
counts['unique_words'] = len(unique_words)
for key, value in counts.items():
print(f'{key}: {value}')
word_count('test_text.txt')
user_input = input("Pls first give the file name and than words to "
"calculate frequencies: \n").split(',')
my_file = user_input[0] + '.txt'
words_to_count = user_input[1:]
# print(my_file)
# print(" \n Word to count: ", words_to_count)
start = time.time()
def words_frequency():
word_dict = {el: 0 for el in words_to_count}
print(word_dict)
for one_line in open(my_file):
for word in one_line.split():
if word in word_dict.keys():
word_dict[word] += 1
print(word_dict)
words_frequency()
# def test_frequency():
# my_dict = {}
# for elemn in words_to_count:
# counter = 0
# for one_line in open(my_file):
# for word in one_line.split():
# if word == elemn:
# print(word)
# counter += 1
# my_dict[elemn] = counter
# print(my_dict)
#
# test_frequency()
print(time.time() - start)
# print(start2 - start1)
|
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the isValid function below.
def isValid(s):
# Iterate and count how many times string occured
character_dict = {}
for character in s:
if character in character_dict:
character_dict[character] += 1
else:
character_dict[character] = 1
#initiate largest and smallest count with last character
min_count = character_dict[character]
max_count = character_dict[character]
# count how many times a count occured
count_dict = {}
for char, value in character_dict.items():
if value in count_dict:
count_dict[value] += 1
else:
count_dict[value] = 1
#also update max and min count
if value < min_count:
min_count = value
if value > max_count:
max_count = value
# final test:
if len(count_dict) == 1:
return "YES"
elif len(count_dict) == 2:
if count_dict[max_count] == 1 and max_count - min_count == 1:
return "YES"
elif count_dict[min_count] == 1 and min_count == 1:
return "YES"
return "NO"
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
s = input()
result = isValid(s)
fptr.write(result + '\n')
fptr.close()
|
def split_and_join(line):
# write your code here
# "split(" ")" method -> splits a string into a list by using space as delimiter
split_line = line.split(" ")
# "join()" method -> joins each element of an iterable (such as list, string and tuple) by a string separator (the string on which the join() method is called) and returns the concatenated string.
# ""-".join()" method -> "-" is used as we need a hypen seperator between strings
join_line = "-".join(split_line)
return join_line
if __name__ == '__main__':
line = input()
result = split_and_join(line)
print(result)
|
# Reverse L1 and L2.
# Amalgamate each digit of the reversed listNodes into two seperate numbers
# Return the sum of those two numbers
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
l1 = ListNode(2)
l1n2 = ListNode(4)
l1n3 = ListNode(3)
l1.next = l1n2
l1n2.next = l1n3
l2 = ListNode(5)
l2n2 = ListNode(6)
l2n3 = ListNode(4)
l2.next = l2n2
l2n2.next = l2n3
# 342 + 465 = 807
# return a listnode with 7->0->8
class Solution():
def __init__(self):
self.cur_node = None
def add_node(self, data):
new_node = ListNode(data)
new_node.next = self.cur_node
self.cur_node = new_node
def addTwoNumbers(self, l1, l2):
l1_list = self.get_rev_num_from_list(l1)
l2_list = self.get_rev_num_from_list(l2)
nums = self.convert_and_add_nums(l1_list, l2_list)
self.create_return_list(nums)
return self.cur_node
def print_list(self, list_to_print):
head = list_to_print
while(head != None):
print(head.val)
head = head.next
def get_rev_num_from_list(self, list_to_parse):
head = list_to_parse
nums_str = ''
while (head != None):
nums_str += str(head.val)
head = head.next
return nums_str[::-1]
def convert_and_add_nums(self, nums_str_1, nums_str_2):
return int(nums_str_1) + int(nums_str_2)
def create_return_list(self, list_to_parse):
for x in list(str(list_to_parse)):
self.add_node(int(x))
# Example driver code
sln = Solution()
asdf = sln.addTwoNumbers(l1, l2)
print(asdf.val)
print(asdf.next.val)
print(asdf.next.next.val)
|
'''
Created on Feb 11, 2015
@author: adudko
'''
from sys import version_info
class DishType():
ENTREE = 1
SIDE = 2
DRINK = 3
DESSERT = 4
class Dish():
def __init__(self, type, name):
self.type = type
self.name = name
def __eq__(self, other):
#should be replaced with a smarter dictionary comparer, but for purposes of this exercise, keeping it simple)
return (self.type == other.type and self.name == other.name)
def __str__(self):
return self.name
class Menu():
ERROR_DISH = Dish(99, "error")
def __init__(self, dishes=[]):
self.dishes = dishes
def __str__(self):
return str(self.__class__.__name__)
def find_item(self, dish_type):
for dish in self.dishes:
if dish.type == dish_type:
return dish
return self.ERROR_DISH
class BreakfastMenu(Menu):
MULTI_DISH_ALLOWED = DishType.DRINK
class DinnerMenu(Menu):
MULTI_DISH_ALLOWED = DishType.SIDE
class FinishedMeal():
def __init__(self):
self.serving_plate = []
def dish_already_on_the_plate(self, item):
for dish in self.serving_plate:
if dish.type == int(item):
return True
return False
def add_dish(self, menu, item):
if self.dish_already_on_the_plate(item) and int(item) != menu.MULTI_DISH_ALLOWED:
self.serving_plate.append(menu.ERROR_DISH)
raise Exception("this dish cannot be served twice : %s" % item)
self.serving_plate.append(menu.find_item(int(item)))
def arrange_dishes(self):
self.serving_plate.sort(key=lambda obj:obj.type)
return self.serving_plate
def find_multiple_dishes(self):
counter_dic = {}
for dish in self.serving_plate:
if dish.name in counter_dic:
counter_dic[dish.name] +=1
else:
counter_dic[dish.name] = 1
multiple_dishes = [{dish:count} for dish,count in counter_dic.iteritems() if count>1]
return multiple_dishes[0] if len(multiple_dishes) > 0 else {}
def presentation(self):
new_plate=[]
multiple_dishes = self.find_multiple_dishes()
for dish in self.serving_plate:
if dish.name in multiple_dishes:
dish_name = dish.name + '(x%s)' % multiple_dishes[dish.name]
else:
dish_name = dish.name
if dish_name not in new_plate:
new_plate.append(dish_name)
return ', '.join(new_plate)
def __eq__(self, other):
return self.serving_plate == other.serving_plate
class OrderValidator():
def __init__(self, order=None):
self.order = order
self.time_of_day = None
self.menu_items = []
def validate_order(self):
if self.order is not None:
parts = self.order.split(',')
if self.order is None or len(parts) == 0:
return 'Nothing ordered!!!'
if parts[0].lower().strip() not in ['morning', 'night']:
return 'time of day should be morning or night... we are simple.'
self.time_of_day = parts[0].lower().strip()
self.menu_items = parts[1:]
return True
class MenuSelector():
BREAKFAST_MENU = 'morning'
BREAKFAST_MENU_ITEMS = [(DishType.ENTREE, 'eggs'), (DishType.SIDE, 'toast'), (DishType.DRINK, 'coffee')]
DINNER_MENU = 'night'
DINNER_MENU_ITEMS = [(DishType.ENTREE, 'steak'), (DishType.SIDE, 'potato'), (DishType.DRINK, 'wine'), (DishType.DESSERT, 'cake')]
def __init__(self, menu_type):
self.menu_type = menu_type
def setup_menu(self):
if self.menu_type == self.BREAKFAST_MENU:
return BreakfastMenu(self.breakfast_menu_dishes)
if self.menu_type == self.DINNER_MENU:
return DinnerMenu(self.dinner_menu_dishes)
@property
def breakfast_menu_dishes(self):
return [Dish(menu_item[0], menu_item[1]) for menu_item in self.BREAKFAST_MENU_ITEMS]
@property
def dinner_menu_dishes(self):
return [Dish(menu_item[0], menu_item[1]) for menu_item in self.DINNER_MENU_ITEMS]
class ProcessOrder():
def __init__(self, menu):
self.menu = menu
def prepare_meal(self, order_items):
try:
meal = FinishedMeal()
for item in order_items:
meal.add_dish(self.menu, item)
except Exception, e:
## uh uh - exception was raise, we would log it here, but give the customer what he wanted....
pass
finally:
meal.arrange_dishes()
return meal
def present_meal(self, order_items):
prepared_meal = self.prepare_meal(order_items)
return prepared_meal.presentation()
if __name__ == '__main__':
print "welcome to this this low-key diner! menu slection: 1- entree; 2 - side 3 - drink, 4 - dessert"
order_str = 'please enter your order in form of "time of day (morning or night), list of numbers of dishes from the above menu separated by commas" : '
if version_info[0] > 2:
order = input(order_str)
else:
order = raw_input(order_str)
print "processing order : " , order
waiter = OrderValidator(order)
if waiter.validate_order():
menu = MenuSelector(waiter.time_of_day).setup_menu()
chef = ProcessOrder(menu)
print "here is your meal: %s " % chef.present_meal(waiter.menu_items)
|
def hanoi(n, _from, _by, _to):
if(n == 1):
print("{} {}".format(_from, _to))
return
hanoi(n - 1, _from, _to, _by)
print("{} {}".format(_from, _to))
hanoi(n - 1, _by, _from, _to)
n = int(input())
if(n != 0):
print(pow(2, n) - 1)
hanoi(n, 1, 2, 3)
|
def binarySearch(arr, l, r, x):
while l <= r:
mid = l + (r - l) // 2;
# Check if x is present at mid
if arr[mid] == x:
return mid
# If x is greater, ignore left half
elif arr[mid] < x:
l = mid + 1
# If x is smaller, ignore right half
else:
r = mid - 1
# If we reach here, then the element
# was not present
return mid
t = int(input())
for test in range(t):
n,k = map(int,input().split())
l = [int(x) for x in input().split()]
l.sort()
c = [i for i in l]
if sum(c) < 2 * k:
print(-1)
continue
oo = k
s = sum(c)
ans = 0
u = []
while oo > 0:
print(oo)
if s > oo:
a = binarySearch(c,0,len(c) - 1,oo)
if c[a] >= oo:
u.append(c[a])
ans += 1
c.pop(a)
break
else:
oo = oo - c[a]
s = s - c[a]
u.append(c[a])
c.pop(a)
ans += 1
|
def coinChange_Combination_amount_respect(denom, amount, lastDenomIndex, ans):
if amount == 0:
print(ans)
return
for i in range(lastDenomIndex, len(denom)):
if amount >= denom[i]:
coinChange_Combination_amount_respect(denom, amount - denom[i], i, ans + str(denom[i]))
def coinChangePermutation(denom, amount, ans):
if amount == 0:
print(ans)
return
for i in range(len(denom)):
if denom[i] <= amount:
coinChangePermutation(denom, amount - denom[i] , ans + str(denom[i]))
def coinChange_Combination_coin_respect(denom, amount, i, ans):
# positive base case
if amount == 0:
print(ans)
return
# negative base case
if amount < 0 or i >= len(denom):
return
# current (i th) coin can contribute in amount
coinChange_Combination_coin_respect(denom, amount - denom[i], i, ans + str(denom[i]) + ' ')
# current (i th) coin can not contribute in amount
coinChange_Combination_coin_respect(denom, amount, i + 1, ans)
denom = [2,3,5,6]
amount = 10
lastDenomIndex = 0
ans = ''
coinChange_Combination_amount_respect(denom, amount, lastDenomIndex, ans)
print("----------------")
coinChangePermutation(denom, amount, ans)
print("\n------------\n")
coinChange_Combination_coin_respect(denom, amount, 0, "")
|
import RPi.GPIO as GPIO
# Define a callback function that will be called by the GPIO
# event system:
def onButton(channel):
if channel == 23:
print("Button",channel,"was pressed!")
# Setup GPIO23 as input with internal pull-up resistor to hold it HIGH
# until it is pulled down to GND by the connected button:
GPIO.setmode(GPIO.BCM)
GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# Register an edge detection event on FALLING edge. When this event
# fires, the callback onButton() will be executed. Because of
# bouncetime=500 all edges 500 ms after a first falling edge will be ignored:
GPIO.add_event_detect(23, GPIO.FALLING, callback=onButton, bouncetime=500)
# The script would exit now but we want to wait for the event to occure
# so we block execution by waiting for keyboard input so every key will exit
# this script
input()
|
import calendar
import time
ticks = time.time() #time intervals are floating point numbers in units of seconds. Particular instants in time are
#expressed in seconds since 12:00am January 1 1970
print("no of ticks since 12:00am January 1 1970 is : " ,ticks)
localtime = time.localtime(time.time())
print(localtime)
localtimeinlocalformat = time.asctime(time.localtime(time.time()))
print(localtimeinlocalformat)
cal = calendar.month(1993,2)
print(cal)
cal = calendar.month(2027,2)
print(cal)
clocktime = time.clock()
print(clocktime)
altzonetime = time.altzone
print("%d" % (altzonetime))
ctime = time.ctime()
print("%s" % (ctime))
print("starting time is %s" % (time.ctime()))
time.sleep(0)
print("ending time is %s" % (time.ctime()))
thisyearcalender=calendar.calendar(2017,w=1,l=1,c=6)
print(thisyearcalender)
weekdaycalender = calendar.firstweekday()
print(weekdaycalender)
leapyearfind = calendar.isleap(2020)
print(leapyearfind)
|
string = input("enter string")
vowels = ['a','e','i','o','u']
string = string.casefold()
count = 0
for char in string:
if char in vowels:
count = count + 1
print(count)
|
"""items = [1,2,3,4,5]
squared = []
for x in items:
squared.append(x**2)
print(squared)"""
squared = []
items = [2,3,4,5]
def sqr(x):
values = x**2
squared.append(values)
list(map(sqr,items))
print(squared)
|
class person:
def __init__(self,id):
print("our class is crated" ,id)
self.id=id
def __del__(self):
classname = person.__name__
myclassname = self.__class__.__name__
print("our class is destroyed",classname,myclassname)
def setfullname(self,firstname,lastname):
self.firstname=firstname
self.lastname=lastname
def printfullname(self):
print(self.firstname," ",self.lastname)
personname = person(5)
prefix = input("enterfirstname")
suffix = input("enterlastaname")
personname.setfullname(prefix,suffix)
personname.printfullname()
personname.setfullname(prefix,suffix)
personname.printfullname()
personname.__del__()
personname.setfullname(prefix,suffix)
personname.printfullname()
personname.setfullname(prefix,suffix)
personname.printfullname()
|
import itertools ,random
deck = list(itertools.product(range(1,14),['spade','Heart','Diamond','Club']))
random.shuffle(deck)
print("you got")
for i in range(5):
print(deck[i][0],"of",deck[i][1])
"""
00 01
10 11
20 21
30 31
40 41
(1,2,3,4,5,6,7,8,9,10,11,12,13) , ['spade','Heart','Diamond','Club'}
"""
|
import math
"""import random
a=math.tan(0)
print(a)
randomnum = random.randrange(0,100)
while (not randomnum == 15):
print(randomnum ,' ', end = '')
randomnum = random.randrange(0,100)"""
i = 0
while (i<=20):
if(i%2==0):
print(i ,"is even num")
i+=1
continue
else:
i+=1
continue
|
#Factorial de N(1 * 2 * 3 ... * n) CON ITERATIVIDAD
def fact(x):
result = 1
i = 1
while i != x+1:
result = result * i
i += 1
return result
#1 * 5 *
print(fact(10))
|
'''
Data Type
int / 정수
float / 소수
str / 문자
bool / True/False
ex)
a = 3
b = 3.1
c = "Hello"
type(a)
type(b)
type(c)
print(a)
print(type(a))
a = "3"
a = int(a)
a = str(a)
Type change
#str -> int
#int -> str
#float -> int etc
연산 +, -, *, **, /, // ,%
부등호
>,<, ==, <=, >=, !=
Variable ?
변하는 수를 집어넣기 위해 만든 공간
키보드로 부터 데이터를 입력받고 형변환 시키는 작업
x = int(input())
*컴퓨터 구조 부분적으로 설명
'''
|
import random
def selectMark():
mark = ''
while(mark != 'X' and mark != 'O'):
mark = input("Select X or O :")
mark = mark.upper()
if(mark == 'X'):
return ['X', 'O']
else:
return ['O', 'X']
def selectTurn():
if(random.randint(0,1) == 0):
return 'person'
else:
return 'computer'
def position_check(game_board, num):
if(game_board[num] == "U"):
return True
else:
return False
|
'''
#if 문
조건이 만족할때 if 문 안에 명령어를 실행
ex) a = 3
if(a == 3):
print("a is 3")
Q. 숫자를 키보드로 부터 입력받아 짝수 인지 홀수 인지 구분하는 프로그램 개발
Q. 숫자를 입력받아 1이면 덧셈 계산 수행, 2이면 뺄셈, 3이면 곱셈, 4이면 나눗셈, 5이면 나머지를 구하는 프로그램 개발
# and, or
and ? 조건이 모두 참일때 참이 된다.
or ? 조건 중 하나만 참이면 참이 된다.
if():
elif():
else:
은 짝을 이뤄서 프로그램에 맞게 코드를 구현한다.
'''
a = 3
if a == 3 and a == 4:
print("hi")
|
'''
This is a program to implement the judgy hexagons from real life.
Idea by Aileen Liang/Hanting Li
Implemented in Python by Owen Fei
Tutorial on judgy hexagons in real life:
First, draw like 8 nested hexagons.
Connect all the points with 6 lines.
Label each of the lines with a trait (should be the traits below).
For each of the traits, rank them from 1-8 and draw the point on the line.
The outer hexagons are higher.
Now, connect all 6 points, and color in the polygon made by them.
'''
from tkinter import (Tk, Frame, Label, Scale, Canvas, Menu, N, S, E, W,
SE, SW, NE, NW, messagebox as msg, HORIZONTAL, Entry, END,
colorchooser as clr)
class App(Tk):
def __init__(self, *args, **kwargs):
'''
the ui stuff
'''
super().__init__(*args, **kwargs)
self.color = 'blue'
self.winfo_toplevel().title('Judgy Hexagon')
#Menu for a bit of documentation and help
self.menu = Menu(self)
self.menu.add_command(label='Change Color', command=self.change_color)
self.menu.add_command(label='Help', command=self.help)
self.menu.add_command(label='People', command=self.people)
self.config(menu=self.menu)
#the main canvas to show the hexagon
self.canvas = Canvas(self, height=566, width=800)
self.canvas.grid(row=1, column=1)
#frame to put all the sliders in
self.sf = Frame(self)
self.sf.grid(row=1, column=3)
#entries for the trait names (with default values)
self.sl1 = Entry(self.sf)
self.sl1.grid(row=0, column=0)
self.sl1.insert(END, 'IQ')
self.sl2 = Entry(self.sf, text='EQ')
self.sl2.grid(row=1, column=0)
self.sl2.insert(END, 'EQ')
self.sl3 = Entry(self.sf)
self.sl3.grid(row=2, column=0)
self.sl3.insert(END, 'Attractiveness')
self.sl4 = Entry(self.sf)
self.sl4.grid(row=3, column=0)
self.sl4.insert(END, 'Personality')
self.sl5 = Entry(self.sf)
self.sl5.grid(row=4, column=0)
self.sl5.insert(END, 'Athleticism')
self.sl6 = Entry(self.sf)
self.sl6.grid(row=5, column=0)
self.sl6.insert(END, 'Artisticness')
#sliders
self.t1scale = Scale(self.sf, from_=0, to=9, orient=HORIZONTAL)
self.t1scale.grid(column=1, row=0)
self.t2scale = Scale(self.sf, from_=0, to=9, orient=HORIZONTAL)
self.t2scale.grid(column=1, row=1)
self.t3scale = Scale(self.sf, from_=0, to=9, orient=HORIZONTAL)
self.t3scale.grid(column=1, row=2)
self.t4scale = Scale(self.sf, from_=0, to=9, orient=HORIZONTAL)
self.t4scale.grid(column=1, row=3)
self.t5scale = Scale(self.sf, from_=0, to=9, orient=HORIZONTAL)
self.t5scale.grid(column=1, row=4)
self.t6scale = Scale(self.sf, from_=0, to=9, orient=HORIZONTAL)
self.t6scale.grid(column=1, row=5)
#the labels to make clear which line is which trait
self.l1 = Label(self, text=self.sl1.get(),
font=('Calibri', 20))
self.l1.grid(row=1, column=2, sticky=E)
self.l2 = Label(self, text=self.sl2.get(),
font=('Calibri', 20))
self.l2.grid(row=1, column=1, sticky=SE)
self.l3 = Label(self, text=self.sl3.get(),
font=('Calibri', 20))
self.l3.grid(row=1, column=1, sticky=SW)
self.l4 = Label(self, text=self.sl4.get(),
font=('Calibri', 20))
self.l4.grid(row=1, column=0, sticky=W)
self.l5 = Label(self, text=self.sl5.get(),
font=('Calibri', 20))
self.l5.grid(row=1, column=1, sticky=NW)
self.l6 = Label(self, text=self.sl6.get(),
font=('Calibri', 20))
self.l6.grid(row=1, column=1, sticky=NE) #:)
#put the person's name in here
self.nameentry = Entry(self.sf)
self.nameentry.grid(row=7, column=1)
Label(self.sf, text='\n\nName of person\n\n').grid(row=7, column=0)
self.namelabel = Label(self, text='Name', font=('Calibri', 20), fg='red')
self.namelabel.grid(row=0, column=1)
#6 lists of points
self.listright = [(400+40*i, 200*2**0.5)
for i in range(10)]
self.listrightdown = [(400+20*i, 200*2**0.5+i*20*2**0.5)
for i in range(10)]
self.listleftdown = [(400-20*i, 200*2**0.5+i*20*2**0.5)
for i in range(10)]
self.listleft = [(400-40*i, 200*2**0.5)
for i in range(10)]
self.listleftup = [(400-20*i, 200*2**0.5-i*20*2**0.5)
for i in range(10)]
self.listrightup = [(400+20*i, 200*2**0.5-i*20*2**0.5)
for i in range(10)]
#Draw the 10 hexagons
for i in range(10):
self.canvas.create_polygon([self.listright[i][0],
self.listright[i][1],
self.listrightdown[i][0],
self.listrightdown[i][1],
self.listleftdown[i][0],
self.listleftdown[i][1],
self.listleft[i][0],
self.listleft[i][1],
self.listleftup[i][0],
self.listleftup[i][1],
self.listrightup[i][0],
self.listrightup[i][1],],
fill='', width=1, outline='black')
def change_color(self):
self.color = clr.askcolor(title='Choose a color for the shape')[1]
def help(self):
msg.showinfo(title='Help', message='''
How to use this app:
Move around the sliders and enter a name.
Type your 6 character traits in the 6 entries.
You can change the color of shape by clicking on the 'Change Color' menu option.
Then, take a snip of the part without the sliders.
Tutorial on judgy hexagons in real life:
First, draw like 8 nested hexagons.
Connect all the points with 6 lines.
Label each of the lines with a trait (should be the traits below).
For each of the traits, rank them from 1-8 and draw the point on the line.
The outer hexagons are higher.
Now, connect all 6 points, and color in the polygon made by them.''')
def people(self):
msg.showinfo(title='People', message='''
List of people related to this:
Ideas: Aileen Liang (probably more this person), Hanting Li
Python implementation: Owen Fei
Another app to check out: Owen Zhang''')
def judge(self, t1, t2, t3, t4, t5, t6):
'''
Draws the filled-in polygon in blue.
'''
#Get which point each level of trait is
t1 = self.listright[t1]
t2 = self.listrightdown[t2]
t3 = self.listleftdown[t3]
t4 = self.listleft[t4]
t5 = self.listleftup[t5]
t6 = self.listrightup[t6]
#REmove the last shape if possible
try:
self.canvas.delete(self.last_polygon)
except:
pass
#Draw the new polygon
self.last_polygon = self.canvas.create_polygon([t1[0],
t1[1],
t2[0],
t2[1],
t3[0],
t3[1],
t4[0],
t4[1],
t5[0],
t5[1],
t6[0],
t6[1],],
fill=self.color,
width=1,
outline=self.color)
self.canvas.update()
def main(self):
'''
Constantly draws the new polygon.
Constantly updates the name.
'''
while True:
#Update the name
self.namelabel.config(text=self.nameentry.get())
#Call judge() on the values of the sliders
self.judge(self.t1scale.get(),
self.t2scale.get(),
self.t3scale.get(),
self.t4scale.get(),
self.t5scale.get(),
self.t6scale.get())
#Updates the labels with trait names.
self.l1.config(text=self.sl1.get())
self.l2.config(text=self.sl2.get())
self.l3.config(text=self.sl3.get())
self.l4.config(text=self.sl4.get())
self.l5.config(text=self.sl5.get())
self.l6.config(text=self.sl6.get())
self.update()
if __name__ == '__main__':
app = App()
app.main()
|
import sqlite3
from urllib.request import urlopen
import requests
import pandas as pd
#Definening URLs
friends_url="https://snap.stanford.edu/data/facebook_combined.txt.gz"
people_url="https://people.cam.cornell.edu/md825/names.txt"
#Read URLs into Python
people=pd.read_csv(people_url,header=None)
friend=pd.read_csv(friends_url,header=None)
#Convert the format so that they can be pushed to the SQL
people_tuple=[tuple(i) for i in people.to_numpy()]
friend_tuple=[tuple(map(int,i[0].split(" "))) for i in friend.values.tolist()]
# Connecting to the database file
conn = sqlite3.connect('p2.db')
c = conn.cursor()
#Creating table for people/pushing the data into the table
c.execute("DROP TABLE IF EXISTS people")
c.execute('''CREATE TABLE people (personId INTEGER,name text)''')
c.executemany('INSERT INTO people VALUES (?,?)', people_tuple)
#Creating table for friends/pushing the data into the table
c.execute("DROP TABLE IF EXISTS friends")
c.execute('''CREATE TABLE friends (personId1 INTEGER,personId2 INTEGER)''')
c.executemany('INSERT INTO friends VALUES (?,?)', friend_tuple)
#SQL Query that querys NumOfFriends
pd.set_option('display.max_rows', None)
print(pd.read_sql_query("Select Name as Name, Count(PersonId1) as NumOfFriends From (Select personId1 From friends UNION ALL Select PersonId2 From friends) As P JOIN people on P.personId1=people.PersonId Group by Name Order by NumOfFriends DESC",conn))
#Committing changes and closing the connection to the database file
conn.commit()
conn.close()
|
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 22 04:46:51 2019
@author: Chris Mitchell
A vector class for mathematical usage. This vector is defined to be useful
in seeing the operations of vector calculus and linear algebra. Other Python
libraries such as NumPy have much more efficient vector and matrix operations.
TO DO:
. Add an attribute for the zero vector associated with the vector.
. Properly format docstring
. Add functionality for a vector with complex components and for
vectors in the complex plane.
. Add cross product for 7-dim vectors (is this even necessary??)
"""
from math import sqrt, acos, asin, pi
class Vector:
def __init__(self, head, axis = 0, origin = []):
"""Initialize the vector object using a list. An axis is provided
to delineate whether this is a row or column vector. Currently,
the axis is just a placeholder for the potential need. The default
is a row vector. An origin can also be provided as a list. If
specified, it must be the same dimension as the vector. If not
specified, the origin will be assumed to be [0, 0, ...].
The init method will also initialize to other variables:
_dtype and _dim. The type of value specified in the head list
will be stored in _dtype. The dimension of the head list will
be stored in _dim."""
#If a Vector is provided as an argument to the constructor,
#copy the attributes or the existing vector and return.
if type(head) == Vector:
self._coordinates = head._coordinates.copy()
self._origin = head._origin.copy()
self._dim = head._dim
self._dtype = head._dtype
self._axis = head._axis
return
#Initialize _coordinates and test whether the constructor is called
#with a list of numeric values.
try:
self._coordinates = list(head)
except TypeError:
raise TypeError("Expected list or similar castable object as vector. Got " + str(type(head)) + ".")
except:
raise Exception("Unknown error in class constructor.")
#Check if coordinate entries are numbers.
for i in self._coordinates:
if not bool(0 == i * 0):
raise Exception("Vector list elements must be numbers.")
#Initialize axis with either 0 or 1.
if type(axis) == int and (axis == 0 or axis == 1):
self._axis = axis
elif type(axis) == str:
if axis == "row": self._axis = 0
elif axis == "column" or axis == "col": self._axis = 1
else: raise Exception('Expected axis to be 0, 1, "row," or "column".')
else:
raise Exception('Expected axis to be 0, 1, "row," or "column".')
#Initialize the origin if given. If the origin is all zeros, then
#the list will remain empty.
try:
self._origin = list(origin)
except TypeError:
print("Expected list or similar castable object as origin. Got " + str(type(origin)) + ".")
except:
raise Exception("Unknown error in class constructor.")
#If the origin is specified, check that the entries are numbers and
#that it is of the same dimension as the vector itself.
if self._origin != []:
for i in self._origin:
if not bool(0 == i * 0):
raise Exception("Origin list elements must be numbers.")
if len(self._origin) != len(self._coordinates):
raise Exception("The specified origin is not the same length as the vector.")
#Upcast the vector and the origin if necessary and set _dtype.
complexNum = False
floatNum = False
for i in self._coordinates:
if type(i) == float: floatNum = True
elif type(i) == complex: complexNum = True
if complexNum:
self._coordinates = [complex(i) for i in self._coordinates]
self._origin = [complex(i) for i in self._origin]
self._dtype = complex
elif not complexNum and floatNum:
self._coordinates = [float(i) for i in self._coordinates]
self._origin = [float(i) for i in self._origin]
self._dtype = float
else:
self._dtype = int
#Set _dim to be the dimensions of the vector.
self._dim = len(self._coordinates)
#Initialization and type check complete.
def __repr__(self):
"""Vector output will be different from that of a list. First, angle brackets
will be used instead of square brackets. If an origin is specified, then
the origin will be printed as well in the form of origin->vector."""
if self._origin == []:
return '\u27e8' + str(self._coordinates)[1:-1] + '\u27e9'
else:
return str(self._origin) + ' \u27f6 \u27e8' + str(self._coordinates)[1:-1] + '\u27e9'
def __str__(self):
"""Use __repr__."""
return self.__repr__()
#Other private methods:
def __add__(self, other):
"""Vector addition."""
self._checkTypeCompatability(other)
return Vector([self._coordinates[i] + other._coordinates[i] for i in range(self._dim)], origin = self._origin, axis = self._axis)
def __div__(self, other):
"""Undefined. If division by a scalar is required, simply perform scalar
multiplication using the reciprocal of the scalar."""
self._undef()
def __getitem__(self, index):
return self._coordinates[index]
def __iter__(self):
return iter(self._coordinates)
def __len__(self):
return self._dim
def __mul__(self, other):
"""Scalar multiplication."""
#Ensure we are given a scalar and nothing else.
if bool(0 == other * 0):
return Vector([self._coordinates[i] * other for i in range(self._dim)], origin = self._origin, axis = self._axis)
else:
raise Exception("Multiplication of vectors with non-scalars is ambiguous. Please use either the dot() or cross() methods.")
def __rmul__(self, other):
"""Scalar multiplication with operands in a different order."""
return self.__mul__(other)
def __sub__(self, other):
"""Vector subtraction."""
self._checkTypeCompatability(other)
return Vector([self._coordinates[i] - other._coordinates[i] for i in range(self._dim)], origin = self._origin, axis = self._axis)
@property
def axis(self):
return self._axis
@property
def dim(self):
return self._dim
@property
def dimension(self):
return self._dim
@property
def dtype(self):
return self._dtype
@property
def head(self):
"""Return as a list."""
return self._coordinates
@property
def origin(self):
"""Return as a list."""
return self._origin
@property
def tail(self):
"""Return as a list."""
return self._origin
def _checkTypeCompatability(self, other):
"""A type check to make sure that operations between vectors are specified
using the Vector class."""
if type(other) != Vector:
raise TypeError("Both arguments must be of the Vector class.")
if len(self._coordinates) != len(other._coordinates):
raise Exception("Vectors are of unequal dimension.")
if self._origin != other._origin:
raise Exception("Specified origins must match.")
def _undef(self):
"""A catch-all method to be called if a mathematical operation is undefined."""
raise Exception("This operation is undefined on vectors.")
def add(self, other):
"""A direct method for the addition of two vectors."""
return self.__add__(other)
def angle(self, other, units = "rad"):
self._checkTypeCompatability(other)
if units == "deg" or units == "degree" or units == "degrees":
rads = False
elif units == "rad" or units == "rads" or units == "radian" or units == "radians":
rads = True
else:
raise Exception('Unknown unit specification. Use "rad" for radians or "deg" for degrees.')
numerator = self.dot(other)
denominator = self.norm() * other.norm()
cosTheta = numerator / denominator
if rads:
return acos(cosTheta)
else:
return acos(cosTheta) * (180 / pi)
def cross(self, other):
"""Compute the cross product of two, three-dimensional vectors."""
if self._dim != 3 or other._dim != 3:
raise Exception("The cross product is only defined for 3-dimensional vectors.")
self._checkTypeCompatability(other)
newVec = []
newVec.append(self[1] * other[2] - self[2] * other[1])
newVec.append(self[0] * other[2] - self[2] * other[0])
newVec.append(self[0] * other[1] - self[1] * other[0])
return Vector(newVec, origin=self.origin)
def dot(self, other):
"""Compute the dot product of two vectors. The dot product is returned as
a float."""
self._checkTypeCompatability(other)
dotProduct = 0
for i in range(self._dim):
dotProduct += self._coordinates[i] * other._coordinates[i]
return dotProduct
def norm(self):
"""Compute the Euclidean norm of a vector. This is the same as length
in a Euclidean space. The norm is returned as a float."""
euclideanNorm = 0.0
if self._origin == []:
tempOrigin = [0 for i in range(self._dim)]
else:
tempOrigin = self._origin
for i in range(self._dim):
euclideanNorm += (self._coordinates[i] - tempOrigin[i]) ** 2
return sqrt(euclideanNorm)
def proj(self, other):
"""Return the projection of self onto other."""
self._checkTypeCompatability(other)
scalar = self.dot(other) / other.norm()
return Vector(scalar * other, origin = self.origin, axis = self.axis)
def shift(self, newOrigin = []):
"""Shift the vector to a new origin. The new origin must be specified
as a list with the same dimension as the Vector. If the origin is
not specified, the origin is moved to [0, 0, ...]."""
if newOrigin == [] and self._origin == []:
return Vector(self)
elif newOrigin == [] and self._origin != []:
return Vector([self._coordinates[i] - self._origin[i] for i in range(self._dim)], origin = [], axis = self._axis)
else:
if len(newOrigin) != self._dim:
raise Exception("Shift is not the same dimension as Vector.")
return Vector([self._coordinates[i] + newOrigin[i] for i in range(self._dim)], origin = newOrigin, axis = self._axis)
def smul(self, other):
"""A direct method for scalar multiplication."""
return self.__mul__(other)
def sub(self, other):
"""A direct method for the subtraction of two vectors."""
return self.__sub__(other)
def triple(self, other1, other2):
"""Compute a . (b x c)."""
return float(self.dot(other1.cross(other2)))
def unit(self):
"""If the dimension of the vector is between one and three, provide a
string representation of the vector as a combination of unit vectors."""
if self._dim > 3:
raise Exception("Unit vector representation only available for vectors of dimension one through three.")
unitString = ""
if self._dim >= 1:
if self[0] >= 0:
unitString = str(self[0]) + "\u00ee"
else:
unitString = "-" + str(abs(self[0])) + "\u00ee"
if self._dim >= 2:
if self[1] >= 0:
unitString += " + " + str(self[1]) + "\u0135"
else:
unitString += " - " + str(abs(self[1])) + "\u0135"
if self._dim == 3:
if self[2] >= 0:
unitString += " + " + str(self[2]) + "k\u0302"
else:
unitString += " - " + str(abs(self[2])) + "k\u0302"
return unitString
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
def val_nota(v):
if(v!=1 and v!=2 and v!=4 and v!=8 and v!=16 and v!=32):
print("ERRO Nº4 - Valor da nota inválido!")
return False
return True
def main(demo):
#demo = "The Simpsons:d=4,o=5,b=160:c.6,e6,f#6,8a,g.6,e6,c6,8a,8f#,8f#,8f#,2g,8p,8p,8f#,8f#,8f#,8g,a#.,8c6,8c6,8c6,c6"
demo = demo.split(":")
if(len(demo)!=3):
print("ERRO Nº1 - Pauta mal construida")
return "ERRO Nº1 - Pauta mal construida"
title = demo[0]
referencias = demo[1]
pauta = demo[2]
#########################################################################3
# Referencias PARSE VVVVVVV
referencias = referencias.split(",")
if(len(referencias)!=3):
if(len(referencias)<3):
if(len(referencias)==0):
d=4
o=6
b=63
if(len(referencias)==2):
if(referencias[0][0]=="d" and referencias[1][0]=="o"):
d = int(referencias[0][2:])
if(val_nota(d)!= True):
return
o = int(referencias[1][2:])
b = 63
if(referencias[0][0]=="o" and referencias[1][0]=="b"):
d = 4
o = int(referencias[0][2:])
b = int(referencias[1][2:])
if(referencias[0][0]=="d" and referencias[1][0]=="b"):
d = int(referencias[0][2:])
if(val_nota(d)!= True):
return
o = 6
b = int(referencias[1][2:])
else:
print("ERRO Nº3 - Referencias invalidas")
return "ERRO Nº3 - Referencias invalidas"
else:
if(referencias[0][0]=="d"):
d = int(referencias[0][2:])
if(val_nota(d)!= True):
return
o = 6
b = 63
if(referencias[0][0]=="o"):
d = 4
o = int(referencias[0][2:])
b = 63
if(referencias[0][0]=="b"):
d = 4
o = 6
b = int(referencias[1][2:])
else:
print("ERRO Nº3 - Referencias invalidas")
return "ERRO Nº3 - Referencias invalidas"
else:
print("ERRO Nº2 - Demasiadas referencias")
return "ERRO Nº2 - Demasiadas referencias"
else:
d = int(referencias[0][2:])
if(val_nota(d)!= True):
return
o = int(referencias[1][2:])
b = int(referencias[2][2:])
#################################################################
# Construtor de freq[] VVVVVV
n = -9
freq = []
for tom in range(0, 108):
freq.insert(tom, int(440 * pow(2,n/float(12))))
if(n!=50):
n +=1
else:
n = -57
#################################################################
# Pauta PARSE e Escrita do ficheiro VVVVVV
indx = ['c', 'c#', 'd', 'd#', 'e', 'f', 'f#', 'g', 'g#', 'a', 'a#', 'b', 'p']
pares_file = open(os.path.join("pares", title.replace(" ","")+"-notes.txt"), 'w')
pares_file.write("[ ")
notas = pauta.split(",")
for n in range(0, len(notas)):
escala = o
## Valor da nota e calculo do tempo (ainda sem o ponto)
if(notas[n][0].isdigit()):
try:
if(val_nota(int(notas[n][:2]))!= True):
return
tempo = (4/float(notas[n][:2])) * (60/float(b))
except:
if(val_nota(int(notas[n][0]))!= True):
return
tempo = (4/float(notas[n][0])) * (60/float(b))
## Nota
if(len(notas[n])>2):
if(notas[n][2] == "#"):
try:
nota = indx.index(notas[n][1:3])
except:
print("ERRO Nº5 - Nota inválida")
return "ERRO Nº5 - Nota inválida"
# Ponto / Oitava
if(len(notas[n])>3):
if(notas[n][3] == "."):
tempo = tempo * 1.5
if(len(notas[n])>4):
if(notas[n][4].isdigit()):
if(int(notas[n][4])>=0 and int(notas[n][4])<=8):
escala = int(notas[n][4])
else:
print("ERRO Nº6 - Escala inválida")
return "ERRO Nº6 - Escala inválida"
else:
if(notas[n][3].isdigit()):
if(int(notas[n][3])>=0 and int(notas[n][3])<=8):
escala = int(notas[n][3])
else:
print("ERRO Nº6 - Escala inválida")
return "ERRO Nº6 - Escala inválida"
else:
try:
nota = indx.index(notas[n][1])
except:
try:
nota = indx.index(notas[n][2])
except:
print("ERRO Nº5 - Nota inválida")
return "ERRO Nº5 - Nota inválida"
# Ponto / Oitava
if(notas[n][2] == "."):
tempo = tempo * 1.5
if(len(notas[n])>3):
if(notas[n][3].isdigit()):
if(int(notas[n][3])>=0 and int(notas[n][3])<=8):
escala = int(notas[n][3])
else:
print("ERRO Nº6 - Escala inválida")
return "ERRO Nº6 - Escala inválida"
else:
if(notas[n][2].isdigit()):
if(int(notas[n][2])>=0 and int(notas[n][2])<=8):
escala = int(notas[n][2])
else:
print("ERRO Nº6 - Escala inválida")
return "ERRO Nº6 - Escala inválida"
else:
try:
nota = indx.index(notas[n][1])
except:
print("ERRO Nº5 - Nota inválida")
return "ERRO Nº5 - Nota inválida"
###################################################
else:
tempo = (4/float(d)) * (60/float(b))
if(len(notas[n])>1):
if(notas[n][1] == "#"):
try:
nota = indx.index(notas[n][0:2])
except:
print("ERRO Nº5 - Nota inválida")
return "ERRO Nº5 - Nota inválida"
# Ponto / Oitava
if(len(notas[n])>2):
if(notas[n][2] == "."):
tempo = tempo * 1.5
if(len(notas[n])>3):
if(notas[n][3].isdigit()):
if(int(notas[n][3])>=0 and int(notas[n][3])<=8):
escala = int(notas[n][3])
else:
print("ERRO Nº6 - Escala inválida")
return "ERRO Nº6 - Escala inválida"
else:
if(notas[n][2].isdigit()):
if(int(notas[n][2])>=0 and int(notas[n][2])<=8):
escala = int(notas[n][2])
else:
print("ERRO Nº6 - Escala inválida")
return "ERRO Nº6 - Escala inválida"
else:
try:
nota = indx.index(notas[n][0])
except:
print("ERRO Nº5 - Nota inválida")
return "ERRO Nº5 - Nota inválida"
# Ponto / Oitava
if(notas[n][1] == "."):
tempo = tempo * 1.5
if(len(notas[n])>2):
if(notas[n][2].isdigit()):
if(int(notas[n][2])>=0 and int(notas[n][2])<=8):
escala = int(notas[n][2])
else:
print("ERRO Nº6 - Escala inválida")
return "ERRO Nº6 - Escala inválida"
else:
if(notas[n][1].isdigit()):
if(int(notas[n][1])>=0 and int(notas[n][1])<=8):
escala = int(notas[n][1])
else:
print("ERRO Nº6 - Escala inválida")
return "ERRO Nº6 - Escala inválida"
else:
try:
nota = indx.index(notas[n][0])
except:
print("ERRO Nº5 - Nota inválida")
return "ERRO Nº5 - Nota inválida"
if(nota!=12):
pares_file.write("("+str(round(tempo, 3))+", "+str(freq[12*(escala-4)+nota])+"), \n")
else:
pares_file.write("("+str(round(tempo,3))+", 0), \n")
pares_file.write(" ]")
pares_file.close()
return "Sucess"
##################################################################
|
def binary_search(lst,item):
found = False
lower = 0
higher = len(lst)-1
lst.sort()
while lower <= higher and not found:
mid = (lower + higher)//2
print("Searching for the number :"+str(lst[lower:higher]))
print("The lower number is: "+str(lst[lower])+"List index is: "+str(lower))
print("The middle number is: "+str(lst[mid])+"List indexis: "+str(mid))
print("The higher number is: "+str(lst[higher])+"List index is: "+str(higher))
print("Is it ?"+str(lst[mid]))
if lst[mid] == item:
print("The number is found at the index {}".format(lst.index(item)))
found = True
elif lst[mid] < item:
lower = mid + 1
print("Higher")
else:
higher = mid - 1
print("Lower")
return found
mylist = [2,3,5,4,8,7,9,11,6,14,25,37]
myitem = 3
print(binary_search(mylist,myitem))
|
def set_x():
x = 2
return None
#print(set_x())
#print(list(map(int,"123")))
items = ['Banana', 'Apple', 'Orange' ]
qty = [1, 2, 3]
print(list(zip(items, map(lambda x: x*10, qty))))
|
import pandas as pd
import numpy as np
import string
pd.set_option('display.max_columns', None)
df = pd.read_csv("starbucks_store_worldwide.csv")
# print(df.info())
# ca cn
groupd = df.groupby(by=["Country","State/Province"])[["Country"]].count()
# print(groupd.loc[['CN'],"Country"])
# CNdf =
# print(CNdf)
df_index = pd.DataFrame(np.random.randint(1,20,(7,5)),index=list(string.ascii_letters[0:7]),columns=list(string.ascii_uppercase[-5:]))
print(df_index)
df1 = df_index.set_index(['X','Z'],drop = False)
print(df1.loc[["2","15"],"W"])
|
arv = float(input("Palun sisesta ruudu külg"))
arv = arv * 4
print("Ruudu ümbermõõt on",arv)
külg_1 = float(input("Sisesta esimese külje pikkus"))
külg_2 = float(input("Sisesta teise külje pikkus"))
print("Ristküliku ümbermööt on",(külg_1+külg_2) * 2,"cm")
|
import math
class Sudoku():
def __init__(self, lista):
self.table = lista
self.tablero_original = []
for i in range(len(self.table)):
for j in range(len(self.table)):
if (self.table[i][j] != "x"):
self.tablero_original.append((i, j))
def validar(self, fila, columna, numero):
#verifica si se repite algun numero en alguna fila o columna
for elemento in range(9):
if self.table[fila][elemento] == numero:
return False
if self.table[elemento][columna] == numero:
return False
return True
#verifica si se repite algun numero en alguna zona
def checkeo_zona(self, fila, columna, valor):
fila = (fila // 3) * 3
columna = (columna // 3) * 3
for i in range(3):
for j in range(3):
if (self.table[int(fila + i)][int(columna + j)] == str(valor)):
return False
return True
def intercambio_numero(self,fila,columna,valor):
if self.checkeo_zona(fila,columna,valor) and self.validar(fila,columna,valor):
self.table [fila][columna] = valor
return True
else:
return False
def gano(self):
for fila in self.table:
if "x" in fila:
return False
else:
return True
|
#!/usr/bin/python3
class Student:
def __init__(self, first_name, last_name, age):
self.first_name = first_name
self.last_name = last_name
self.age = age
def to_json(self, attrs=None):
if type(attrs) == list:
dic = {}
for x in attrs:
if self.__dict__.__contains__(x):
dic[x] = self.__dict__[x]
return dic
return self.__dict__
def reload_from_json(self, json):
for x in json.keys():
if self.__dict__.__contains__(x):
self.__dict__[x] = json[x]
|
class NoFly:
def fly(self):
return "Cannot fly"
class NoSound:
def make_sound(self):
return "..."
class Duck(NoFly, NoSound):
def __init__(self, name="Duck"):
self.name = name
def fly(self):
return print(" ".join((self.name, '-', super().fly())))
def make_sound(self):
return print(" ".join((self.name, '-', super().make_sound())))
if __name__ == '__main__':
d = Duck(name="Nemopy")
d.fly()
d.make_sound()
# print(help(d))
|
import json
"""
This module is used to make sure the mail isn't from a non allowed email address and the destination is
a valid email address
Return values :
100 : The destination address is whitelisted and the sending address is not blacklisted
0 : The destination address isn't whitelisted (sender won't be checked in this case)
0 : The destination address is whitelisted but the sending address is blacklisted
"""
def CheckMailValidity(jsonFile,to, sender):
# Opening the json file given in params
with open(jsonFile) as json_file:
data = json.load(json_file)
# Debug
print(data['to'])
print(data['sender'])
# Check if the destination mail is in the whitelist
if to in data['to']:
# If it is then we make sure the sender isn't blacklisted
if sender in data['sender']:
# If the sender is blacklisted we return 2
return 2
else:
# The sender is allowed to send mail we return 0
return 0
else:
# The destination address isn't allowed we return 1
return 1
print(CheckMailValidity('/xxx/xxx/xxx/xxx/parameters',"[email protected]","[email protected]"))
|
import random
user_choice = 0
comp_choice = 0
def user_choose():
print("")
choice = input("Choose any one from Rock[r/R], Paper[p/P], Scissor[s/S]: ")
if choice in ["Rock", "r", "rock", "ROCK", "R"]:
choice = "r"
elif choice in ["Paper", "p", "paper", "PAPER", "P"]:
choice = "p"
elif choice in ["Scissor", "s", "scissor", "SCISSOR", "S"]:
choice = "s"
else:
print("Please enter from the given.....")
user_choose()
return choice
def comp_choose():
print("")
choice = random.randint(1,3)
if choice == 1:
choice = "r"
if choice == 2:
choice = "p"
if choice == 3:
choice = "s"
return choice
while True:
print("")
choice1 = user_choose()
choice2 = comp_choose()
print("")
if choice1 == "r":
if choice2 == "r":
print("Your choice is: Rock\nComputer's choice is: Rock\nSo no points for this round ;)")
elif choice2 == "p":
print("Your choice is: Rock\nComputer's choice is: Paper\nSo you loose :(")
comp_choice +=1
elif choice2 == "s":
print("Your choice is: Rock\nCompuetr's choice is: Scissor\nSo you win :)")
user_choice +=1
if choice1 == "p":
if choice2 == "p":
print("Your choice is: Paper\nComputer's choice is: Paper\nSo no points for this round ;)")
elif choice2 == "r":
print("Your choice is: Paper\nComputer's choice is: Rock\nSo you win :)")
user_choice +=1
elif choice2 == "s":
print("Your choice is: Paper\nComputer's choice is: Scissor\nSo you loose :(")
comp_choice +=1
if choice1 == "s":
if choice2 == "s":
print("Your choice is: Scissor\nComputer's choice is: Scissor\nSo no points for this round ;)")
elif choice2 == "r":
print("Your choice is: Scissor\nComputer's choice is: Rock\nSo you loose :(")
comp_choice +=1
elif choice2 == "p":
print("Your choice is: Scissor\nComputer's choice is: Paper\nSo you win :)")
user_choice +=1
print("")
print("Score=========>>>>>>>>\nUser -> {0}\nComputer -> {1}".format(str(user_choice),str(comp_choice)))
choice3 = input("Continue[y/n]?")
if choice3 == "y":
pass
elif choice3 == "n":
print('Final score:\n User: {0}\n Computer: {1}'.format(str(user_choice), str(comp_choice)))
if (user_choice > comp_choice):
print('Conrats, you won!')
else:
print('Better luck next time.')
break
else:
print('Final score:\n User: {0}\n Computer: {1}'.format(str(user_choice), str(comp_choice)))
if (user_choice > comp_choice):
print('Conrats, you won!')
else:
print('Better luck next time.')
break
|
# Python program to print Prime Numbers Between 1 to 20
firstNumber =1
lastNumber =20
print("Prime Numbers Between 1 to 20 are :")
while firstNumber<=lastNumber:
for i in range(lastNumber+1):
if i==lastNumber:
firstNumber +=1
# print("number now ", number)
for j in range(2, lastNumber):
if firstNumber!=j:
if(firstNumber%j)==0:
# print(number)
break
else:
print(firstNumber)
'''
Prime Numbers Between 1 to 20 are :
2
3
5
7
11
13
17
19
'''
|
# Python program to check whether a number is prime number
# 2,3,5,7,11,13,17,19
number = int(input("Enter a number "))
if(number<=1):
print("Enter number greater than 1")
else:
for i in range(2,number):
if(number%i)==0:
print(number ," is not a Prime ")
break
else:
print(number," is Prime Number")
'''
Test Case 1
Enter a number 1
Enter number greater than 1
Test Case 2
Enter a number 2
2 is Prime Number
Test Case 3
Enter a number 7
7 is Prime Number
Test Case 4
Enter a number 10
10 is not a Prime
'''
|
"""
Python 2
2-player Battleship
Author: Pairode Jaroensri
Last visited: August 2016
"""
import os
os.system('clear')
board1 = [] # Show to the other player
board1_content = [] # Show to owner
board2 = []
board2_content = []
for x in range(8):
board1.append(["O"] * 8)
board1_content.append(["O"] * 8)
board2.append(["O"] * 8)
board2_content.append(["O"] * 8)
def print_board(board):
for row in board:
print " ".join(row)
#cv bb ca dd
#Place the ship on the board after the user has entered values
def place_ship(board, len_ship):
undo_board = [x for x in board]
repeat = True
while repeat:
board = undo_board
if len_ship == 5: #Tell ship class
print "Place your aircraft carrier."
elif len_ship == 4:
print "Place your battleship"
elif len_ship == 3:
print "Place your cruiser"
elif len_ship == 2:
print "Place your destroyer"
print_board(board)
orientation = raw_input("Choose your orientation. V = verticle; H = horizontal: ")
if orientation == 'v' or orientation == 'V': #vertical
x = input("X coordinate: ") - 1
y = input("Y coordinate: ") - 1
if x <= len(board) and y + len_ship <= len(board): #Check if the ship is on the board.
space = [] #Check if the coordinate is empty.
for i in range(len_ship):
space.append(board[y+i][x])
space.sort()
check = []
index = 0
while index < len(space):
if index != 0 and space[index] == space[index-1]:
index += 1
else:
check.append(space[index])
index += 1
#print "check is: ", check
if len(check) == 1 and check[0] != 'S': #Okay to place the ship.
for i in range(len_ship):
board[y+i][x] = 'S'
print "Ship placed"
print_board(board)
repeat = False
else:
print "The coordinates are not empty. Try again."
else:
print "That is not on the board. Try again."
elif orientation == 'h' or orientation == 'H': #horizontal
x = input("X coordinate: ") - 1
y = input("Y coordinate: ") - 1
if y <= len(board) and x + len_ship <= len(board): #Check if the ship is on the board.
space = [] #Check if the coordinate is empty.
for i in range(len_ship):
space.append(board[y][x+i])
space.sort()
check = []
index = 0
while index < len(space):
if index != 0 and space[index] == space[index-1]:
index += 1
else:
check.append(space[index])
index += 1
print "check is: ", check
if len(check) == 1 and check[0] != 'S': #Okay to place the ship.
for i in range(len_ship):
board[y][x+i] = 'S'
print "Ship placed"
print_board(board)
repeat = False
else:
print "The coordinates are not empty. Try again."
else:
print "That is not on the board. Try again."
else:
print "Invalid orientation. Try again."
print "Kim's Battleship v.2.0 build 072616"
print "Player1's turn to place the ships."
place_ship(board1_content, 5)
place_ship(board1_content, 4)
place_ship(board1_content, 3)
place_ship(board1_content, 2)
go_on = raw_input("Press enter to continue.")
os.system('clear')
print "Player2's turn to place the ships."
place_ship(board2_content, 5)
place_ship(board2_content, 4)
place_ship(board2_content, 3)
place_ship(board2_content, 2)
go_on = raw_input("Press enter to start the game.")
os.system('clear')
player = 1
game_on = True
while game_on:
while player == 1 and game_on:
print "Player1's turn"
print_board(board2)
x_p1 = int(raw_input("Guess X:")) - 1
y_p1 = int(raw_input("Guess Y:")) - 1
if board2_content[y_p1][x_p1] == 'S':
print "Hit!"
board2[y_p1][x_p1] = 'H' #Mark the hit spot on board2.
elif board2[y_p1][x_p1] == 'X':
print "You've already guessed that spot."
else:
print "Miss"
board2[y_p1][x_p1] = 'X' #Mark the miss spot on board2.
player = 2
hit_count_p2 = 0 #Number of hits player2 received.
for row in board2: #Check if player2 has any ship left.
for ele in row:
if ele == 'H':
hit_count_p2 += 1
if hit_count_p2 == 14:
winner = 1
game_on = False
else:
print_board(board2)
go_on = raw_input("Press enter to continue.")
os.system('clear')
while player == 2 and game_on:
print "Player2's turn"
print_board(board1)
x_p2 = int(raw_input("Guess X:")) - 1
y_p2 = int(raw_input("Guess Y:")) - 1
if board1_content[y_p2][x_p2] == 'S':
print "Hit!"
board1[y_p2][x_p2] = 'H'
elif board1[y_p2][x_p2] == 'X':
print "You've already guessed that spot."
else:
print "Miss"
board1[y_p2][x_p2] = 'X'
player = 1
hit_count_p1 = 0 #Number of hits player1 received.
for row in board1:
for ele in row:
if ele == 'H':
hit_count_p1 += 1
if hit_count_p1 == 14:
winner = 2
game_on = False
else:
print_board(board1)
go_on = raw_input("Press enter to continue.")
os.system('clear')
print "Player%i win!" % winner
answer = raw_input("Would you like to see the boards?(Y/N): ")
while answer == 'y' or answer == 'Y' or answer == "":
print "Options:\n 1: Player 1's guesses\n 2: Player 2 ships' positions\n 3: Player 2's guesses\n 4: Player 1 ships' positions\n 5: Exit\n"
choice = raw_input()
if choice == '1':
print_board(board2)
elif choice == '2':
print_board(board2_content)
elif choice == '3':
print_board(board1)
elif choice == '4':
print_board(board1_content)
else:
answer = 'N'
else:
print "Thank you for playing!"
|
"""
Author: Pairode Jaroensri
Last revision: March 3, 2018
This program plots the CPU temperature in real time with the poll rate of FREQUENCY Hz
and plotting up to TIME_LENGTH seconds back.
FREQUENCY is best kept under 5 Hz.
Dependencies: lm-sensors, matplotlib, tkinter
Usage: python3 plot_cpu_temp.py [-h] [frequency] [time]
Remark:
Before using it, you might need to change the variable PAT in GET_CPU_TEMP function
to match your system's lm-sensors output.
"""
import os, re, argparse
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
from matplotlib import animation
from collections import deque
from tkinter import messagebox
def get_cpu_temp():
sensors = os.popen('sensors').read()
pat = 'Package id 0:\s*(\+?\d+\.?\d?)°C'
m = re.search(pat, sensors)
return float(m.group(1))
def animate(temps):
physical = get_cpu_temp()
print(physical, "°C")
if physical >= 80:
messagebox.showwarning("Warning","The CPU temperature has reached 80°C.")
temps.append(physical)
temps.popleft()
line.set_ydata(temps) # update the data
return line,
def init():
line.set_ydata([None for _ in range(-time_length*frequency,1)])
return line,
if __name__ == '__main__':
parser = argparse.ArgumentParser(description = "CPU Temperature Monitor")
parser.add_argument("frequency", nargs='?', default=2, type=int, help = "Poll frequency")
parser.add_argument("time", nargs='?', default=60, type=int, help = "History length in seconds")
args = parser.parse_args()
frequency = args.frequency
time_length = args.time
print("Poll frequency: {0} Hz\nTime: {1} s\n".format(frequency, time_length))
# Set up the figure
fig, ax = plt.subplots()
plt.title("CPU temperature")
ax.yaxis.tick_right()
ax.yaxis.set_label_position("right")
ax.set_ylim([0, 100])
ax.set_xlim([-time_length, 0])
ax.set_xlabel("Time (s)")
ax.set_ylabel("CPU Temp (°C)")
ax.xaxis.set_major_locator(ticker.MultipleLocator(10))
ax.xaxis.set_minor_locator(ticker.MultipleLocator(2))
ax.yaxis.set_major_locator(ticker.MultipleLocator(10))
ax.yaxis.set_minor_locator(ticker.MultipleLocator(2))
for i in range(0, 10):
plt.axhline(i*10, color='0.75')
plt.axvline(-i*10, color='0.75')
# Define history range and temperature polling interval
x = [i/frequency for i in range(-time_length*frequency,1)]
temps = deque()
for i in range(time_length*frequency+1):
temps.append(None)
assert len(x) == len(temps)
line, = ax.plot(x, temps)
line.set_color('r')
ani = animation.FuncAnimation(fig, animate, [temps], init_func=init,
interval=1000/frequency, blit=True)
plt.show()
|
#!/usr/bin/python3
import time
import calendar
#获取时间戳,使用time.time()是时间戳
ticks = time.time()
print("当前时间戳为:",ticks)
#获取本地时间,通过localtime()可以将时间戳显示为年月日时分秒
localtime = time.localtime(time.time())
print("本地时间为:",localtime)
#通过time.asctime()对获取的时间进行处理,显示为 星期 月份 日 时间 年份 的便于浏览样式
localtime1 = time.asctime(localtime)
print("本地时间为:",localtime1)
#通过time.strftime()来显示自己需要的格式
#格式2018-03-20 11:45:39
print(time.strftime("%Y-%m-%d %H:%M:%S"),time.localtime)
#格式Sat Mar 28 22:24:24 2018形式
print(time.strftime("%a %b %d %H:%M:%S %Y"),time.localtime)
#将格式字符串为时间戳
a = "Sat Mar 28 22:24:24 2018"
print(time.mktime(time.strptime(a,"%a %b %d %H:%M:%S %Y")))
cal = calendar.month(2018,1)
cal1 = calendar.calendar(2018,w=2,l=1,c=6)
print("以下是2018年1月的日历")
print(cal)
print(cal1)
|
def getduplicate_numbers(my_number_list):
non_duplicate_list = []
duplicate_list = []
for number in my_number_list:
if number not in non_duplicate_list:
non_duplicate_list.append(number)
else:
duplicate_list.append(number)
#Append the missing number to the list of duplicate number list
duplicate_list.append(4)
return duplicate_list
input_list = [3, 1, 2, 5, 3]
print(getduplicate_numbers(input_list))
|
#Using the word import to import the random function
import random
#shuffle is also part of random, which allows a word to be shuffled
from random import shuffle
#Set the original word so that the code can compare what it is later
originword='jason'
#Create a list so that the word can be shuffled, shuffle only works on lists
word=list('jason')
#Shuffle the actual word
random.shuffle(word)
#The new scrambled word
scrambled= ''.join(word)
#Output the new scrambled word to the user
print ('Can you guess this word ' + scrambled)
lives=5 #Defining how many lives are remaining
guess=0 #Defining how many guesses the user has had
while lives>0:
print('You have {} lives left'.format(lives) ) #Outputting how many lives
userguess=input('What is the word? ')
guess=guess+1
if userguess == originword:#Compare input to original word
print ('Well done! You got it in {} guesses'.format(guess))
exit() #Quit the program
else:
lives=lives-1 #Deducting a life
guess=guess+1 #Adding a guess to no. of guesses
print ('Try again, you have {} remaining'.format(lives))
print('You used up all of your lives, sorry!') #End of program where all lives used
|
##CHANGES -V1.0##
#NA - Beginning of the code!
import turtle
import math
#creating a new screen
window = turtle.Screen()
#set backbground to black
window.bgcolor("black")
#Name window A mAze game
window.title("A Maze game")
#How big the window should be
window.setup(700,700)
#A class is a definition of an object - defines its behaviour + properties
#Defining a new class called Pen that will become a turtle
class Pen(turtle.Turtle):
def __init__(self): #referring to the object that will be called on
turtle.Turtle.__init__(self) #initialise pen
self.shape("square") #shape of the person
self.color("white") #color of the person
self.penup() #By default, a turtle leaves a trail behind, we don't want this
self.speed(0) #Animation speed
#Defining a new class for the player
class Player(turtle.Turtle):
def __init__(self):
turtle.Turtle.__init__(self)
self.shape("square")
self.color("yellow")
self.penup()
self.speed(0)
#defining the movement of the player
def go_up(self):
move_x = player.xcor()
move_y = player.ycor() + 24
if (move_x, move_y) not in wall_coords: #if where the player will move to is not in the wall coords list, then it will move
self.goto(move_x, move_y) #Y cor is vertical so + is up
def go_down(self):
move_x = player.xcor()
move_y = player.ycor() - 24
if (move_x, move_y) not in wall_coords:
self.goto(move_x, move_y)
#Going left is negative
def go_left(self):
move_x = player.xcor() - 24
move_y = player.ycor()
if (move_x, move_y) not in wall_coords:
self.goto(move_x, move_y)
#Going right is positive
def go_right(self):
move_x = player.xcor() + 24
move_y = player.ycor()
if (move_x, move_y) not in wall_coords:
self.goto(move_x, move_y)
def reached_end(self,other): #other would be the player
a = self.xcor()-other.xcor()
b = self.ycor()-other.ycor()
distance = math.sqrt((a ** 2) + (b ** 2) )
if distance < 5:
return True
else:
return False
class End(turtle.Turtle):
def __init__(self, x, y): #referring to the object that will be called on
turtle.Turtle.__init__(self) #initialise pen
self.shape("circle") #shape of the person
self.color("red") #color of the person
self.penup() #By default, a turtle leaves a trail behind, we don't want this
self.speed(0) #Animation speed
self.goto(x, y)
levels = [""]
#defining the first level
#grid size is 25x25 in text
#x -> horizxontal
#y ^ vertical
level0 = [
"XXXXXXXXXXXXXXXXXXXXXXXXX",
"XXXXXXXXXXXXXXXXXXP XXXXX",
"XXXXXXXXXXXXXXXXXX XXXXX",
"XXXXXXXXXXXXXXXX XXXXX",
"XXXXXXXXXXXXXXXX XXXXXXX",
"XXXXXXXXXXXXXXX XXXXXXXX",
"XXXXXXXXXXXXXXX XXXXXXXX",
"XXXXXXXXXXXXXXX XXXXXXXX",
"XXXXXXXX XXXXXXXX",
"XXXXXXXX XXXXXXXXXX",
"XXXXXXXX XXXXXXXXXXXXXXX",
"XXXXXXXX XXXXXXXXXXXXXXX",
"XXXXXXXX XXXXXXXXXXXXXXX",
"XXXXXXXX XXXXXXXXXXXXXXX",
"XXXXXXXX XXXXXXXXXXXXXXX",
"XXXXXXXX XXXXXXXXXXXXXXX",
"XXXXXXXX ",
"XXXXXXXX ",
"XXXXXXXXXXXXXXXXXX XXXXX",
"XXXXXXXXXXXXXXXXXX XXXXX",
"XXXXXXXXXXXXXXXXXX XXXXX",
"XXXXXXXXXXXXXXXXXX XXXXX",
" E XXXXX",
" XXXXX",
"XXXXXXXXXXXXXXXXXXXXXXXXX"
]
levels.append(level0)
print (levels)
def draw_maze(level): #the levels list
for y in range(len(level)): #for y coords
for x in range(len(level[y])):
#Get the characgter at each x,y coord
#Y goes first as the maze is stored in a LIST, so goes line by line, vertically
character = level[y][x]
#Go through the list and note down all coordinates for each character
x_coords = -288 + (x * 24) #24 is for each bl ock accross
y_coords = 288 - (y * 24)
finalcoords = (x_coords, y_coords)
#If an X is down, draw a block in the maze
if character == "X":
pen.goto(finalcoords)
pen.stamp()
#also add the coords to the wall_coords list to be saved later
wall_coords.append((finalcoords))
if character == "P":
player.goto(finalcoords) #set the player to start where P is located
if character == "E":
endpointcoord.append(End(x_coords, y_coords))
pen = Pen()
player = Player()
#create a list calles walls so we know the coordinates of the walls so player cant walk into it
wall_coords = []
endpointcoord =[]
#Setup the level
draw_maze(levels[1])
#Keyboard controls
window.listen()
window.onkey(player.go_left,"Left") #left arrow
window.onkey(player.go_right,"Right") #right arrow
window.onkey(player.go_up,"Up") #Up key
window.onkey(player.go_down,"Down") #Down key
window.tracer(0)
while True:
window.update() #update the screen
for end in endpointcoord:
if player.reached_end(end):
print("Conratulations you have reached the end!")
turtle.bye()
window.update
|
import sys
def read_stdin_col(col_num):
"""
Function that reads an input file from stdin, takes a column number and
converts the numbers in the column to a list
Arguments
---------
col_num : int
Column number to read from stdin and convert to list
Returns
-------
column : list
The list of values in the specified column
"""
if col_num is None:
raise TypeError('read_stdin_col: No column number supplied to function')
if not isinstance(col_num,int):
raise TypeError('read_stdin_col: Column number must be an integer')
array = sys.stdin.readlines()
if len(array[0].rstrip().split(' ')) < col_num:
raise IndexError('read_stdin_col: Column number is out of range')
column = []
for line in array:
column.append(int(line.rstrip().split(' ')[col_num]))
return column
|
from article import Article
import os
class Warehouse:
def __init__(self):
self.run = True
self.spaces = {
"a1": None,
"a2": None,
"a3": None,
"b1": None,
"b2": None,
"b3": None
}
self.weight = 0
self.occupied = 0
self.available = 6
self.status = None
def add_article(self, place, article):
print("add article", article.name)
if self.spaces[place]:
self.status = "The choosen space is already taken!"
else:
self.spaces[place] = article
def remove_article(self, place):
if (self.spaces[place]):
self.spaces[place] = None
def calculate_current_weight_and_stock(self):
weight = 0
occupied = 0
for _, v in self.spaces.items():
if (v):
weight = weight + v.weight
occupied = occupied + 1
self.weight = weight
self.occupied = occupied
self.available = 6 - occupied
def next_tick(self):
userInput = input(
"(a) to add, (r) to remove and (e) to exit: ")
if (userInput == "a"):
if (self.available == 0):
self.status = "Stock is full! Not able to add new item!"
else:
name = input("Name of your article? ")
weight = float(
input("Weight of your article?"))
place = input("On which Space should i put your item?")
article = Article(name, weight)
self.add_article(place, article)
if (userInput == "r"):
place = input("Which space should i empty")
self.remove_article(place)
if (userInput == "e"):
self.run = False
def print_current_stock(self):
for k in self.spaces.keys():
if (self.spaces[k]):
print(k, ":", self.spaces[k].name)
else:
print(k, ": Empty")
def print_status(self):
self.calculate_current_weight_and_stock()
print("Available Spaces: ", self.available)
print("Occupied Spaces: ", self.occupied)
print("Total Weight: ", self.weight)
if (self.status):
print("")
print(self.status)
print("")
self.status = None
def start(self):
while self.run:
os.system("cls")
print("Hello my name is Bob! I'm your personal warehouse assistent!")
self.print_current_stock()
print("")
self.print_status()
self.next_tick()
|
#Mathematische Formel zur Berechnung des Pascalschen Dreiecks:
#Im Prinzip ist das Pascalsche Dreieck die Darstellung der Binomialkoeffizienten.
#Es ergibt sich also, dass der untergeordnete Wert die Summe der darübergeordneten Elemente ist.
list1 = [[1]]
list2 = []
count = 0
print("Hallo mein Name ist Bob! \nIch werde heute ihr Pascalsches Dreieck erstellen!")
print("Bitte Anzahl der Zeilen eingeben!")
rows = int(input(">> "))
while count != rows:
for i in range(rows - 1):
for j in range(len(list1[i]) + 1):
if 1 <= j <= len(list1[i]) - 1:
number = list1[i][j - 1] + list1[i][j]
list2.append(number)
else:
list2.append(1)
if list2 not in list1:
list1.append(list2)
list2 = []
count += 1
bige = len(str(max(list1[-1]))) #Auslesen des größten Wertes der Liste
lastrow = ' '.join([str(eintrag).center(bige) for eintrag in list1[-1]]) #Auslesen der letzten Zeile
for i in list1:
print(' '.join([str(eintrag).center(bige) for eintrag in i]).center(len(lastrow))) #Ausgabe des Dreiecks
|
"""Implimentation of the recursive binary search algorithm.
Uses the divide-and-conquer method to find an element in a list.
"""
def binary_search(lst: list, left: int, right: int, target: int):
if right >= left:
mid = left + (right - left) // 2
#print(mid)
if lst[mid] == target:
return mid
elif lst[mid] > target:
return binary_search(lst, left, mid - 1, target)
else:
return binary_search(lst, mid + 1, right, target)
else:
return None
def main(lst: list, target: int):
left = 0
right = len(lst) - 1
return binary_search(lst, left, right, target)
|
sqr = []
for i in range(1, 11):
sqr.append(i**2)
print(sqr)
sqr1 = [i**2 for i in range(1, 11)]
print(sqr1)
neg = []
for j in range(1, 11):
neg.append(-j)
print(neg)
neg1 = [-j for j in range(1, 11)]
print(neg1)
names = ["neeraj", "kumar", "chauhan"]
first = []
for name in names:
first.append(name[0])
print(first)
first1 = [name[0] for name in names]
print(first1)
|
class Laptop:
def __init__(self, brand, model, price):
self.brand = brand
self.model = model
self.price = price
self.name = brand + " " + model
l1 = Laptop("dell", "n5010", 45000)
l2 = Laptop("lenovo", "l3451", 30000)
print(l1.brand)
print(l2.brand)
print(l1.name)
|
s = {"a", "b", "c"}
if "a" in s:
print("present")
else:
print("not present")
for i in s:
print(i)
s1 = {1, 2, 3, 4, 5, 6, 7}
s2 = {4, 5, 6, 7, 8, 9, 10}
union = s1 | s2
intersection = s1 & s2
print(union)
print(intersection)
|
num = int(input("Enter number upto which you want sum : "))
sum = 0
for i in range(1, num + 1):
sum = sum + i
print(f"Sum = {sum}")
|
num = int(input("Enter an +ve integer : "))
def cube(n):
c = {}
for i in range(1,n+1):
c[i] = i**3
return c
print(cube(num))
|
fruits1 = ["grapes", "banana", "apple", "mango"]
fruits2 = ("grapes", "banana", "apple", "mango")
fruits3 = {"grapes", "banana", "apple", "mango"}
print(sorted(fruits1))
print(fruits1)
print(sorted(fruits2))
print(fruits2)
print(sorted(fruits3))
print(fruits3)
names = [
{"name" : "neeraj", "age" : 23},
{"name" : "kumar", "age" : 22},
{"name" : "chauhan", "age" : 25}
]
print(sorted(names, key = lambda d : d["age"]))
print(sorted(names, key = lambda d : d["age"], reverse = True))
|
num = [1, 2, 3, 4]
square = list(map(lambda a : a**2, num))
print(square)
names = ["Neeraj", "Kumar", "Chauhan"]
length = list(map(len, names))
print(length)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.