text stringlengths 37 1.41M |
|---|
# https://leetcode.com/problems/second-minimum-node-in-a-binary-tree/description/
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def findSecondMinimumValue(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root: return -1
return self.dfs(root, root.val)
def dfs(self, root, val):
if not root: return -1
if root.val != val: return root.val
if not root.left and not root.right: return -1
res = left = self.dfs(root.left, val)
if left == -1: res = self.dfs(root.right, val)
else:
right = self.dfs(root.right, val)
if right == -1: return res
else: return min(res, right)
return res
|
# https://leetcode.com/problems/path-sum-iii/description/
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def pathSum(self, root, T):
"""
:type root: TreeNode
:type sum: int
:rtype: int
"""
if not root: return 0
self.res = 0
self.dfs(root, 0, T, set())
return self.res
def dfs(self, root, sum, T, resetted):
sum += root.val
if sum == T: self.res += 1
if root.left:
self.dfs(root.left, sum, T, resetted)
if root not in resetted: self.dfs(root.left, 0, T, resetted)
if root.right:
self.dfs(root.right, sum, T, resetted)
if root not in resetted: self.dfs(root.right, 0, T, resetted)
resetted.add(root)
|
# https://leetcode.com/problems/convert-a-number-to-hexadecimal/description/
class Solution(object):
def toHex(self, num):
"""
:type num: int
:rtype: str
"""
if num == 0: return '0'
if num < 0: num &= ((1 << 32) - 1)
hex = {n:str(n) for n in xrange(10)}
hex.update({10:'a',11:'b',12:'c',13:'d',14:'e',15:'f'})
res = ''
while num:
res += hex[num & 15]
num = num >> 4
return res[::-1]
|
# anagram = both strings must contain the same exact letters in the same exact frequency
# --> the length of both strings must be equal
# we'll have two strings --> both can be any length, and can be different
# to make into anagram, we have to remove characters from the longer string
#
# how will we know which characters to delete?
# keep an internal dict of both strings w/key = char, and value = charcount
# iterate through the longer dictionary, check each character count
# if the the other dict doesn't have the char, then delete all from the current dict (and change the str)
# delete #currentdict
# elif the other dict has less chars, delete some from the current dict (and change the str)
# delete (#currentdict - #otherdict) characters
# elif the other dict has more chars, delete some from that dict (and change the str)
# delete (#otherdict - #currentdict) characters
# else if they're equal --> perfect! go to next iteration
def number_needed(a, b):
nA = len(a); nB = len(b)
map_a = {c : a.count(c) for c in a}; map_b = {c : b.count(c) for c in b};
longer_dict = map_a if nA > nB else map_b
shorter_dict = map_b if longer_dict == map_a else map_a
count = 0
for c in set(longer_dict.keys()):
if c not in shorter_dict:
count += longer_dict[c]
longer_dict.pop(c)
elif longer_dict[c] > shorter_dict[c]:
count += longer_dict[c] - shorter_dict[c]
longer_dict[c] = shorter_dict[c]
elif longer_dict[c] < shorter_dict[c]:
count += shorter_dict[c] - longer_dict[c]
longer_dict[c] = shorter_dict[c]
for c in shorter_dict:
if c not in longer_dict:
count += shorter_dict[c]
elif shorter_dict[c] > longer_dict[c]:
count += shorter_dict[c] - longer_dict[c]
elif shorter_dict[c] < longer_dict[c]:
count += longer_dict[c] - shorter_dict[c]
return count
a = input().strip()
b = input().strip()
print(number_needed(a, b))
|
# https://leetcode.com/problems/find-largest-value-in-each-tree-row/description/
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def largestValues(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return []
self.max_map = dict()
self.dfs(root, 0)
result = [0 for k in range(max(self.max_map.keys()) + 1)]
for level in self.max_map:
result[level] = self.max_map[level]
return result
def dfs(self, root, level):
if not root:
return
if level not in self.max_map:
self.max_map[level] = root.val
else:
self.max_map[level] = max(self.max_map[level], root.val)
self.dfs(root.left, level + 1)
self.dfs(root.right, level + 1)
|
# Implement binary search given an integer array
# Given integer array, integer to find --> output whether integer is inside the array
# Array --> not guaranteed to be sorted
# [1, 2, 3], 4
def binarySearch(array, integer):
# WE can asssume the array is sorted
if not array:
return False
left = 0
right = len(array)-1
while left < right:
mid = (left + right) // 2
if array[left] == integer or array[right] == integer:
return True
if array[mid] == integer:
return True
elif array[mid] < integer:
# push our bounbds to the right
left = mid + 1
else:
# push our bounds to the left
right = mid
return False
|
# https://leetcode.com/problems/add-two-numbers/description/
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, L1, L2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if not L1: return L2
if not L2: return L1
A, B = self.validate(L1, L2)
C, res, curr = 0, None, None
while A and B:
S = A.val + B.val + C
carry, sum = S//10, S%10
if not res: curr = res = ListNode(sum)
else:
curr.next = ListNode(sum)
curr = curr.next
A, B, C = A.next, B.next, carry
if C: curr.next = ListNode(C)
return res
def validate(self, L1, L2):
C1, C2 = L1, L2
len1, len2 = 1, 1
while C1.next:
len1 += 1
C1 = C1.next
while C2.next:
len2 += 1
C2 = C2.next
for _ in xrange(max(0, len2-len1)):
C1.next = ListNode(0)
C1 = C1.next
for _ in xrange(max(0, len1-len2)):
C2.next = ListNode(0)
C2 = C2.next
return (L1, L2)
|
# https://leetcode.com/problems/find-right-interval/description/
# Definition for an interval.
# class Interval(object):
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution(object):
def findRightInterval(self, intervals):
"""
:type intervals: List[Interval]
:rtype: List[int]
"""
start_indices = {intervals[i].start:i for i in xrange(len(intervals))}
starts = sorted(start_indices.keys())
res = []
for interval in intervals:
end = interval.end
index = -1
# Binary search for this end in our starts
L, R = 0, len(starts)-1
while L < R:
M = (L+R)//2
if starts[M] < end: L = M+1
else: R = M
if starts[L] >= end: index = start_indices[starts[L]]
res.append(index)
return res
|
a = int(input("Donnez un entier : "))
for i in range(1, a+1):
if a % i == 0:
print(i) |
# a = 1
# b = 2
# print("a =", a, "et b = ", b)
# a, b = b, a
# print("a =", a, "et b = ", b)
#
# # methode 2
# a = 1
# b = 2
# print("a =", a, "et b = ", b)
# ainit = a
# a = b
# b = ainit
# print("a =", a, "et b = ", b)
# TD 2 EX 1
# TD 2 EX 3
|
def creditAAoAIncreaseStrategy( annualApplicationCount, initialCreditWait, numberOfYears ):
int_format_str = '{:2d}';
float_format_str = '{:8.4f}';
i = 1.0;
step = 1.0 / float(annualApplicationCount);
temp = float(initialCreditWait);
while ( i < annualApplicationCount * numberOfYears ):
newTemp = ( temp + step ) * i / ( i + 1.0 );
i = i + 1.0;
print( "Year ", int_format_str.format( int( i / annualApplicationCount) ) ,
" Application ", int_format_str.format( int( i % int(annualApplicationCount) + 1 ) ) ,
" | Average Age of Accounts = ", float_format_str.format( newTemp ) ,
" years - efficiency = ", float_format_str.format( (newTemp-temp)*100/step ), "% | Total Age of Accounts = ",
float_format_str.format( newTemp * i ) + " years | Count of Accounts = ", int(i) );
temp = newTemp;
creditAAoAIncreaseStrategy( 2.0, 1.0, 25 );
input("Press any key to continue...");
|
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import os
import csv
# In[6]:
#open the csv path
csvpath = os.path.join('budget_data.csv')
#import the csv
with open(csvpath) as csvfile:
csvreader=csv.reader(csvfile,delimiter=',')
months=0
revenue=0
rows=[r for r in csvreader]
change_revenue=int(rows[1][1])
max = rows[1]
min=rows[1]
for i in range(1,len(rows)):
months=months+1
row=rows[i]
revenue= int(row[1]) + revenue
#Not include the header
if i > 1:
change_revenue=change_revenue + int(row[1])-int(rows[i-1][1])
#Find the Max Revenue
if int(max[1]) < int(row[1]):
max=row
#Find the Min Revenue
if int(min[1]) > int(row[1]):
min=row
#Find the average change in revenue
average= int(revenue /months)
average_change_revenue=int(change_revenue/months)
#Print the output
print("Financial Analysis")
print("------------------")
print(f"Total Months: " + str(months))
print(f"Total Revenue: " +"$" +str(revenue))
print(f"Average Revenue Change: " +"$"+ str(average))
print(f"Average Change in Revenue Change: " +"$"+ str(average_change_revenue))
print(f"Greatest Increase in Revenue:" + str(max[0])+" ($" + str(max[1])+")")
print(f"Greatest Decrease in Revenue:" + str(min[0])+" ($" + str(min[1])+")")
#export to text file
output = open("output.txt", "w")
output.write('Financial Analysis')
output.write('\n---------------------')
output.write('-------------------------')
output.write('\nTotal Months: '+ str(months))
output.write('\nAverage Revenue Change: ' +"$"+ str(average))
output.write('\nAverage Change in Revenue Change: '+"$"+ str(average_change_revenue))
output.write('\nGreatest Increase in Revenue:' + str(max[0])+" ($" + str(max[1])+")")
output.write('\nGreatest Decrease in Revenue:' + str(min[0])+" ($" + str(min[1])+")")
|
"""
GeneticAlorithm operates over populations of chromosomes
Properties:
population_size: # chromosomes in populations
genotype: structure of each chromosome
generations: list of successive populations
Methods:
fit: runs the genetic algorithm, using selection, crossover, and mutation operations
"""
import core.selectors as sel
import core.crossover as xo
import core.chromosome as chrom
import random
class GeneticAlgorithm:
def __init__(self, population_size, genotype):
self._population_size = population_size
self._genotype = genotype
self._generations = []
def fit(self, fitness_function, num_generations=10, selector=sel.RankSelector(threshold=10), crossover_op=xo.OnePointCrossover(), crossover_rate=.6, mutation_rate=.01):
# initialize population
population = []
for x in range(self._population_size):
chromosome = self._genotype.create_random_instance()
population.append(chromosome)
# process each generation
for g in range(num_generations):
# track generations
self._generations.append(population)
next_population = []
# calculate fitness function
for c in population:
c.fitness = fitness_function(c)
# select parents for next generation
parents = selector.select_pairs(population=population)
# perform crossover
for parent in parents:
do_crossover = random.random() < crossover_rate
if do_crossover:
child_1, child_2 = crossover_op.recombine(parent[0].genes, parent[1].genes)
chrom_child_1 = chrom.Chromosome(genes=child_1)
chrom_child_2 = chrom.Chromosome(genes=child_2)
# add new children to next population
next_population.append(chrom_child_1)
next_population.append(chrom_child_2)
else:
# no crossover, add parents as is
next_population.append(parent[0])
next_population.append(parent[1])
# mutate
population = next_population
@property
def populations(self):
return self._generations |
'''
May 2017
@author: Burkhard
'''
# Spaghetti Code #############################
def PRINTME(me):print(me)
import tkinter
x=y=z=1
PRINTME(z)
from tkinter import *
scrolW=30;scrolH=6
win=tkinter.Tk()
if x:chVarUn=tkinter.IntVar()
from tkinter import ttk
WE='WE'
import tkinter.scrolledtext
outputFrame=tkinter.ttk.LabelFrame(win,text=' Type into the scrolled text control: ')
scr=tkinter.scrolledtext.ScrolledText(outputFrame,width=scrolW,height=scrolH,wrap=tkinter.WORD)
e='E'
scr.grid(column=1,row=1,sticky=WE)
outputFrame.grid(column=0,row=2,sticky=e,padx=8)
lFrame=None
if y:chck2=tkinter.Checkbutton(lFrame,text="Enabled",variable=chVarUn)
wE='WE'
if y==x:PRINTME(x)
lFrame=tkinter.ttk.LabelFrame(win,text="Spaghetti")
chck2.grid(column=1,row=4,sticky=tkinter.W,columnspan=3)
PRINTME(z)
lFrame.grid(column=0,row=0,sticky=wE,padx=10,pady=10)
chck2.select()
try: win.mainloop()
except:PRINTME(x)
chck2.deselect()
if y==x:PRINTME(x)
# End Pasta #############################
|
'''
May 2017
@author: Burkhard A. Meier
'''
#======================
# imports
#======================
import tkinter as tk
from tkinter import ttk
# Create instance
win = tk.Tk()
# Add a title
win.title("Python GUI")
# Adding a Label
ttk.Label(win, text="A Label").grid(column=0, row=0)
#======================
# Start GUI
#======================
win.mainloop() |
'''
May 2017
@author: Burkhard A. Meier
'''
#======================
# imports
#======================
import tkinter as tk
from tkinter import ttk
# Create instance
win = tk.Tk()
# Add a title
win.title("Python GUI")
tabControl = ttk.Notebook(win) # Create Tab Control
tab1 = ttk.Frame(tabControl) # Create a tab
tabControl.add(tab1, text='Tab 1') # Add the tab
tab2 = ttk.Frame(tabControl) # Add a second tab
tabControl.add(tab2, text='Tab 2') # Make second tab visible
tabControl.pack(expand=1, fill="both") # Pack to make visible
# LabelFrame using tab1 as the parent
mighty = ttk.LabelFrame(tab1, text=' Mighty Python ')
mighty.grid(column=0, row=0, padx=8, pady=4)
# Label using mighty as the parent
a_label = ttk.Label(mighty, text="Enter a name:")
a_label.grid(column=0, row=0, sticky='W')
#======================
# Start GUI
#======================
win.mainloop()
|
'''
May 2017
@author: Burkhard
'''
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import tkinter as tk
#--------------------------------------------------------------
fig = Figure(figsize=(12, 5), facecolor='white')
#--------------------------------------------------------------
axis = fig.add_subplot(111) # 1 row, 1 column
xValues = [1,2,3,4]
yValues0 = [6,7.5,8,7.5]
yValues1 = [5.5,6.5,8,6]
yValues2 = [6.5,7,8,7]
# the commas after t0, t1 and t2 are required
t0, = axis.plot(xValues, yValues0)
t1, = axis.plot(xValues, yValues1)
t2, = axis.plot(xValues, yValues2)
# t0, = axis.plot(xValues, yValues0, color = 'purple') # change the color of the plotted line to purple
# t0, = axis.plot(xValues, yValues0, color = 'r') # change the color of the plotted line
# t1, = axis.plot(xValues, yValues1, color = 'b')
# t2, = axis.plot(xValues, yValues2, color = 'purple')
axis.set_ylabel('Vertical Label')
axis.set_xlabel('Horizontal Label')
axis.grid()
fig.legend((t0, t1, t2), ('First line', 'Second line', 'Third line'), 'upper right')
#--------------------------------------------------------------
def _destroyWindow():
root.quit()
root.destroy()
#--------------------------------------------------------------
root = tk.Tk()
root.withdraw()
root.protocol('WM_DELETE_WINDOW', _destroyWindow)
#--------------------------------------------------------------
canvas = FigureCanvasTkAgg(fig, master=root)
canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1)
#--------------------------------------------------------------
root.update()
root.deiconify()
root.mainloop()
|
# -*- coding:utf-8 -*-
"""
剑指offer第29题
问题:数组中有一个数字出现次数超过数组长度的一半,请找出这个数字
思路:这个数出现的次数肯定比其它数出现的次数加起来还多,
当遇到相同的数时,count+=1,当遇到不同的数时,count-=1,当count==0时,表示前面出现次数最多
的数的次数少于等于其它数出现次数的总和,那么后面的数组中,显然有出现最多的数的次数比后面中其它出现次数的总和
还有多,重置当前数,count重新+/-1即可
网友提供:
采用阵地攻守的思想:
第一个数字作为第一个士兵,守阵地;count = 1;
遇到相同元素,count++;
遇到不相同元素,即为敌人,同归于尽,count--;当遇到count为0的情况,又以新的i值作为守阵地的士兵,继续下去,到最后还留在阵地上的士兵,有可能是主元素。
再加一次循环,记录这个士兵的个数看是否大于数组一般即可。
"""
def more_than_half_num(arr):
count = 0
for item in arr:
if count == 0:
curr_num = item
count = 1
elif curr_num == item:
count += 1
else:
count -= 1
if check_more_than_half(arr, curr_num):
return curr_num
else:
return None
def check_more_than_half(arr, number):
times = 0
for item in arr:
if number == item:
times += 1
if times*2 <= len(arr):
return False
else:
return True
arr = [1,2,3,2,2,2,5,4,2]
print(more_than_half_num(arr)) |
#-*- coding:utf-8 -*-
"""
剑指offer第7题
问题:使用两个栈实现队列,appendTail在队列尾插入节点,pop删除头结点
思路:使用两个栈
"""
class Stack:
def __init__(self, maxsize):
self.maxsize = maxsize
self.arr = [0]*self.maxsize
self.top = 0
def isEmpty(self):
return self.top == 0
def getSize(self):
return self.top
def pop(self):
self.top = self.top - 1
temp = self.arr[self.top]
return temp
def push(self, elem):
self.arr[self.top] = elem
self.top = self.top + 1
class Queue:
def __init__(self, maxsize):
self.maxsize = maxsize
self.stack1 = Stack(maxsize)
self.stack2 = Stack(maxsize)
def appendtail(self, elem):
self.stack1.push(elem)
def pop(self):
if not self.stack2.isEmpty():
return self.stack2.pop()
else:
while not self.stack1.isEmpty():
temp = self.stack1.pop()
self.stack2.push(temp)
return self.stack2.pop()
def isEmpty(self):
return self.stack1.isEmpty() and self.stack2.isEmpty()
q = Queue(20)
q.appendtail(2)
q.appendtail(10)
q.appendtail(18)
q.appendtail(40)
print(q.pop())
q.appendtail(50)
while not q.isEmpty():
print(q.pop()) |
# -*- coding:utf-8 -*-
"""
剑指offer第27题
问题:输入一颗二叉搜索树,将该树转换成一个排序的双向链表。要求不能创建任何新的结点,
只能调整树中结点指针的指向
思路:递归,先完成左子树,使得左子树中的每个结点的右指针指向比它大的数,左指针指向比它小的数,
并获得左子树的最大结点即双向链表往右走的最后一个节点,在递归完成右子树,
最后可以得到整个双向链表往右走的最后一个结点
"""
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def convert(root):
last_node = None
last_node = convert_node(root, last_node)
while last_node is not None and last_node.left is not None:
last_node = last_node.left
return last_node
def convert_node(root, last_node):
if root is None:
return
current = root
if current.left is not None:
last_node = convert_node(current.left, last_node)
current.left = last_node
if last_node is not None:
last_node.right = current
last_node = current
if current.right is not None:
last_node = convert_node(current.right, last_node)
return last_node
if __name__ == "__main__":
root = Node(4)
node1 = Node(2)
node2 = Node(6)
node3 = Node(1)
node4 = Node(3)
node5 = Node(5)
node6 = Node(7)
root.left = node1
root.right = node2
node1.left = node3
node1.right = node4
node2.left = node5
node2.right = node6
head = convert(root)
print(head.data)
|
# -*- coding:utf-8 -*-
"""
剑指offer第12题
问题:输入数字n,按顺序打印1到最大的n位进制数
思路:n太大时,暴力法不好,可以考虑求n位数的全排列,然后把前面的0不打印
全排列递归思路:首先固定最高位,然后全列剩下的——固定当前最高位,当位数超过n时,即排列好了一个数,再打印
"""
def print_to_max(n):
if n <= 0:
return
arr = [0]*n
print_arr(arr, 0)
def print_arr(arr, n):
for i in range(10):
# 先固定第n位,这里最高位即第0位
if n != len(arr):
arr[n] = i
print_arr(arr, n+1)
# 当n达到len(arr),即排列完一个数后,打印这个数
else:
flag = False # 用来标记是否遇到了第一个不为0的数
for j in range(len(arr)):
if arr[j] != 0:
print(arr[j], end="")
if not flag:
flag = True
else:
if flag: # 遇到了第一个不为0的数,那么后面的都可以打印
print(arr[j], end="")
if flag: # 表示遇到了不为0的数,即不是全0的数,打印换行
print() # 如果是全0的数,什么都不打印
return
print_to_max(2)
|
# -*- coding:utf-8 -*-
"""
剑指offer第13题
问题:在给定单向链表的头指针和一个结点指针,要求在O(1)时间内删除该结点
思路:由于是单向,如果查找到该结点的前一个节点,那时间复杂度是O(n),可以将该结点的
下个结点的数据复制给该节点,然后删除下一个结点
例如:1->2->3->4,删除3
1->3->3->4
1->3->4
"""
class Node:
def __init__(self, data):
self.data = data
self.next = None
def delete_node(head, node):
if node is head: # 头结点,直接指向None
head = None
elif node.next is None: # 尾节点,只有遍历
curr_node = head
while curr_node.next.next is not None:
curr_node = curr_node.next
curr_node.next = None
else: # 中间节点
node.data = node.next.data
node.next = node.next.next
if __name__ == "__main__":
head = Node(1)
second = Node(2)
third = Node(3)
head.next = second
second.next = third
delete_node(head, second)
print(head.next.data)
|
# -*- coding:utf-8 -*-
"""
剑指offer第21题
问题:定义栈的数据结构,实现一个能够得到栈的最小元素的min函
调用min,push,pop时间复杂度都是O(1)
思路:直接用两个栈,一个存储元素,一个存储当前最小值,
比如 4 5 2 3 6 1
元素栈4 5 2 3 6 1
最小栈4 4 2 2 2 1
当pop时,两个栈同时pop,元素栈top永远是压入的元素,最小栈top永远是当前最小值
"""
class Stack:
def __init__(self, max_size):
self.top = 0
self.max_size = max_size
self.arr = [0]*max_size
def push(self, data):
self.arr[self.top] = data
self.top += 1
def pop(self):
self.top -= 1
return self.arr[self.top]
def lenght(self):
return self.top
def peek(self):
return self.arr[self.top-1]
class Stack2:
def __init__(self, max_size):
self.max_size = max_size
self.min_stack = Stack(max_size)
self.data_stack = Stack(max_size)
def push(self, data):
self.data_stack.push(data)
if self.min_stack.lenght() == 0:
self.min_stack.push(data)
elif data < self.min_stack.peek():
self.min_stack.push(data)
else:
self.min_stack.push(self.min_stack.peek())
def pop(self):
self.min_stack.pop()
return self.data_stack.pop()
def min(self):
return self.min_stack.peek()
stack = Stack2(10)
stack.push(4)
stack.push(5)
stack.push(2)
stack.push(3)
stack.push(1)
stack.push(6)
print(stack.pop())
stack.pop()
stack.push(0)
print(stack.min()) |
import requests
import json
"""this function allows one to specify the exchange rate base
as a parameter and a json object specifying the foreign exchange rates is returned
"""
def get_base(n):
url = "http://api.fixer.io/latest?base="+n
r = requests.get(url)
return (r.json())
|
grade = int(input())
max = int(input())
if 0.9 * max <= grade <= max:
print("A")
elif 0.8 * max <= grade < 0.9 * max:
print("B")
elif 0.7 * max <= grade < 0.8 * max:
print("C")
elif 0.6 * max <= grade < 0.7 * max:
print("D")
else:
print("F") |
import logging
from random import randint
from time import sleep
from turtle import Turtle, Screen
logging.basicConfig(level = logging.DEBUG)
players = \
[
{ 'name': 'Ronny', 'color': 'red' },
{ 'name': 'Ginny', 'color': 'green' },
{ 'name': 'Bevin', 'color': 'blue' },
{ 'name': 'Clive', 'color': 'cyan' },
{ 'name': 'Pauly', 'color': 'purple' },
{ 'name': 'Other', 'color': 'orange' }
]
line_location = 220
def draw_finish_line():
bob = Turtle()
bob.penup()
bob.goto(x = line_location, y = 200)
bob.setheading(to_angle = 270)
bob.pensize(width = 5)
bob.pendown()
for dash in range(17):
bob.forward(distance = 12)
bob.penup()
bob.forward(distance = 12)
bob.pendown()
def init_race():
y_pos = 160
scr = Screen()
scr.setup(width = 500, height = 400)
draw_finish_line()
for player in players:
player['turtle'] = Turtle(shape = "turtle")
player['nickname'] = player['name'].lower()[:1]
player['turtle'].shapesize(2)
player['turtle'].color(player['color'])
player['turtle'].penup()
player['turtle'].goto(x = -230, y = y_pos)
y_pos -= 60
user_bet = scr.textinput( \
title = "Pick the winner",
prompt = "who is going to win"
).lower()[:1]
for player in players:
if player['nickname'] == user_bet:
user_bet = player['name']
return (scr, user_bet)
def race():
while True:
distance = randint(5,20)
player_number = randint(0,len(players) -1)
players[player_number]['turtle'].forward(distance)
if players[player_number]['turtle'].xcor() >= line_location -20:
return players[player_number]
scr, user_bet = init_race()
result = race()
def end_race(screen):
screen.bye()
print(f"The winner is {result['name']}")
print(f"you chose {user_bet}")
if {result['name']} == {user_bet}:
print("Well done, you win !!!")
else:
print("Better luck next time.")
sleep(5)
scr.bye()
# logging.debug(stuff)
|
# -*- coding: utf-8 -*-
"""
@author: timpr
"""
class Player(object):
"""
An NBA player object, associated with a particular fantasy league in a particular week
"""
def __init__(self, player_name, player_id, nba_team, team_id, player_key,
stat_dict, is_injured):
"""
Initialize an NBA team object
Parameters:
player_name (string): name of the player
player_id (string): the players unique id, used to look up player in yahoo queries
nba_team (NBAteam): the NBA team that the player is on
team_id (string): the name of the fantasy team that the player is on (None if on the waivers)
player_key (string): the players unique key, used to look up player in some yahoo queries
stat_dict (Dict<string,float): A dictionary containing a players average stats, statistical category as key, average as value
is_injured (Boolean): True if the player is injured and not playing, False otherwise
"""
# Convert acronyms to match the format from Sportsipy
if nba_team == "BKN":
self.nba_team = "BRK"
elif nba_team == "CHA":
self.nba_team = "CHO"
elif nba_team == "PHX":
self.nba_team = "PHO"
elif nba_team == "TOT":
self.nba_team = "TOR"
else:
self.nba_team = nba_team
self.player_name = player_name
self.team_id = team_id
self.player_id = player_id
self.player_key = player_key
self.stat_dict = stat_dict
self.is_injured = is_injured
def set_player_id(self, player_id):
self.player_id = player_id
return
def set_player_fantasy_team_id(self, team_id):
self.team_id = team_id
return
def set_player_key(self, player_key):
self.player_key = player_key
return
def set_injury_status(self, is_injured):
self.is_injured = is_injured
return
def get_player_name(self):
return(self.player_name)
def get_player_id(self):
return(self.player_id)
def get_player_nba_team(self):
return(self.nba_team)
def get_player_fantasy_team_id(self):
return(self.team_id)
def get_player_key(self):
return(self.player_key)
def get_average_stats(self):
return(self.stat_dict)
def get_injury_status(self):
return(self.is_injured) |
# program Grading Nilai
nama = str(input("Masukan Nama: "))
nilai = int(input("Masukan Nilai: "))
hasil = None
if(nilai >= 85 and nilai <=100):
hasil = 'A'
print("Hallo",nama,"! Nilai anda setelah dikonversi adalah",hasil)
elif(nilai >= 80 and nilai <=84):
hasil = 'A-'
print("Hallo",nama,"! Nilai anda setelah dikonversi adalah",hasil)
elif(nilai >= 75 and nilai <=79):
hasil = 'B+'
print("Hallo",nama,"! Nilai anda setelah dikonversi adalah",hasil)
elif(nilai >= 70 and nilai <=74):
hasil = 'B'
print("Hallo",nama,"! Nilai anda setelah dikonversi adalah",hasil)
elif(nilai >= 65 and nilai <=69):
hasil = 'C+'
print("Hallo",nama,"! Nilai anda setelah dikonversi adalah",hasil)
elif(nilai >= 60 and nilai <=64):
hasil = 'C'
print("Hallo",nama,"! Nilai anda setelah dikonversi adalah",hasil)
elif(nilai < 60):
hasil = 'E'
print("Hallo",nama,"! Nilai anda setelah dikonversi adalah",hasil)
else:
print("invalid number") |
def tachycardia(age, average_heart_rate):
"""
Uses age and average heart rate data to determine if the patient is
tachycardic
:param age: user age
:param average_heart_rate: the average heart rate
:returns is_tachycardic: indication if average heart rate is tachycardic
"""
if age > 15:
if average_heart_rate > 100:
tachycardia = True
else:
tachycardia = False
if 12 <= age <= 15:
if average_heart_rate > 119:
tachycardia = True
else:
tachycardia = False
if 8 <= age <= 11:
if average_heart_rate > 130:
tachycardia = True
else:
tachycardia = False
if 5 <= age <= 7:
if average_heart_rate > 133:
tachycardia = True
else:
tachycardia = False
if 3 <= age <= 4:
if average_heart_rate > 137:
tachycardia = True
else:
tachycardia = False
if 1 <= age <= 2:
if average_heart_rate > 151:
tachycardia = True
else:
tachycardia = False
is_tachycardic = tachycardic(tachycardia)
return is_tachycardic
def tachycardic(tachycardia):
"""
Returns string declaring whether or not given the tachycardia boolean the
patient is tachycardic
:param tachycardia: boolean for if heart rate is in tachycardic range
:returns is_tachycardic: indication if average heart rate is tachycardic
"""
if tachycardia is True:
is_tachycardic = "User is tachycardic"
else:
is_tachycardic = "User is NOT tachycardic"
return is_tachycardic
|
import turtle
# fruit = "apple"
# for idex in range(5):
# currentChar = fruit[idex]
# print(currentChar)
# fruit = "apple"
# for idx in range(len(fruit) - 1, 1, -1):
# print(fruit[idx])
# fruit = "dragons"
#
# position = 0
# while position < len(fruit):
# print(fruit[position])
# position = position + 1
#
#
# s = "python rocks"
# idx = 1
# while idx < len(s):
# print(s[idx])
# idx = idx + 2
# def removeVowels(s):
# vowels = "aeiouAEIOU"
# sWithoutVowels = ""
# for eachChar in s:
# if eachChar not in vowels:
# sWithoutVowels = sWithoutVowels + eachChar
# return sWithoutVowels
#
#
# print(removeVowels("This sentences has a few vowels, but not all"))
# print(removeVowels("aAbEefIijOopUus"))
#
# s = "ball"
# r = ""
# for item in s:
# r = item.upper() +r
# print(r)
#
# def applyRules(lhch):
# rhstr = ""
# if lhch == 'A':
# rhstr = 'B' # Rule 1
# elif lhch == 'B':
# rhstr = 'AB' # Rule 2
# else:
# rhstr = lhch # no rules apply so keep the character
#
# return rhstr
# def processString(oldStr):
# newstr = ""
# for ch in oldStr:
# newstr = newstr + applyRules(ch)
#
# return newstr
#
#
# def createLSystem(numIters,axiom):
# startString = axiom
# endString = ""
# for i in range(numIters):
# endString = processString(startString)
# startString = endString
#
# return endString
#
# print(createLSystem(4, "A"))
#Looping and counting
def count(text, aChar):
lettercount = 0
for c in text:
if c == aChar:
lettercount = lettercount + 1
return lettercount
print(count("afunnybunny", "a"))
# To find the locations of the second or third occurrence of a character in a string,
# we can modify the find function, adding a third parameter for the starting position in the search string:
# Save & Run
def find2(astring, achar, start):
"""
Find and return the index of achar in astring.
Return -1 if achar does not occur in astring.
"""
ix = start
found = False
while ix < len(astring) and not found:
if astring[ix] == achar:
found = True
else:
ix = ix + 1
if found:
return ix
else:
return -1
print(find2('banana', 'a', 2))
#how to check for every character in ascii
import string
print(string.ascii_lowercase)
print(string.ascii_uppercase)
print(string.digits)
print(string.punctuation) |
class Person:
def __init__(self, name, email, phone, friends=0):
self.name = name
self.email = email
self.phone = phone
self.friends = []
self.greeting_count = 0
def greet(self, other_person): #greet is method aka function. other_person is an argument
self.greeting_count+=1
print ('Hello {}, I am {}!'.format(other_person.name, self.name))
print('My phone number is {}!'.format(other_person.name))
def goodbye(self, other_person):
print('Goodbye {}'.format(other_person.name))
def print_contact_info(self):
print("{}'s email address is {}, Sonny's phone number is {}.".format(self.name, self.email, self.phone))
def add_friends(self, friend):
self.friends.append(friend)
sonny = Person('Sonny','sonny@hotmail.com','483-485-4948')
jordan = Person('Jordan', 'jordan@aol.com', '495-586-3456')
sonny.greet(jordan)
sonny.greet(jordan)
sonny.greet(jordan)
sonny.greet(jordan)
sonny.greet(jordan)
jordan.greet(sonny)
print(sonny.greeting_count)
print(jordan.greeting_count)
# sonny.goodbye(jordan) #sony is self and jordan is other_person
# sonny.print_contact_info()
# jordan.add_friends(sonny)
# sonny.add_friends(jordan)
# print(len(jordan.friends))
# class Vehicle:
# def __init__(self, make, model, year):
# self.make = make
# self.model = model
# self.year = year
#
# def vehicledetail(self):
# print('The make of your vehicle is: {}\n'.format(self.make))
# print('The model of your vehicle is: {}\n'.format(self.model))
# print('The year of your vehicle is: {}\n'.format(self.year))
#
# def print_info(self):
# print(car.make, car.model, car.year)
#
#
# car = Vehicle('Nissan','Altima SL', '2015\n') #creating an instance for the class vehicle aka creating
# #an object for the class Vehicle
# print(car.make, car.model, car.year) #grabs the details from constructors to print
#
# car.vehicledetail() #prints the vehicledetail method
# car.print_info() #prints the print_info method
|
# m1 = [
# [1,3],
# [2,4],
# ]
#
# m2 = [
# [5, 2],
# [1, 0],
# ]
#
# answer= []
# for i in range(0, len(m1)):
# row = m1[i]
# for j in range(0, len(row)):
# print(i, j)
# ans = m1[i][j] + m2[i][j]
# answer.append(ans)
#
#
# print(answer)
m1 = [
[1,3],
[2,4],
]
m2 = [
[5, 2],
[1, 0],
]
answer= []
for i in range(0, len(m1)):
row = m1[i]
temp=[]
for j in range(0, len(row)):
print(i, j)
ans = m1[i][j] + m2[i][j]
temp.append(ans)
print(answer) |
#Ahmer Malik 9/16/2017
# Loop Exercises
# 1. 1 to 10
# Using a for loop and the range function, print out the numbers between 1 and 10 inclusive, one on a line. Example output:
# def sloop():
#
# for i in range(1,11):
# print (i)
#
# sloop()
# 2. n to m
# Same as the previous problem, except you will prompt the user for the number to start on and the number to end on. Example session:
# a=[]
#
# b = int(input('Enter start number: '))
#
# e = int(input('Enter end number: '))
# for i in range(b,e):
#
# print(i)
#
# a.append(i)
#
# print(a)
#3. Odd Numbers
# Print each odd number between 1 and 10 inclusive. Example output:
# Hint: you will need to use the modulus operator % to determine whether a number is odd or even.
# for i in range(0,10):
#
# if i % 2 == 1:
# print(i)
#4. Print a Square
#Print a 5x5 square of * characters. Example output:
# n = int(input('How many squares would you like to print?'))
# for i in range(0, n):
# print(n*"*")
# 7. Print a Triangle
# Print a triangle consisting of * characters like this:
n = int(input('How many squares would you like to print?'))
for i in range(0,n+1):
print((n - (n - i)) * "*")
|
def convert_units(typ,constant,f,t):
"""Converts units
type should be one of them
'metric','time'
f and t should be one of them:
'pico','nano','micro','mili','centi','deci','base','deca','hecta','kilo','mega','giga','tera'
Attributes
----------
constant: int
constant number
f: str
converting unit
t: str
converted unit
"""
units = {'pico':1e-12,'nano':1e-9,'micro':1e-6,'mili': 1e-3,'centi':1e-2,'deci':1e-1,
'base':1,
'deca':1e1,'hecta':1e2,'kilo':1e3,'mega':1e6,'giga':1e9,'tera':1e12}
return constant*units.get(f)/units.get(t) |
# -*- coding: UTF-8 -*-
from bs4 import BeautifulSoup
import re
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
soup = BeautifulSoup(html_doc, 'html.parser', from_encoding='uft-8')
print '获取所有的链接'
links = soup.find_all('a')
for link in links:
print link.name, link['href'], link.get_text()
print '获取lacie的链接'
link_node = soup.find('a', href='http://example.com/lacie')
print link_node.name, link_node['href'], link_node.get_text()
print '正则匹配'
link_node = soup.find('a', href=re.compile(r"ill"))
print link_node.name, link_node['href'], link_node.get_text()
print '获取P段落文字'
p_node = soup.find('p', class_="title")
print p_node.name, p_node.get_text()
doc = """
<span class="btn btn-success btn-custom download-button" data-id="367839" data-type="jpg" data-server="images7" data-user-id="23195">
<span class="glyphicon glyphicon-download-alt"></span>
Download Original 1440x900
</span>
"""
soup1 = BeautifulSoup(doc, 'html.parser', from_encoding='uft-8')
print '获某取class的各种属性'
class_attr = soup1.find('span', class_="btn btn-success btn-custom download-button")
# print class_attr['data-id']
print class_attr.get_text()
print class_attr['data-id']
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 3 08:41:49 2019
@author: mukuljos
"""
#Strings
st = "10.10.101.21"
print(st.count("."))
#List
list_1 = ["1", "2", "3"]
list_1.append("4")
for i in list_1:
print (i)
even = [1,2,3,4,5]
odd = [7,8,9]
numbers = even+odd
#sort doesn't create a new objet, it works on the given list
numbers.sort()
#sorted returns the new list object
print(numbers)
numbers_sort = sorted(numbers)
print(even+odd) |
print("\n\033[1;7;30m {:=^150} \033[m\n".format(" | MAIN MENU (2.0) | "))
from time import sleep
n1 = int(input('\033[1;30mEnter the 1th value:\033[m '))
n2 = int(input('\033[1;30mEnter the 2th value:\033[m '))
exit_program = False
while not exit_program:
sleep(0.5), print('\n\n\n\033[1;30m{}\033[m \033[1;31m>>>\033[m \033[1;30mMain Menu\033[m \033[1;31m<<<\033[m \033[1;30m{}\033[m'.format('=-=' * 10, '=-=' * 10))
print('\033[1;32m[1] Sum\033[m'
'\n\033[1;35m[2] Multiply\033[m'
'\n\033[1;36m[3] Check the highest number\033[m'
'\n\033[1;33m[4] Enter new values\033[m'
'\n\033[1;31m[5] Exit program\033[m')
print('{}'.format('\033[1;30m=-=\033[m' * 30)), sleep(0.5)
option = int(input('\n\033[30mEnter the number corresponding to the action you want.\033[m \033[1;30mWhat do you want to do:\033[m '))
if option == 1:
print('\n\033[32mYou chose to sum the two values.\033[m'), sleep(0.75)
print('\033[32mThe result of {} + {} is equal to {}.\033[m'.format(n1, n2, n1 + n2)), sleep(0.25)
elif option == 2:
print('\n\033[35mYou chose to multiply the two values.'), sleep(0.75)
print('\033[35mThe result of {} x {} is equal to {}.\033[m'.format(n1, n2, n1 * n2)), sleep(0.25)
elif option == 3:
print('\n\033[36mYou chose to check the highest value.\033[m'), sleep(0.75)
if n1 == n2:
print('\033[1;31mError!\033[m \033[36mThe numbers you entered are the same.\033[m'), sleep(0.25)
else:
high = n1
if n2 > n1:
high = n2
print('\033[36mBetween {} and {}, the highest is {}.\033[m'.format(n1, n2, high)), sleep(0.25)
elif option == 4:
print('\n\033[33mYou chose to enter new two values. Please, insert them below.\033[m'), sleep(0.75)
n1 = int(input('\033[1;30mEnter the new 1th value:\033[m ')), sleep(0.25)
n2 = int(input('\033[1;30mEnter the new 2th value:\033[m ')), sleep(0.25)
elif option == 5:
print('\n\033[31mYou chose to shut down the program.\033[m'), sleep(1)
exit_program = True
else:
print('\033[1;31mInvalid option!\033[m \033[1;30mPlease, try again...\033[m ')
print('\n\033[30mShutting down... Please, wait...\033[m'), sleep(3)
print('\n\n\n\n\n{}\n{:^100}\n{}'.format('==' * 45, '\033[1;30mGoodbye... See you later...\033[m', '==' * 45))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
def make_rectangle(upper_left_point, lower_rect_point):
rect = {
'left_point': upper_left_point,
'right_point': lower_rect_point
}
return rect
def check_x_overlapping(left_rect, right_rect):
if left_rect['right_point'][0] >= right_rect['left_point'][0]:
return True
else:
return False
def check_y_overlapping(top_rect, bottom_rect):
if top_rect['right_point'][1] <= bottom_rect['left_point'][1]:
return True
else:
return False
def check_overlapping(rect_1, rect_2):
if rect_1['left_point'][0] < rect_2['left_point'][0]:
left_rect = rect_1
right_rect = rect_2
else:
left_rect = rect_2
right_rect = rect_1
if rect_1['left_point'][1] > rect_2['left_point'][1]:
top_rect = rect_1
bottom_rect = rect_2
else:
top_rect = rect_2
bottom_rect = rect_1
overlapping = check_x_overlapping(left_rect, right_rect) and \
check_y_overlapping(top_rect, bottom_rect)
return overlapping
if __name__ == '__main__':
with open(sys.argv[1], 'r') as test_cases:
for test in test_cases:
data = test.replace('\n', '').split(",")
rect_1 = make_rectangle((int(data[0]), int(data[1])), (int(data[2]), int(data[3])))
rect_2 = make_rectangle((int(data[4]), int(data[5])), (int(data[6]), int(data[7])))
if check_overlapping(rect_1, rect_2):
print "True"
else:
print "False"
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
def eval_prefix_expression(expression):
value = expression.pop(0)
if value in ["*", "+", "/"]:
op_1 = eval_prefix_expression(expression)
op_2 = eval_prefix_expression(expression)
if value == "*":
return op_1 * op_2
elif value == "+":
return op_1 + op_2
else:
return op_1 / op_2
else:
return float(value)
if __name__ == '__main__':
with open(sys.argv[1], 'r') as test_cases:
for test in test_cases:
test_case = [data.replace("\n", "") for data in test.split(" ")]
result = eval_prefix_expression(test_case)
print(int(result)) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
def mth_element(line):
line.replace("\n", "")
tokens = line.split(" ")
index = tokens[-1]
tokens = tokens[:len(tokens)-1]
if int(index) > len(tokens):
return
print tokens[len(tokens) - int(index)]
if __name__ == '__main__':
with open(sys.argv[1], "r") as test_cases:
for line in test_cases:
mth_element(line)
|
def computeArea(a, b, h):
A = (1/2)*(a+b)*h
return A
def main():
# receive values.
upperSide = float(input('Enter the upper side:'))
bottomSide = float(input('Enter the bottom side:'))
height = float(input('Enter the height of Trapezoid:'))
# Call the function.
area = computeArea(upperSide, bottomSide, height)
print('The area of Trapezoid is : ', area)
main() |
import random
number = random.randint(1, 20)
def rand_call(guess ):
#global number
if guess < number:
print("Your guess number is low")
elif guess > number:
print("Your guess number is high")
def main():
guesses_no = 1
print("Type a number betwen 1 and 20: ")
while guesses_no < 6:
user_guess=int(input("What is your guess mate?\n"))
guesses_no = guesses_no + 1
rand_call(user_guess)
if user_guess == number:
break
if user_guess == number:
print("The random number was",number,"and your guess was correct ")
print("The number of guesses you took is",guesses_no - 1)
else:
print("The random number was",number,"and your guess was incorrect ")
main() |
def main():
sentence = str(input('Please Enter a Sentence so I can fix it: '))
cleanedSentence = ''
for char in sentence:
char = char.lower()
if char.isnumeric():
char = ','
cleanedSentence = cleanedSentence + char
words_list = cleanedSentence.split(',')
print("The fixed string is: ", end ='')
for word in words_list:
# check if word at the first index
if word == words_list[0]:
word = word.title()
if word == words_list[len(words_list)-2]:
print(word , end = '')
else:
print(word + ' ' , end = '')
# call main function
main()
|
# Write your code here...
S = input()
lst = S.split(' ')
maxword = ''
minword = lst[0]
for word in lst:
if len(word) > len (maxword):
maxword = word
if len(word) < len ( minword):
minword = word
print( maxword)
print( minword) |
# Write a Python program that will accept the base and height of a
# triangle and compute the area.
# (Format the output -> 2 decimal places)
base = float(input("Enter the base of triangle: "))
height = float(input("Enter the height of triangle: "))
area = (base * height)/2
print("the Area is: ", format(area, '.2f'))
|
pwd = int(input("Enter the password : "))
count = 1
while pwd!=128:
if(count <5):
print("wrong!, tray again")
count = count + 1
pwd = int(input("Enter the password : "))
else:
print("You exceeded the number of allowed attempts! ")
break
if pwd ==128:
print("True password")
|
def Factorial(n):
fact = 1
if n < 0:
fact = 'Error'
elif n == 0:
fact = 1
else:
x = n
while x > 0:
fact = fact * x
x -=1
return fact
def main():
number = int(input('Enter positive number:'))
print('Factorial (', number, ') = ', Factorial(number))
main()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division
import sys
import re
import nltk
fh = open(sys.argv[1], 'r')
rawtext = fh.read()
# based on several papers analysing the differences of male and female writers
# in English, we try to apply those rules to German - the quick and dirty way. :)
# supposedly, women use a certain range of pronouns more often than men
f_pronouns = ['ich', 'du', 'sie', 'ihr']
# on the other hand, men refer more often to he/him/his
m_pronouns = ['er', 'sein', 'wir', 'denen']
# men use more negatives
negatives = ['nicht', 'kein', 'non']
# men use more "determiners"
determiners = ['ein', 'manch', 'jed', 'jen', 'dies', 'kein', 'einig']
# let's also check who uses more (weak) adjectives in German
adjectives = ['bar', 'haft', 'ig', 'isch', 'lich', 'los', 'sam']
# the use of numerals is supposedly also a male identifier
numerals = ['zwei', 'drei', 'vier', 'fünf', 'sechs', 'sieben', 'acht', 'neun', 'zehn']
# other indicators for male writers are the use of quanitifers
# other indicators for a female writer is the use of present tense
# we simply go over every word list and count the matches
def count_words (wordlist, expr):
count = {}
for word in wordlist:
regex = re.compile(expr % word, re.I)
occurences = len(re.findall(regex, rawtext))
count[word] = occurences
return count
# calculating the percentage of occurences
def calc_percent (values):
word_count = len(nltk.word_tokenize(rawtext))
return "%.3f" % (100 * (sum(values) / word_count))
stats = {}
# yes, it seems in German, female writers use more of these pronouns
f_count = count_words(f_pronouns, '%s')
stats['female pronouns'] = calc_percent(f_count.values())
# yes, it seems in German, male writers use a little more of the male-indicating pronouns
m_count = count_words(m_pronouns, ' ?%s[e]?[rmsn]?')
stats['male pronouns'] = calc_percent(m_count.values())
# no, in my German example texts, men don't use more determiners - women do
d_count = count_words(determiners, '%s[e]?[srmn]?')
stats['determiners'] = calc_percent(d_count.values())
# no, in my German example texts, men don't use more negatives - women do
n_count = count_words(negatives, '%s[e]?[srmn-]?')
stats['negatives'] = calc_percent(n_count.values())
# a quick check on a certain range of adjectives shows women use more of them
a_count = count_words(adjectives, '[a-züöä]+?%s')
stats['adjectives'] = calc_percent(a_count.values())
# in German, it seems men are using a little more numerals than women
num_count = count_words(numerals, '%s')
stats['numerals'] = calc_percent(num_count.values())
print stats
|
'''
Comparing single layer MLP with deep MLP (using TensorFlow)
'''
import numpy as np
import pickle
import scipy
from scipy.optimize import minimize
from scipy.io import loadmat
from math import sqrt
import time
import matplotlib.pyplot as plt
# Do not change this
def initializeWeights(n_in,n_out):
"""
# initializeWeights return the random weights for Neural Network given the
# number of node in the input layer and output layer
# Input:
# n_in: number of nodes of the input layer
# n_out: number of nodes of the output layer
# Output:
# W: matrix of random initial weights with size (n_out x (n_in + 1))"""
epsilon = sqrt(6) / sqrt(n_in + n_out + 1);
W = (np.random.rand(n_out, n_in + 1)*2* epsilon) - epsilon;
return W
# Replace this with your sigmoid implementation
def sigmoid(z):
sigmoidresult = 1.0 / (1.0 + np.exp(-z))
return sigmoidresult
# Replace this with your nnObjFunction implementation
def nnObjFunction(params, *args):
n_input, n_hidden, n_class, training_data, training_label, lambdaval = args
w1 = params[0:n_hidden * (n_input + 1)].reshape((n_hidden, (n_input + 1)))
w2 = params[(n_hidden * (n_input + 1)):].reshape((n_class, (n_hidden + 1)))
obj_val = 0
# Your code here
label = np.array(training_label);
rows = label.shape[0];
rowsIndex = np.array([i for i in range(rows)])
training_label = np.zeros((rows,2))
# Set the kth column in "training_label" to 1 for label k
training_label[rowsIndex,label.astype(int)]=1
# Adding bias to training data and feed forwarding
BiasTerm = np.ones(training_data.shape[0])
training_data = np.column_stack((training_data,BiasTerm))
num_samples = training_data.shape[0]
# Finding the hidden output using sigmoid
HiddenOutput = sigmoid(np.dot(training_data,w1.T))
# Adding bias term to hidden layer
NewBias = np.ones(HiddenOutput.shape[0])
HiddenOutputWithBias = np.column_stack((HiddenOutput, NewBias))
# Finding the final output using sigmoid
FinalOutput = sigmoid(np.dot(HiddenOutputWithBias,w2.T))
# Calculating error to find the Gradient using formula given in handout
Delta = FinalOutput - training_label
# Using the formula shared in handout.
Gradient_w2 = np.dot(Delta.T,HiddenOutputWithBias)
Gradient_w1 = np.dot(((1-HiddenOutputWithBias)*HiddenOutputWithBias* (np.dot(Delta,w2))).T,training_data)
# Updating gradient w1 to remove bias hidden nodes
Gradient_w1 = np.delete(Gradient_w1, n_hidden,0)
# Calculating NLL error function and gradient of error function
lnFinal = np.log(FinalOutput)
lnOneFinal = np.log(1-FinalOutput)
part_1 = (np.sum(-1*(training_label*lnFinal+(1 - training_label)*lnOneFinal)))
part_1 = part_1/num_samples
# Adding Regularization
sw1 = np.sum(np.square(w1))
sw2 = np.sum(np.square(w2))
part_2 = (lambdaval/(2*num_samples))* (sw1 + sw2)
# Final formula
obj_val = part_1 + part_2
# Regularization will not impact for lambdaval 0, for others it will
Gradient_w1 = Gradient_w1 + lambdaval * w1
Gradient_w2 = Gradient_w2 + lambdaval * w2
# Make sure you reshape the gradient matrices to a 1D array. for instance if your gradient matrices are grad_w1 and grad_w2
# you would use code similar to the one below to create a flat array
# obj_grad = np.concatenate((grad_w1.flatten(), grad_w2.flatten()),0)
obj_grad = np.array([])
obj_grad = np.concatenate((Gradient_w1.flatten(), Gradient_w2.flatten()),0)
obj_grad = obj_grad/num_samples
return (obj_val, obj_grad)
# Replace this with your nnPredict implementation
def nnPredict(w1,w2,data):
Num_of_Items=data.shape[0]
# Adding bias term
Bias = np.zeros([len(data), 1])
DataWithBias = np.append(data, Bias ,1)
hidden_input = np.dot(DataWithBias ,w1.T)
hidden_output = sigmoid(hidden_input)
# Second layer - Adding Bias Term
Bias = np.zeros([len(hidden_output), 1])
FinalDataWithBias = np.append(hidden_output, Bias, 1)
final_input = np.dot(FinalDataWithBias, w2.T)
final_output = sigmoid(final_input)
#Initialize an dummy output array
label_list = [-1]*Num_of_Items
for i in range(Num_of_Items):
label_list[i] = np.argmax(final_output[i]);
labels = np.array(label_list)
return labels
# Do not change this
def preprocess():
pickle_obj = pickle.load(file=open('face_all.pickle', 'rb'))
features = pickle_obj['Features']
labels = pickle_obj['Labels']
train_x = features[0:21100] / 255
valid_x = features[21100:23765] / 255
test_x = features[23765:] / 255
labels = labels[0]
train_y = labels[0:21100]
valid_y = labels[21100:23765]
test_y = labels[23765:]
return train_x, train_y, valid_x, valid_y, test_x, test_y
"""**************Neural Network Script Starts here********************************"""
train_data, train_label, validation_data, validation_label, test_data, test_label = preprocess()
# Train Neural Network
# set the number of nodes in input unit (not including bias unit)
n_input = train_data.shape[1]
# set the number of nodes in hidden unit (not including bias unit)
n_hidden = 256
# set the number of nodes in output unit
n_class = 2
# initialize the weights into some random matrices
initial_w1 = initializeWeights(n_input, n_hidden);
initial_w2 = initializeWeights(n_hidden, n_class);
# unroll 2 weight matrices into single column vector
initialWeights = np.concatenate((initial_w1.flatten(), initial_w2.flatten()),0)
# set the regularization hyper-parameter
lambdaval = 10;
args = (n_input, n_hidden, n_class, train_data, train_label, lambdaval)
#Train Neural Network using fmin_cg or minimize from scipy,optimize module. Check documentation for a working example
opts = {'maxiter' :50} # Preferred value.
nn_params = minimize(nnObjFunction, initialWeights, jac=True, args=args,method='CG', options=opts)
params = nn_params.get('x')
#Reshape nnParams from 1D vector into w1 and w2 matrices
w1 = params[0:n_hidden * (n_input + 1)].reshape( (n_hidden, (n_input + 1)))
w2 = params[(n_hidden * (n_input + 1)):].reshape((n_class, (n_hidden + 1)))
#Test the computed parameters
predicted_label = nnPredict(w1,w2,train_data)
#find the accuracy on Training Dataset
print('\n Training set Accuracy:' + str(100*np.mean((predicted_label == train_label).astype(float))) + '%')
predicted_label = nnPredict(w1,w2,validation_data)
#find the accuracy on Validation Dataset
print('\n Validation set Accuracy:' + str(100*np.mean((predicted_label == validation_label).astype(float))) + '%')
predicted_label = nnPredict(w1,w2,test_data)
#find the accuracy on Validation Dataset
print('\n Test set Accuracy:' + str(100*np.mean((predicted_label == test_label).astype(float))) + '%') |
def generate_key(n):
letters = 'ABCDEFGHIJKLMNOPQRXTUVWXYZ'
key = {}
count = 0
# for each character in letters
for char in letters:
# assign char keys to key dict, assign the remainder of the count + the num n,
# divided by the length of the letters (25)
# this staggers all the letters by n without allowing the number to ever go above 25
key[char] = letters[(count + n) % len(letters)]
count += 1
return key
def encrypt(key, message):
cipher = ''
for char in message:
if char in key:
cipher += key[char]
else:
cipher += char
return cipher
def get_decryption_key(key):
dkey = {}
for char in key:
dkey[key[char]] = char
return dkey
# this is done by your enemy
key = generate_key(3)
print(key)
message = 'YOU ARE AWESOME'
cipher = encrypt(key, message)
# this is us breaking the cipher
for i in range(1, 26):
dkey = generate_key(i)
message = encrypt(dkey, cipher)
print(i, message)
|
def readInput(seperator):
inPath = input('Please enter the path to the input file\n')
input_raw = open(inPath).read()
# obsolete end of lines
noObseol = 0
for c in input_raw[::-1]:
if(c == '\n'):
noObseol+=1
else:
break
if noObseol != 0:
input_clean = input_raw[:-noObseol]
else:
input_clean = input_raw
input_sliced = input_clean.split(seperator)
return input_sliced
input_sliced = readInput("\n")
# convert trees to ones
geometry = [[int(field=="#") for field in l] for l in input_sliced]
## Task 1 ##
# initialize variables
i,j,trees = 0,0,0
width = len(geometry[1])
# traverse the slope, each tree adds one
while(i < len(geometry)):
trees += geometry[i][j]
i += 1
# if the right edge is reached, start back at left, as the pattern repeats
j = (j+3) % width
print(trees)
## Task 2 ##
trees = 1
# for one bottom step, perform for right stepsizes and multiply to count according to rules
for step in [1,3,5,7]:
i,j,curTrees = 0,0,0
while(i < len(geometry)):
curTrees += geometry[i][j]
i += 1
j = (j+step) % width
trees *= curTrees
# finally perform for 2 bottom, 1 right step
i,j,curTrees = 0,0,0
while(i < len(geometry)):
curTrees += geometry[i][j]
i += 2
j = (j+1) % width
trees *= curTrees
print(trees)
|
a=int(input("Enter 1st no "))
b=int(input("Enter 2nd no "))
print("Addition = {}".format(a+b))
print("Subtraction = {}".format(a-b))
print("Multiplication = {}".format(a*b))
print("Floor Division = {}".format(a//b))
print("Decimal Division = {}".format(a/b))
print("Remainder = {}".format(a%b))
print("Power = {}".format(a**b))
|
input_str="hello world happy birthday"
input_list=input_str.split()
print(input_list)
print(input_list[::-1])
|
currentYear= 2021
birthYear=int(input("Enter ypu birth year "))
age=currentYear- birthYear
print("Your age is ",age," years")
|
import re
def min_length_validation(value, length):
return len(value) >= length
def max_length_validation(value, length):
return len(value) <= length
def is_digit_validation(value):
return value.is_digit()
def contains_digit_validation(value):
pattern = r'\d'
if re.findall(pattern, value):
return True
def pattern_validation(value, pattern):
return re.match(pattern, value) is not None and re.match(pattern, value).string == value
|
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def clear_false_index(*data_frames):
"""Clears the false indexing created by Pandas when saved as a CSV.
WARNING: ONLY USE ONCE PER DATA FRAME.
:param data_frames: Data Frames
:return: None
"""
for df in data_frames:
df.drop(df.columns[0], axis=1, inplace=True)
def make_sub_set(keys, data_frame):
"""Creates subsets of data by passing in a List of column keys and a Data Frame
to pull from
:param keys: List of String Keys
:param data_frame: Data Frame
:return: Data Frame
"""
df = data_frame[keys]
df.columns = keys
return df
def simple_feature_scale(key, data_frame):
"""Uses Simple Feature Scaling to normalize a column.
Col / Col.max()
:param key: String Key
:param data_frame: Data Frame
:return: Data Frame Column
"""
return data_frame[key]/data_frame[key].max()
def create_bins(key, data_frame, div):
"""Creates a Numpy Linspace based on the min/max of the column,
and how many dividers you pass in.
:param key: String Key
:param data_frame: Data Frame
:param div: Integer
:return: Numpy Linspace
"""
return np.linspace(min(data_frame[key]), max(data_frame[key]), div)
def create_binned_column(key, bin_names, data_frame):
"""Creates a binned column
:param key: String Key
:param bin_names: List of String Keys
:param data_frame: Data Frame
:return: Data Frame Column
"""
return pd.cut(data_frame[key],
create_bins(key, data_frame, len(bin_names) + 1),
labels=bin_names, include_lowest=True)
|
#! /usr/bin/python3
import pygame
from pygame.sprite import Sprite
class Bullet(Sprite):
"""A class to control bullets fired from the ship"""
def __init__(self, ai_settings, screen, ship):
""" Create a bullet at the ship's current place"""
super().__init__()
self.screen = screen
# createa bullet rect at (0,0)
self.rect = pygame.Rect(0, 0, ai_settings.bullet_width, ai_settings.bullet_height)
self.rect.centerx = ship.rect.centerx
self.rect.top = ship.rect.top
# store the bullet's position as a decimal value
self.y = float(self.rect.y)
self.colour = ai_settings.bullet_colour
self.speed = ai_settings.bullet_speed
def update(self):
"""Move the bullet up"""
self.y -= self.speed
self.rect.y = self.y
def draw_bullet(self):
pygame.draw.rect(self.screen, self.colour, self.rect)
|
'''
Can you create a program to solve a word jumble? (More info here.)
The program should accept a string as input, and then return a list of words
that can be created using the submitted letters. For example, on the input
"dog", the program should return a set of words including "god", "do", and "go".
Please implement the program in Python but refrain from using any helper
modules or imports (e.g. itertools). In order to verify your words, just
download an English word list (here are a few).
Then uplaod your program to GitHub or Gist, and send it back!
Assumptions I am following:
- Can NOT use any imported libraries/modules
- Can use built-in python data structures (lists, dicts, tuples) and functions (strip())
- Allow input string to contain any of the 256 extended ASCII chart characters
- Whitespace at the beginning and end of the input string will be ignored
- Whitespace that's not at the beginning or end of the input string (between the
other characters) will not be ignored and will be used towards character limits
when comparing with the reference list of words
Created on Mar 10, 2014
@author: Prahalika
'''
'''
Print out the list of words that can be made from the input string
and are legitimate words, as compared to the reference list of words
'''
def print_output(output_list):
for word in output_list:
print(word)
'''
Iterate through the list of words in the reference list.
For each word, iterate through each letter and compare with the dict
created in parse_input_word(). If the letter in the reference word
doesn't appear in the input string dict or if the number of times
that character appears in the reference word exceeds the number of
times that character appears in the input string, that reference word
cannot be created from the input string. At that point, move on to
checking the next word.
If all of the letters in the reference word appear with appropriate
counts in the input string, the reference word is a valid creation
using the input string letters. Save that word to an output list.
'''
def check_words(input_dict, file_path):
output_list = []
try:
word_list = open(file_path)
except IOError as err:
print('File error: ' + str(err))
return list()
for word in word_list:
clean_word = word.strip()
word_dict = {}
let_cnt = 0
for let in clean_word:
if let not in input_dict:
break
if let not in word_dict:
word_dict[let] = 1
else:
word_dict[let] += 1
if word_dict[let] > input_dict[let]:
break
let_cnt += 1
if let_cnt == len(clean_word):
output_list.append(clean_word)
return output_list
'''
Go through the input string and determine how many of each character
are present. Save that information to a dict where the key is the character
and the value is the count of appearance of that character.
'''
def parse_input_word(input_word):
input_dict = {}
for let in input_word:
if let not in input_dict:
input_dict[let] = 1
else:
input_dict[let] += 1
return input_dict
'''
Ask the user to input the string and path to the reference list
and save that information
'''
def get_input():
input_word = input("Enter input word: ")
file_path = input("Enter path to reference list: ")
return (input_word, file_path)
'''
Start the program here.
Retrieve the input from the user
Parse the inputted string to create a character histogram
Read in the reference list of words and compare with the
character histogram
Output the list of valid words
'''
def main():
(input_word, file_path) = get_input()
input_dict = parse_input_word(input_word)
output_list = check_words(input_dict, file_path)
print_output(output_list)
if __name__ == "__main__":
main() |
# a = 12
# b = -a
# print(b) # -12
#
# c = a // b
# print(c)
#
# a += 2
# print(a)
#
# x = 1
# y = 2
# x += 2
# x = x + y
# y = x + y
# y = x + y
# print(y)
# operatory porównania
print("3" == 3) # false
print(3 > 3) # false
print(4 != 5) # true
print(4 >= 5) # false
print(3 <= 3) # true
print("Asia" < "Marta") # true, sprawdza gdzie znajduja sie poszczegolne litery
# operatory logiczne
print((5 > 3) and (7 <= 4)) # false poniewaz nie oba sa prawda
|
class Node:
def __init__(self, value=None, next=None):
self.value = value
self.next = next
def intersection(ll_a, ll_b):
ll_a_tail, ll_a_size = get_tail_and_size(ll_a)
ll_b_tail, ll_b_size = get_tail_and_size(ll_b)
# the tails of intersecting linked lists should be the same
if ll_a_tail is not ll_b_tail: return False
longer = ll_a if ll_a_size > ll_b_size else ll_b
shorter = ll_b if ll_a_size > ll_b_size else ll_a
longer = get_nth_node(longer, abs(ll_a_size - ll_b_size))
while longer and shorter:
if longer is shorter:
return longer.value
longer, shorter = longer.next, shorter.next
return False
def get_nth_node(head, n):
cur = head
for _ in range(n):
cur = cur.next
return cur
def get_tail_and_size(head):
size = 0
cur = head
while cur.next:
size += 1
cur = cur.next
return (cur, size)
n1_a, n1_b, n1_c, n1_d, n1_e = Node('a'), Node('b'), Node('c'), Node('d'), Node('e')
n1_a.next, n1_b.next, n1_c.next, n1_d.next = n1_b, n1_c, n1_d, n1_e
n2_a, n2_b = Node('q'), Node('w')
n2_a.next, n2_b.next = n2_b, n1_d
print(intersection(n1_a, n2_a)) |
def longest_subsequence(string, lst):
res = ''
for word in lst:
# print('{} is a subsequence of {} : {}'.format(word, string, is_subsequence(word, string)))
if is_subsequence(word, string) and len(word) > len(res):
res = word
return res
# tests if s1 is a subsequence of s2
def is_subsequence(s1, s2):
# i: current s1 index
i, j = 0, 0
while i < len(s1):
# j: current s2 index
while j < len(s2):
if s1[i] == s2[j]:
break
if j == len(s2) - 1:
return False
j += 1
i += 1
return True
print(longest_subsequence("abppplee", ["able", "ale", "apple", "bale", "kangaroo"])) |
def set_zero(matrix):
row_has_zero = False
col_has_zero = False
amt_of_rows = len(matrix)
amt_of_cols = len(matrix[0])
# check if first row has a zero
for col in range(amt_of_cols):
if matrix[0][col] == 0:
row_has_zero = True
break
# check if first column has a zero
for row in range(amt_of_rows):
if matrix[row][0] == 0:
col_has_zero = True
break
# check for zeros in the rest of the array
for row in range(amt_of_rows):
for col in range(amt_of_cols):
if matrix[row][col] == 0:
matrix[0][col] = 0
matrix[row][0] = 0
# zero out columns
for col in range(1, amt_of_cols):
if matrix[0][col] == 0:
nullify_col(matrix, col)
# zero out rows
for row in range(1, amt_of_rows):
if matrix[row][0] == 0:
nullify_row(matrix, row)
# zero our first row
if row_has_zero: nullify_row(matrix, 0)
# zero out first column
if col_has_zero: nullify_col(matrix, 0)
return matrix
def nullify_col(matrix, col):
for row in range(len(matrix)):
matrix[row][col] = 0
def nullify_row(matrix, row):
for col in range(len(matrix[0])):
matrix[row][col] = 0
def print_matrix(matrix):
for row in range(len(matrix)):
print(matrix[row])
matrix = [
[4, 3, 5, 6, 9],
[0, 3, 1, 3, 0],
[3, 4, 3, 4, 1],
[9, 3, 4, 0, 4]
]
matrix = set_zero(matrix)
print_matrix(matrix)
|
def string_compression(string):
count = 1
res = []
i = 0
while i < len(string)-1:
if string[i] == string[i+1]:
count += 1
else:
res.append(string[i] + str(count))
count = 1
i += 1
if i > 0:
res.append(string[i] + str(count))
return min(string, ''.join(res), key = len)
print(string_compression('aabcccccaaa')) |
def rotate_matrix(matrix):
length = len(matrix)
amt_of_layers = length // 2
for layer in range(amt_of_layers):
first, last = layer, length - layer - 1
for i in range(first, last):
# Select the 4 coordinates to be rotated by 90 degrees. The manner in which coordinates are selected is governed by the 'layer' we are currently on and by the current index 'i' which, itself, is bound by the length/size of the current layer.
p1 = matrix[layer][i]
p2 = matrix[i][-layer - 1]
p3 = matrix[-layer - 1][-i - 1]
p4 = matrix[-i - 1][layer]
# swap values of 4 coordinates (p1, p2, p3, p4 = p4, p1, p2, p3)
matrix[layer][i] = p4
matrix[i][-layer - 1] = p1
matrix[-layer - 1][-i - 1] = p2
matrix[-i - 1][layer] = p3
return matrix
def print_matrix(matrix):
for row in range(len(matrix)):
print(matrix[row])
matrix = [
[3, 2, 1, 4],
[0, 7, 6, 9],
[5, 2, 4, 3],
[6, 9, 2, 4]
]
print('Original:')
print_matrix(matrix)
print('Rotated:')
m = rotate_matrix(matrix)
print_matrix(matrix)
# Another way to rotate matrix:
# 1. transpose matrix (flip each elements row with column)
# 2. change rows to rotate left or columns to rotate right
# 'change rows' means 'flip row 0 with row n, row 1 with row n-1, etc'. Similar for columns.
# Above method is easier but requires O(n) extra space. |
# https://www.youtube.com/watch?v=ZRB7rIWO81U
# https://www.youtube.com/watch?v=7XmS8McW_1U
class TrieNode:
def __init__(self):
self.children = {}
self.is_end_of_word = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
current = self.root
for char in word:
if char not in current.children:
current.children[char] = TrieNode()
current = current.children[char]
current.is_end_of_word = True
return self
def search(self, word):
current = self.root
for char in word:
if char not in current.children:
return False
current = current.children[char]
return True
def get_words_bellow_node(self, node, prefix=''):
words = []
def helper(node, string):
for char, child in node.children.items():
helper(child, string + [char])
if node.is_end_of_word:
words.append(''.join(string))
helper(node, [prefix])
return words
def get_node(self, prefix):
current = self.root
for char in prefix:
if char not in current.children:
return None
current = current.children[char]
return current
def get_words_by_prefix(self, prefix):
node = self.get_node(prefix)
if node:
return self.get_words_bellow_node(node, prefix)
else:
return None
def __str__(self):
return ','.join(self.get_words_bellow_node(self.root))
trie = Trie()
trie.insert('ball').insert('beer').insert('balloon').insert('bat').insert('doll').insert('dork').insert('dorm').insert('send').insert('sense')
print(trie)
print('prefix "b":', trie.get_words_by_prefix('b'))
print('prefix "ba":', trie.get_words_by_prefix('ba'))
print('prefix "bal":', trie.get_words_by_prefix('bal'))
print('prefix "dol":', trie.get_words_by_prefix('dol')) |
from stack import Stack
from sys import maxsize
class StackWithMin(Stack):
def __init__(self):
Stack.__init__(self)
self.min_stack = Stack()
def cur_min(self):
if self.min_stack.is_empty():
return maxsize
return self.min_stack.peek()
def pop(self):
value = super(StackWithMin, self).pop()
if value == self.cur_min():
self.min_stack.pop()
return value
def push(self, value):
if value <= self.cur_min():
self.min_stack.push(value)
return super(StackWithMin, self).push(value)
stack = StackWithMin()
stack.push(4).push(2).push(1).push(1).push(9)
print(stack)
print(stack.min_stack.peek())
stack.pop()
print(stack)
print(stack.min_stack.peek())
stack.pop()
print(stack)
print(stack.min_stack.peek())
stack.pop()
print(stack)
print(stack.min_stack.peek()) |
from collections import Counter
# Count char frequencies and return True if no more than one char freq is odd and False otherwise.
# A permutation may not have more than one type of char with odd freq.
def is_palindrome_permutation_1(a):
counter = Counter(a)
is_permutation = True
for count in counter.most_common():
if is_permutation == False:
return is_permutation
if count[1] % 2 == 1:
is_permutation = False
return True
def is_palindrome_permutation_2(a):
# use a bit vector to signal occurence of a char
bit_vector = [0] * 26
for char in a:
# get char position in bit vector using its ASCII encoding
index = ord(char) - ord('a')
# replace 1 with 0 to indicate that freq of this char (so far) is even
if bit_vector[index] == 1:
bit_vector[index] = 0
else:
bit_vector[index] = 1
# sum of bit_vector should be 1 if all but one char has a odd freq
bit_vector_sum = sum(bit_vector)
return bit_vector_sum == 1 or bit_vector_sum == 0
a = 'abas'
print(is_palindrome_permutation_2(a)) |
'''
This script showing you how to use a sliding window
'''
from itertools import islice
def sliding_window(a, n, step):
'''
a - sequence
n - width of the window
step - window step
'''
z = (islice(a, i, None, step) for i in range(n))
return zip(*z)
##Example
sliding_window(range(10), 2, 1)
|
import urllib2
'''
Script to download pdf from a url, you need specify the website URL, and change the
filename in the loop, it mostly useful to download a sequence of files with the
filename only differ by a sequence number, e.g. CH1.PDF, CH2.PDF, CH3.PDF ...
'''
def download_file(download_url, output_name):
'''
Download part,
download_url is the url point to the file
output_name is filename you want to output
'''
response = urllib2.urlopen(download_url)
file = open(output_name, 'w')
file.write(response.read())
file.close()
print(output_name + " Completed")
if __name__ == "__main__":
path = 'http://www.dspguide.com/'
for i in range(35):
#exmaple of the file name is: CH1.PDF
filename = 'CH' + str(i) + '.PDF'
fileloc = path + filename
download_file(fileloc, filename) |
print('Enter "x" for exit!!!')
print('Tests were all out of 100')
print('Enter marks obtained in 5 subjects')
m1 = input()
if m1 == 'x':
exit()
else:
m2 = input()
m3 = input()
m4 = input()
m5 = input()
mark1 = int(m1)
mark2 = int(m2)
mark3 = int(m3)
mark4 = int(m4)
mark5 = int(m5)
total = mark1 + mark2 + mark3 + mark4 + mark5
average = total/5
percentage = (total/500) * 100
ranking = ''
if percentage >= 60:
ranking = 'Distinction'
print(f'Your Average Mark is {average}')
print(f'You got a {ranking}')
print(f'You percentage is {percentage} %')
elif percentage >= 45:
ranking = 'Merit'
print(f'Your Average Mark is {average}')
print(f'You got a {ranking}')
print(f'You percentage is {percentage} %')
elif percentage >= 33:
ranking = 'Pass'
print(f'Your Average Mark is {average}')
print(f'You got a {ranking}')
print(f'You percentage is {percentage} %')
else:
ranking = 'Fail'
print(f'Your Average Mark is {average}')
print(f'You got a {ranking}')
print(f'You percentage is {percentage} %')
|
# is_hot = False
# is_cold = False #True
# is_cool = True #False True
# is_hazy = False #True
# # 0 stands for
# if is_hot:
# print("Its hot today")
# print(
# else:
# print("Its a clumsy warm day take a chill")
# print("You can do whatever you want except for getting married!!!!!")"Please take an umbrella")
# elif is_cold:
# print("Its freezing dude")
# print("Eat an Eskimo Pie")
# elif is_hazy:
# print("Its hazy")
# print("Call Hazel")
# elif is_cool:
# print("Its cool")
# print("Sing along with me: 'Domo Arigato Mr Roboto...Domo...Domo...Domo'")
#password = 'justus'
# print("Enter your password")
# lock = input()
# if lock == password:
# print("You are logged in Domo")
# else:
# print("Oga this is not your account")
house = 1000000
has_good_credit = True
if has_good_credit:
down_payment = 0.1 * house
price = house - down_payment
print(price)
else:
up = 0.2 * house
price = house + up
print(price)
|
# names = ["Sankwa", "Lapha", "Gaxa", 1, 2, 8]
# # names [2] = "Pa Gaxa"
# for name in names:
# if name not in [1, 2, 8]:
# print(f'String: {name}')
# print("#####################################")
# else:
# print(f'Number: {name}')
# nums = [1, 20, 3, 5, 7]
# print(max(nums), " IS the largest number")
# max_num = nums[0]
# for number in nums:
# if number > max_num:
# max_num = number
# print(max_num)
# print("#####################################")
# min_num = nums[0]
# for number in nums:
# if number < min_num:
# min_num = number
# print(min_num)
# #2dimnsional lists
# matrix = [
# [1, 2, 3],
# [4, 5, 6],
# [7, 8, 9],
# ]
# print(matrix[1][0])
# list methods
# nums = [50, 34, 67, 89, 90]
# print(nums)
# nums.append(909)
# print(nums)
# nums.insert(2, 13)
# print(nums)
# nums.clear()
# print(nums)
# nums.pop()
# print(nums)
# print(nums.count(2))
# nums.sort()
# nums.reverse()
# print(nums)
# numbers = [1, 1, 2, 3, 4, 4, 5, 6, 6, 6]
# uniques = []
# for num in numbers:
# if num not in uniques:
# uniques.append(num)
# print(uniques)
# numbers1 = (1, 2, 7, 8, 9, 0)
# numbers1.append(100)
# storing information that comes as key value pairs
customer = {
"name" : "Bash Aguero",
"age" : 29,
"purchase" : 500,
}
print(customer)
print(customer["age"])
customer["age"] = "Turning 50 in 21 years"
print(customer.get("age"))
nums = (1, 2, 5, 7, 8, 9, 10)
nums.append(789)
for num in nums:
print(f'Num: {num}')
|
#from datetime import datetime, date, time
import datetime
#date and time -- today's date -- no time component
dan = datetime.date.today()
print (dan);
#dan = datetime.now()
#print (dan);
dan = datetime.time()
print (dan); #00:00:00
#hard-code a date
dan = datetime.datetime(2013, 6, 9, 11, 13, 3, 57000)
print (dan);
# Combine a date and a time
d = date(2017,11,18)
t = time(13,45,23)
dt = datetime.datetime.combine ( d,t)
print ("\nCombining date and time")
print (d)
print (t)
print (dt)
print ("\nAdding and substracting with dates")
#Adding to a date
date1 = date (2017,11,18)
date2 = date (1964, 2, 12)
dan = date2 + datetime.timedelta (days=20000) #Adding 20,000 days to my DOB
print ( dan)
#Difference between dates
print (date1 - date2)
print ("\nFormatting date output")
print ( dan.strftime( "%d %b, %y"))
print ( dan.strftime( "%b %d %y"))
dates = (1000, 2000, 3000, 4000, 5000, 10000, 20000, 30000)
# Examples of both styles of formatting, right-aligned
for i in range (len(dates)):
print ("%5d" % (dates[i]))
for i in range (len(dates)):
print ("{0:5d}".format(dates[i]))
#DOB entered as String (input always accepts String)
DOB_str = input ("\nEnter DOB in format MM/DD/YYYY: ")
# # Firstone results in 00:00:00 on end, second one, not
#DOB = datetime.datetime.strptime(DOB_str, "%m/%d/%Y")
DOB = datetime.datetime.strptime(DOB_str, "%m/%d/%Y").date()
print (DOB)
for i in range (len(dates)):
# print ( DOB + datetime.timedelta (days=dates[i]))
print ("{0:5d} days on {1:%Y-%m-%d}".format(dates[i], DOB + datetime.timedelta (days=dates[i])))
|
str1 = input("Enter a string: ")
print("Entered string is: ", str1)
print()
a = int(input("Enter the value of a: "))
b = int(input("Enter the value of b: "))
c = a + b
print("Value of c is: ", c)
print()
num1 = float(input("Enter num 1: "))
num2 = float(input("Enter num 2: "))
num3 = num1/num2
print("Value of num 3 is: ", num3)
|
import arithmetic
import unittest
# Testing add_numbers function from arithmetic.
class Test_addition(unittest.TestCase):
# Testing Integers
def test_add_numbers_int(self):
sum = arithmetic.add_numbers(50, 50)
self.assertEqual(sum, 100)
# Testing Floats
def test_add_numbers_float(self):
sum = arithmetic.add_numbers(50.55, 78)
self.assertEqual(sum, 128.55)
# Testing Strings
def test_add_numbers_strings(self):
sum = arithmetic.add_numbers('hello','python')
self.assertEqual(sum, 'hellopython')
class Test_subtraction(unittest.TestCase):
# Testing Integers
def test_sub_numbers_int(self):
diff = arithmetic.sub_numbers(50, 50)
self.assertEqual(diff, 0)
# Testing Floats
def test_sub_numbers_float(self):
diff = arithmetic.sub_numbers(80.00, 78)
self.assertEqual(diff, 2.00)
class Test_multiplication(unittest.TestCase):
# Testing Integers
def test_mul_numbers_int(self):
multi = arithmetic.mul_numbers(78, 46)
self.assertEqual(multi, 3588)
# Testing Floats
def test_mul_numbers_float(self):
multi = arithmetic.mul_numbers(77.85, 8)
self.assertEqual(multi, 622.8)
class Test_division(unittest.TestCase):
# Testing Integers
def test_div_numbers_int(self):
quotient = arithmetic.div_numbers(78, 2)
self.assertEqual(quotient, 39)
# Testing Floats
def test_div_numbers_float(self):
quotient = arithmetic.div_numbers(77.8, 2)
self.assertEqual(quotient, 38.9)
if __name__ == '__main__':
unittest.main()
|
import sqlite3
con_obj = sqlite3.connect("test.db")
with con_obj:
cur_obj = con_obj.cursor()
cur_obj.execute("INSERT INTO books VALUES ('Pride and Prejudice', 'Jane Austen')")
cur_obj.execute("INSERT INTO books VALUES ('Harry Potter', 'J.K Rowling')")
cur_obj.execute("INSERT INTO books VALUES ('The Lord of the Rings', 'J. R. R. Tolkien')")
cur_obj.execute("INSERT INTO books VALUES ('Murder on the Orient Express', 'Agatha Christie')")
cur_obj.execute("INSERT INTO books VALUES ('A Study in Scarlet', 'Arthur Conan Doyle')")
con_obj.commit()
print("Data inserted Successfully !!")
|
#!/usr/bin/python3
str1 = 'Hello Python!'
print("Original String: - ", str1)
print ("Updated String: - ", str1 [:6] + 'John')
|
# printing a simple string on the screen.
print("Hello Python")
# Accessing only a value.
a = 80
print(a)
# printing a string on screen as well as accessing a value.
a = 50
b = 30
c = a/b
print("The value of c is: ", c)
|
# Basic formatting
a = 10
b = 30
print("The values of a and b are %d %d" % (a, b))
c = a + b
print("The value of c is %d" % c)
str1 = 'John'
print("My name is %s" % str1)
x = 10.5
y = 33.5
z = x * y
print("The value of z is %f" % z)
print()
# aligning
name = 'Mary'
print("Normal: Hello, I am %s !!" % name)
print("Right aligned: Hello, I am %10s !!" % name)
print("Left aligned: Hello, I am %-10s !!" % name)
print()
# truncating
print("The truncated string is %.4s" % ('Examination'))
print()
# formatting placeholders
students = {'Name' : 'John', 'Address' : 'New York'}
print("Student details: Name:%(Name)s Address:%(Address)s" % students)
|
#! /usr/bin/python
def main():
maxLength = 0
maxNumber = 0
for i in xrange(1000000):
print 'current number: ' + str(i)
length = getCollatzlen(i);
if (length > maxLength):
maxLength = length
maxNumber = i
print maxNumber;
def getCollatzlen(number):
count = 1
while number > 1:
if number % 2 == 1:
number = 3*number + 1
else:
number = number/2
count += 1
return count
if __name__ == '__main__':
main() |
class A:
def __init__(self):
print('In A init')
def feature1(self):
print('Feature1 is working')
def feature2(self):
print('Feature2-A is working')
class B(A):
def __init__(self):
super().__init__()
print('Init B printing')
def feature2(self):
print('Feature2-B is working')
def feature4(self):
print('Feature4 is working')
b1 = B()
b1.feature2() |
class Calculator:
@staticmethod
def sum(a=None, b=None, c=None):
if a!=None and b!=None and c!=None:
return a + b + c
elif a!=None and b!=None:
return a + b
else:
return a
print('Sum of 5 + 6 + 10:{}'.format(Calculator.sum(5, 6, 10)))
print('Sum of 6 + 7:{}'.format(Calculator.sum(6, 7)))
|
from numpy import array
from numpy import concatenate
arr1 = array([ 3, 4, 23, 12, 67])
arr2 = array([ 78, 23, 45, 25, 34])
arr1Copy = arr1
arr1[1] = 3
print('arr1:', arr1, " shallowCopy:", arr1Copy)
arr2DeepCopy = arr2.copy()
print('arr2:', arr2, " Deep Copy:", arr2DeepCopy)
arr2[0] = arr2[0] + 12
print('arr2:', arr2, " Deep Copy:", arr2DeepCopy)
print('Addresses:', 'arr2:', id(arr2), ' arr2DeepCopy:', id(arr2DeepCopy)) |
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def compare(self, other):
if(self.name == other.name and self.age == other.age):
return True
else:
return False
harish = Person('Harish', 42)
radhika = Person('Radhika', 37)
harish2 = Person('Harish', 42)
if(harish.compare(radhika)):
print(harish.name, ' and ', radhika.name, ' are same')
else:
print(harish.name, ' and ', radhika.name, ' are not')
if(harish2.compare(harish)):
print('harish and harish2 are same')
else:
print('harish and harish2 are not same')
|
import pandas as pd
df = pd.DataFrame([[1,2,3],[4,5,6]],columns=["a", "b", "c"])
# 获取列名字
df.columns.values
# 读取文件
csv = pd.read_csv('../SalesJan2009.csv')
# 获取数据
csv.iloc[1,:]
csv.Transaction_date
# 添加列
csv["Price2"] = csv.Price
# 添加行
csv2 = csv.append(csv, ignore_index=True)
# 复杂查询
# select * from csv where Latitude>30
a = csv.loc[(csv.Latitude>30) & (csv.Latitude>0),:].reset_index()
# select * from csv where Country like 'Aus%'
b = csv.loc[csv.Country.str.startswith('Aus') , :].reset_index()
# 去除空格 左边空格lstrip 右空格 rstrip
csv.Country = csv.Country.str.rstrip()
# order by
csv.sort_values('Price', ascending=False)
# group by
f = csv.groupby(csv.Country).mean()
print(f)
|
"单分类的逻辑回归"
import tensorflow as tf
import pandas as pd
import matplotlib.pyplot as plt
data = pd.read_csv('./dataset/credit-a.csv', header=None)
# 获取数据
x = data.iloc[:, 0:-1]
# 用replace方法替换-1
y = data.iloc[:, -1].replace(-1, 0)
# 定义模型
model = tf.keras.Sequential()
# 给模型里面添加层
model.add(tf.keras.layers.Dense(4, input_shape=(15,), activation="relu"))
model.add(tf.keras.layers.Dense(4, activation="relu"))
model.add(tf.keras.layers.Dense(1, activation="sigmoid"))
# 查看模型总体情况
# model.summary()
# 对模型进行编译 metrics=["acc"]表示输出正确率
model.compile(
optimizer="adam",
loss="binary_crossentropy",
metrics=["acc"]
)
# 这里的histroy 是一个dict里面存放了一些信息
history = model.fit(x, y, epochs=100)
# print(history.history.keys())
# 通过plt进行绘图
plt.plot(history.epoch, history.history.get('loss'))
plt.show()
|
#1.write a python program to loop through a list of numbers and add +2 to every value to elements in list
list1=[1,2,3,4,5]
print("list1 is: ",list1)
for i in range(len(list1)):
list1[i]=list1[i]+2
print("After adding 2 to every elements in list1: ",list1)
print()
#2.write a program to get the below pattern
# 54321
# 4321
# 321
# 21
# 1
for i in range(5,0,-1):
for j in range(i,0,-1):
print(j,end='')
print()
print()
#3.python program to print the fibonacci sequence
def fibonacci(n):
n1,n2=0,1
c=0
if n<0:
print("Please Enter positive integer")
if n==0 or n==1:
return(n)
else:
return (fibonacci(n-1)+fibonacci(n-2))
s=int(input("Enter the number for fibonaaci sequence: "))
print('The fibonacci sequence for %d integers is: '%s)
for i in range(s):
print(fibonacci(i))
print()
#4.explain Armstrong number and write a code with function
print("Armstrong number is a number that forms total of the same number when each digits is raised to the power of the number of digits in the number")
def armstrong(n):
sum=0
while(n>0):
unitdigit=n%10
sum+=unitdigit**order
n=n//10
return sum
n=int(input("Enter the number to check whether it is an Armstrong number: "))
order=len(str(n))
arm=armstrong(n)
if arm==n:
print(n,"is an Armstrong number")
else:
print(n,"is not an Armstrong number")
print()
#5.write a program to print multiplication table of 9
for i in range(1,11):
print("9 x %d = %d"%(i,(i*9)))
print()
#6.check if a program is negative or positive
posorneg=int(input("Enter the integer to check if it is positive or negative: "))
if posorneg>=0:
print(posorneg,"is positive")
else:
print(posorneg,"is negative")
print()
#7.write a python program to convert the number of days to ages
days=int(input("Enter the no. of days: "))
ages=days//365
print("The age is ",ages)
print()
#8.solve trigonometry problem with math function, write a program to solve using math function
import math
def trigonometry(a,b):
if a=='sin':
return math.sin(b)
elif a=='cos':
return math.cos(b)
elif a=='tan':
return math.tan(b)
else:
return "invalid input"
a=input("Enter the trigonometric function: ")
b=int(input("Enter the theta value: "))
print(trigonometry(a,b))
print()
#9.create a basic calculator by using if condition
def calculator(x,y,z):
if x=='add':
return y+z
elif x=='sub':
return y-z
elif x=='mul':
return y*z
elif x=='div':
return y/z
elif x=='expo':
return y**z
else:
return "Invaid input"
x=input("Enter the basic operation: ")
y=int(input("Enter the first number: "))
z=int(input("Enter the second nuumber: "))
print("The answer is: ",calculator(x,y,z))
|
print("Яке з введених чисел є найменшим ")
print("Число 1")
while True :
try:
n1=int(input())
break
except:
print("Please enter number")
print("Число 2")
while True :
try:
n2=int(input())
break
except:
print("Please enter number")
minimum = n1
if n2< minimum:
minimum = n2
print("minimum")
|
# MEMOIZATION:
# first of all, note that it is not momorization.
# memoization is an optimization technique used primarily to speed up computer programs
# by storing the result of expensive fucntion calls and returning the catched result
# when the same inputs occur again.
import time
def expensive_func(n):
print("Computing {}........".format(n))
time.sleep(1) # here sleep function sleeps our program for 1 sec.
# time.sleep isn't actually computing anything. But this is kind of artificial expensive function call.
return n*n
# here we are calling this function four different times.
result=expensive_func(4)
print(result)
result=expensive_func(10)
print(result)
#again doing the same operation.
result=expensive_func(4)
print(result)
result=expensive_func(10)
print(result)
# since expensive_func sleeps 1 sec for every function call then this entire program should take about 4 sec.
# Here we have computed 4 and 10 first time with sleep and that is our atrificial computing time and that fine.
# Because the first time it sees that it has to do that. But then when we do the same operation second time which we've already run earliar.
# So instead of computing those values again it will be nice if we just remember those answers and remembering the answer is what memorIzation all about.
# Here we are saving the result to a cache so that whenever we see the expensive function call again with the same values passed in
# then instead of computing of values again we can just return the result that we have already computed from that cache.
# so to do that we can-
import time
expen_cache={} # here we have created a dictionary as cache.
def expensive_func2(n):
if n in expen_cache:
return expen_cache[n]# if the value in dictionary it will return that value with out sleeping.
print("Computing {}........".format(n))
time.sleep(1)
result=n*n
expen_cache[n]=result # if the value is not in dictionary, it will do that artificial expensive function and retun the value and save the value in the dictionary.
return result
result=expensive_func2(4)
print(result)
result=expensive_func2(10)
print(result)
result=expensive_func2(4)
print(result)
result=expensive_func2(10)
print(result)
# here it will computed onetime for 4 and one time for 10.
# but second time it wont compute, it will return the value from dictionary.
# and this time memorIzation will cut the computation time of our program in half time of previous program.
# there are more advanced thing that we can do with memorIzation.
# we can set up ways to where it does memorIzation automatically and things like that. |
# IMMUTABLE:
# an immutable object is an object whose state cannot be modified after it is created.
# MUTABLE:
# this is in contrast of an immutable object, which can be modified after it is created.
a="shawki"
print(a)
# in python, a string is immutable.
# immutable doesn't mean that we can not assign it.
a="john"
print(a)
# here a is immutable. so what's going on here?
#= it is not actually modifing the string object, it is creating a new string object.
# we can see that in detail with id() function.
a="shawki"
print("Address of a : ",id(a))
a="john"
print("New address of a: ",id(a))
# here we can see that the memory addresses dont match.
# so whenever we change that string object it will create a new object since strings are immutable.
# if we want to modify our string.
#a[0]="J"
#print(a)
# here we are getting a type error.
a=[1,2,3,4,5] # in python, a list is mutable.
print(a)
print("Address of a: ",id(a))
a[0]=6 # here we modified our list.
print(a)
print("Address of a: ",id(a))
# we can see that we are getting same memory address even though we modified our list.
# Why is important to know the diffferences between mutable and immutable object?
#= Aside from just avoiding errors, there is also a problem with memory as well.
# So something can seem harmless which really end up being really bad in performance.
employees=["Shawki","John","Corey","Steve","Mike"]
output="<uL>\n"
for emp in employees:
output+="\t<li>{}</li>\n".format(emp)
print("Address of output is {}".format(id(output)))
output+="</ul>"
print(output)
print("\n")
# this actually look fine. but in production code we may have thousands of code that we are concatenating. So, sometimes that becomes an issue.
# here we can see every time it loops though this object memory address is different. So every time it creates a new string object.
# if we have thousands of emp in our list it will vreate thousands of objects in memory.
# so it is good to keep those differences between mutable and immutable objects.
|
SIZES = ['small', 'medium', 'large']
STYLES = ['A', 'B']
class Tuxedo(object):
def __init__(self, style, size):
self.style = style
self.size = size
self.day = int()
def __str__(self):
return '%s%s' % (self.size, self.style)
def set_day(self, day):
self.day = day
def is_available(self, day):
return any([not self.day, self.day + 3 < day])
class Inventory(object):
def __init__(self):
self.tuxedos = [Tuxedo(style, size) for size in SIZES for m in range(5) for style in STYLES]
def get_tuxs(self, style, size, day):
return [tux for tux in self.tuxedos if tux.style == style and tux.size == size and tux.is_available(day)]
def place_order(self, small, medium, large, day):
for style in STYLES:
stock = dict(small = list(), medium = list(), large = list())
for size in stock:
stock[size] = self.get_tuxs(style, size, day)
if len(stock['small']) >= small and len(stock['medium']) >= medium and len(stock['large']) >= large:
[tux.set_day(day) for size, tuxs in stock.items() for tux in tuxs]
print 'Tuxedos style %s are available for day %s' % (style, day)
break
else:
print 'We need more tuxedos!'
if __name__ == '__main__':
inv = Inventory()
for i in range(1, 9):
inv.place_order(small = 4, medium = 0, large = 3, day = i)
|
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
pivot = pivot_binary_search(nums)
if pivot <= 0:
return target_binary_search(nums, 0, len(nums) - 1, target)
if target >= nums[0]:
return target_binary_search(nums, 0, pivot, target)
else:
return target_binary_search(nums, pivot, len(nums) - 1, target)
def pivot_binary_search(nums):
low = 0
high = len(nums) - 1
while (low <= high):
mid = (high + low) // 2
if nums[mid - 1] > nums[mid]:
return mid
elif nums[mid] > nums[high]:
low = mid + 1
else:
high = mid - 1
return low
def target_binary_search(nums, low, high, target):
while (low <= high):
mid = (high + low) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
low = (mid + 1)
else:
high = (mid - 1)
return -1
|
decision='Y' #to get inside the while loop the first time
productA=1000 -(1000 * 0.75)
productB=500 - (500 * 0.50)
productC=250 - (250 *0.25)
productD=100
productE=50
# varibles needed for the loops and the final invoice
quantA=0
quantB=0
quantC=0
quantD=0
quantE=0
priceA=0
priceB=0
priceC=0
priceD=0
priceE=0
Fprice=0
while (decision =='Y'):
try:
# to know if the user wants to continue buying
decision=input('Do you want to buy a new product? Write Y or N \n').upper()
if decision=='Y':
print ('You choose to buy')
producto= input ('Available products: A, B, C, D, E. Write the corresponding letter\n').upper()
quant=0 # the amount of products to buy, in case the users wants to continue buying more items of the same product
if producto=='A':
quant= int (input ('You have choose product A. How many items do you want?\n'))
if quant>=0:
Fprice=Fprice - priceA # in case previously the user had bought the same product, to not duplicate prices
quantA=quant + quantA # in case previously the user had bought the same product
print ('You have choose {} items'. format (quantA))
priceA=quantA * productA
print ('The original price is ${} .The reduced price is $ {}'.format ((1000 * quantA),priceA))
Fprice=Fprice + priceA # for the final invoice
else:
print ('You have to write a positive number')
elif producto=='B':
quant= int (input('You have choose product B. How many items do you want?\n'))
if quant>=0:
Fprice=Fprice - priceB # in case previously the user had bought the same product, to not duplicate prices
quantB=quant + quantB # in case previously the user had bought the same product
print ('You have choose {} items'. format (quantB))
priceB=quantB * productB
print ('The original price is ${} .The reduced price is $ {}'.format ((500 * quantB),priceB))
Fprice=Fprice + priceB # for the final invoice
else:
print ('You have to write a positive number')
elif producto=='C' :
quant= int (input('You have choose product C. How many items do you want?\n'))
if quant>=0:
Fprice=Fprice - priceC # in case previously the user had bought the same product, to not duplicate prices
quantC=quant + quantC # in case previously the user had bought the same product
print ('You have choose {} items'. format (quantC))
priceC=quantC * productC
print ('The original price is ${} .The reduced price is $ {}'.format ((250 * quantC),priceC))
Fprice=Fprice + priceC # for the final invoice
else:
print ('You have to write a positive number')
elif producto=='D':
quant= int (input('You have choose product D. How many items do you want?\n'))
if quant>=0:
Fprice=Fprice - priceD # in case previously the user had bought the same product, to not duplicate prices
quantD=quant + quantD # in case previously the user had bought the same product
print ('You have choose {} items'.format (quantD))
priceD=quantD * productD
print ('The price is $', priceD)
Fprice=Fprice + priceD # for the final invoice
else:
print ('You have to write a positive number')
elif producto=='E':
quant= int (input('You have choose product E. How many items do you want?\n'))
if quant>=0:
Fprice=Fprice - priceE # in case previously the user had bought the same product, to not duplicate prices
quantE=quant + quantE # in case previously the user had bought the same product
print ('You have choose {} items'.format (quantE))
priceE=quantE * productE
print ('The price is $', priceE)
Fprice=Fprice + priceE # for the final invoice
else:
print ('You have to write a positive number')
else: # input different to A-E
print ('Invalid option. Write A, B, C, D,E')
# final invoice
print ('\nTotal amount to pay for all the selected products ${} \n'. format (Fprice))
else: # continuation of the 'if' of line 23
if decision!='N':
print('Invalid option. Write Y or N')
decision='Y' # allow the user to continue buying by showing the initial question again
else: # user choose to leave the program
print ('Good bye. Thanks for using our services')
#to close the while loop
print ('\nProduct A: {} items. Price: $ {}'.format (quantA, priceA))
print ('\nProduct B: {} items. Price: $ {}'.format (quantB, priceB))
print ('\nProduct C: {} items. Price: $ {}'.format (quantC, priceC))
print ('\nProduct D: {} items. Price: $ {}'.format (quantD, priceD))
print ('\nProduct E: {} items. Price: $ {}'.format (quantE, priceE))
print ('\nTotal amount to pay ${} \n'. format (Fprice))
except: # in case the user write a letter instead of the amount of products to buy
print ('invalid option. You have to write a number')
|
'''В диапазоне натуральных чисел от 2 до 99 определить,
сколько из них кратны каждому из чисел в диапазоне от 2 до 9.'''
multiple_numbers = [2, 99]
dividers = [i for i in range(2, 10)]
multiple_count = 0
for i in range(multiple_numbers[0], multiple_numbers[-1] + 1):
for j in dividers:
if i % j != 0:
break
else:
multiple_count += 1
print(f'В диапозоне от {multiple_numbers[0]} до {multiple_numbers[1]} есть {multiple_count} чисел кратных числам от {dividers[0]} до {dividers[-1]}')
|
# First Variant
import sys
import random
def Count_memory(things):
summ = 0
for thing in things:
summ += sys.getsizeof(thing)
return summ
# FirstLesson
number = str(random.randint(100, 999))
summ = 0
prod = 1
for f in number:
summ += int(f)
prod *= int(f)
# SecondLesson
number = str(random.randint(10, 500))
even = 0
odd = 0
for f in number:
i = int(f)
if i % 2 == 0:
even += 1
else:
odd += 1
# ThirdLesson
r = [random.randint(0, 99) for _ in range(10)]
index_even = []
for n in r:
if n % 2 == 0:
index_even.append(r.index(n))
# Counting
# FirstVariant
count_things = [summ, prod]
print(f'First lesson first task is {Count_memory(count_things)}')
count_things = [number, even, odd]
print(f'Second lesson second task is {Count_memory(count_things)}')
count_things = [r, index_even]
print(f'Third lesson Second task is {Count_memory(count_things)}')
# SecondVariant
print(f'First lesson first task is {sys.getsizeof(summ) + sys.getsizeof(prod)}')
print(f'Second lesson Second task is {sys.getsizeof(number) + sys.getsizeof(even) + sys.getsizeof(odd)}')
print(f'Third lesson Second task is {sys.getsizeof(r) + sys.getsizeof(index_even)}')
# ThirdVariant
memory = 0
memory_thing = [summ, prod]
for thing in memory_thing:
memory += sys.getsizeof(thing)
print(f'First lesson first task is {memory}')
memory = 0
memory_thing = [number, even, odd]
for thing in memory_thing:
memory += sys.getsizeof(thing)
print(f'Second lesson Second task is {memory}')
memory = 0
memory_thing = [r, index_even]
for thing in memory_thing:
memory += sys.getsizeof(thing)
print(f'Third lesson Second task is {memory}')
|
# pygamede oyun animasyonlarını yapıp karakter hareketlerini kontrol edebileceğimiz önemli bir class var sprite
# bu hem kodumuzun daha temiz gözükmesi hem de karışmaması için böyle bir yol izleniyor.
import pygame
from random import randint, choice
pygame.init()
class Player(pygame.sprite.Sprite): # sprite.Sprite ı inherit ediyoruz.
def __init__(self):
super().__init__() # super kullanarak inherit ediyoruz.
# surfaceları buraya yazıyoruz.
walk1 = pygame.image.load("graphics/Player/player_walk_1.png")
walk2 = pygame.image.load("graphics/Player/player_walk_2.png")
self.jump = pygame.image.load("graphics/Player/jump.png")
self.walk = [walk1, walk2]
self.index = 0
self.gravity = 0
self.image = self.walk[0] # self.image ve self.rect özel instancelar onlar pygame tarafından otomatik
# oynatılacak oyüzden bunları kullanma # fakat diğer instnclar özel değil benim atadığımı isimler.
self.rect = self.image.get_rect(midbottom=(100, 300))
# Diğer özellikleri buraya dağıtıyoruz.
def gravity_p(self):
self.gravity += 1
self.rect.y += self.gravity
if self.rect.bottom > 300:
self.rect.bottom = 300
def jump_f(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_SPACE] and self.rect.bottom >= 300:
self.gravity = -20
def animation(self):
if self.rect.bottom < 300:
self.image = self.jump
else:
self.index += 0.1
if self.index >= len(self.walk): self.index = 0
self.image = self.walk[int(self.index)]
# ardından bu özellikleri update e yazıyoruz. ve while klasınını içinde groupe.update yapıyoruz.
# update de özel bir method isminin update olamsı lazım
def update(self):
self.jump_f()
self.gravity_p()
self.animation()
class Obstacles(pygame.sprite.Sprite):
# Aynı şeyler bu sınıf için de geçerli ayrıca göründüğü gibi
# birden fazla farklı görüntüdeki şekli de aynı class ın içinde topluyabiliyoruz.
# ve karakterlerin hızlı hareket etmesi için bug olmaması için 2 ye bölerek yazdık surfaceları
def __init__(self, n_type):
super().__init__()
if n_type == "Fly":
fly1 = pygame.image.load("graphics/Fly/Fly1.png")
fly2 = pygame.image.load("graphics/Fly/Fly2.png")
self.frames = [fly1, fly2]
else:
snail1 = pygame.image.load("graphics/snail/snail1.png")
snail2 = pygame.image.load("graphics/snail/snail2.png")
self.frames = [snail1, snail2]
self.image = self.frames[0]
if n_type == "Fly":
self.rect = self.image.get_rect(bottomleft=(randint(900, 1100), randint(100, 200)))
else:
self.rect = self.image.get_rect(bottomleft=(randint(900, 1100), 300))
self.index = 0
def animation(self):
self.index += 0.1
if self.index >= 2:
self.index = 0
self.image = self.frames[int(self.index)]
def move(self):
if self.rect.right <= 0:
self.kill() # self.kill() özel bir fonksiyon sprite classının objesinin ölmesini sağlıyor.
else:
self.rect.x -= 5
def update(self):
self.animation()
self.move()
# Mains
screen = pygame.display.set_mode((800, 400))
pygame.display.set_caption("Runner")
clock = pygame.time.Clock()
# Surfaces
ground_s = pygame.image.load("graphics/ground.png")
sky_s = pygame.image.load("graphics/Sky.png")
# Classes Groups
# Ardından bunlardan elde ettiğimiz objeleri grouplara aktarıyoruz.
# Eğerki sadece 1 tane obje yer alacaksa singlegroup birden fazla yer alacaksa groupe açılır.
pl = Player()
player_group = pygame.sprite.GroupSingle(pl)
obstacles = pygame.sprite.Group()
event1 = pygame.USEREVENT + 1
pygame.time.set_timer(event1, 1500)
# Score
score = 0
last_score = 0
font = pygame.font.Font("font/Pixeltype.ttf", 50)
score_s = font.render(f"Score:{score}", False, (64, 64, 64))
score_r = score_s.get_rect(bottomleft=(400, 400))
font1 = pygame.font.Font("font/Pixeltype.ttf", 35)
font2 = pygame.font.Font("font/Pixeltype.ttf", 60)
my_game_s = font.render("My Game", False, (64, 64, 64))
my_game_r = my_game_s.get_rect(midtop=(400, 0))
game_active = False
# Side Screen
def side_screen():
a = pygame.image.load("graphics/Player/player_stand.png")
a = pygame.transform.scale2x(a).convert_alpha()
a_r = a.get_rect(center=(400, 200))
b = font1.render("Press space to start the game", False, (111, 196, 169)).convert()
c = font2.render("PixelRunner", False, (111, 196, 169)).convert()
b.get_rect()
c.get_rect()
screen.fill((94, 129, 162, 0))
screen.blit(a, a_r)
screen.blit(c, c.get_rect(midbottom=(a_r.centerx + 5, a_r.top - 20)))
screen.blit(b, b.get_rect(center=(a_r.centerx, a_r.bottom + 35)))
score_s = font.render(f"Score:{score // 1000}", False, (64, 64, 64))
screen.blit(score_s, score_s.get_rect(center=(a_r.centerx, a_r.bottom + 70)))
def play_check():
if pygame.sprite.spritecollide(player_group.sprite, obstacles, False): # aynı zamanda pygame.sprite.spritecollide
# ile collisionları kontrol edebiliriz.eğer collision varsa 2 groupe arasında evet dönderir.
return False
return True
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
if game_active:
if event.type == event1:
obstacles.add(Obstacles(choice(["Fly", "Snail", "Snail"])))
else:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
game_active = True
last_score = pygame.time.get_ticks()
if event.type == pygame.MOUSEBUTTONDOWN:
game_active = True
last_score = pygame.time.get_ticks()
if game_active:
# Score
score = pygame.time.get_ticks() - last_score
score_s = font.render(f"{score // 1000}", False, (64, 64, 64))
# Blit operations
screen.blit(sky_s, (0, 0))
screen.blit(ground_s, (0, 300))
screen.blit(score_s, score_r)
pygame.draw.rect(screen, "#c0e8ec", my_game_r, 0, 6)
screen.blit(my_game_s, my_game_r)
player_group.draw(screen) # grouplardaki objeleri çizmek için draw kullanıyoruz.
obstacles.draw(screen)
# Update
player_group.update() # ardından grouplardakileri hareket ettirmek ve güncellemek için groupename.update i
# kullanıyoruz.
obstacles.update()
game_active = play_check()
else:
pl.rect.bottom = 300
obstacles.empty() # groupname.empty() de özel bir methoddur.grubun içini boşaltmayı sağlar.
side_screen()
clock.tick(60)
pygame.display.update()
|
import random
IMAGES = ['''
+---+
| |
|
|
|
|
=========''', '''
+---+
| |
O |
|
|
|
=========''', '''
+---+
| |
O |
| |
|
|
=========''', '''
+---+
| |
O |
/| |
|
|
=========''', '''
+---+
| |
O |
/|\ |
|
|
=========''', '''
+---+
| |
O |
/|\ |
| |
|
=========''', '''
+---+
| |
O |
/|\ |
| |
/ |
=========''', '''
+---+
| |
O |
/|\ |
| |
/ \ |
=========''', '''
''']
WORDS =['AVIONA','AVIONA','AVIONA']
def startGame():
attempts = 0
word = WORDS[random.randint(0,len(WORDS)-1)]
word_list = list(word)
joker = '*'
secret_list= list(joker*len(word_list))
while attempts<=7:
print('=============== H A N G E D G A M E ===============')
print(' Attempts: {}/7'.format(attempts))
print(IMAGES[attempts])
print(' Secret Word: {}'.format(secret_list))
if attempts >= 7:
print('You lost, Im Sorry the correct word its {}'.format(word))
break
letter = input(' Please insert a letter: ')
list_index = list()
for index in range(0,len(word_list)):
if letter == word_list[index]:
list_index.append(index)
if len(list_index)==0:
attempts = attempts+1
else:
for letter_index in list_index:
secret_list[letter_index]= letter
if(''.join(secret_list)==word):
print ('Congratulations, You Win the correct word its {}'.format(word))
break
def run():
startGame()
if __name__=="__main__":
run() |
def validarCadena(word):
word_list = list(word)
letters = list()
letters.append(word_list.pop(0))
for i in range(0,len(word_list)-1):
if(word_list[i]==letters[0]):
print(word_list[i]==letters[0])
word_list.pop(i)
else:
print (word_list)
def run():
word = input(' Ingresa la Cadena de Caracteres: ')
validarCadena(word)
if __name__ =='__main__':
run() |
#Findest the greater number
list = [9,41,12,3,74,15]
maxNumber = list[0]
minNumber = list[0]
sum =0
avg =0
for num in list:
if num > maxNumber:
maxNumber = num
if num < minNumber:
minNumber = num
sum += sum+num
print('El mayor numero es:'+ str(maxNumber))
print('El menor numero es:'+ str(minNumber))
print('La suma de todos los elementos es: '+str(sum))
print ('EL promedio de todos los elementos es: '+str(sum /len(list))) |
def factorial(n):
f = 1
for i in range (n,0,-1):
f = f*n
n= n-1
print(f)
num = input("enter your number")
factorial (int(num))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.