text
stringlengths 37
1.41M
|
---|
anterior = int(input("Digite um primeiro valor inicial:"))
decrescente = True
valor = 1
while valor != 0 and decrescente:
valor = int(input("Digite o valor da sequência:"))
if anterior < valor:
decrescente = False
anterior = valor
if decrescente:
print("Decrescente.")
else:
print("Não decrescente.") |
x = int(input("Enter a number: "))
i = 1
while i < x+1:
n = 1
while n <= x:
print( "%4d" % (i * n),end="")
n += 1
print ("")
i += 1
print() |
numbers = ['1', '6', '8', '1', '2', '1', '5', '6']
numb = input("Enter a number? ")
sum= sum(x == numb for x in numbers)
print("{} appears {} in my list".format(numb, sum))
# count = 0
# for n in numbers:
# if n == numb:
# count += 1
# print("{} appears {} in my list".format(numb, count))
|
radius = input(" Radius ?")
r = float(radius)
area = 3.14 * r **2
print( "Area = ", area) |
some_list = ['192.168.1.1', '10.1.1.1', '10.10.20.30', '172.16.31.254']
ip_address_list = some_list
print(ip_address_list)
for ip in ip_address_list:
print("My IP address is")
print(ip)
print("the end")
print(ip_address_list[1])
print("-"*40)
#Enumerate with index plus the value in a tuple
for my_var in enumerate(ip_address_list):
print(my_var)
#Enumerate both index and tuple value
for i, ip_addr in enumerate(ip_address_list):
print(i)
print(ip_addr)
print('-' * 30)
# break
print("-"*40)
for ip in ip_address_list:
print(ip)
if ip == '10.10.20.30':
break
# continue - goes back to original for statement (and does not print 10.10.20.30)
print("-"*40)
for ip in ip_address_list:
print('hello')
if ip == '10.10.20.30':
continue
print(ip )
# pass -- no op
# Nest for loops
print("-"*40)
some_list = ['192.168.1.1', '10.1.1.1', '10.10.20.30', '172.16.31.254']
ip_list2 = ['8.8.8.8', '8.8.4.4']
for ip in some_list:
for ip2 in ip_list2:
print(ip)
print(ip2)
|
# Lamda Functions
# one line disposible functions
def my_func(x):
return x**2
print(my_func(10))
print('-'*40)
# assigned value is variable x, and what is the return value
# Why is it used? Useful to have function that can be passed as an argument. Easy to defice and use in one line
f = lambda x: x**2
print(f(10)) |
"""Open the "show_version.txt" file for reading. Use the .read() method to read in the entire file contents to a variable.
Print out the file contents to the screen. Also print out the type of the variable (you should have a string at this point).
Close the file.
Open the file a second time using a Python context manager (with statement). Read in the file contents using
the .readlines() method. Print out the file contents to the screen. Also print out the type of the variable
(you should have a list at this point)."""
f = open("show_version.txt")
output = f.read()
print(output)
print(type(output))
f.close()
print("X"*80)
with open("show_version.txt") as f:
output = f.read()
print(type(output))
print(output) |
#!/usr/bin/env python
# coding: utf-8
# In[2]:
import numpy as np
rulenumber = int(input("Enter the number of the rule you will use: "))
#rule 1
if rulenumber == 1:
dA = float(input("Enter value for dA: "))
c = float(input("Enter value for c: "))
def rule1(dA, c):
dQ = abs(c)*dA
return dQ
dQ = rule1(dA, c)
print("dQ =", dQ)
#rule 2
if rulenumber == 2:
c = float(input("Enter value for c: "))
m = float(input("Enter value for m: "))
A = float(input("Enter value for A: "))
dA = float(input("Enter value for dA: "))
def rule2(c, m, A, dA):
dQ = abs(c*m*(A**(m-1)))*dA
return dQ
dQ = rule2(c, m, A, dA)
print("dQ =", dQ)
#rule 3
if rulenumber == 3:
dA = float(input("Enter value for dA: "))
dB = float(input("Enter value for dB: "))
def rule3(dA, dB):
dQ = np.sqrt(dA**2+dB**2)
return dQ
dQ = rule3(dA, dB)
print("dQ =", dQ)
#rule 4
if rulenumber == 4:
dA = float(input("Enter value for dA: "))
dB = float(input("Enter value for dB: "))
Q = float(input("Enter value for Q: "))
A = float(input("Enter value for A: "))
B = float(input("Enter value for B: "))
m = float(input("Enter value for m: "))
n = float(input("Enter value for n: "))
def rule4(dA, dB, Q, A, B, m, n):
dQ = abs(Q)*np.sqrt(((m*(dA/A))**2)+((n*(dB/B))**2))
return dQ
dQ = rule4(dA, dB, Q, A, B, m, n)
print("dQ =", dQ)
#activity 2
x = np.array([ 1.1, 1.3, 1.4, 0.9, 0.95, 1.05])
mean = np.average(x)
dx = np.std(x)/np.sqrt(6)
print("mean =", mean)
print("error in the mean =", dx)
#activity 3
# # Practice Heading
# $\delta Q = \sqrt{(\delta A)^2 + (\delta B)^2}$
#
# $\delta F_{c} = f_{c} * \sqrt{(\delta m_{h} / m_{h})^2 + (\delta m / m)^2}$
#
# $0.00796 = 0.784 * \sqrt{(0.0001 / 0.2083)^2 + (0.106 / 10.5)^2}$
# In[ ]:
|
import pygame
pygame.init()
def click():
if pygame.mouse.get_pressed()==(True, False, False):
return True
def mouse_over():
mx, my = pygame.mouse.get_pos()
if mx > 50 and mx < 100 and my > 50 and my < 100:
return True
else:
return False
#Mouse is hovering over button
aafText = "iaweruawbr"
RED = (250, 0, 0)
BLUE = (0, 0, 250)
GREEN = (0, 250, 0)
surface = pygame.display.set_mode((500, 500))
#pygame.draw.rect(surface, (250, 0, 0))
surface.fill((0, 250, 0))
def update():
h = True
while h:
button_filler = pygame.Surface((50, 50))
button_filler.fill(BLUE)
surface.blit(button_filler, (50, 50))
r = True
while r:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.type == pygame.QUIT or event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
r = False
if event.key == pygame.K_a:
print("a-getypt")
if event.key == pygame.K_b:
print("b-getypt")
if event.key == pygame.K_c:
update()
surface.fill((250, 250, 250))
if mouse_over() == True:
pygame.draw.rect(surface, GREEN, (50, 50, 50, 50))
if click():
print("1")
else:
pygame.draw.rect(surface, RED, (50, 50, 50, 50))
pygame.draw.rect(surface, BLUE, (150, 50, 50, 50))
pygame.display.update()
|
"""
根据一定文件夹结构下的图片,生成训练或检验所需的列表文件
Example train.txt:
/path/to/train/image1.png 0
/path/to/train/image2.png 1
/path/to/train/image3.png 2
/path/to/train/image4.png 0
.
.
@author: wgshun
"""
import os
import re
import shutil
def cut(x):
x = x.split('_')
n = ''
for i in x[:-1]:
n += '_' + i
return n[1:]
def gen_val():
image_path_test = 'data/补拍_test'
label_dic ={}
with open(os.path.join(image_path_test, 'val.txt'), 'w') as txt1:
files = os.listdir(image_path_test)
for _, file in enumerate(files):
label_dic[file] = file.split('-')[0]
for file in files:
if os.path.splitext(file)[-1] != '.txt':
str2 = str(label_dic[file])[:-1]
if len(str(label_dic[file]))==1:
str2 = str(0)
wr_str = os.path.join(image_path_test + '/', file) + ' ' + str2 + "\n"
txt1.write(wr_str)
txt1.close()
def gen_train():
image_path = 'data/补拍1000'
label_dic = {}
with open(os.path.join(image_path, 'train.txt'), 'w') as txt:
files = os.listdir(image_path)
for _, file in enumerate(files):
label_dic[file] = file.split('-')[0]
for file in files:
if os.path.splitext(file)[-1] != '.txt':
str2 = str(label_dic[file])[:-1]
if len(str(label_dic[file]))==1:
str2 = str(0)
wr_str = os.path.join(image_path+'/', file) + ' ' + str2 + "\n"
txt.write(wr_str)
txt.close()
def file_mv():
image_path = 'data/补拍1000'
image_path_test = 'data/补拍_test'
label_dic = {}
files = os.listdir(image_path)
for file in files:
if os.path.splitext(file)[-1] != '.txt':
if file.split('-')[1] == '93.png':
shutil.move(os.path.join(image_path+'/', file), os.path.join(image_path_test+'/', file))
def file_mv2():
image_path = 'data/黑底试纸'
image_path_test = 'data/补拍1000'
label_dic = {}
files = os.listdir(image_path)
for file in files:
if os.path.splitext(file)[-1] != '.txt':
# if file.split('-')[1] == '94.png':
file1 = file.split('-')
file2 = file1[1].split('.')
file3 = int(file2[0])+100
file4 = file1[0]+'-'+str(file3)+'.'+file2[1]
shutil.move(os.path.join(image_path+'/', file), os.path.join(image_path_test+'/', file4))
def corr():
with open('data/simpsons_dataset/train.txt', 'r+')as fp:
dict = {}
for line1 in fp.readlines():
dict[line1.split('/')[-2]]=line1[-2]
with open('data/kaggle_simpson_testset/val.txt','r+')as fb:
with open('data/kaggle_simpson_testset/val1.txt','w+')as fb1:
for line in fb.readlines():
try:
label = dict[cut(line.split('/')[-1])]
except KeyError:
continue
line2 = line[:-2]+str(label)+'\n'
fb1.writelines(line2)
# file_mv()
gen_val()
gen_train() |
from string import ascii_lowercase
text = """
One really nice feature of Python is polymorphism: using the same operation
on different types of objects.
Let's talk about an elegant feature: slicing.
You can use this on a string as well as a list for example
'pybites'[0:2] gives 'py'.
The first value is inclusive and the last one is exclusive so
here we grab indexes 0 and 1, the letter p and y.
When you have a 0 index you can leave it out so can write this as 'pybites'[:2]
but here is the kicker: you can use this on a list too!
['pybites', 'teaches', 'you', 'Python'][-2:] would gives ['you', 'Python']
and now you know about slicing from the end as well :)
keep enjoying our bites!
"""
def slice_and_dice(text: str = text) -> list:
"""Get a list of words from the passed in text.
See the Bite description for step by step instructions"""
results = []
text = text.strip().split('\n')
#print(text)
for i in text:
i = i.strip()
if i[0].islower():
results.append(i.split().pop().strip('.!'))
return results
# Theirs
# def slice_and_dice(text: str = text) -> list:
# result = []
# for line in text.strip().splitlines():
# line = line.lstrip()
#
# if line[0] not in ascii_lowercase:
# continue
#
# words = line.split()
# last_word_stripped = words[-1].rstrip('!.')
# results.append(last_word_stripped)
if __name__ == '__main__':
print(slice_and_dice()) |
def function():
if a>b and a>c:
print(a," is max num")
if b>a and b>c:
print(b," is max num")
if c>a and c>b:
print(c," is max num")
a=int(input("enter any num"))
b=int(input("enter any num"))
c=int(input("enter any num"))
function() |
##################################################
## This script generates a report of an exam with section wise marks for all students appeared in exam by taking data from CSV
##################################################
## Author: Pennada S V Naga Sai
## Email: [email protected]
##################################################
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.text
from pandas import Series,DataFrame
import pandas as pd
from matplotlib import patches
import fitz
from fitz.utils import insertImage
#function will be used later for integrating with a dictionary
def Merge(stat, profile):
return(profile.update(stat))
#iterating over the csv file rows
dt = pd.read_csv("D:\Ken related\HazCom_students\Project\interface\data.csv", index_col='ID')
for i in dt.index:
marks = list(dt.iloc[i-1,4:9])
score = sum(marks)
if score <= 10 :
remark = 'Poor'
elif score >10 and score <=20 :
remark = 'Good'
else :
remark = ' Excellent'
#Report Analysis (marks 1,2,3,4,5 are different subjects)
marks1 = list(dt.iloc[i-1,4:5])
score = sum(marks1)
if score ==0 :
retort1 = "Needs improvement. Your speed is average. A little work on\n your speed management will help you in solving more number of questions\n accurately."
elif score in range(1,6):
retort1 ="Your speed is average. A little work on your speed management\n will help you in solving more number of questions accurately."
elif score in range(6,10):
retort1 ="Your speed is good and you have a good presence of mind.\n Maintaining accuracy can fetch you a better score."
else :
retort1 = "You have excellent speed and accuracy."
marks2 = list(dt.iloc[i-1,5:6])
score = sum(marks2)
if score ==0 :
retort2 = "Needs improvement.Try to find a smart and organized approach to\n score more."
elif score in range(1,7):
retort2 ="Your consistency is good. Try to find a smart and organized\n approach to score more."
else :
retort2 = "Your consistency and accuracy are excellent and you have an\n organized approach towards questions."
marks3 = list(dt.iloc[i-1,6:7])
score = sum(marks3)
if score ==0 :
retort3 = "Improvement in speed and method of solving is needed."
elif score in range(1,4):
retort3 ="You have a good logical approach. Improvement in speed and method\n of solving is needed."
else :
retort3 = "Your logical approach and method of solving the questions is \nexcellent."
marks4 = list(dt.iloc[i-1,7:8])
score = sum(marks4)
if score ==0 :
retort4 = "Needs improvement. More effort in accuracy is required."
elif score in range(1,6):
retort4 ="Your logic was moderate. More effort in accuracy is required."
elif score in range(6,11):
retort4 ="You have a good balance between logic and accuracy."
else :
retort4 = "You have an excellent balance between logic and accuracy. Along with\n that, you have made a good use of bonus marking."
marks5 = list(dt.iloc[i-1,8:9])
score = sum(marks5)
if score ==0 :
retort5 = "Needs improvement in accuracy."
elif score >=1 and score <= 2.5:
retort5 ="You have a good logic but you need to work a bit more on accuracy."
else :
retort5 = "You have an excellent balance between finding the trick and solving\n the question accurately."
#Using the function from the beginning to create a new dataframe suitable for plotting
stat = {'Section':['A', 'B', 'C', 'D','E'], 'Marks':marks, 'Remark':remark , "Retort1": retort1, "Retort2": retort2,"Retort3": retort3,"Retort4": retort4,"Retort5": retort5}
profile = dict(dt.iloc[i-1,0:4])
Merge(stat, profile)
df = pd.DataFrame(profile)
#using matplotlib as a canvas to plot the data ad pie chart
plt.figure(figsize=(10,20))
colors = ['#3B4D85', '#E5FFC9', '#000800', '#BDCDFF', '#9ACC64']
ay = plt.pie(marks, labels=stat['Section'], colors=colors, autopct='%.1f%%', shadow= True, startangle=140)
plt.title('Students Marks')
plt.axis('equal')
plt.annotate('Name - ' + profile['NAME'],
xy=(.10,1000), xycoords='axes points',fontsize=17)
plt.annotate('School - ' + profile['SCHOOL NAME'],
xy=(.10, 970), xycoords='axes points',fontsize=13)
plt.annotate('Contact - ' + str(profile['CONTACT NO.']),
xy=(.10, 940), xycoords='axes points',fontsize=13)
plt.annotate('ROUND 1 Test: Report Analysis',
xy=(120, 850), xycoords='axes points',fontsize=20)
plt.annotate('SectionA - ' + profile['Retort1'],
xy=(0, 200), xycoords='axes points',fontsize=15)
plt.annotate('SectionB - ' + profile['Retort2'],
xy=(0, 150), xycoords='axes points',fontsize=15)
plt.annotate('SectionC - ' + profile['Retort3'],
xy=(0, 100), xycoords='axes points',fontsize=15)
plt.annotate('SectionD - ' + profile['Retort4'],
xy=(0, 50), xycoords='axes points',fontsize=15)
plt.annotate('SectionE - ' + profile['Retort5'],
xy=(0, 0), xycoords='axes points',fontsize=15)
#Saving the file as pdf
myfile = profile['NAME']
plt.savefig(myfile+'.pdf')
#opening the file again to add an image at the top
doc = fitz.open(myfile + '.pdf')
rect= fitz.Rect(0,0,1000,210)
for page in doc:
page.insertImage(rect, filename="D:\\Ken related\HazCom_students\Project\interface\dex.jpg")
doc.saveIncr()
#########################################################################
|
from typing import List
'''
1. Container With Most Water
Given a non-negative integers a1, a2, ..., an, where each represents a point at
coordinate (i, ai). n vertical lines are draw such that the two endpoints of line
i is at (i,ai) and (i, 0). Find two lines, which together with x-axis forms a
container, such that the container the most water.
Note: You may not slant the container and n is at least 2.
Example:
Input: [1, 8, 6, 2, 5, 4, 8, 3, 7]
Output: 49
'''
'''
解题思路:
1. 每移动一个值,底都减1,如果想要获得更大值,期望通过移动到较大的值上来计算。
'''
EXAMPLES = [
(
([1, 8, 6, 2, 5, 4, 8, 3, 7],), 49,
),
]
class Solution:
def maxArea(self, height: List[int]) -> int:
i = 0
j = len(height) - 1
max_value = 0
while i < j:
v = min(height[i], height[j])
max_value = max(max_value, v * (j - i))
if height[i] < height[j]:
i += 1
else:
j -= 1
return max_value
|
from typing import List
from utils import build_tree
from utils.types import Node
'''
590. N-ary Tree Postorder Traversal
Given an n-ary tree, return the postorder traversal of its nodes' values.
Nary-Tree input serialization is represented in their level order traversal, each
group of children is separated by the null value (See examples).
Follow up:
Recursive solution is trivial, could you do it iteratively?
Example 1:
1
/ | \
3 2 4
/ \
5 6
Input: root = [1, null, 3, 2, 4, null, 5, 6]
Ouput: [5, 6, 3, 2, 4, 1]
Example 2:
1
/ / \ \
2 3 4 5
/ \ | / \
6 7 8 9 10
| | |
11 12 13
|
14
Input: root = [
1, null, 2, 3, 4, 5, null, null, 6, 7, null,
8, null, 9, 10, null, null, 11, null, 12, null,
13, null, null, 14
]
Output: [2, 6, 14, 11, 7, 3, 12, 8, 4, 13, 9, 10, 5, 1]
'''
'''
总结:
1. 后序遍历,从左子树开始再到根结点,再到右子树。
'''
EXAMPLES = [
# (
# build_tree(*[
# 1, None, 2, 3, 4, 5, None, None, 6, 7, None, 8, None, 9, 10,
# None, None, 11, None, 12, None, 13, None, None, 14,
# ]),
# [2, 6, 14, 11, 7, 3, 12, 8, 4, 13, 9, 10, 5, 1]
# ),
(
build_tree(*[
1, None, 3, 2, 4, None, 5, 6
]),
[5, 6, 3, 2, 4, 1],
),
]
class Solution:
def postorder(self, root: Node) -> List[int]:
r = []
if root:
if root.children:
r += sum([
self.postorder(child)
for child in root.children
], [])
r.append(root.val)
return r
|
import math
from utils import build_list_node
from utils.types import ListNode
'''
21. Merge Two Sorted Lists
Merge two sorted linked lists and return it as a new list. The new list should be
made by splicing together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
'''
'''
解题思路:
1. 归并排序的链表实现
'''
EXAMPLES = [
(
(build_list_node(1, 2, 4), build_list_node(1, 3, 4)),
build_list_node(1, 1, 2, 3, 4, 4),
),
]
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
n = ListNode(0)
temp = n
node1 = l1
node2 = l2
while not (node1 is None and node2 is None):
node1_val = node1.val if node1 else math.inf
node2_val = node2.val if node2 else math.inf
if node1_val < node2_val:
v = node1_val
node1 = node1.next
else:
v = node2_val
node2 = node2.next
temp.next = ListNode(v)
temp = temp.next
return n.next
|
import math
from typing import Union # noqa
class ListNode:
def __init__(self, x: int) -> None:
self.val = x
self.next: Union[ListNode, None] = None
def __repr__(self) -> str:
values = []
cls: Union[ListNode, None] = self
while cls:
values.append(str(cls.val))
cls = cls.next
v = '->'.join(values)
return f'LN: {v}'
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def get_tree(self):
depth = self.get_depth()
values = [self]
for i in range(depth):
n = 2**i - 1
for node in values[n:]:
values += [
node.left if node else None,
node.right if node else None,
]
return [v.val if v else '.' for v in values]
def show_tree(self):
values = self.get_tree()
depth = int(math.log(len(values) + 1, 2))
for i in range(depth, 0, -1):
n = depth - i
for v in values[2**n-1:2**(n+1)-1]:
print(i*' ', v, end='')
print(i*' ')
def get_depth_from_node(self, node):
left_depth = 0
if node.left:
left_depth += 1
left_depth += self.get_depth_from_node(node.left)
right_depth = 0
if node.right:
right_depth += 1
right_depth += self.get_depth_from_node(node.right)
return max(left_depth, right_depth)
def get_depth(self):
return self.get_depth_from_node(self)
def __repr__(self) -> str:
return f'<TreeNode: {self.val}>'
class Node:
def __init__(self, val, children=None):
self.val = val
self.children = children
def print_tree(self, node, depth=0):
print(depth*' ', node.val)
if node.children:
for child in node.children:
self.print_tree(child, depth=depth+1)
def show_tree(self):
self.print_tree(self)
|
from typing import List
'''
1. Two Sum
Given an array of integers, return indices of the two numbers such that
they add up to a specific target.
You may assume that each input would have exactly one solution, and you
may not use the same element twice.
Examples:
Given nums = [2, 7, 11, 15], target = 9
Becacuse nums[0] + nums[1] = 2 + 7 = 9
return [0, 1].
'''
'''
总结:
1. hash_map 寻找速度大于 array.index
2. target - nums[i] = new_target,hash_map有两种方式
a. 当前值是需要找到的 new_target, nums[i] in memeroy
b. new_target 是否在以前迭代过的某个值,new_target in memeroy
'''
EXAMPLES = [
(
([2, 7, 11, 15], 9),
[0, 1]
),
]
class Solution:
def twoSum_myself(self, nums: List[int], target: int) -> List[int]:
r = []
for i, v in enumerate(nums):
next_value = target - v
if next_value in nums[i+1:]:
r = [i, nums[i+1:].index(next_value) + i + 1]
break
return r
class Solution1:
'''
用时最小
'''
def twoSum(self, nums: List[int], target: int) -> List[int]:
memeroy = {}
for i, v in enumerate(nums):
if v in memeroy:
return [memeroy[v], i]
memeroy[target - v] = i
class Solution2:
'''
内存最小
'''
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(len(nums)):
for j in range(i+1, len(nums)):
if nums[i]+nums[j] == target:
return [i, j]
|
from typing import List
'''
14. Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of
strings.
If there is no common prefix, return an empty string ''.
Example 1:
Input: ['flower', 'flow', 'flight']
Output: 'fl'
Exmaple 2:
Input: ['dog', 'racecar', 'car']
Output: ''
Explanation: There is no common prefix among the input strings.
Note:
All given inputs are in lowercase letters a-z.
'''
'''
解题思路:
1. 从数组中不断去寻找两个词最大相同前缀。
2. 如果按顺序循环迭代数组,时间复杂度为 O(n)
待解决问题:
1. 该算法的时间复杂度
'''
class Solution:
def getPrefix(self, strs: List[str], low: int, high: int) -> str:
if high < low:
return ''
elif low == high:
return strs[low]
else:
mid = int((low + high) / 2)
l_str = self.getPrefix(strs, low, mid)
r_str = self.getPrefix(strs, mid + 1, high)
r = ''
if l_str and r_str:
r = min(l_str, r_str)
while not (l_str.startswith(r) and r_str.startswith(r)):
r = r[0:-1]
return r
def longestCommonPrefix(self, strs: List[str]) -> str:
return self.getPrefix(strs, 0, len(strs) - 1)
|
from utils import build_binary_tree
from utils.types import TreeNode
'''
404. Sum of Left Leaves
Find the sum of all left leaves in a given binary tree.
Example:
3
/ \
9 20
/ \
15 7
There are two left leaves in the binary tree, with values 9 and 15 respectively.
Return 24.
'''
EXAMPLES = [
(
build_binary_tree(*[
3, 9, 20, None, None, 15, 7,
]),
24,
)
]
class Solution:
def check_leavf(self, root: TreeNode) -> bool:
return root.left is None and root.right is None
def sumOfLeftLeaves(self, root: TreeNode) -> int:
r = 0
if root:
if root.left:
if self.check_leavf(root.left):
r += root.left.val
else:
r += self.sumOfLeftLeaves(root.left)
if root.right and not self.check_leavf(root.right):
r += self.sumOfLeftLeaves(root.right)
return r
|
from typing import List
from utils import build_binary_tree
from utils.types import TreeNode
'''
437. Path Sum III
You are given a binary tree in which each more contains an integers value.
Find the number of paths that sum to a given value.
The path does not need to start or end at the root or a leaf, but it must go
downwards (traveling only from parent nodes to child nodes).
The tree has no more than 1,000 nodes and the values are in range -1,000,000
to 1,000,000.
Example:
root = [10, 5, -3, 3, 3, null, 11, 3, -2, null, 1], sum = 8
10
/ \
5 -3
/ \ \
3 2 11
/ \ \
3 -2 1
Return 3. The paths tha sum to 8 are:
1. 5 -> 3
2. 5 -> 2 -> 1
3. -3 -> 11
'''
'''
总结:
1. 前序遍历,target = sum - node.val,分别从左子树和右子树中寻找新的路径。
2. 左右子树均有可能找出符合要求的路径
3. 符合要求的答案中,可能还存在余下节点和为 0 的情况,这种情况是一个新的正确路径
'''
EXAMPLES = [
# (
# (build_binary_tree(*[10, 5, -3, 3, 3, None, 11, 3, -2, None, 1]), 8),
# 3,
# ),
(
(build_binary_tree(*[1, -2, -3, 1, 3, -2, None, -1]), -1),
4
)
]
class Solution:
def path_sum(self, node: TreeNode, sum: int) -> List[TreeNode]:
count = 0
if node:
target = sum - node.val
if target == 0:
count += 1
count += self.path_sum(node.left, target)
count += self.path_sum(node.right, target)
return count
def pathSum(self, root: TreeNode, sum: int) -> int:
r = 0
if root:
r += self.path_sum(root, sum)
r += self.pathSum(root.left, sum)
r += self.pathSum(root.right, sum)
return r
|
r=input()
x=['a','e','i','o','u']
if r in x:
print('vowels')
else:
print('invalid')
|
import random
import pygame
import tkinter as tk
from tkinter import messagebox
from collections import Counter
'''
Drawing in pygame starts in upper left hand corner of object
'''
class Cube(object):
rows = 20
w = 500
def __init__(self, start, dirnx=1, dirny=0,color=(255,0,0)):
self.pos = start
self.dirnx = 1
self.dirny = 0
self.color = color
def move(self, dirnx, dirny):
self.dirnx = dirnx
self.dirny = dirny
self.pos = (self.pos[0]+self.dirnx, self.pos[1] + self.dirny)
def draw(self, surface, eyes=False):
dis = self.w//self.rows
i = self.pos[0] # grid row
j = self.pos[1] # grid col
# add 1s and minus 2s to stay inside grid lines
pygame.draw.rect(surface, self.color, ((i*dis)+1, (j*dis)+1, dis-2, dis-2))
# draw eyes
if eyes:
centre = dis//2
radius = 3
circMid1 = ((i*dis)+centre-radius, (j*dis)+8)
circMid2 = ((i*dis)+dis-radius*2, (j*dis)+8)
pygame.draw.circle(surface, (255,255,255), circMid1, radius)
pygame.draw.circle(surface, (255,255,255), circMid2, radius)
# Snake obj contains multiple Cube objs
class Snake(object):
# "snake body", will contain the Cubes
body = []
turns = {}
def __init__(self, color, pos):
self.color = color
# create head Cube at current position (preset) and append it to body.
self.head = Cube(pos)
self.body.append(self.head)
# directions for x and y (either -1, 0, or 1) keepin track of the direction we're moving
# only one value can be !=0 (can only move in one direction at once)
self.dirnx = 0
self.dirny = 1
def move(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
# dict of all key values, indicating keys that are pressed or not
keys = pygame.key.get_pressed()
for key in keys:
if keys[pygame.K_LEFT]:
self.dirnx = -1
self.dirny = 0
# add key to turns that is the current position of head of snake
# set it equal to the direction we turned
self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]
elif keys[pygame.K_RIGHT]:
self.dirnx = 1
self.dirny = 0
self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]
elif keys[pygame.K_UP]:
self.dirnx = 0
self.dirny = -1
self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]
elif keys[pygame.K_DOWN]:
self.dirnx = 0
self.dirny = 1
self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]
for i, c in enumerate(self.body):
p = c.pos[:]
if p in self.turns:
turn = self.turns[p]
c.move(turn[0], turn[1])
if i == len(self.body)-1:
# once we reach the last cube, remove turn from list
self.turns.pop(p)
# check if we've reached a window edge
else:
# if yes, move back in opposite direction, causing a loss
# ex. (if moving left, hitting left wall, move right)
if c.dirnx == -1 and c.pos[0]<=0: c.pos = (c.rows-1, c.pos[1])
elif c.dirnx == 1 and c.pos[0] >= c.rows-1: c.pos = (0, c.pos[1])
elif c.dirny == 1 and c.pos[1] >= c.rows-1: c.pos = (c.pos[0], 0)
elif c.dirny == -1 and c.pos[1]<=0: c.pos = (c.pos[0], c.rows-1)
# if no edge is met, move cube 1 position in current direction
else: c.move(c.dirnx, c.dirny)
def reset(self, pos):
pass
def addCube(self):
tail = self.body[-1]
dx, dy = tail.dirnx, tail.dirny
# check which way the tail of snake is moving (so we know the directions and location of the added Cube)
if dx == 1 and dy == 0:
self.body.append(Cube((tail.pos[0]-1, tail.pos[1])))
elif dx == -1 and dy == 0:
self.body.append(Cube((tail.pos[0]+1, tail.pos[1])))
elif dx == 0 and dy == 1:
self.body.append(Cube((tail.pos[0], tail.pos[1]-1)))
elif dx == 0 and dy == -1:
self.body.append(Cube((tail.pos[0], tail.pos[1]+1)))
# add direction to added cube
self.body[-1].dirnx = dx
self.body[-1].dirny = dy
def draw(self, surface):
for i, c in enumerate(self.body):
# check if Cube is head
if i == 0:
# if yes, add eyes and draw
c.draw(surface, True)
else:
# else draw without eyes
c.draw(surface)
def drawGrid(w, rows, surface):
size_btwn = w//rows
x = 0
y = 0
for i in range(rows):
x += size_btwn
y += size_btwn
# start, end positions
pygame.draw.line(surface, (255,255,255), (x,0), (x,w)) # vertical line
pygame.draw.line(surface, (255,255,255), (0,y), (w,y)) # horizontal line
def redrawWindow(surface):
global width, rows, snake, snack
# fill the screen (with black)
surface.fill((0,0,0))
# draw the grid
drawGrid(width, rows, surface)
# draw the snake
snake.draw(surface)
# draw the snack
snack.draw(surface)
# update display
pygame.display.update()
pass
def randomSnack():
global rows, snake
positions = snake.body
while True:
x = random.randrange(rows)
y = random.randrange(rows)
# check if random position is the same as current position of any snake cubes
if len(list(filter(lambda z: z.pos == (x,y), positions)))>0:
continue
else:
break
return (x,y)
def message_box(subject, content):
pass
def main():
global width, rows, snake, snack
width = 500
rows = 20
win = pygame.display.set_mode((width, width))
#color(red) #position
snake = Snake((255, 0, 0), (10,10))
snack = Cube(randomSnack(), color=(0,255,0))
flag = True
clock = pygame.time.Clock()
while flag:
# create 50 ms time delay
pygame.time.delay(50)
# make sure our game doesn't run faster than 10 fps
clock.tick(10)
# move snake
snake.move()
# log and check positions
positions = [x.pos for x in snake.body]
#check if there are more than one body squares in the same position
if filter(lambda x: x.value>1,Counter(positions)):
win.fill("green")
pygame.draw.text(f"Game Over, you're score was {len(snake.body)}",
topleft=(100,350), fontsize=30)
if snake.body[0].pos == snack.pos:
snake.addCube()
snack = Cube(randomSnack(), color=(0,255,0))
redrawWindow(win)
pass
main() |
class HashFunction:
def __init__(self, size):
self.list_size = size
self.the_list = []
for i in range(size):
self.the_list.append("-1")
def hash_func_1(self, str_list):
for j in str_list:
index = int(j)
self.the_list[index] = j
def hash_func_2(self, str_list):
for k in str_list:
str_int = int(k)
index = str_int % 29
print(f"Mod Index: {index} Value: {str_int}")
# search for a collision
while self.the_list[index] != "-1":
index += 1
print(f"Collision. Try {index} instead.")
index %= self.list_size
self.the_list[index] = k
def is_prime(self, num):
if num <= 1:
return False
if num <= 3:
return True
if num % 2 == 0 or num % 3 == 0:
return False
# 6k +/- 1
j = 5
while j * j <= num:
if num % j == 0 or num % (j+2) == 0:
return False
j = j+6
return True
def get_next_prime(self, min_size):
while True:
if self.is_prime(min_size):
return min_size
else:
min_size += 1
def increase_list_size(self, min_size):
new_list_size = self.get_next_prime(min_size)
self.move_old_list(new_list_size)
def fill_list_with_none(self):
for k in range(self.list_size):
self.the_list.append(None)
def remove_empty_spaces_in_list(self):
temp_list = []
for j in self.the_list:
if j is not None:
temp_list.append(j)
return temp_list
def move_old_list(self, new_list_size):
self.list_size = new_list_size
clean_list = self.remove_empty_spaces_in_list()
self.fill_list_with_none()
self.hash_func_2(clean_list)
def find_key(self, key):
list_index_hash = int(key) % 29
while self.the_list[list_index_hash] != "-1":
if self.the_list[list_index_hash] == key:
print(f"{key} in index {list_index_hash}")
return self.the_list[list_index_hash]
list_index_hash += 1
list_index_hash %= self.list_size
return False
if __name__ == "__main__":
hash_table = HashFunction(30)
str_list = ["1", "5", "13", "21", "27"]
hash_table.hash_func_1(str_list)
# for i in range(hash_table.list_size):
# print(i, end=" ")
# print(hash_table.the_list[i])
hash_table_2 = HashFunction(30)
str_list_2 = [
"100", "510", "170", "214", "268", "398", "235", "802", "900",
"723", "699", "1", "16", "999", "890", "725", "998", "990", "989",
"984", "320", "321", "400", "415", "450", "50", "660", "624"
]
print(f"list size: {len(str_list_2)}")
hash_func = HashFunction(31)
hash_table_2.hash_func_2(str_list_2)
for i in range(hash_func.list_size):
print(i, end=" ")
print(hash_func.the_list[i])
# hash_table_2.find_key("660")
# print("Find Primes")
# hash_func.hash_func_2(str_list_2)
# for i in range(500):
# if hash_func.is_prime(i):
# print(i)
hash_func.increase_list_size(60)
for i in range(hash_func.list_size):
print(i, end=" ")
print(hash_func.the_list[i])
|
#Create a program that plays the game "Plinko" with the EV3 robot.
#The robot will 'fall' down a series of white pieces of paper randomly.
#This will be accomplished by creating an array of left and right moves that EV3 can do,
#but the user will select n number of terms to determine which moves are called
#and guess where EV3 will end up. If the value in the 'x' array is more or less than
#a certain 'if' value, then EV3 will turn left or right based on the condition. This should
#create a truly 'random' experience for the user. To further the randomization, the numbers will
#be shuffled before executing the "Plinko" game. If the user wins, then a display will
#tell them that they have won. If they lose, then the display will tell them
#they have lost. EV3 will joke during the game.
#Goals:
# Create a truly 'random' experience if possible.
# Create a fun atmosphere with Snatch3r's charm.
# Create an aesthetically pleasing interface.
import random
#def plinko (x, ):
|
###Part 1
class Member():
def __init__(self, name):
self.name = name
def intro(self):
print(f'Hi! My name is {self.name}')
class Student(Member):
def __init__(self,name, reason):
Member.__init__(self, name)
self.reason = reason
class Instructor(Member):
def __init__(self, name, bio):
Member.__init__(self, name)
self.bio = bio
self.skill = []
def add_skill(self,new_skill):
self.skill.append(new_skill)
###Part 2
class Workshops:
def __init__ (self, date,subject):
self.date = date
self.subject = subject
self.instructors = []
self.students = []
def add_participant(self, participant):
if isinstance( participant, Instructor ):
self.instructors.append(participant)
elif isinstance( participant,Student ):
self.students.append(participant)
def print_details(self):
print(f'This workshop is on {self.date} and is {self.subject}')
print('Students')
for i in range(len(self.students)):
print(f'{i + 1} {self.students[i].name}, {self.students[i].reason}')
print('Instructors')
for i, instructor in enumerate(self.instructors):
print(f"{i +1} {instructor.name} - {instructor.skill} {instructor.bio}")
workshop = Workshops("12/03/2014", "Shutl")
jane = Student("Jane Doe", "I am trying to learn programming and need some help")
lena = Student("Lena Smith", "I am really excited about learning to program!")
vicky = Instructor("Vicky Python", "I want to help people learn coding.")
vicky.add_skill("HTML")
vicky.add_skill("JavaScript")
nicole = Instructor("Nicole McMillan", "I have been programming for 5 years in Python and want to spread the love")
nicole.add_skill("Python")
workshop.add_participant(jane)
workshop.add_participant(lena)
workshop.add_participant(vicky)
workshop.add_participant(nicole)
workshop.print_details() |
def computepay(h,r):
if h>40 :
return 40*10.5+(h-40)*10.5*1.5
else :
return (h)*10.5
#return ((h>40)?40*10.5+(h-40)*10.5*1.5:(h)*10.5)
hrs = input("Enter Hours:")
h=float(hrs)
rate=input("Enter Rate:")
r=float(rate)
p = computepay(h,r)
print("Pay",p)
|
#!/usr/bin/env python3
def cod_virgulas(spam):
""" Imprime todos os itens separados por uma vírgula e um espaço,
com and inserido antes do último item. """
new_spam = []
# inserir ',' aos itens da lista original, excluindo os dois últimos.
for item in spam[:-2]:
new_spam.append(item + ',')
# inserir os dois últimos itens da lista original.
new_spam.append(spam[-2])
new_spam.append(spam[-1])
# inserir a string 'and' antes do último item da nova lista.
new_spam.insert(-1, 'and')
# imprimir nova lista: nova_lista[0], nova_lista[1], ... nova_lista[n].
print(*new_spam)
spam = []
try:
while True:
item = input("Entre com um item: ")
print("Ou pressione ENTER para sair.")
if item == '':
break
else:
spam.append(item)
cod_virgulas(spam)
except:
print("Sua sessão foi encerada.")
|
#!/usr/bin/env python3
# Este é um jogo de adivinhar o número.
import random
# Gera um número aleatório entre 1 e 20.
secretNumber = random.randint(1, 20)
print("I am thinking of a number between 1 and 20.")
# Peça para o jagodor adivinhar 6 vezes.
for guessesTaken in range(1, 7):
print("Take a guess.")
guess = int(input())
# Verificam se o palpite é menor ou maior que o número secreto.
if guess < secretNumber:
print("Your guess is too low.")
elif guess > secretNumber:
print("Your guess is too hight.")
else:
break # Esta condição corresponde ao palpite correto!
# Verifica se o jogador adivinhou corretamente o número e exibe uma
# mensagem apropriada na tela.
if guess == secretNumber:
print("Good job! You guessed my number in " + str(guessesTaken) +
" guesses!")
else:
print("Nope. The number I was thinking of was " + str(secretNumber))
|
# x=lambda a:a+3
# print(x(5))
# y=lambda a,b:a*b
# print(y(3,4))
def multiply(n):
return lambda a:a*n
num1=multiply(6)
print(num1(11))
num2=multiply(7)
print(num2(11))
|
from tkinter import *
root=Tk()
Label(root,text="x direction",bg="red").pack(fill=X)
Label(root,text="y direction",bg="cyan").pack(side=RIGHT,fill=Y)
root.mainloop() |
def squarevalues():
l=list()
for i in range(1,10):
l.append(i**2)
print(l)
squarevalues() |
from tkinter import *
import tkinter.messagebox
root=Tk()
# tkinter.messagebox.showinfo("title","this is information")
# tkinter.messagebox.showwarning("WARNING","This is warning")
# tkinter.messagebox.showerror("ERROR","404 error is found")
msgbox=tkinter.messagebox.askquestion("Main","Do you need to continue?")
if msgbox=='yes':
print("yes I want to continue")
else:
print("No I dont want to continue")
root.mainloop() |
class student:
def __init__(self,name,mark):
self.name=name
self.mark=mark
def getData(self):
self.name=input("enter your name: ")
self.mark=input("enter your mark: ")
def putData(self):
print(self.name,"\n",self.mark)
obj=student("","")
obj.getData()
obj.putData()
|
# try:
# a=100
# b=0
# print(a//b)
# except:
# print('sorry')
# finally:
# print("its finally")
try:
list=[1,2,3,4,5,6,7]
print(list[3])
except:
print("sorry elements is not found")
finally:
print("its finally") |
from functools import wraps
# ------ basic example of a function decorator ------------
def add_greeting(f):
@wraps(f)
def wrapper(*args, **kwargs):
print("Hello!")
return f(*args, **kwargs)
return wrapper
@add_greeting
def print_name(name):
print(name)
print_name("sandy")
# ------ pass argument from decorator into function wrapper ------------
def add_greeting(greeting=''):
def add_greeting_decorator(f):
@wraps(f)
def wrapper(*args, **kwargs):
print(greeting)
return f(*args, **kwargs)
return wrapper
return add_greeting_decorator
@add_greeting("what's up!")
def print_name(name):
print(name)
print_name("kathy")
# ------ pass argument from decorator into wrapped function input -------
def add_greeting(greeting=''):
def add_greeting_decorator(f):
@wraps(f)
def wrapper(*args, **kwargs):
print(greeting)
return f(greeting, *args, **kwargs)
return wrapper
return add_greeting_decorator
@add_greeting("Yo!")
def print_name(greeting, name):
print(greeting)
print(name)
print_name("Abe") |
# Tyler M Smith
# Section A06
# [email protected]
# I worked on this assignment alone, using only this semester's course materials.
import math
def celciusToFahrenheit():
c = float(input('Enter temperature in Celcius'))
c1 = c / 5 #F = ((9/5) * C ) + 32
c2 = c1 * 9
c3 = c2 + 32
print('The temperature in Fahrenheit is:' ,c3, 'degrees.')
def cylinderVolume():
r = float(input('Cylinder radius (in inches)'))
h = float(input('Cylinder height (in inches)'))
v = math.pi * h * (r**2)
print('The cylinder\'s volume is:' ,v, 'inches cubed.')
def timeCleanUp():
t = int(input('Please enter a whole number of seconds'))
seconds = t % 60 #Finds the remaining number of seconds
t2 = t // 60 #Finds the number of whole minutes
minutes = t2 % 60 #Finds the remaining number of minutes
t3 = t2 // 60 #Finds the number of whole hours
hours = t3 % 24 #Finds the number of remaining hours
t4 = t3 // 24 #Finds the number of whole days
days = t4 % 7 #Finds the number of remaining days
weeks = t4 // 7 #Finds the number of whole weeks
print('That corresponds to:', weeks, 'weeks,', days, 'days,', hours, 'hours,', minutes, 'minutes, and', seconds, 'seconds.')
def rohrerIndex():
weight = float(input('What is your weight (in pounds)?'))
height = float(input('How tall are you (in inches)?'))
h = height ** 3 #Cubes height
ratio = weight / h #Divides weight by the cube of height
RI = ratio * 2768 #Multiplies by constant
RI_round = round(RI,1)
RI_str = str(RI_round) #Converts RI value to string for concatenation
print('Your RI is', RI_str + '.')
"""Concatenation used in order to add the period at the
end of the sentence without a space between the
value and period.""" |
import httplib2
import string
'''Using a dataset ( the "Adult Data Set") from the UCI Machine-Learning Repository we can predict based on a number of
factors whether someone's income will be greater than $50,000.
The technique:
The approach is to create a 'classifier' - a program that takes a new example record and, based on previous examples,
determines which 'class' it belongs to. In this problem we consider attributes of records and separate these into
two broad classes, <50K and >=50K. We begin with a training data set - examples with known solutions.
The classifier looks for patterns that indicate classification. These patterns can be applied against new data
to predict outcomes. If we already know the outcomes of the test data, we can test the reliability of our model.
if it proves reliable we could then use it to classify data with unknown outcomes.
We must train the classifier to establish an internal model of the patterns that distinguish our two classes.
Once trained we can apply this against the test data - which has known outcomes. We take our data and split it into
two groups - training and test - with most of the data in the training set.
Building the classifier
Look at the attributes and, for each of the two outrcomes, make an average value for each one, Then aveage these two
results for each attribute to compute a midpoint or 'class separation value'. For each record, test whether each
attribute is above or below its midpoint value and flag it accouringly. For each record the overall result is the
greater count of the individual results (<50K, >=50K). You should track the accuracy of your model, i.e how many
correct classifications you made as a percentage of the total number of records.'''
def count_lines(file):
'''Counts the lines in the file inputed
:param file:
:return: the tolal lines in the file
'''
count = 0
for line in file:
count += 1
return count
def count_word(search_str, file_entered):
'''Counts the no of times the search str appears in the file entered
:param search_str: string to be searched for
:param file_entered: file to be searched through
:return: total count of the occurences in the file
'''
count = 0
for line in file_entered:
count += line.count(search_str)
return count
def get_num(str_entered, list_entered):
'''Obtains a numerical value for the inputed string. The string is counted and
divided by the total no of line in the file
:param str_entered: string to be changed
:param list_entered: file to be iterated through
:return: numerical value for string
'''
line_count = count_lines(list_entered)
count = 0
for line in list_entered:
count += line.count(str_entered)
total = count / line_count
return total
def file_creation(file_entered):
'''Splits the file into a training file and a testing file
:param file_entered: file to be split
:return: the two seperated files
'''
count = 0
training_file_list = []
testing_file_list = []
for line_str in file_entered:
line_str.strip(string.whitespace).strip(string.punctuation)
if count <= 21710:
training_file_list.append(line_str)
else:
testing_file_list.append(line_str)
count += 1
return training_file_list, testing_file_list
def make_data_set(list_entered):
'''Searches the file for band records and changes the file entered into a list of tupeles
:param list_entered: file to be changed
:return: list of tuples and total bad records
'''
data_tuple_list = []
bad_records = 0
for line_str in list_entered:
if '?' in line_str:
bad_records += 1
continue
if len(line_str) < 14:
bad_records += 1
continue
age_str, workclass_str, fnlwgt_str, education_str, ednum_str, marital_status_str, occupation_str,\
relationship_str, race_str, sex_str, cap_gain_str, cap_loss_str, hours_str, country_str,\
result_str = line_str.split(',')
fnlwgt_str, education_str, country_str = '0', '0', '0'
training_tuple = int(age_str), get_num(workclass_str, list_entered), int(fnlwgt_str), int(education_str),\
int(ednum_str), get_num(marital_status_str, list_entered),\
get_num(occupation_str, list_entered), get_num(relationship_str, list_entered),\
get_num(race_str, list_entered), get_num(sex_str, list_entered), int(cap_gain_str),\
int(cap_loss_str), int(hours_str), int(country_str), result_str
data_tuple_list.append(training_tuple)
return data_tuple_list, bad_records
def sum_of_lists(list_1, list_2):
'''Adds the elements of the two lists entered together
:param list_1: first list entered
:param list_2: second list entered
:return: Total of the two lists
'''
total_list = []
for i in range(14):
total_list.append(list_1[i] + list_2[i])
return total_list
def get_average(list,total_int):
'''Averages the elements of the list by divideing each
element by the total
:param list: file to be iterated through
:param total_int: total for division
:return: list of average values
'''
average_list = []
for value_int in list:
average_list.append(value_int/total_int)
return average_list
def train_classifier(list_entered):
'''Splits the list into greater and less than lists,
then we use the average function to obtain average values
and the sum of function to add the lists together.
:param list_entered:list to be used
:return: the result of the averages and sumation
'''
greater_than_50_list = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, " "]
greater_count = 0
less_than_50_list = [0] * 15
less_count = 0
for person in list_entered:
if person[14] == ' <=50K':
less_than_50_list = sum_of_lists(less_than_50_list, person[:15])
less_count += 1
else:
greater_than_50_list = sum_of_lists(greater_than_50_list, person[:15])
greater_count += 1
less_than_average_list = get_average(less_than_50_list, less_count)
greater_than_average_list = get_average(greater_than_50_list, greater_count)
classifier_list = get_average(sum_of_lists(less_than_average_list, greater_than_average_list), 2)
return classifier_list
def classify_test_set_list(test_set_list, classifier_list):
'''checks each index in the tipple against its coressponding
value within the classifier list
:param test_set_list:the list of tupples to be checked
:param classifier_list:the list agaist which the tuple is compared
:return:list of tuples with 3 elements
'''
result_list = []
for person_tuple in test_set_list:
less_than_count = 0
greater_than_count = 0
result_str = person_tuple[14]
for index in range(14):
if person_tuple[index] > classifier_list[index]:
greater_than_count += 1
else:
less_than_count += 1
result_tuple = (less_than_count, greater_than_count, result_str)
result_list.append(result_tuple)
return [result_list]
def report_results(result_set_list):
'''displays the total count of records used,
the no of inaccurate records and the percentage accuracy rate
:param result_set_list:
:return:
'''
total_count = 0
inaccurate_count = 0
for first_list in result_set_list:
for result_tuple in first_list:
less_than_count, greater_than_count, result_str = result_tuple[:3]
total_count += 1
if (less_than_count > greater_than_count) and (result_str == '<=50K'):
inaccurate_count += 1
elif result_str == ' >50K':
inaccurate_count += 1
print("out of", total_count, "people, there were ", inaccurate_count, "inaccuaracies")
one_percen = total_count / 100
percentage = (total_count - inaccurate_count) / one_percen
print("that gives a percentage accuracy of %{:.2f}".format(percentage))
def main():
'''
:return:
'''
# The request method gives us http header information and the content as a bytes object.
try:
h = httplib2.Http(".cache")
header, content = h.request("http://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data", "GET")
contents_str = content.decode().split('\n')
print('Total lines in main file ', count_lines(contents_str))
print("Creating the two files")
training_file_list, testing_file_list = file_creation(contents_str)
print("Files created successfully\n")
print('The train file has', count_lines(training_file_list))
print('The test file has', count_lines(testing_file_list))
print("Reading in training data...")
training_tuple, bad_train_records = make_data_set(training_file_list)
print("Done reading training data.\n")
print("Bad records total in the training set is", bad_train_records)
print('The total no of tuples in the training set is', count_lines(training_tuple))
print("Training classifier...")
classifier_list = train_classifier(training_tuple)
print("Done training classifier.\n")
print("Reading in test data...")
test_set_list, bad_test_records = make_data_set(testing_file_list)
print("Done reading training data.\n")
print("Bad records total in the testing set is", bad_test_records)
print("The total no of tuples in the test set is", count_lines(test_set_list))
print("Classifying records...")
result_list = classify_test_set_list(test_set_list, classifier_list)
print("Done classifying.\n")
print("Printing results")
report_results(result_list)
print("Program finished.")
except IOError as e:
print(e)
quit()
# Run if stand-alone
if __name__ == '__main__':
main()
|
def distance_from_zero(wok):
if type(wok) == int or type(wok) == float:
return abs(wok)
else:
return "nope"
print(distance_from_zero(-12))
def rental_car_cost(days):
car_cost = 40 * days
# if days > |
grade = float(input("Enter your Grade in %: "))
if grade >= 90:
print("Your grade is A")
else:
if grade >= 80:
print("Your grade is B")
else:
if grade >= 70:
print("Your grade is C")
else:
if grade >= 60:
print("Your grade is D")
else:
if grade >= 50:
print("Your grade is E")
else:
if grade < 50:
print("Your grade is F")
|
try: # start with try when using exception handling.
x = int(input('enter number: '))
except Exception: # not recommended, it's GENERIC error exception. whenever an error occurs it will appear
print('An error occurred')
except ZeroDivisionError:
print('You can\'t divide by zero!')
except ValueError:
print('enter a valid integer')
else: # 'finally' can also be used, but cannot be used with else and vice versa.
print('Arigato')
|
class Solution(object):
def merge(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: List[List[int]]
"""
initialIntervals = len(intervals)
result = []
for newInterval in intervals:
isNewInterval = True
if len(result) > 0:
i = 0
while i < len(result):
targetInterval = result[i]
if targetInterval[1] < newInterval[0] or newInterval[1] < targetInterval[0]:
# pass check next targetInterval
# check next newInterval:
i = i + 1
else:
# there is overlap
result[i] = [min(targetInterval[0], newInterval[0]), max(targetInterval[1], newInterval[1])]
isNewInterval = False
i = i + 1
break
if isNewInterval:
result.append(newInterval)
#print(result)
mergedIntervals = len(result)
if initialIntervals == mergedIntervals:
return result
else:
return self.merge(result)
def merge2(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: List[List[int]]
"""
out = []
if len(intervals)<2:
return intervals
intervals.sort(key = lambda x: x[0])
low = intervals[0][0]
high = intervals[0][1]
out.append(intervals[0])
for (x, y) in intervals:
if high < x: # meaning no overallping
out.append((x, y))
low = x
high = y
else:
out.pop()
out.append((min(x, low), max(high, y)))
low = min(low, x)
high = max(high, y)
return out |
""" Нужно запилить класс или несколько классов, в которых нормальным образом
будут храниться точки и их принадлежность и положение на кругах """
import math as m
import networkx as nx
import calculations as calc
import copy as cp
class Point():
def __init__(self, x, y, alpha, circle):
self.xy = cp.deepcopy((x, y))
a = alpha
while a < 0:
a += 2 * m.pi
self.alpha = a - (int(a/(2 * m.pi)) * 2 * m.pi)
self.circle = cp.deepcopy(circle)
class Circle():
def __init__(self, circle, center, Eps, params):
self.pList = []
self.aList = []
self.circle = cp.deepcopy(circle)
self.center = cp.deepcopy(center)
self.Eps = Eps
self.M = params[0]
self.offset = params[1]
def add_fullList(self, fullList):
self.fullList = fullList
def add_point(self, point):
if point.circle != self.circle:
return None
self.pList.append(cp.deepcopy(point))
self.aList.append(cp.deepcopy(point.alpha))
def sort(self):
self.aList, self.pList = zip(*sorted(zip(self.aList, self.pList)))
self.aList, self.pList = (list(t) for t in zip(*sorted(zip(self.aList, self.pList))))
def build_subgraph(self):
self.G = nx.Graph()
self.cir_length = 2 * m.pi * self.Eps
self.real_length = 0
self.sort()
for a in range(0, len(self.aList) - 1):
self.G = Arc(self.pList[a], self.pList[a + 1], self.fullList, self.Eps, (self.M, self.offset)).push_to_graph(self.G)
self.G = Arc(self.pList[a + 1], self.pList[0], self.fullList, self.Eps, (self.M, self.offset)).push_to_graph(self.G)
def push_to_graph(self, G):
self.build_subgraph()
joinedG = nx.compose(self.G, G)
return joinedG
class Tangent():
def __init__(self, p_1, p_2, fullList, cList, params):
self.C_1 = cp.deepcopy(p_1.circle)
self.p_1 = cp.deepcopy(p_1.xy)
self.drawable = False
self.C_2 = cp.deepcopy(p_2.circle)
self.p_2 = cp.deepcopy(p_2.xy)
self.line = cp.deepcopy([[self.p_1[0], self.p_1[1]], [self.p_2[0], self.p_2[1]]])
self.length = cp.deepcopy(calc.my_norm(self.p_1, self.p_2))
self.fullList = fullList
self.M = (params[0])
self.offset = (params[1])
def check_collisions(self):
return calc.chk_tan_collisions(self)
def build_subgraph(self):
self.G = nx.Graph()
f = False
f = self.check_collisions()
if f:
self.drawable = True
self.G.add_edge(self.p_1, self.p_2, weight=self.length, label=str(self.C_1) + '-' + str(self.C_2))
def push_to_graph(self, G):
self.build_subgraph()
joinedG = nx.compose(self.G, G)
return joinedG
class Arc():
def __init__(self, p_1, p_2, fullList, Eps, params):
# print(p_1.circle)
self.C = cp.deepcopy(p_1.circle)
self.p_1 = cp.deepcopy(p_1.xy)
self.a_1 = cp.deepcopy(p_1.alpha)
self.p_2 = cp.deepcopy(p_2.xy)
self.a_2 = cp.deepcopy(p_2.alpha)
self.Eps = Eps
self.length = cp.deepcopy(calc.arc_length(self.Eps, abs(self.a_2 - self.a_1)))
self.fullList = fullList
self.M = (params[0])
self.offset = (params[1])
def check_collisions(self):
return calc.chk_arc_collisions(self)
def build_subgraph(self):
self.G = nx.Graph()
# if self.check_collisions() is True:
self.G.add_edge(self.p_1, self.p_2, weight=self.length, label=str(self.C) + '_' + str(round(self.a_1)) + '-' + str(round(self.a_2)))
def push_to_graph(self, G):
self.build_subgraph()
joinedG = nx.compose(self.G, G)
return joinedG
|
#variables
myVar = 5
otherVar = "cancer"
#comment
print(myVar)
print(otherVar)
#Var type
print(type(myVar))
print(type(otherVar))
#string
x = "string"
x = 'string'
#multiple value
one, two, three = "one", "two", "three"
print(one)
print(two)
print(three)
|
import turtle
print 'What is the size of the board: Default size = 40'
harsha=40
harsha=int(raw_input())
class TicToe(object):
def __init__(self):
for k in range(0,harsha*3,harsha):
for j in range(0,harsha*3,harsha):
#a=turtle.pos()
turtle.sety(j)
turtle.setx(k)
for i in range(4):
turtle.right(90)
turtle.forward(harsha)
#turtle.setx(k)
turtle.up()
turtle.setx(-harsha)
turtle.sety(-harsha)
turtle.down()
self.ox=-harsha
self.oy=-harsha
def placeX(self,x,y):
turtle.up()
tx=x*harsha
ty=y*harsha
turtle.setx(tx)
turtle.sety(ty)
turtle.down()
turtle.goto(tx-harsha,ty-harsha)
turtle.goto(tx-harsha,ty)
turtle.goto(tx,ty-harsha)
turtle.up()
turtle.goto(-harsha,-harsha)
turtle.down()
return
def placeO(self,x,y):
turtle.up()
tx=x*harsha
ty=y*harsha
turtle.goto(tx,ty)
x2=tx-harsha
y2=ty-harsha
turtle.up()
turtle.goto(float(tx+x2)/2,float(ty+y2)/2)
turtle.down()
turtle.dot(harsha)
turtle.up()
turtle.goto(-harsha,-harsha)
turtle.down()
return
turtle.title("Tic-Tac-Toe")
turtle.shape("arrow")
turtle.color("red", "green")
turtle.bgcolor("blue")
game=TicToe()
print 'The bottom left co-ordinates are 0,0 and the top right co-ordinates are 2,2'
##game.placeO(2,2)
surender={0:['','',''],1:['','',''],2:['','','']}
def victory(d,x,y):
y=int(y)
if d[x][y]=='':
return False
if d[x][y]=='X':
#print "DEBUG:X,Y in victory:",x,y
row=d[x]
colum=[]
for i in d:
colum.append(d[i][y])#for X
diag1=[]
diag2=[]
if x==1 and y==1:
diag1=[d[0][0],d[1][1],d[2][2]]
diag2=[d[0][2],d[1][1],d[2][0]]
return (('X' in row) and all(x==row[0] for x in row)) or (('X' in colum) and all(x==colum[0] for x in colum)) or (('X' in diag1) and all(x==diag1[0] for x in diag1)) or (('X' in diag2) and all(x==diag2[0] for x in diag2))
if d[x][y]=='O':
#print "DEBUG:X,Y in victory:",x,y
row=d[x]
colum=[]
for i in d:
#print "DEbug string indi in victory:",i,y
#print "Debug String in Victory:",d[i][y]
colum.append(d[i][y])#for O
diag1=[]
diag2=[]
if x==1 and y==1:
diag1=[d[0][0],d[1][1],d[2][2]]
diag2=[d[0][2],d[1][1],d[2][0]]
return (('O' in row) and all(x==row[0] for x in row)) or (('O' in colum) and all(x==colum[0] for x in colum)) or (('O' in diag1) and all(x==diag1[0] for x in diag1)) or (('O' in diag2) and all(x==diag2[0] for x in diag2))
def win(d,v):
#print "This is d:",d
c=d.copy()
#print c
for i in range(3):
for j in range(3):
if c[i][j]=='':
c[i][j]=v
#print "DEBUG: WIN:",i,j
if victory(c,i,j)==True:
return (i,j,True)
else:
c[i][j]=''
continue
else:
continue
return (0,0,False)
#import math
def getopp(d,x,y):
if d[abs(2-x)][abs(2-y)]=='':
return (abs(2-x),abs(2-y),True)
else:
return (0,0,False)
def drawg(d):
l=[]
for i in d:
for j in range(3):
l.append(d[i][j])
return '' in l
def chkcorner(d):
if d[2][2]=='':
return (2,2,True)
if d[0][0]=='':
return (0,0,True)
if d[2][0]=='':
return (2,0,True)
if d[0][2]=='':
return (0,2,True)
return (0,0,False)
print "Welcome, This is a game of Tic-Tac-Toe with improved Graphics over the C++ version, Created by Surender Harsha:\n1.Player Start"
print "2.Computer Start"
n=int(raw_input())
if n==1:
print 'You are X , computer is O'
while 1:
#print d
if drawg(surender)==False:
print 'Its a draw'
break
print 'Enter the co-ordinates you wish to put X on:'
x,y=raw_input().split()
x=int(x)
y=int(y)
if surender[x][y]!='':
print 'The Position you have entered is invalid,Please enter again'
continue
game.placeX(y,x)
surender[x][y]='X'
if victory(surender,x,y):
print 'Congratulations! You have won!'
break
k=win(surender,'O')
if k[2]==True:
surender[k[0]][k[1]]='O'
game.placeO(k[1],k[0])
print 'Computer has won!'
break
k=win(surender,'X')
#print k
if k[2]==True:
surender[k[0]][k[1]]='O'
game.placeO(k[1],k[0])
continue
flag=0
if x==1 and y==1:
if surender[0][0]=='':
surender[0][0]='O'
game.placeO(0,0)
continue
if surender[2][2]=='':
surender[2][2]='O'
game.placeO(2,2)
continue
if surender[2][0]=='':
surender[2][0]='O'
game.placeO(0,2)
continue
if surender[0][2]=='':
surender[0][2]='O'
game.placeO(2,0)
continue
for i in range(3):
for j in range(3):
if surender[i][j]=='':
surender[i][j]='O'
game.placeO(j,i)
flag=1
break
if flag==1:
break
else:
l=getopp(surender,x,y)
if l[2]==True:
surender[l[0]][l[1]]='O'
game.placeO(l[1],l[0])
continue
else:
flag=0
for i in range(3):
for j in range(3):
if surender[i][j]=='':
surender[i][j]='O'
game.placeO(j,i)
flag=1
break
if flag==1:
break
else:
print 'you are X, computer is O'
while 1:
if drawg(surender)==False:
print 'Its a draw'
break
AI=0
k=win(surender,'O')
if k[2]==True:
surender[k[0]][k[1]]='O'
game.placeO(k[1],k[0])
print 'Computer has won!'
turtle.bye()
import sys
sys.exit()
k=win(surender,'X')
#print k
if k[2]==True:
surender[k[0]][k[1]]='O'
game.placeO(k[1],k[0])
AI=1
if AI==0:
k=chkcorner(surender)
if k[2]==True:
surender[k[0]][k[1]]='O'
game.placeO(k[1],k[0])
AI=1
if AI==0:
if surender[1][1]=='':
surender[1][1]='O'
game.placeO(1,1)
AI=1
if AI==0:
flag=0
for i in range(3):
for j in range(3):
if surender[i][j]=='':
surender[i][j]='O'
game.placeO(j,i)
flag=1
break
if flag==1:
break
AI=1
#Player Turn
if drawg(surender)==False:
print 'Its a draw'
break
while 1:
x,y=raw_input('Enter The co-ordinates of X:').split()
x=int(x)
y=int(y)
if surender[x][y]!='':
print 'Please Enter Valid Co-ordinates'
continue
else:
break
surender[x][y]='X'
game.placeX(y,x)
if victory(surender,x,y)==True:
print 'Congratulations You have won this game!'
break
if drawg(surender)==False:
print 'Its a draw'
break
turtle.bye() |
def convert_hex_to_rgb(hex_name):
string = str(hex_name)
rgb = [0,0,0]
rgb[0] = int("0x" + string[0].lower() + string[1].lower(),0)
rgb[1] = int("0x" + string[2].lower() + string[3].lower(),0)
rgb[2] = int("0x" + string[4].lower() + string[5].lower(),0)
return rgb
def elo(eloA, eloB, score_A):
K = 32
expected_A = 1/(1 + 10**((eloB - eloA)/400))
expected_B = 1 - expected_A
score_B = 1 - score_A
new_eloA = eloA + K*(score_A - expected_A)
new_eloB = eloB + K*(score_B - expected_B)
elo = [new_eloA , new_eloB]
return elo
|
n1 = float(input('Enter the first number: '));
n2 = float(input('Enter the second number: '));
n3 = float(input('Enter the thrid number: '));
if n1 > n2 and n1 > n3 and n2 > n3:
print(f'The first number is the bigger is the third is the smaller.');
elif n2 > n3 and n2 > n1 and n1 > n3:
print('The second number is the bigger is the third is the smaller.');
elif n3 > n1 and n3 > n2 and n2 > n1:
print('The third number is the bigger is the first is the smaller.');
elif n1 > n2 and n1 > n3 and n3 > n2:
print(f'The first number is the bigger is the second is the smaller.');
elif n2 > n3 and n2 > n1 and n3 > n1:
print('The second number is the bigger is the first is the smaller.');
elif n3 > n1 and n3 > n2 and n1 > n2:
print('The third number is the bigger is the second is the smaller.'); |
# Faça um programa que pergunte o preço de três produtos e informe qual produto você deve comprar, sabendo
# que a decisão é sempre pelo mais barato.
n1 = float(input('Enter the price of spaghetti: '));
n2 = float(input('Enter the price of soda: '));
n3 = float(input('Enter the price of banana: '));
if n1 < n2 and n1 < n3:
print('The best option is spaghetti.');
elif n2 < n1 and n2 < n3:
print('The best option is soda.');
elif n3 < n1 and n3 < n2:
print('The best option is banana.');
else:print('ERROR'); |
sexo = str(input('Digite "F" para Feminino ou "M" para Masculino.'));
if sexo.lower() == 'f':
print(f'Mulher.');
elif sexo.lower() == 'm':
print(f'Masculino.');
else:
print(f'Sexo inválido.');
|
#!/usr/local/bin/python3
# NAME: NESTOR ALVAREZ
# FILE: shape.py
# DESC: A Shape class from The Quick Python Book (p. 30), set x,y coordinates,
# moves objects, and reports location.
import math
class Shape:
def __init__(self, x, y):
"""Assign x,y coordinates to the object"""
self.x = x
self.y = y
def move(self, deltaX, deltaY):
"""Moves Shape object by adding values to the object's x and y coordinates."""
self.x = self.x + deltaX
self.y = self.y + deltaY
def location(self):
return (self.x, self.y)
def __str__(self):
"""Return class name, x, and y"""
return "{}, x:{}, y:{}".format(type(self).__name__, self.x, self.y)
def __main__():
"""Testing Shape class move(), location(), and __str__() methods"""
print("--- START ---")
i2 = 0
c1 = Shape(0, 5)
c2 = Shape(5, 5)
for i in range(10):
i2 += i
c1.move(i, i)
c2.move(i, i2)
print('--')
print('Shape 1: ',c1)
print('Shape 2: ',c2)
print(c1.location())
print(c2.location())
print("--- END ---")
if __name__ == '__main__':
__main__()
|
# Cole Rau -- TCSS 142, Section A
# Code logic:
# The program starts with the function "main." The variable "user_napier1" is tested using the
# "character_validation" function. If "user_napier1" is a character, "user_napier1" is passed to the function
# "letters_to_numbers," which translates "user_napier1" (a character) into an integer. The result is printed
# to the screen. Next, the variable "user_napier2" is processed and printed the same way as "user_napier1" if
# "user_napier2" is a character. Then,
# the variable "user_operator" is tested using the function "operator_validation." If "user_operator" is an allowed
# operator (+, -, *, or /), the second half of the function "main" is executed. The second half of "main" has four
# if statements. One if statement is executed depending on whether "user_operator" is +, -, * or /.
# Next, one of the following operations occurs. Depending on whether "user_operator" is +, -, *, or /,
# "user_napier1 is either added to "user_napier2;" or "user_napier2" is subtracted from "user_napier1;" or
# "user_napier1" is multiplied by "user_napier2;" or "user_napier1" is divided by "user_napier2."
# The result of the calculation is printed to the screen. Finally, the "main" function asks the user if
# they want to repeat the program. If the user types "y," the program is repeated.
# If the user types "n," "Good bye" is printed to the screen.
# This function passes the variables "user_napier1" and "user_napier2" to the "character_
# validation" function, the "operator_validation function," the "letters_to_numbers" function, and the
# "integer_to_napier" function.
def main():
user_response = "y"
while user_response == "y":
user_napier1 = input("Please enter a number in Napier's notation: ")
while character_validation(user_napier1) == False:
user_napier1 = input("Invalid input. Please enter a number in Napier's notation: ")
print("The first number is {}.".format(letters_to_numbers(user_napier1)))
user_napier2 = input("Please enter a second number in Napier's notation: ")
while character_validation(user_napier2) == False:
user_napier2 = input("Invalid input. Please enter a second number in Napier's notation: ")
print("The second number is {}.".format(letters_to_numbers(user_napier2)))
user_operator = input("Please enter a mathmatical operation (either +, -, *, or /): ")
while operator_validation(user_operator) == False:
user_operator = input("Invalid input. Please enter a mathmatical operation (either +, -, *, or /): ")
# The "addition," "subtraction," "multiplication, and "division" variables are passed to the
# "integer_to_napier" function.
if user_operator == "+":
addition = letters_to_numbers(user_napier1) + letters_to_numbers(user_napier2)
print("The result is {}.".format(addition))
if user_operator == "-":
subtraction = letters_to_numbers(user_napier1) - letters_to_numbers(user_napier2)
print("The result is {}.".format(subtraction))
if user_operator == "*":
multiplication = letters_to_numbers(user_napier1) * letters_to_numbers(user_napier2)
print("The result is {}.".format(multiplication))
if user_operator == "/":
division = letters_to_numbers(user_napier1) // letters_to_numbers(user_napier2)
print("The result is {}.".format(division))
user_response = input("Would you like to repeat the program? Enter y for yes, n for no: ")
print("Good bye.") # If user enters "n," the beginning while loop is exited and "Good bye" is printed.
# This function receives as parameters the variables "user_napier1" and "user_napier2" from the "main" function.
# This function returns True to "main" if the user's Napier's value is a character a-z. The function returns
# False to "main" if the user's Napier's value is not a character.
def character_validation(possible_napier):
return possible_napier.isalpha()
# This function receives as a parameter the "user_operator" variable from the "main" function.
# This function returns True to "main" if the user's operator is +, -, /, or *. The function returns False to "main"
# if the user's operator is anything other than +, -, /, or *.
def operator_validation(operator):
if (operator == "+" or operator == "-" or operator == "/"
or operator == "*"):
result = True
else:
result = False
return result
# This function receives as parameters the variables "user_napier1" and "user_napier2" from "main."
# This function translates the user's alphabetical input into an integer and returns the value to "main."
def letters_to_numbers(napier):
napier_counter = 0
for letter in napier:
if letter == "a":
napier_counter += 2 ** 0
if letter == "b":
napier_counter += 2 ** 1
if letter == "c":
napier_counter += 2 ** 2
if letter == "d":
napier_counter += 2 ** 3
if letter == "e":
napier_counter += 2 ** 4
if letter == "f":
napier_counter += 2 ** 5
if letter == "g":
napier_counter += 2 ** 6
if letter == "h":
napier_counter += 2 ** 7
if letter == "i":
napier_counter += 2 ** 8
if letter == "j":
napier_counter += 2 ** 9
if letter == "k":
napier_counter += 2 ** 10
if letter == "l":
napier_counter += 2 ** 11
if letter == "m":
napier_counter += 2 ** 12
if letter == "n":
napier_counter += 2 ** 13
if letter == "o":
napier_counter += 2 ** 14
if letter == "p":
napier_counter += 2 ** 15
if letter == "q":
napier_counter += 2 ** 16
if letter == "r":
napier_counter += 2 ** 17
if letter == "s":
napier_counter += 2 ** 18
if letter == "t":
napier_counter += 2 ** 19
if letter == "u":
napier_counter += 2 ** 20
if letter == "v":
napier_counter += 2 ** 21
if letter == "w":
napier_counter += 2 ** 22
if letter == "x":
napier_counter += 2 ** 23
if letter == "y":
napier_counter += 2 ** 24
if letter == "z":
napier_counter += 2 ** 25
return napier_counter
main()
|
def test_abs1():
assert abs(-42) == 42, "Should be absolute value of a number"
def test_abs2():
assert abs(-42) == -42, "Should be absolute value of a number"
# Команда для запуска с подробным отчетом
# pytest -v stepik_auto_tests_course/S3_lesson3_step8.py
|
nome = input ("digite seu nome:")
print("ola!" ,nome)
perg1 = int(input( "você tem quantos anos?"))
print("olha você tem" , 14, "anos")
if perg1 > 18 :
print("você é de maior!")
else:
print("você não é de maior")
pais= input("você é brasileiro?")
if pais == "sim":
print("você é brasileiro aue legal!")
else:
print("você não é brasileiro que pena")
pais2 = input("você é de qual país então?")
print("que legal!")
print("vamos jogar um jogo?")
jogo = int(input("qual é a raiz quadrada de 144?"))
if jogo == "144":
print("você acertou parabéns!")
else:
print(" que pena você errou!")
|
nihi# -*- coding: utf-8 -*-
"""
Created on Sat Sep 23 22:34:27 2017
@author: Nikhil Bansal
* Objective : Find longest string in incresing alphabetic order
"""
alphabet = "abcdefghijklmnopqrstuvwxyz"
str = input("type : ")
#check and reprompt if user enter empty string
while len(str) <= 0:
print("Please enter valid string")
str = input("type : ")
# result = longest string in alphabetic order
# ss = temp. intermediate result in process
# pr = contain position of char in alphabet string, used to decide order
result = str[0]
pr = alphabet.index(str[0])
ss = result
#traversing input string
for c in str[1:]:
#check if next char is in alphabetically increasing order than previous
if(alphabet.index(c) >= pr):
#if yes - update temp. result and ordring position
ss = ss + c
pr = alphabet.index(c)
print("S", c, ss, pr, result)
else:
#if no - update result, temp. resilt and ordring position
if(len(ss) > len(result)):
result = ss
ss = c
pr = alphabet.index(c)
if(len(ss) > len(result)):
result = ss
print(result) |
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 3 22:13:45 2018
@author: Nikhil Bansal
Here we are going to create a word counter.
* steps - 1. We are gointn to screap a web page to get words.
"""
import requests
from bs4 import BeautifulSoup
import re
import operator
# This method is going to give us word list
def get_words(url):
word_list = []
# get whole html code in text format in source_code
source_code = requests.get(url).text
soup = BeautifulSoup(source_code, "lxml")
# find all titles in source code
for line in soup.findAll("a", {"class" : "cellMainLink"}):
# strip html code form line
title = line.string
# used re(regex) module to split title with multiple delimeters.
# use escape character with "."
words = re.split('-|\.', title.lower())
word_list.extend(words)
return word_list
# This method will take word list and return dictionary with words and their frequency.
def calculate_freq(words):
freq_table = {}
#check if word is already in dictonary
for word in words:
if word in freq_table:
freq_table[word] += 1
else:
freq_table[word] = 1
#sort dictonary according to key
sorted_table = sorted(freq_table.items(),key=operator.itemgetter(0))
return sorted_table
url = "https://kickass.unblocked.lat/tv/"
word_count = calculate_freq(get_words(url))
#display word count
for key, value in word_count:
print(key, value) |
# -*- coding: utf-8 -*-
import random
import avengers_helpline
"""
Created on Tue May 8 22:58:43 2018
@author: Nikhil Bansal
* Module - A python file which contain python code
- Generally contains function, which are going to be resued by other python files
* Use - Modularity in programs and reusability of code
* Importing module must be the first lines of program
"""
vilian_list = ["loki", "thanos", "ultron", "hydra"]
def take_counter_attack():
# Coz Hulk fears thanos
attacker = vilian_list[random.randint(0, len(vilian_list) - 1)]
if(attacker == "thanos"):
print("We need to call Iron Man ASAP")
while attacker != "thanos":
print("Ohh! for you %s we have %s" %(attacker, avengers_helpline.attack_hulk()))
attacker = vilian_list[random.randint(0, len(vilian_list) - 1)]
print("Earth is Under attack, Please Help!!")
take_counter_attack()
|
# -*- coding: utf-8 -*-
"""
Created on Tue May 8 22:42:58 2018
@author: Nikhil Bansal
* Dictonary - similar to map
- have key, value pairs
"""
#this will create an empty dict
avengers_ids = dict()
avengers_ids["Iron Man"] = "Tony Stark"
avengers_ids["Spider Man"] = "Peter parker"
avengers_ids["Black Panther"] = "T'Chala"
avengers_ids["Hulk"] = "Bruce"
# You could have use this easy method to make dict
gurdians_ids = {"Star Lord" : "Peter Quill", "Gamora" : "Green girl"}
# Ohh, You are so cool
print("You know Iron man is ", avengers_ids["Iron Man"])
# Now you are boasting...Really
for name, id in gurdians_ids.items():
print("And %s is %s" %(name, id))
|
import threading
"""
Created on Sun Jun 3 16:05:35 2018
@author: Nikhil Bansal
* Thread - a Sub process that can run independently
* To create thread in python - 1. Import "threading" module.
2. create subclass of "threading.Thread" class and override "run()" method.
3. Call "start()" method on thread object. (start will call run() and make status of thread alive.
"""
class MyThread(threading.Thread):
def __init__(self, name, purpose):
threading.Thread.__init__(self, name=name)
self.purpose = purpose
def run(self):
for _ in range(5):
print(self.purpose)
print(str(self.is_alive()) + " - " + self.name + " - " + str(
self.ident) + " - " + threading. ().name)
if __name__ == "__main__":
t1 = MyThread(name="sender thread", purpose="I am sender")
t2 = MyThread(name="receiver thread", purpose="I am receiver")
# this line here will give "RuntimeError: cannot join current thread" as this line will create dead lock.
# It block current thread until current thread terminate
#threading.current_thread().join()
t1.start()
t2.start()
t1.join()
t2.join()
|
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 3 22:10:28 2017
@author: Nikhil Bansal
"""
count = 0
s = input("enter string : ")
i = 0
state = 0
while i < (len(s)):
if s[i] == "b":
if state == 0:
state = 1
if state == 2:
count += 1
state = 1
elif s[i] == "o":
if state == 1:
state = 2
else:
state = 0
i += 1
print(count)
|
from abc import ABCMeta, abstractmethod
HE_BETRAYED_ME = 0
BOTH_BETRAYED = 1
BOTH_COOPERATED = 3
I_BETRAYED_HIM = 5
class Player(metaclass = ABCMeta):
def __init__(self):
self.score = 0
self.last_score = None
self.generator = self.play()
def award(self, points):
self.score += points
self.last_score = points
def decide(self):
return next(self.generator)
def he_cooperated(self):
return self.last_score in [BOTH_COOPERATED, I_BETRAYED_HIM]
def i_cooperated(self):
return self.last_score in [BOTH_COOPERATED, HE_BETRAYED_ME]
@abstractmethod
def play(self):
pass
def __repr__(self):
return "<{} {} points>".format(self.__class__.__name__, self.score)
def play_round(players):
cooperates = [ player.decide() for player in players ]
if all(cooperates):
scores = [ BOTH_COOPERATED for player in players ]
elif not any(cooperates):
scores = [ BOTH_BETRAYED for player in players ]
else:
scores = [
I_BETRAYED_HIM if not cooperates else HE_BETRAYED_ME
for player, cooperates in zip(players, cooperates)
]
for player, points in zip(players, scores):
player.award(points)
return scores
def play(PlayerClasses, rounds = 3):
players = [ Player() for Player in PlayerClasses ]
for round in range(rounds):
play_round(players)
return players
|
import copy
from hash_table import HashTable
def one_away(s1, s2):
if s1 == s2:
return True
len_diff = len(s1) - len(s2)
if abs(len_diff) > 1:
return False
if len_diff == 0:
for i in range(len(s1)):
if s1[i] != s2[i]:
sc = s1[:i] + s2[i] + s1[i+1:]
print(sc)
if sc == s2:
return True
return False
elif len_diff > 0:
# remove (s1)
return check_replace(s1, s2)
else:
# insert (or remove from s2)
return check_replace(s2, s1)
return False
def remove_char(string, index):
return string[:index] + string[index+1:]
# def one_away_ht(s1, s2):
# ht1 = create_ht(s1)
# ht2 = create_ht(s2)
# diff_cnt = 0
# for c in s1:
# val = ht2.get_val(c)
# if val == "No record found":
# diff_cnt = diff_cnt + 1
def check_replace(s1, s2):
for i in range(len(s1)):
sc = remove_char(s1, i)
# print(sc)
if sc == s2:
return True
return False
s1 = "abcd"
s2 = "abcde"
print(one_away(s1, s2))
print(one_away(s2, s1))
s1 = "abcdef"
s2 = "abxdef"
print(one_away(s1, s2))
print(one_away(s2, s1))
s1 = "abcdef"
s2 = "abxdey"
print(one_away(s1, s2))
print(one_away(s2, s1))
|
mat1 = [[1,2,3],[4,5,6]]
mat2 = [[7,8,9],[6,7,3]]
result= [[0,0,0],[0,0,0]]
for i in range(len(mat1)):
for j in range(len(mat2[0])):
for k in range(len(mat2)):
result[i][j]+= mat1[i][k]*mat2[j][k]
for r in result:
print(r)
|
"""
R 1.12
---------------------------------
Problem Statement : Python’s random module includes a function choice(data) that returns a
random element from a non-empty sequence. The random module includes
a more basic function randrange, with parameterization similar to
the built-in range function, that return a random choice from the given
range. Using only the randrange function, implement your own version
of the choice function.
Author : Saurabh
"""
import random
def choice(seq):
return seq[len(seq) % random.randrange(1, 10)]
if __name__ == "__main__":
a = (2, 3, 10, 5, 6, 7, 8, 18, 9, 12, 23, 4, 8, 1)
print(choice(a))
|
"""
R 1.3
---------------------------------
Problem Statement : Write a short Python function, minmax(data), that takes a sequence of
one or more numbers, and returns the smallest and largest numbers, in the
form of a tuple of length two. Do not use the built-in functions min or
max in implementing your solution.
Author : Saurabh
"""
def min_max(data):
min_d = max_d = data[0]
for d in data:
min_d = d if d < min_d else min_d
max_d = d if d > max_d else max_d
return min_d, max_d
if __name__ == "__main__":
print(min_max((6, 3, 2, 6, 9, 8, 7, 0)))
|
class Tile(object):
def __init__(self, letter, points):
self.letter = letter
self.points = points
def __eq__(self, other):
return self.letter == other.letter and self.points == other.points
def __str__(self):
string = self.letter + " " + str(self.points)
return string
|
import requests
import os
import json
from typing import List
class Spotify:
def __init__(self, user_id: str, auth_token: str):
self.user_id = user_id
self.auth_token = auth_token
def read_playlists(self):
""" Returns all the playlist data for a user. """
url = "https://api.spotify.com/v1/users/{user_id}/playlists".format(
user_id=self.user_id
)
response = requests.get(
url,
headers={
"Content-Type": "application/json",
"Authorization": "Bearer " + self.auth_token,
},
)
data = response.json()
playlist_data = data["items"]
return playlist_data
def print_playlists(self):
""" Prints the name of each playlist and how many tracks that playlist has. """
playlist_data = self.read_playlists()
for playlist in playlist_data:
print(
"The playlist "
+ playlist["name"]
+ " contains "
+ str(playlist["tracks"]["total"])
+ " tracks."
)
def filter_titles(self, song_list: List[str]) -> List[str]:
""" Filters a list of titles so they are more likely to provide search results. """
# Removes text to the right of the key character
split_chars = ["(", "|", "[", "."]
for char in split_chars:
i = 0
for song in song_list:
song_list[i] = song.split(char)[0]
i = i + 1
# removes any of the key words from the string
replace_words = [
"Lyrics",
"lyrics",
"LYRICS",
"Lyric",
"lyric",
"LYRIC",
"VIDEO",
"video",
"Video",
"ft",
"feat",
]
for word in replace_words:
i = 0
for song in song_list:
song_list[i] = song.replace(word, "")
i = i + 1
return song_list
def create_playlist(self, playlist_name: str) -> str:
""" Returns the playlist id of a newly created playlist. """
url = "https://api.spotify.com/v1/users/{user_id}/playlists".format(
user_id=self.user_id
)
headers = {
"Content-Type": "application/json",
"Authorization": "Bearer " + self.auth_token,
}
data = json.dumps({"name": playlist_name, "public": "false"})
response = requests.post(url, headers=headers, data=data)
data = response.json()
playlist_id = data["id"]
return playlist_id
def get_spotify_song_uri(self, search: str) -> str:
""" Returns the track_uri of the first song from a search result."""
url = "https://api.spotify.com/v1/search"
headers = {"Authorization": "Bearer " + self.auth_token}
params = {
"q": "{search}".format(search=search),
"type": "track",
"market": "from_token",
"limit": 1,
}
response = requests.get(url, headers=headers, params=params)
data = response.json()
# if there are no search results, return none
if data["tracks"]["total"] == 0:
print("No results for this search")
return None
# return the uri of the first track from the search result
else:
track_uri = data["tracks"]["items"][0]["uri"]
return track_uri
def add_song_to_playlist(self, playlist_id: str, song_uri: str):
""" Adds a song to a playlist using the uri and a playlist id. """
song_uri = song_uri
url = "https://api.spotify.com/v1/playlists/{playlist_id}/tracks".format(
playlist_id=playlist_id
)
headers = {
"Content-Type": "application/json",
"Authorization": "Bearer " + self.auth_token,
}
data = json.dumps({"uris": [song_uri]})
response = requests.post(url, headers=headers, data=data)
|
import sqlite3
from sqlite3 import Error
def create_connection(db_file):
""" create a database connection to the SQLite database specified by db_file
:param db_file: database file
:return Connection object or None"""
try:
conn = sqlite3.connect(db_file)
return conn
except Error as e:
print(e)
return None
def select_all_data(conn, select_sql):
"""
Execute the select_sql statement to get all rows from database
:param conn: the Connection object
:param select_sql: the SELECT statement
:return:
"""
cur = conn.cursor()
cur.execute(select_sql)
rows = cur.fetchall()
for row in rows:
print(row)
def main():
database = "C:\\Users\\user\\Desktop\\Bella\\sqlite\\db\\chinook.db"
select_all_customers = "SELECT * FROM customers"
# create a database connection
conn = create_connection(database)
with conn:
print("Query all customers")
select_all_data(conn, select_all_customers)
if __name__ == '__main__':
main() |
import math
num=int(input())
print(" ")
for i in range(1,int(math.sqrt(num)+1)):
print(i**2)
|
import torch
# 2.2.4 运算的内存开销
# 索引操作不会开辟新内存,像y = x + y这样的运算是会新开内存的,然后将y指向新内存。
x = torch.tensor([1, 2])
y = torch.tensor([3, 4])
id_before = id(y)
y = y + x
print("执行y = y + x运算前后y的id是否一致:" + str(id(y) == id_before))
print("----------------------------------------------")
# 如果想指定结果到原来的y的内存,我们可以使用前面介绍的索引来进行替换操作。
# 在下面的例子中,我们把x + y的结果通过[:]写进y对应的内存中。
x = torch.tensor([1, 2])
y = torch.tensor([3, 4])
id_before = id(y)
y[:] = y + x
print("执行y = y + x运算前后y的id是否一致:" + str(id(y) == id_before))
print("----------------------------------------------")
# 我们还可以使用运算符全名函数中的out参数或者自加运算符+=(也即add_())达到上述效果.
# 例如torch.add(x, y, out=y)和y += x(y.add_(x))。
x = torch.tensor([1, 2])
y = torch.tensor([3, 4])
id_before = id(y)
torch.add(x, y, out=y) # y += x, y.add_(x)
print("执行y = y + x运算前后y的id是否一致:" + str(id(y) == id_before))
print("----------------------------------------------")
# 注:虽然view返回的Tensor与源Tensor是共享data的,但是依然是一个新的Tensor(因为Tensor除了包含data外还有一些其他属性),二者id(内存地址)并不一致。
|
import torch
# 一、算数操作
# 加法
# 1.直接相加
x = torch.rand(5, 3)
y = torch.rand(5, 3)
print("x + y = " + str(x + y))
# 2.torch.add
print("x + y = " + str(torch.add(x, y)))
# 3. 指定输出
result = torch.empty(5, 3)
torch.add(x, y, out=result)
print("x + y = " + str(result))
# 4.inplace
# adds x to y
y.add_(x)
print("x + y = " + str(y))
# 二、索引
# 索引出来的结果与原数据共享内存,也即修改一个,另一个会跟着修改
print("索引前的x[0, :] = " + str(x[0, :]))
y = x[0, :]
y += 1
print("y = " + str(y))
print("索引后的x[0, :] = " + str(x[0, :])) # 源tensor也被改了
# 三、改变形状
# 用view()来改变Tensor的形状
y = x.view(15)
z = x.view(-1, 5) # -1所指的维度可以根据其他维度的值推出来
print("x.size() = {} \ny.size() = {} \nz.size() = {}".format(x.size(), y.size(), z.size()))
# 注意view()返回的新Tensor与源Tensor虽然可能有不同的size,注意view()返回的新Tensor与源Tensor虽然可能有不同的size,但是是共享data的,也即更改其中的一个,另外一个也会跟着改变。
# (顾名思义,view仅仅是改变了对这个张量的观察角度,内部数据并未改变)
# 进行验证
x += 1
print("x = " + str(x))
print("y = " + str(y)) # 也加了1
# 如果我们想返回一个真正新的副本,应先用clone创造一个副本然后再使用view。
x_copy = x.clone().view(3, 5)
x -= 1
print("x = " + str(x))
print("x_copy = " + str(x_copy))
# 使用clone还有一个好处是会被记录在计算图中,即梯度回传到副本时也会传到源Tensor。
# item()函数可以将一个标量Tensor转换成一个Python number
x1 = torch.randn(1)
print("x1 = " + str(x1))
print("x1.item() = {}".format(x1.item())) |
def find_max_min(x):
minimum = maximum = x[0]
for i in x[1:]:
if i < minimum: #check if element is lowest
minimum = i
else:
if i > maximum: maximum = i#check if element is largest
a=int(minimum) #convert minimum element to int
b=int(maximum) #convert max element to int
c=[a,b] #the list to return
d=[len(x)] #return array of lenth of x if the maximum and minimum are equal
if a == b:
return d
return c |
class Account:
def __init__(self,accountNumber: int,firstName: str,lastName: str,accountBalance: float):
self.accountNumber = accountNumber if accountNumber>10001 else 0
self.firstName = firstName
self.lastName = lastName
self.accountBalance = accountBalance if accountBalance>0 else 0
def display(self):
print(self.accountNumber)
print(self.firstName)
print(self.lastName)
print(self.accountBalance)
a = Account(10002,'Gaurav','Ramani',2500)
a.display()
|
from tkinter import *
from tkinter import messagebox, Entry
hourlySalary = [150.00,200.00,250.00]
def calcSalary():
hoursWorked = e.get()
taxRate = tax.get()
grossPay = hoursWorked*hourlySalary[skill.get()-1]
incomeTax = grossPay*taxRate/100
netPay = grossPay - incomeTax
messagebox.showinfo("Salary",f" Gross Pay: ₹{grossPay} \n Income Tax: ₹{incomeTax} \n Net Pay: ₹{netPay}")
window = Tk()
skill = IntVar()
tax = IntVar()
e = IntVar()
window.title("Calculate Payroll")
window.geometry("300x300")
Label(window, text="Hours worked").grid(row=0,padx=100)
Entry(window,textvariable=e).grid(row=1)
Label(window,text='Choose your skill group').grid(row=2)
Radiobutton(window,text="1",variable=skill,value=1).grid(row=3)
Radiobutton(window,text="2",variable=skill,value=2).grid(row=4)
Radiobutton(window,text="3",variable=skill,value=3).grid(row=5)
Label(window,text='Choose your tax category rate').grid(row=6)
Radiobutton(window,text='Single Rate',variable=tax,value=18).grid(row=7)
Radiobutton(window,text='Family Rate',variable=tax,value=15).grid(row=8)
Button(window,text="Show Salary",command=calcSalary).grid(row=10)
window.mainloop()
|
import re
pattern = re.compile(r'[aeiouAEIOU]')
str1 = input('Enter a string to count vowels present in it:')
print('Number of vowels in the entered string is ' + str(len(pattern.findall(str1))))
|
# -*- coding: utf-8 -*-
class Jogador():
def __init__(self, nome):
self.pontos = 0
self.nome = nome
self.desistir = False
def zerarPontuacao(self):
self.pontos = 0
self.desistir = False
def aumentarPontuacao(self, valor):
self.pontos += valor
def calcProbCartaBoa(self, valores):
#verifica a probabilidade de tirar uma carta boa
#entende-se por carta boa uma carta que não fará a pontuação estourar
#Probabilidade = nCartasBoas / totalDeCartas
cartasBoas = 0
for v in valores:
if (v <= (21 - self.pontos)):
cartasBoas += 1
if (len(valores) == 0):
return 0
return cartasBoas / len(valores) |
"""This module makes the actual call to the USGS service and it is used by the
main script. The functions get_alert_info and get_available levels only read
local files. The get_earthquake function makes a call to a third party service
and an internet connection is required."""
import requests
import datetime
import json
import csv
import pandas as pd
base_url = 'https://earthquake.usgs.gov/fdsnws/event/1/query?'
query_url = 'starttime={}&format=geojson&limit=20000&'
USGS_URL = base_url + query_url
path_to_csv = 'earthquakes_package/pager_levels.csv'
def get_alert_info(level, file_path=path_to_csv):
"""Get the description of an alert level given by the user
:param level: The PAGER alert level given by the user
:type file_path: string
:param file_path: The path to the csv file
:type file_path: string
:return: The official description elements of the chosen alert level
:rtype: list
"""
try:
with open(file_path) as csvfile:
inforeader = csv.reader(csvfile, delimiter=',')
next(inforeader) # skip the header
for row in inforeader:
if row[0] == level:
return row
# if the level is not found in the csv return False
return False
# if the file is not found (maybe incorrect name) return False
except FileNotFoundError:
return False
def get_available_levels(file_path=path_to_csv):
"""Return the choices available for the PAGER alert levels.
:param file_path: The path to the csv file
:type file_path: string
:return: The PAGER alert levels available
:rtype: list
"""
df = pd.read_csv(file_path, index_col=False)
choices = df['alert_and_color'].tolist()
return choices
def get_earthquake(days_past, alertlevel, verbosity):
"""Return the magnitude and the place of the earthquake with the highest
magnitude given a starting time.
:param days_past: Number of days in the past (used as starting point)
:type days_past: int
:return: The magnitude and the place of the strongest earthquake found
:rtype: float, string
"""
# get the date of today - days_past days at 00 AM
start_date = (datetime.datetime.now() +
datetime.timedelta(days=-days_past)).strftime("%Y-%m-%d")
URL = USGS_URL.format(start_date)
# add the parameter alertlevel only if specified by the user
if alertlevel:
URL = URL + '&alertlevel=' + alertlevel
if verbosity:
print('I am now starting to search for earthquakes with the following '
'parameters: \ndays_past = {}\nalertlevel = {}'
.format(days_past, alertlevel))
r = requests.get(URL)
events = json.loads(requests.get(URL).text)
magnitude = 0
place = ''
# find the earthquake with the highest magnitude among the received results
if verbosity:
print('Search completed')
if len(events['features']) == 0:
return False, False
# iterate all the events and find the one with the largest magnitude
for event in events['features']:
try:
mag = float(event['properties']['mag'])
except TypeError:
pass
if mag > magnitude:
magnitude = mag
place = event['properties']['place']
return magnitude, place
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Time-stamp: <2016-09-19 06:40:08 cp983411>
import sys
def count_lines_words(text):
""" input:
text: a string
output:
number of lines and words in text """
nlines, nwords = 0, 0
for line in text:
nlines += 1
nwords += len(line.split())
return (nlines, nwords)
if __name__ == '__main__':
fname = sys.argv[1]
text = file(fname).readlines()
print(count_lines_words(text))
|
from PIL import Image
import os
def jpg_to_png(folder):
for infile in os.listdir(folder):
print "infile:" , infile
outfile = os.path.splitext(infile)[0] + '.png'
print "outfile:" , outfile
if infile !=outfile:
try:
Image.open("../PythonLearning/CV_sampleImages/"+infile).save("../PythonLearning/CV_sampleImages/"+outfile)
except IOError:
print "cannot convert",infile
jpg_to_png("../PythonLearning/CV_sampleImages/") |
# coding: utf-8
# In[3]:
import numpy as np
import pandas as pd
import numpy as np # import numpy for later use in this tutorial.
import matplotlib.pyplot as plt
pd.__version__
# Pandas objects: Pandas objects can be thought of as enhanced versions of NumPy structured array in which rows and columns are identified with labels rather than simple integer indices.
#
# Three fundamental Pandas data structures: the Series, DataFrame, and Index.
# <h2>The Pandas Series Object</h2>
# A Pandas Series is a one-dimensional array of indexed data. It can be created from a list or array.
# In[4]:
data = pd.Series([1,0.5,0.25,0.125])
data
# In[5]:
print(data.values)
print(data.index)
# In[6]:
# accessing the value-using index
data[1]
# In[7]:
#data[5] # it will give an error because index 5 is not present in the data.
# In[8]:
data[1:3] #index starts from zero. Here values for index 1 and index 2 are selected. Note that end index is not inclusive while selecting values.
# In[9]:
# Data can be scalar, which is repeated to fill the specified index.
pd.Series(5, index=[100,200,300])
# In[10]:
#pd.Series([5,6], index=[100,200,300]) # it will give and error because length of passed values is not same as no. of indices.
# In[11]:
# Series creation using dictionary:
pd.Series({2:'a',1:'b',3:'c'})
# In[12]:
# Index can be explicitly set if different result is preferred.
pd.Series({2:'a',1:'b',3:'c'}, index=[3,2])
# <h2>The Pandas DataFrame Object</h2>
#
# DataFrame is an analog of a two-dimensional array with both flexible row indices and flexible column names.
#
# Therefore, we can them as generalization of a NumPy array or as a specialization of a Python dictionary.
# In[13]:
# Let's create two dictionary objects:
population_dict = {'California': 38332521,
'Texas': 26448193,
'New York': 19651127,
'Florida': 19552860,
'Illinois': 12882135}
area_dict = {'California': 423967, 'Texas': 695662, 'New York': 141297,
'Florida': 170312, 'Illinois': 149995}
# In[14]:
# Now let's create series objects from dictionaries:
area = pd.Series(area_dict)
population = pd.Series(population_dict)
#area
#population
# In[15]:
# We can now create a DataFrame using both series objects:
states = pd.DataFrame({'population':population, 'area':area})
states
# In[16]:
print("Indices are:", states.index)
print("Columns are:", states.columns)
# <h2>Constructing DataFrame objects</h2>
# In[17]:
# From a single Series object:
pd.DataFrame(population, columns=['population'])
# In[18]:
# From a list of dicts:
data = [{'a': i, 'b': 2*i} for i in range(3)]
data
# In[19]:
pd.DataFrame(data)
# In[20]:
# Even if some keys in the dictionary are missing, Pandas will fill them in with NaN (i.e.,
#“not a number”) values:
pd.DataFrame([{'a': 1, 'b': 2}, {'b': 3, 'c': 4}])
# In[21]:
# From a dictionary of Series objects
pd.DataFrame({'population':population,
'area':area})
# In[22]:
# From a two-dimensional NumPy array
pd.DataFrame(np.random.rand(3,2),
columns = ['x','y'],
index= ['a','b','c'])
# In[23]:
# From a NumPy structure array
A = np.zeros(3, dtype=[('A','i8'),('B','f8')])
A
# In[24]:
pd.DataFrame(A)
# In[25]:
#pd.Index?
# In[26]:
ind = pd.Index([2,3,4,13,5,7,11])
ind
# In[27]:
print(ind[1])
print(ind[::2])
# In[28]:
print(ind.size, ind.shape, ind.ndim, ind.dtype)
# In[29]:
# Note: Index objects are immutable while NumPy arrays are mutable.
# ind[1] = 0 # it will give an error: TypeError: Index does not support mutable operations
# In[30]:
indA = pd.Index([1,3,5,7,9])
indB = pd.Index([2,3,5,7,11])
# In[31]:
indA & indB #intersection
# In[32]:
indA | indB #union
# In[33]:
indA ^ indB #symmetric difference
# In[34]:
# Other way to get above results through object methods:
indA.intersection(indB)
# <h2>Selection</h2>
# In[35]:
sample_numpy_data = np.array(np.arange(24)).reshape((6,4))
sample_numpy_data
# In[36]:
dates_index = pd.date_range('20160101', periods=6)
dates_index
# In[37]:
sample_df = pd.DataFrame(sample_numpy_data, index= dates_index, columns=list('ABCD'))
sample_df
# <h5>Selection using column name</h5>
# In[38]:
sample_df['C']
# <h5>Selection using slice</h5>
#
# - note: last index is not included
# In[39]:
sample_df[1:4]
# <h5>Selection using date time index</h5>
# - note: last index is included
# In[40]:
sample_df['2016-01-01':'2016-01-04']
# <h2>Selection by label</h2>
#
# label-location based indexer for selection by label
# In[41]:
sample_df.loc[dates_index[1:3]]
# <h5>Selecting using multi-axis by label</h5>
# In[42]:
sample_df.loc[:, ['A','B']]
# <h5>Label slicing, both endpoints are included</h5>
# In[43]:
sample_df.loc['2016-01-01':'2016-01-03', ['A','B']]
# <h5>Reduce number of dimensions for returned object
# - notice order of 'D' and 'B'
# In[44]:
sample_df.loc['2016-01-03', ['D', 'B']]
# In[45]:
sample_df.loc['2016-01-03', ['D', 'B']][0] * 4
# <h5>Select a scalar</h5>
# In[46]:
sample_df.loc[dates_index[2],'C']
# <h2>Selection by Position</h2>
# integer-location based indexing for selection by position
# In[47]:
sample_df
# In[48]:
sample_numpy_data
# In[49]:
sample_numpy_data[3]
# In[50]:
sample_df.iloc[3]
# <h5>integer slices</h5>
# In[51]:
sample_df.iloc[1:3, 2:4] #two rows, two columns, last index value not included in each case.
# In[52]:
#Note:
sample_df.iloc[1:13, 2:10] #note that indices 13,10 are not available in rows and columns, but it doesn't
#throw any error. from first position to last index available, values are selected.
# <h5>list of integers</h5>
# In[53]:
sample_df.iloc[[0,1,3],[0,2]] #select first(index 0), second(index 1) and fourth(index 3) rows and first(index 0) and third(index 2) columns.
# <h5>slicing rows explicitly</h5>
# implicitly selecting all columns
# In[54]:
sample_df.iloc[1:3,:]
# <h5>slicing columns explicitly</h5>
# implicitly selecting all rows
# In[55]:
sample_df.iloc[:, 1:3]
# ### NumPy Universal Functions
#
# If the data within a DataFrame are numeric, NumPy's universal functions can be used on/with the DataFrame.
# In[88]:
df = pd.DataFrame(np.random.randn(10, 4), columns=['A', 'B', 'C', 'D'])
df2 = pd.DataFrame(np.random.randn(7, 3), columns=['A', 'B', 'C'])
sum_df = df + df2
sum_df
# ##### NaN are handled correctly by universal function
# In[89]:
np.exp(sum_df)
# ##### Transpose availabe T attribute
# In[90]:
sum_df.T
# In[91]:
np.transpose(sum_df.values)
# ##### dot method on DataFrame implements matrix multiplication
# Note: row and column headers
# In[93]:
A_df = pd.DataFrame(np.arange(15).reshape((3,5)))
B_df = pd.DataFrame(np.arange(10).reshape((5,2)))
A_df.dot(B_df)
# ##### dot method on Series implements dot product
# In[94]:
C_Series = pd.Series(np.arange(5,10))
C_Series.dot(C_Series)
# ### dictionary like operations
# ##### dictionary selection with string index
# In[95]:
cookbook_df = pd.DataFrame({'AAA' : [4,5,6,7], 'BBB' : [10,20,30,40],'CCC' : [100,50,-30,-50]})
cookbook_df['BBB']
# ##### arithmetic vectorized operation using string indices
# In[96]:
cookbook_df['BBB'] * cookbook_df['CCC']
# ##### column deletion
# In[97]:
del cookbook_df['BBB']
cookbook_df
# In[98]:
last_column = cookbook_df.pop('CCC')
last_column
# In[99]:
cookbook_df
# ##### add a new column using a Python list
# In[100]:
cookbook_df['DDD'] = [32, 21, 43, 'hike']
cookbook_df
# ##### insert function
# documentation: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.insert.html
# In[101]:
cookbook_df.insert(1, "new column", [3,4,5,6])
cookbook_df
# <h2>Boolean Indexing</h2>
# test based upon one column's data
# In[56]:
(sample_df['C']) >= 14
#sample_df.C >= 14 #both are equivalent.
#type((sample_df['C']) >= 14) #pandas.core.series.Series
# In[57]:
(sample_df[['C','A']]) >= 14
#type((sample_df[['C','A']]) >= 14) #pandas.core.frame.DataFrame
# <h5>test based upon entire data set </h5>
# In[58]:
sample_df[sample_df >= 11]
# <h5>isin() method
# ----------------------------
# Returns a boolean Series showing whether each element in the Series is exactly contained in the passed sequence of values.
# In[59]:
sample_df_2 = sample_df.copy()
sample_df_2['Fruits'] = ['apple', 'orange','banana','strawberry','blueberry','pineapple']
sample_df_2
# select rows where 'Fruits' column contains either 'banana' or 'pineapple'; notice 'smoothy', which is not in the column
# In[60]:
sample_df_2[sample_df_2['Fruits'].isin(['banana','pineapple', 'smoothy'])]
# <h2>Assignment Statements</h2>
# In[61]:
sample_series = pd.Series([1,2,3,4,5,6], index=pd.date_range('2016-01-01', periods=6))
sample_series
# In[62]:
sample_df_2['Extra Data'] = sample_series*3 + 1
sample_df_2
# <h5>Setting values by label</h5>
# In[63]:
sample_df_2.at[dates_index[3], 'Fruits'] = 'pear'
sample_df_2
# <h5>Setting values by position</h5>
# In[64]:
sample_df_2.iat[3,2] = 4444 #assign the value at position (3,2) i.e at intersection of 4th column and 3rd row.
sample_df_2
# <h5>Setting by assigning with a numpy array</h5>
# In[65]:
second_numpy_array = np.array(np.arange(len(sample_df_2))) * 100 + 7
second_numpy_array
# In[66]:
sample_df_2['G'] = second_numpy_array
sample_df_2
# <h2>Missing Data</h2>
#
# pandas uses np.nan to represent missing data.Bye default, n.nan is not included in computations.
#
# nan represents - 'not a number'
# In[67]:
browser_index = ['Firefox', 'Chrome', 'Safari', 'IE10', 'Konqueror']
browser_df = pd.DataFrame({
'http_status': [200,200,404,404,301],
'response_time': [0.04, 0.02, 0.07, 0.08, 1.0]},
index = browser_index)
browser_df
# <h5>reindex() create a copy(not a view)</h5>
# In[68]:
new_index= ['Safari', 'Iceweasel', 'Comodo Dragon', 'IE10', 'Chrome']
browser_df_2 = browser_df.reindex(new_index)
browser_df_2
# <h5>drop rows that have missing data</h5>
# In[69]:
browser_df_3 = browser_df_2.dropna(how='any')
browser_df_3
# <h5>fill-in missing data</h5>
# In[70]:
browser_df_2.fillna(value=0.001)
# <h5>get boolean mask where values are nan</h5>
# In[71]:
pd.isnull(browser_df_2)
# <h5>NaN propagates during arithmetic operations</h5>
# In[72]:
browser_df_2 * 10
# <h2>Operations</h2>
# ### descriptive statistics
# In[73]:
pd.set_option('display.precision', 2)
sample_df_2.describe()
# ##### column mean
# In[74]:
sample_df_2.mean()
# ##### row mean
# In[75]:
sample_df_2.mean(1) # 1 specifies mean value along rows.
# ### apply(a function to a data frame)
# In[76]:
sample_df_2.apply(np.cumsum) # values are cumulatively added from previous row value to current row value until last row.
# In[77]:
sample_df_2
# #### string methods
# In[78]:
s = pd.Series(['A', 'B', 'C', 'Aaba', 'Baca', np.nan, 'CABA', 'dog', 'cat'])
s.str.lower()
# In[79]:
s.str.len()
# # Merge
# - Concat
# - Join
# - Append
# In[80]:
second_df_2 = sample_df.copy()
sample_df_2['Fruits'] = ['apple', 'orange','banana','strawberry','blueberry','pineapple']
sample_series = pd.Series([1,2,3,4,5,6], index=pd.date_range('2016-01-01', periods=6))
sample_df_2['Extra Data'] = sample_series *3 +1
second_numpy_array = np.array(np.arange(len(sample_df_2))) *100 + 7
sample_df_2['G'] = second_numpy_array
sample_df_2
# ### concat()
# ##### separate data frame into a list with 3 elements
# In[81]:
pieces = [sample_df_2[:2], sample_df_2[2:4], sample_df_2[4:]]
pieces[0]
# In[82]:
pieces # list elements
# ##### concatenate first and last elements
# In[83]:
new_list = pieces[0], pieces[2]
pd.concat(new_list)
# ### append()
# In[84]:
new_last_row = sample_df_2.iloc[2]
new_last_row
# In[85]:
sample_df_2.append(new_last_row)
# ### merge()
# Merge DataFrame objects by performing a database-style join operation by columns or indexes.
#
# If joining columns on columns, the DataFrame indexes will be ignored. Otherwise if joining indexes on indexes or indexes on a column or columns, the index will be passed on.
# In[86]:
left = pd.DataFrame({'my_key': ['K0', 'K1', 'K2', 'K3'],
'A': ['A0', 'A1', 'A2', 'A3'],
'B': ['B0', 'B1', 'B2', 'B3']})
right = pd.DataFrame({'my_key': ['K0', 'K1', 'K2', 'K3'],
'C': ['C0', 'C1', 'C2', 'C3'],
'D': ['D0', 'D1', 'D2', 'D3']})
left
# In[87]:
result = pd.merge(left, right, on='my_key')
result
|
#TO RUN: just type python geoDistance.py
import geoip2.database
from math import radians, cos, sin, asin, sqrt
# This creates a Reader object to read from the file
reader = geoip2.database.Reader('GeoLite2-City.mmdb')
#reads off the IPs and puts them in a python list
targets = open("targets.txt")
ip_list = targets.read().splitlines()
#according to www.whataremycoordinates.com, my current coordinates are:
lat1 = 41.50720007
lon1 = -81.6096177
print "My current coordinates are:"
print "Latitude",lat1
print "Longitude",lon1
print
#loops through list of IPs
for x in ip_list:
#Locates IP by its city in the database
response = reader.city(x)
print "IP: ",x
#Gets latitude and longitude
lat2 = response.location.latitude
lon2 = response.location.longitude
print "Latitude: ",lat2
print "Longitude: ",lon2
#I used the Haversine formula to calculate the geographical distance:
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
# haversine formula
#(via http://stackoverflow.com/questions/4913349/haversine-formula-in-python-bearing-and-distance-between-two-gps-points)
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
c = 2 * asin(sqrt(a))
r = 6371 # Radius of earth in kilometers. Use 3956 for miles
distance = c * r
print "Distance(km): ",distance, "\n" |
# For reading data set
# importing necessary libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# reading a csv file using pandas library
wcat=pd.read_csv("E:\\Bokey\\Excelr Data\\Python Codes\\all_py\\Simple Linear Regression\\wc-at.csv")
wcat.columns
plt.hist(wcat.Waist)
plt.boxplot(wcat.Waist,0,"rs",0)
plt.hist(wcat.AT)
plt.boxplot(wcat.AT)
plt.plot(wcat.Waist,wcat.AT,"bo");plt.xlabel("Waist");plt.ylabel("AT")
wcat.AT.corr(wcat.Waist) # # correlation value between X and Y
np.corrcoef(wcat.AT,wcat.Waist)
# For preparing linear regression model we need to import the statsmodels.formula.api
import statsmodels.formula.api as smf
model=smf.ols("AT~Waist",data=wcat).fit()
# For getting coefficients of the varibles used in equation
model.params
# P-values for the variables and R-squared value for prepared model
model.summary()
model.conf_int(0.05) # 95% confidence interval
pred = model.predict(wcat.iloc[:,0]) # Predicted values of AT using the model
# Visualization of regresion line over the scatter plot of Waist and AT
# For visualization we need to import matplotlib.pyplot
import matplotlib.pylab as plt
plt.scatter(x=wcat['Waist'],y=wcat['AT'],color='red');plt.plot(wcat['Waist'],pred,color='black');plt.xlabel('WAIST');plt.ylabel('TISSUE')
pred.corr(wcat.AT) # 0.81
# Transforming variables for accuracy
model2 = smf.ols('AT~np.log(Waist)',data=wcat).fit()
model2.params
model2.summary()
print(model2.conf_int(0.01)) # 99% confidence level
pred2 = model2.predict(pd.DataFrame(wcat['Waist']))
pred2.corr(wcat.AT)
# pred2 = model2.predict(wcat.iloc[:,0])
pred2
plt.scatter(x=wcat['Waist'],y=wcat['AT'],color='green');plt.plot(wcat['Waist'],pred2,color='blue');plt.xlabel('WAIST');plt.ylabel('TISSUE')
# Exponential transformation
model3 = smf.ols('np.log(AT)~Waist',data=wcat).fit()
model3.params
model3.summary()
print(model3.conf_int(0.01)) # 99% confidence level
pred_log = model3.predict(pd.DataFrame(wcat['Waist']))
pred_log
pred3=np.exp(pred_log) # as we have used log(AT) in preparing model so we need to convert it back
pred3
pred3.corr(wcat.AT)
plt.scatter(x=wcat['Waist'],y=wcat['AT'],color='green');plt.plot(wcat.Waist,np.exp(pred_log),color='blue');plt.xlabel('WAIST');plt.ylabel('TISSUE')
resid_3 = pred3-wcat.AT
# so we will consider the model having highest R-Squared value which is the log transformation - model3
# getting residuals of the entire data set
student_resid = model3.resid_pearson
student_resid
plt.plot(model3.resid_pearson,'o');plt.axhline(y=0,color='green');plt.xlabel("Observation Number");plt.ylabel("Standardized Residual")
# Predicted vs actual values
plt.scatter(x=pred3,y=wcat.AT);plt.xlabel("Predicted");plt.ylabel("Actual")
# Quadratic model
wcat["Waist_Sq"] = wcat.Waist*wcat.Waist
model_quad = smf.ols("AT~Waist+Waist_Sq",data=wcat).fit()
model_quad.params
model_quad.summary()
pred_quad = model_quad.predict(wcat.Waist)
model_quad.conf_int(0.05) #
plt.scatter(wcat.Waist,wcat.AT,c="b");plt.plot(wcat.Waist,pred_quad,"r")
plt.scatter(np.arange(109),model_quad.resid_pearson);plt.axhline(y=0,color='red');plt.xlabel("Observation Number");plt.ylabel("Standardized Residual")
plt.hist(model_quad.resid_pearson) # histogram for residual values
############################### Implementing the Linear Regression model from sklearn library
from sklearn.linear_model import LinearRegression
import numpy as np
plt.scatter(wcat.Waist,wcat.AT)
model1 = LinearRegression()
model1.fit(wcat.Waist.values.reshape(-1,1),wcat.AT)
pred1 = model1.predict(wcat.Waist.values.reshape(-1,1))
# Adjusted R-Squared value
model1.score(wcat.Waist.values.reshape(-1,1),wcat.AT)# 0.6700
rmse1 = np.sqrt(np.mean((pred1-wcat.AT)**2)) # 32.760
model1.coef_
model1.intercept_
#### Residuals Vs Fitted values
import matplotlib.pyplot as plt
plt.scatter(pred1,(pred1-wcat.AT),c="r")
plt.hlines(y=0,xmin=0,xmax=300)
# checking normal distribution for residual
plt.hist(pred1-wcat.AT)
### Fitting Quadratic Regression
wcat["Waist_sqrd"] = wcat.Waist*wcat.Waist
model2 = LinearRegression()
model2.fit(X = wcat.iloc[:,[0,2]],y=wcat.AT)
pred2 = model2.predict(wcat.iloc[:,[0,2]])
# Adjusted R-Squared value
model2.score(wcat.iloc[:,[0,2]],wcat.AT)# 0.67791
rmse2 = np.sqrt(np.mean((pred2-wcat.AT)**2)) # 32.366
model2.coef_
model2.intercept_
#### Residuals Vs Fitted values
import matplotlib.pyplot as plt
plt.scatter(pred2,(pred2-wcat.AT),c="r")
plt.hlines(y=0,xmin=0,xmax=200)
# Checking normal distribution
plt.hist(pred2-wcat.AT)
import pylab
import scipy.stats as st
st.probplot(pred2-wcat.AT,dist="norm",plot=pylab)
# Let us prepare a model by applying transformation on dependent variable
wcat["AT_sqrt"] = np.sqrt(wcat.AT)
model3 = LinearRegression()
model3.fit(X = wcat.iloc[:,[0,2]],y=wcat.AT_sqrt)
pred3 = model3.predict(wcat.iloc[:,[0,2]])
# Adjusted R-Squared value
model3.score(wcat.iloc[:,[0,2]],wcat.AT_sqrt)# 0.74051
rmse3 = np.sqrt(np.mean(((pred3)**2-wcat.AT)**2)) # 32.0507
model3.coef_
model3.intercept_
#### Residuals Vs Fitted values
import matplotlib.pyplot as plt
plt.scatter((pred3)**2,((pred3)**2-wcat.AT),c="r")
plt.hlines(y=0,xmin=0,xmax=300)
# checking normal distribution for residuals
plt.hist((pred3)**2-wcat.AT)
st.probplot((pred3)**2-wcat.AT,dist="norm",plot=pylab)
# Let us prepare a model by applying transformation on dependent variable without transformation on input variables
model4 = LinearRegression()
model4.fit(X = wcat.Waist.values.reshape(-1,1),y=wcat.AT_sqrt)
pred4 = model4.predict(wcat.Waist.values.reshape(-1,1))
# Adjusted R-Squared value
model4.score(wcat.Waist.values.reshape(-1,1),wcat.AT_sqrt)# 0.7096
rmse4 = np.sqrt(np.mean(((pred4)**2-wcat.AT)**2)) # 34.165
model4.coef_
model4.intercept_
#### Residuals Vs Fitted values
import matplotlib.pyplot as plt
plt.scatter((pred4)**2,((pred4)**2-wcat.AT),c="r")
plt.hlines(y=0,xmin=0,xmax=300)
st.probplot((pred4)**2-wcat.AT,dist="norm",plot=pylab)
# Checking normal distribution for residuals
plt.hist((pred4)**2-wcat.AT)
|
# 리스트, 튜플
# 리스트(순서o, 중복, 수정과 삭제 가능)
# 선언
a = []
b = list()
c = [1,2,3,4]
d = [1,100,'pen','cap','plate']
e = [1,100,['pen','cap','plate']]
print(d[3])
print(d[-1])
print(d[0]+d[1])
print(d[3] + d[4])
print(e[2][2])
print(e[-1][-3])
print('===='*20)
print(d[0:3])
print(d[2:])
print(e[2][0:2])
print('===='*20)
print(c+d)
print(c*3)
print('bol'+ d[2])
print('Hi'+ str(c[2]))
print('===='*20)
c[0] = 5
print(c)
c[1:2] = ['a','b','c']
print(c)
c[1] = ['a','b','c']
print(c)
c[1:3] = []
print(c)
del c[3] #3번 인덱스가 삭제
print(c)
c = [1,2,3,4]
print(c)
print('===='*20)
c[:1] = [2,5,4,8]
print(c)
c.append(6)
print(c)
c.sort()
print(c)
c.reverse()
print(c)
c.insert(2, 9)
print(c)
c.pop()
print(c)
c.pop()
print(c)
print(c.count(8))
ex = [10,11]
c.append(ex)
print(c)
c.extend(ex)
print(c)
# 튜플(수정, 삭제x)
a = ()
b = (1,)
c = (1,2,3,4)
d = (10,100,'banana','pineapple','apple')
e = (10,100,('banana','pineapple','apple'))
#인덱싱
print(d[1])
print(d[0]+d[1]+d[1])
#슬라이싱
print(d[:3])
print(type(d))
print(e[2][:2])
print('hi'+e[2][1])
print('hi'+str(e[1]))
print(c+d)
print(c*3)
|
class Node(object):
"""
LRU Cache node which keeps track of key, value, previous and next nodes
"""
def __init__(self, key, value):
self.key = key
self.value = value
self.next = None
self.prev = None
def setNext(self, node):
self.next = node
def setPrev(self, node):
self.prev = node
class LRUCache(object):
"""
LRU Cache implementation in python
- cache can be initialized with a fixed size: LRUCache(size)
- most recent item is at the end of the linked list
- if cache is full, remove least recently used element
"""
def __init__(self, size):
self.size = size
self.map = {}
self.head = Node(0, "Head")
self.tail = Node(0, "Tail")
self.head.setNext(self.tail)
self.tail.setPrev(self.head)
def __str__(self):
string = []
for node in self.map.values():
string.append([node.key, node.value])
return str(string)
def get(self, key):
if key not in self.map:
return -1
else:
n = self.map[key]
return n.value
def insert(self, key, value):
n = Node(key, value)
if key in self.map:
oldnode = self.map[key]
self._del(oldnode)
self.map[key] = n
else:
self._add(n)
self.map[key] = n
if (len(self.map)) > self.size:
oldnode = self.head.next
del self.map[oldnode.key]
self._del(oldnode)
del oldnode
def _del(self, node):
node.prev.setNext(node.next)
node.next.setPrev(node.prev)
def _add(self, node):
node.setNext(self.tail)
node.setPrev(self.tail.prev)
self.tail.prev.setNext(node)
self.tail.setPrev(node)
c = LRUCache(2)
c.insert(1, "Hello")
print(c.get(1))
c.insert(2, "Hiya")
print(c.get(2))
c.insert(3, "Haii")
print(c.get(3))
print(c.get(1))
print(c)
|
#!/usr/bin/env python3
""" Created: Average Joe
Simple dice game """
#import stuff
#from cheatdice import Player
from cheatdice import Cheat_Swapper
from cheatdice import Cheat_Loaded_Dice
def main():
""" execute teh main logic """
cheater1 = Cheat_Swapper() #create player object1
cheater2 = Cheat_Loaded_Dice() #create player object2
cheater1.roll() #roll the dice!
cheater2.roll() #roll the dice
cheater1.cheat() # apply the cheat
cheater2.cheat() #apply the cheat
print("Cheater 1 rolled" + str(cheater1.get_dice())) # get the values of the dice rolls
print("Cheater 2 rolled" + str(cheater2.get_dice())) # get teh value of the dice rolls
if sum(cheater1.get_dice()) == sum(cheater2.get_dice()): # determine if it was a tie.
print("Draw!") # print the result
elif sum(cheater1.get_dice()) > sum(cheater2.get_dice()): # determine the winner
print("Cheater 1 wins!") # print result
else:
print("Cheater 2 wins!") # print the result
if __name__ == '__main__':
main()
|
from time import sleep
def password():
tries = 0
while tries < 3:
pin = int(input("Please enter your pin in the screen "))
if pin == (1234):
print("Correct..fetching your data in a few seconds...")
return True
else:
print("Incorrect password, please try again")
tries = tries + 1
print("Incorrect password, and system is self-destructing for attempts in 3 seconds")
sleep(3)
return False
def start():
balance = 500
print("Hello, and welcome to your virtual ROBUX ATM")
if password():
print("1: for Balance")
print("2: for Withdrawal")
print("3: for Deposit")
print("4 for Exit")
transaction = int(input("Choose which robux transaction fits your day: "))
if transaction == 1:
print("Your balance is R$",balance,'\n')
restart = input("would you like to go back? ")
if restart in('No','no'):
print("Thanks for using ROBUX ATM. Bye!")
elif restart in('Yes','y'):
print("")
start()
elif transaction == 2:
withdrawal = float(input("How much would you like to withdraw?\nR$80\nR$400\nR$800\nR$1000\nR$10000\nR$20000"))
if withdrawal in [80,400,800,100,10000,20000]:
balance = balance - withdrawal
print("Your balance is: ", balance)
restart = input("Would you like to go back? ")
if restart in('No', 'no'):
print("Thanks for using ROBUX ATM. Bye!")
elif restart in('Yes','y'):
print("")
start()
elif withdrawal != [80,400,800,100,10000,20000]:
print("Invalid Amount, try again.")
restart = ('yes')
elif transaction == 3:
deposit = float(input("How much robux do you want to deposit? "))
balance = deposit + balance
print("Your balance is R$:", balance, '\n')
restart = input("Woud you like to go back? ")
if restart in ('No', 'no'):
print('Thanks for using ROBUX ATM. Bye!')
elif restart in ('Yes', 'y'):
print("")
start()
elif transaction == 4:
print("Thanks for using ROBUX ATM, hope you have a great day for you ahead.")
print("Exiting program....")
start()
|
# create a new file Warmups.py
# 12.4.17
# Write a Python Function
# which accepts the user's
# first and last name
# and prints them in reverse order
# with a space between them.
# def reverse_order(first_name, last_name):
# # print("%s, %s" % (last_name, first_name))
# print(last_name + " " + first_name) # Concatenation
#
# first = input("What is your first name?")
# last = input("What is your last name?")
#
# reverse_order(first, last)
# 12.5.17
"""Write a function called add_py
that takes one parameter called "name"
and prints out name.py
example:
add_py("John") == "John.py"
"""
# def add_py(name):
# print(name + ".py")
#
#
# add_py("Jeffery")
# 12.6.17
"""Write a function called "add"
which takes three parameters
and prints the sum of the numbers
"""
# def add(three, nine, five):
# print (three + nine + five)
#
# add(3,9,5)
# 12.7.17
# Write a function called "repeat"
# that takes one parameter (string)
# and prints it three times
#
# example:
# repeat("Hello") prints:
# Hello
# Hello
# Hello
def repeat(word):
print(word)
print(word)
print(word)
repeat("Jeffery") |
# This is a guide of how to make hangman
# 1. Make a word bank - 10 items
# 2. Select a random item to guess
# 3. Take in a letter and add it to a list of letters_guessed
# 4. Hide and reveal letters
# 5. Create win and lose conditions
import random
import string
import sys
alphabet = string.ascii_lowercase
words_phrases = ['gabriella montez', 'chad danforth', 'sharpay evans', 'kelsi nielsen', 'taylor mckessie',
'ms darbus', 'zeke baylor', 'troy bolton', 'ryan evans', 'coach jack bolton']
def hangman():
guesses_left = 10
regular_word = random.choice(words_phrases).lower()
word = list(regular_word)
guesses = [' ']
hidden_word = ('*' * len(regular_word))
print(hidden_word)
while guesses_left > 0:
print(guesses)
print("Hello. Welcome to Hangman. The word is %s letters long." % len(regular_word))
print("If it gets difficult for you, type quit and the game will stop.")
player_guess = input("take a guess >_").lower()
guesses.append(player_guess)
if player_guess == 'quit':
print("Sorry it was hard. The word was %s. Have a good day." % regular_word)
again = input("Would you like to play again? (yes/no)")
if again == "yes":
hangman()
else:
exit(0)
if player_guess not in regular_word:
guesses_left -= 1
print("You now have %s guesses" % guesses_left)
output = []
for letter in regular_word:
if letter in guesses:
output.append(letter)
else:
output.append('*')
output = ''.join(output)
if '*' not in output:
print('Congrats you win. The word was %s' % regular_word)
again = input("Would you like to play again? (yes/no)")
if again == "yes":
hangman()
else:
exit(0)
print(output)
print("Sorry you didn't guess correct. The word was %s" % regular_word)
again = input("Would you like to play again? (yes/no)")
if again == "yes":
hangman()
else:
exit(0)
hangman() |
print("Hello, this is a money calculator that calculates how much your money will increase in how many years if an interest percentage is some amount.")
def CalcCurrYearMoney(money,percentage):
i=percentage/100
i = i+1
money = money*i
return money
def main():
x = int(input("please insert initial money in digit(s) (ex:1000)"))
y = int(input("please insert interest percentage in digit(s) (ex:2)"))
z = int(input("please insert the number of years that will pass (ex:5)"))
j = z
i = x
while z>0:
x=CalcCurrYearMoney(x,y)
z = z-1
return print("after", j, "years, your money",i, "will increase to", x)
print(main())
|
def check(n):
add=0
while n>0:
add += n%10
n = n/10
z=add
if z <10:
return z
elif z >= 10:
f=check(z)
return f
k = int(input())
h = check(k)
if h < 10:
if h == 7:
print "The number is a lucky number"
else:
print "The number is not a lucky number"
|
var=raw_input()
i=0
l=0
var=var.upper()
#print var
while i<len(var):
if var[i]!=" ":
#print ord(var[i])-64
l=l+ ord(var[i])-64
"""if var[i]==" ":
l=l-4"""
i=i+1
print l
|
# Exercise 1
class Bus(object):
counter = 0
def __init__(self, seats, color, bus_driver):
self.seats = seats
self.color = color
self.bus_driver = bus_driver
Bus.counter += 1
def change_color(self, recolor):
self.color = recolor
# Today's date
from datetime import datetime, timedelta, time
dt = datetime(2021, 5, 18)
answer = dt + timedelta (days=7)
x = datetime.now
print(answer)
print(x)
# Print 10 dates 14 days apart
for x in range(10):
print(x + 1, "-", end=" ")
print(dt.strftime("%Y/ %m/ %d - %H:%M"))
dt = dt + timedelta(days=7)
# Exercise 2
year_born = int(input("Enter year born :"))
month_born = int(input("Enter month born :"))
day_born = int(input("Enter day born :"))
current_year = int(datetime.today().strftime("%Y"))
current_month = int(datetime.today().strftime("%m"))
current_day = int(datetime.today().strftime("%d"))
age = current_year - year_born - 1
if month_born < current_month:
age += 1
elif month_born == current_month:
if day_born <= current_day:
age += 1
print("")
print("You are {} years old".format(age))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Solution:
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
count1 =0
count2 =0
cand1 =0
cand2=1
for x, n in enumerate(nums):
if n == cand1:
count1 +=1
elif n == cand2:
count2 +=2
elif count1 == 0:
cand1 = n
count1 +=1
elif count2 == 0:
cand2 =n
count2 +=1
else:
count1 -= 1
count2 -= 1
return [n for n in (cand1, cand2) if nums.count(n) > len(nums)/3]
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Solution:
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
cursize = 0
maxsize = 0
rl = len(height)
l = 0
r = rl -1
while l < r:
cursize = abs(r-l) * min(r, l)
maxsize = max(maxsize, cursize)
if l < r:
l += 1
else:
r -= 1
return maxsize
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Solution:
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
r = []
c = []
for x in range(len(matrix)):
for y in range(len(matrix[0])):
if matrix[x][y] == 0:
r.append(x)
c.append(y)
for x in range(len(matrix)):
for y in range(len(matrix[0])):
if x in r or y in c:
matrix[x][y] = 0
|
from termcolor import *
import time
import random
class FinalBoss(object):
def __init__(self, user):
self.user = user
def colorize(self, text, color='red'):
text = colored(text, color, attrs=['bold'])
return text
def typeWriter(self, text, isColored=False, lag=0.005, color='red'):
text = list(str(text))
if isColored:
for letter in text:
time.sleep(lag)
print(self.colorize(letter, color), end='', flush=True,)
else:
for letter in text:
time.sleep(lag)
print(letter, end='', flush=True)
def dodge(self):
self.typeWriter('He swipes at you, what direction do you want to dodge?', isColored=True)
self.typeWriter('\n\nA) Duck Right. \nB) Roll Left. \nC) Stand your ground. He is expecting you to dodge.\n')
while True:
user_choice = input()
if user_choice == 'A' or user_choice == 'B' or user_choice == 'C':
break
else:
self.typeWriter('Try typing something valid.\n')
directions=["A", "B", "C"]
attackdirection=random.randint(0, 2)
dodge=False
if directions.index(user_choice)==attackdirection:
dodge=True
return dodge
def grandmaster_damage(self, grandmaster_health, damage):
grandmaster_health -= damage
self.typeWriter('The Grandmaster has taken ' + str(damage) + ' damage\n', isColored=True)
if grandmaster_health>60:
self.typeWriter("You've barely made a dent, he smiles and charges at you again. ")
elif grandmaster_health>30:
self.typeWriter("His actions seem to be slowing as various wounds on his body bleed out. \nYou must keep "
"fighting. He charges, no longer having that smirk on his face. ")
elif grandmaster_health>0:
self.typeWriter("He seems as if he is about to faint, but he picks himself back up. He looks at you with "
"a deathly glare. \nThe world around you is fading closer to reality and freedom is within "
"reach \n", isColored=True)
return grandmaster_health
def attack(self, grandmaster_health):
self.typeWriter('He appears to be tired as he lays down after his last swipe. This is your chance to attack!'
' Where do you attack him?\n', isColored=True)
self.typeWriter('\n\nA) Arms \nB) Legs \nC) Chest\n\n')
while True:
user_choice = input()
if user_choice == 'A' or user_choice == 'B' or user_choice == 'C':
break
else:
self.typeWriter('Try typing something valid.\n')
directions = ["A", "B", "C"]
weakness = random.randint(0, 2)
if directions.index(user_choice) == weakness:
damage=(float(self.user.returnDamage())*3)
self.typeWriter('The Grandmaster stumbles and stares at you in confusion, wondering how you knew that was '
'his current weakness\n', isColored=True)
grandmaster_health=self.grandmaster_damage(grandmaster_health, damage)
else:
damage = (float(self.user.returnDamage()))
self.typeWriter('The Grandmaster grins and gets to his feet as you charge. Side stepping his next attack'
', you hesitate and barely graze him.\n')
grandmaster_health=self.grandmaster_damage(grandmaster_health, damage)
return grandmaster_health
def death(self):
self.typeWriter('\n\nYou\'ll never make it back to reality and you are out of lives.'
'You stumble around as the world starts to fade to black...')
def takedamage(self):
damage=random.randint(0,30)
self.typeWriter('You take ' + str(damage) + ' damage.\n')
lifelost=self.user.losehealth(damage)
self.typeWriter('Health remaining: ')
self.typeWriter(self.user.returnChangingHealth())
print()
if lifelost:
self.typeWriter('\nLives left: ')
self.typeWriter(self.user.returnLives(), color=self.user.returnColor())
print()
def grandmasterdeath(self):
self.typeWriter('\nThe Grandmaster stumbles, frantically scrambling to find something to hold him up as he falls.\n This is it. You dash for him,'
' delivering one last blow, and watch him fall.\n The world around you fades to black and then zones back to reality'
'. It is done. The game is won.\n', isColored=True)
def battle(self):
self.typeWriter('The Grandmaster swipes at you and you dodge at the last second.\n', isColored=True)
self.typeWriter('You know that it was just a warning attack, the rest will not be so easy.\n')
grandmaster_health=100
while self.user.returnLives()!=0:
dodge=self.dodge()
if not dodge:
self.takedamage()
self.typeWriter("He knew where to attack too well, he hits you and you are knocked to your feet, but"
" you keep looking for an opening\n")
if dodge:
self.typeWriter('Almost as if you could read his mind, you avoid his attack and look for an opening. \n')
opening=False
if random.randint(1,2)==2: opening=True
if opening:
grandmaster_health = self.attack(grandmaster_health)
else:
self.typeWriter('You must bide your time, there is no opening in sight, death looks you in the face as '
'he charges you again.\n')
if grandmaster_health<=0:
self.grandmasterdeath()
result = "success"
return result
if self.user.returnLives() == 0:
self.death()
result="failure"
return result
def run(self):
self.typeWriter('As you look around, you can see the fabric of reality and the game almost mixing.\n', isColored=True)
self.typeWriter('This is your path to escape and you know it.\n')
self.typeWriter('A huge laugh fills the room, and the Grandmaster looks you dead in the eyes with a cold '
'expression on his face.\n\n')
self.typeWriter('You never should have come to my realm, this will be the end of you!\n\n', isColored=True)
result=self.battle()
if result=="failure":
return result
|
mix = ['magical unicorns', 19, 'hello', 98.98, 'world']
integers = [2, 3, 1, 7, 4, 12]
words = ['magical', 'unicorns']
def typeList(arr):
string = ""
sum = 0
stringCount = 0
numCount = 0
for i in range(0, len(arr)):
if type(arr[i]) is str:
string += arr[i]
stringCount += 1
if type(arr[i]) is int:
sum += arr[i]
numCount += 1
if type(arr[i]) is float:
sum += arr[i]
numCount += 1
if stringCount == len(arr):
print("The list you entered is of string type")
print("Strings:", string)
elif numCount == len(arr):
print("The list you entered is of integer type")
print("Sum:", sum)
else:
print("The list you entered is of mixed type")
print("Strings:", string)
print("Sum:", sum)
typeList(mix)
typeList(integers)
typeList(words)
|
from random import randint
def scoresGrades(end):
for i in range (0, end):
num = randint(60, 100)
if (num < 70):
print("Score: " + str(num) + "; Your grade is D")
elif (num < 80 and num >= 70):
print("Score: " + str(num) + "; Your grade is C")
elif (num < 90 and num >= 80):
print("Score: " + str(num) + "; Your grade is B")
else:
print("Score: " + str(num) + "; Your grade is A")
print("End of the program. Bye!")
scoresGrades(10) |
"""
Program: get_user_input.py
Author: Donald Butters
Last date modified: 10/5/2020
The purpose of this program is prompt a name, age, and hourly pay.
Then the program out prints the input as a string
"""
def get_user_input(): # keyword def with function name then ():
"""Prompts the user for name, age and prints a message""" # docstring
name = input("Please enter your name:") # user input string
age = int(input('Please enter your age. :')) # user input int
if age in range(1,120): # handle the bad
print("Thank you")
else:
input("Please enter your age between 1-120. :")
rate = float(input('Please enter your hourly pay rate. :')) # user inputs pay rate
if rate in range(7,500): # handle the bad
print("Thank you")
else:
input("Please enter your pay rate between 7 and 500. :")
print('Name:',name,'\nAge:',age,'\nRate:',rate, sep="\n") # Prints the inputs as a string
if name == 'main':
get_user_input() # function call
|
#!/usr/local/bin/python
days = 365
numPeople =23
prob = 0
while prob < 0.5:
numPeople += 1
prob = 1 -((1-prob)*(days-(numPeople-1))/days)
print("Number of people:",numPeople)
print("Prob. of same birthday:",prob) |
from functools import wraps
def thisIsliving(fun):
@wraps(fun)
def living(*args,**kw):
return fun(*args,**kw)+ 'living is eating'
return living
@thisIsliving
def whatIsLiving():
"what is living"
return "mygod,what is living,"
print whatIsLiving()
print whatIsLiving.__doc__ |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.