text
stringlengths 37
1.41M
|
---|
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 18 16:52:06 2020
@author: patel
"""
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
prev = None
temp= None
carry= 0
while l1 is not None or l2 is not None:
fdata=0 if l1 is None else l1.data
sdata=0 if l2 is None else l2.data
s =sum(carry+fdata+sdata)
carry=1 if s>10 else 0
s=s if s<10 else s%10
temp = Node(s)
if self.head is None:
self.head = temp
else:
prev.next = temp
prev = temp
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
|
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 28 02:03:59 2020
@author: patel
"""
if __name__ == '__main__':
arr1=[]
n=int(input())
for _ in range(n):
name = input()
score = float(input())
arr = [name , score]
arr1.append(arr)
m=min(arr1,key= lambda x:x[1])
i=0
while(n>i):
if m==min(arr1,key= lambda x:x[1]):
arr1.remove(m)
i+=1
print(min(arr1,key= lambda x:x[1])) |
#Read a list of integers from user input.
numbers = list()
totalNumber = 0
next = False
while not next:
try:
totalNumber = int(input('How many numbers are you putting in?'))
if totalNumber > 1:
next = True
else:
print("There are no pair.... Input a number that is larger than 1.....")
except:
print('Please input a number.')
print('Start:')
i = 0
while i < totalNumber:
try:
userInput = int(input())
numbers.append(userInput)
i += 1
except:
print('Please input a number')
#Find all pairs of numbers in the list whose
productEven = list()
sumOdd = list()
for i in range(len(numbers)):
for j in range(i+1, len(numbers)):
if ((numbers[i] * numbers[j]) % 2) == 0: # product is even
productEven.append((numbers[i], numbers[j]))
if ((numbers[i] + numbers[j]) % 2) != 0: # sum is odd
sumOdd.append((numbers[i], numbers[j]))
#Print out a formatted list of the pairs.
print()
print('Pair of numbers with even product:')
i = 1
for thisPair in productEven:
print('Pair {2}: {0}, {1}'.format(thisPair[0], thisPair[1], i))
i += 1
print()
print('Pair of numbers with odd sum:')
i = 1
for thisPair in sumOdd:
print('Pair {2}: {0}, {1}'.format(thisPair[0], thisPair[1], i))
i += 1
|
"""Mathematical utilities for CS41's Assignment 1: Cryptography."""
import math
class Error(Exception):
"""Base class for exceptions in this module."""
class BinaryConversionError(Error):
"""Custom exception for invalid binary conversions."""
class NotCoprimeError(Error):
"""Custom exception for arguments that are not coprime but need to be."""
def is_superincreasing(seq):
"""Return whether a given sequence is superincreasing.
A sequence is superincreasing if each element is greater than the sum of
all elements before it.
Usage::
is_superincreasing([1, 1, 1, 1, 1]) # => False
is_superincreasing([1, 3, 4, 9, 15, 90]) # => False
is_superincreasing([1, 2, 4, 8, 16]) # => True
:param seq: The iterable to check.
:returns: Whether this sequence is superincreasing.
"""
total = 0 # Total so far
for n in seq:
if n <= total:
return False
total += n
return True
def modinv(a, b):
"""Return the modular inverse of a mod b.
The returned value s satisfies a * s == 1 (mod b).
As a precondition, a should be less than b and a and b must be coprime.
Errors are raised if these conditions do not hold.
Adapted from https://en.wikibooks.org/wiki/Algorithm_Implementation/
Mathematics/Extended_Euclidean_algorithm#Python
:param a: Value whose modular inverse to find.
:param b: The modulus.
:raises: ValueError if a >= b.
:raises: NotCoprimeError if a and b are not coprime.
:returns: The modular inverse of a mod b.
"""
if a >= b:
raise ValueError("First argument to modinv must be less than the second argument.")
if not coprime(a, b):
raise NotCoprimeError("Mathematically impossible to find modular inverse of non-coprime values.")
# Actually find the modular inverse.
saved = b
x, y, u, v = 0, 1, 1, 0
while a:
q, r = b // a, b % a
m, n = x - u*q, y - v*q
# Tuple packing and unpacking can be useful!
b, a, x, y, u, v = a, r, u, v, m, n
return x % saved
def coprime(a, b):
"""Return whether a and b are coprime.
Two numbers are coprime if and only if their greater common divisor is 1.
Usage::
print(coprime(5, 8)) # => True (5 and 8 have no common divisors)
print(coprime(6, 9)) # => False (6 and 9 are both divisible by 3)
"""
return math.gcd(a, b) == 1
def byte_to_bits(byte):
"""Convert a byte to an tuple of 8 bits for use in Merkle-Hellman.
The first element of the returned tuple is the most significant bit.
Usage::
byte_to_bits(65) # => [0, 1, 0, 0, 0, 0, 0, 1]
byte_to_bits(b'ABC'[0]) # => [0, 1, 0, 0, 0, 0, 0, 1]
byte_to_bits('A') # => raises TypeError
:param byte: The byte to convert.
:type byte: int between 0 and 255, inclusive.
:raises: BinaryConversionError if byte is not in [0, 255].
:returns: An 8-tuple of bits representing this byte's value.
"""
if not 0 <= byte <= 255:
raise BinaryConversionError(byte)
out = []
for i in range(8):
out.append(byte & 1)
byte >>= 1
return tuple(out[::-1])
def bits_to_byte(bits):
"""Convert a tuple of 8 bits into a byte for use in Merkle-Hellman.
The first element of the returned tuple is assumed to be the most significant bit.
:param bits: collection of 0s and 1s representing a bit string.
:type bits: tuple
:raises: BinaryConversionError if the supplied tuple isn't all 0s and 1s.
:returns: A converted byte value for this bit tuple.
"""
if not all(bit in (0, 1) for bit in bits):
raise BinaryConversionError("Encountered non-bits in bit tuple.")
byte = 0
for bit in bits:
byte *= 2
if bit:
byte += 1
return byte
|
# Standalone node class for de Bruijn graph Implemented by Charles Eyermann
# and Sam Hinh for Computational Biology (CS362) Winter 2016
class Node:
def __init__(self,name):
self.name = name
self.neighbors = []
self.unique_neighbors = 0
self.parents = []
self.unique_parents = 0
self.indegree = 0
self.outdegree = 0
def __eq__(self, other):
this = self.name
that = other.name
if this == that:
return True
else:
return False
def __hash__(self):
return hash(self.name)
def data_dump(self):
print "|name: ", self.name,
print "|unique neighbors: ", self.unique_neighbors,
print "|unique parents: ", self.unique_parents,
print "|indegree: ", self.indegree,
print "|outdegree: ", self.outdegree, "|"
def get_name(self):
return self.name
def get_neighbors(self):
return self.neighbors
def get_parents(self):
return self.parents
def get_balance(self):
if self.indegree == self.outdegree:
return True
else:
return False
def get_semi_balance(self):
if abs(self.indegree - self.outdegree) == 1:
return True
else:
return False
def get_degree(self):
return self.indegree - self.outdegree
def is_head(self):
if self.get_degree() < 0 and self.indegree == 0:
return True
else:
return False
def is_branching(self):
return (self.unique_neighbors*self.unique_parents) > 1
def is_leaf(self):
if self.outdegree == 0:
return True
else:
return False
def is_collapsible(self):
if self.indegree == 1 and (self.outdegree == 0 or 1):
return True
else:
return False
|
#!/usr/bin/python
# -*- coding=utf8 -*-
"""
Python 有三类字符串:
1. 通常意义的字符串( str )
2. unicode字符串 ( unicode )
3. 抽象类 ( basestring ) 不能被实例化
"""
s = "hello world"
#切片
print s[:5]
print s[6:]
print s[2]
#字符串长度
print len(s)
print s[0:len(s)]
#成员操作符 in, not in
print "a" in s
print "he" in s
print "ss" not in s
#大小写
import string
print string.uppercase
print string.lowercase
print string.letters
print string.digits
print string.lower("HELLO world")
print "XXX".lower()
print string.upper("hello WORLD")
print "xxx".upper()
print string.capwords("hello world sjclijie")
#字符串连接
print 'http://www.baidu.com' ':8080' '/cgi-bin/hello.py'
#如果一个普通字符串和一个unicode字符串相连接,python会在连接操作前将普通字符串转成unicode字符串
print "hello" u'我是unicode字符串'
#字符串格式化
"""
%c 转成ascii
%r 优先使用repr()
%s 优先使用str()
其它的都一样...
"""
print "%c %r %s" % (65, "hello", "world")
#也可以使用字典类型
print "%(name)s %(age)d" % {"age":22, "name":"sjclijie" }
#模板字符串
from string import Template
#Template.substitute() 在缺少key的时候会报错 KeyError
#Template.safe_substitute()
s = Template("There are ${how} ${lang} Quotation Symbols.")
print s.substitute(lang="python", how="xxxs")
print s.safe_substitute( lang="python" )
#原始字符串
print r"\n"
print "\n"
f = open( r"./README.md", 'r')
print f.readline()
f.close()
import re
m = re.search( r"\\[rtvnf]", r"hello world!\n" )
print m
#Unicode字符串
print u'abc\u1234\n'
###### 内建函数
# 1.cmp 按ascii比较大小
print cmp("a", "A")
print ord("A") #65
print ord("a") #97
# 2.len
print len("hello world")
# 3.max min
print max("abc")
print min("abc")
# 4.enumerate
s = "hello world"
for i in range(0, len(s)):
print i, s[i]
for index, text in enumerate(s):
print index, text
# 字符串类型函数
print isinstance( u"\0xAB", str )
print isinstance( u"\0AB", unicode )
print isinstance( u"\00AB", basestring )
#chr ord unichr
print chr(65)
print ord("A")
try:
print unichr(1236)
print unichr(123456)
except ValueError, e:
print e
else:
print unichr(1111)
finally:
print unichr(2222)
print ord( u"\u1235" )
print unichr(4661)
########## 内建函数
print "#######################################\n"
#1. 将字符串第一个字符大写
print string.capitalize("hello world")
print "hello world".capitalize()
#2. 填充
print "|" + "hello world".center( 50 ) + "|"
#3. string.count(str, start, end) str出现现string中的次数
print "hello world".count("o", 0, 8)
#4. string.decode( encoding='UTF-8', errors='strict|ignore|replace') 解码
#5. string.encode( encoding='UTF-8', errors='strict|ignore|replace' ) 编码
#6. string.endswith(str, beg=0, end=len(string) ) 检查string是否以str结束
print "string".endswith("ing")
#7. string.expandtabs( tabsize = 8 ) 把tan转为空格
print "Hello\tworld".expandtabs(4)
#8. string.find( str, beg=0, end=len(string)) str是否包含在string中, 返回首次出现的index
print "hello world".find("world")
#9. string.index( str, beg=0, end=len(string) ) 和find一样,如果不存在会抛出异常
try:
print "hello world".index("world111")
except ValueError, e:
print e
#10. string.isalnum() string不为空并且所有的字符都是字母或者数字
print "helloworld_".isalnum()
print "hello1234".isalnum()
#11. string.isalpha() string不为空并且所有的字符都是字母
print "hello".isalpha()
print "h1234".isalpha()
#12. string.isdigit() string不为空并且所有的字符都是数字
print "1234xxx".isdigit()
print "1234".isdigit()
print "1234".isalnum()
#13. string.islower() 所有字符都是小写
print "abcdefgH".islower()
print "abcdefg".islower()
#14. string.isupper() 所有字符都是大写
print "HELLO".isupper()
#15. string.isspace() 只包含空格
print " ".isspace()
#16. string.join(str) 以string为分隔符,将str合并为新字符串
print "|".join("abc")
#17. string.ljust(with) 左对齐+填充长度
print "|" + "hello".ljust(50) + "|"
print "|" + "hello".rjust(50) + "|"
#18. lower upper 转换大小写
print "hello".upper()
print "HELLO".lower()
#19. string.lstrip() 去除空格
print "|"+" he".lstrip() + "|"
print "|"+"he ".rstrip() + "|"
#20. string.partition( str ) 从str出现的第一个位置起,把string切成一个三元祖
print "helloworld".partition("llo")
print "helloworld".partition("xxx")
print "1aahelloworldaa1".rpartition("aa") #从右边开始
#21. string.replace( str1, str2, num=string.count(str1) ) 把string中str1替换成str2
print "hello world".replace( "l", "i", 2 )
#22. string.rfind() 从字符串右边开始查找
print "aaaaastringa".find("a")
print "aaaaastringa".rfind("a")
print "aaaaastringa".index("a")
print "aaaaastringa".rindex("a")
#23. string.split( str="", num=string.count(str) ) 以str为分隔符切片
print "hello,world".split(",")
#24. string.splitlines( num=string.count("\n") ) 按行分隔
print "hello\nworld".splitlines()
#25. string.startswith( str, beg=0, end=len(string) ) 检查字符串string是否以str开头
print "helloworld".startswith("hello")
#26. string.strip([obj]) 同时执行lstrip和rstrip
print "|" + " helloworld ".strip() + "|"
#27. string.swapcase() 翻转大小写
print "HELLO world".swapcase()
#28. string.title()
print "hello world".title()
#29. string.zfill(with) 返回长度为with的字符串,不够前面补0
print "hello".zfill(10)
a = "abc"
print id(a)
a = a + "dec"
print id(a)
s = "abcdefg"
print "%sC%s" % ( s[0:2], s[3:] )
s = u"我是李杰"
print unicode( s )
print ord( u"李" )
print unichr( 26446 )
#=========== ===== ===== ===== ===== =====
# 1. 程序员出现字符串一定要使用unicode字符串
# 2. 不要使用str()函数,用unicode()代替
# 3. 不要使用过时的string模块
# 4. 不到必须时不要在程序中使用encode和decode unicode字符串,除非要写入文件或者数据库
# UnicodeError异常是在exceptions中定义的,ValueError的字类
|
class Employee:
def __init__(self,f_name,s_name):
self.f_name=f_name
self.s_name = s_name
@property
def email(self):
return self.f_name + self.s_name +"@gmail.com"
@property
def full_name(self):
return "{} {}".format(self.f_name, self.s_name)
@full_name.setter
def full_name(self, name):
f_name,s_name = name.split(" ")
self.f_name = f_name
self.s_name = s_name
emp1=Employee("prasanna", "sekar")
emp2=Employee("kannan", "sekar")p
#emp1.full_name="hrithick roshan"
print(emp1.f_name)
print(emp1.email)
print(emp1.full_name)
|
class Employee:
num_of_emp = 0
raise_amt = 1.04
def __init__(self, name, age, email, pay):
self.name=name
self.age = age
self.email= email
self.pay = pay
Employee.num_of_emp += 1
def name_age(self):
return "{} age is {}".format(self.name, self.age)
def apply_raise(self):
self.pay = int(self.pay * self.raise_amt)
class Developer(Employee):
raise_amt = 1.10
def __init__(self, name, age, email, pay, prog_lang):
super().__init__(name,age,email,pay)
self.prog_lang = prog_lang
class Manager(Employee):
def __init__(self, name, age, email, pay, employees = None):
super().__init__(name, age, email, pay)
if employees is None:
self.employees = []
else:
self.employees = employees
def add_emp(self,emp):
if emp not in self.employees:
self.employees.append(emp)
return self.employees
def del_emp(self,emp):
if emp in self.employees:
self.employees.remove(emp)
def print_emp(self):
for emp in self.employees:
print (emp.name_age())
dev_1 = Developer("prasanna",25,"[email protected]",25000,"python")
dev_2 = Developer("kannan",30,"[email protected]", 30000,"java")
mgr_1 = Manager("ragu",35,"[email protected]",50000,[dev_1])
print(mgr_1.add_emp())
dev_1.__repr__()
|
#print the characters present at even index and odd index separately for the given string
s = input('enter the string: ')
print('print char in even index')
i=0
while i<len(s):
print(s[i])
i=i+2
print('enter char in odd index')
i=1
while i<len(s):
print(s[i])
i=i+2
print('char in odd index')
|
class A:
def __init__(self,a,b):
self.a = a
self.b = b
self.c = None
def add(self):
self.c = self.a + self.b
return self.c
obj=A(1,1)
print(obj.add())
class printer:
def __init__(self,obj):
self.obj = obj
def getobj(self):
return obj.add()
p=printer(obj)
print(p.getobj()) |
import sqlite3
import sys
if len(sys.argv) != 2:
print("One argument should be given")
sys.exit(1)
conn = sqlite3.connect('students.db')
c = conn.cursor()
c.execute('SELECT * FROM students WHERE house=? ORDER BY last, first', sys.argv[1:])
students = c.fetchall()
for student in students:
student = '|'.join([str(i) for i in student[1:]])
print(student)
conn.commit()
conn.close()
|
"""
authors: Zirong Chen, Haotian Xue
Evaluator for Dialogue System
11/27/2020
"""
from utils import bcolors, Sigmoid
class Evaluator(object):
def __init__(self, num_of_turns, task_reward, turn_penalty, score_factor):
self.num_of_turns = num_of_turns
self.task_completion = False
self.task_reward = task_reward
self.turn_penalty = turn_penalty
self.user_experience = None
self.user_name = "anonymous"
self.score_factor = Sigmoid(score_factor)
def getScores(self):
self.user_name = input(f"{bcolors.OKCYAN}What is your preferred name? {bcolors.ENDC}")
self.user_experience = int(input(f"{bcolors.OKCYAN}What is your rate for using this system (0-10)? {bcolors.ENDC}"))
# if self.user_experience > 10 or self.user_experience < 0:
# raise ValueError("Invalid input, please choose a correct one")
if self.user_experience > 10 or self.user_experience < 0:
print("Invalid input, please choose a correct one between 0-10")
self.user_experience = int(
input(f"{bcolors.OKCYAN}What is your rate for using this system (0-10)? {bcolors.ENDC}"))
self.task_completion = True if input(
f"{bcolors.OKCYAN}Did this system help you solve your problem? Y for yes, N for no {bcolors.ENDC}") == "Y" else False
turn_score = self.turn_penalty * self.num_of_turns
task_score = self.task_reward if self.task_completion else -self.task_reward
user_score = self.user_experience
total_score = user_score * self.score_factor + (turn_score + task_score) * (1 - self.score_factor)
fname = "UserScores/{}.txt".format(self.user_name)
with open(fname, 'a+', encoding='utf-8') as f:
f.write(str(total_score) + ", ")
return total_score
|
#!/usr/bin/env python
def red():
return chr(27)+"[91m"
def green():
return chr(27)+"[92m"
def off():
return chr(27)+"[0m"
def cyan():
return chr(27)+"[36m"
def yellow():
return chr(27)+"[33m"
def blink():
return chr(27)+"[5m"
def rred():
return chr(27)+"[41m"
def rgreen():
return chr(27)+"[42m"
BLACK=30
RED=31
GREEN=32
YELLOW=33
BLUE=34
MAGENTA=35
CYAN=36
WHITE=37
BG_BLACK=40
BG_RED=41
BG_GREEN=42
BG_YELLOW=43
COLORSET = [
BLACK,
RED,
GREEN,
YELLOW,
BLUE,
MAGENTA,
CYAN,
WHITE,
]
def color(n):
return chr(27)+"["+str(n)+"m"
if __name__ == "__main__":
for i in range(90,108):
print i,chr(27)+"["+str(i)+"mColor"+off()
for i in COLORSET:
print color(i)+str(i)+off()
for i in COLORSET:
print color(i+10)+str(i+10)+off()
print rred()+"RED"+off()
print rgreen()+"GREEN"+off()
|
# plot a function like y = sin(x) with Tkinter canvas and line
# tested with Python24 by vegaseat 25oct2006
from Tkinter import *
import math
import random
root = Tk()
root.title("Simple plot using canvas and line")
width = 900
height = 300
center = height//2
x_increment = 1
# width stretch
x_factor = 0.04
# height stretch
y_amplitude = 80
c = Canvas(width=width, height=height, bg='grey')
c.pack()
str1 = "sin(x)=blue cos(x)=red"
c.create_text(10, 20, anchor=SW, text=str1)
center_line = c.create_line(0, center, width, center, fill='green')
# create the coordinate list for the sin() curve, have to be integers
xy1 = []
for x in range(width):
# x coordinates
xy1.append(x * x_increment)
# y coordinates
xy1.append(int(math.sin(x * x_factor) * y_amplitude) + center)
#sin_line = c.create_line(xy1, fill='blue')
# create the coordinate list for the cos() curve
xy2 = []
for x in range(width):
# x coordinates
xy2.append(x * x_increment)
# y coordinates
xy2.append(int(math.cos(x * x_factor) * y_amplitude) + center)
#cos_line = c.create_line(xy2, fill='red')
# create a random line
rl = []
for x in range(width):
r = random.randint(1,height)
rl.append(x * x_increment)
rl.append(r)
rline = c.create_line(rl, fill='blue')
root.mainloop()
|
# This program is written in Python3
def detect_edge(present_value, previous_value):
different = present_value - previous_value
if (different == 1):
edge = 1
else:
edge = 0
return edge
|
import time
def collatz_step(n):
if n % 2 == 0:
return int(n/2)
return int(3*n + 1)
def stepcount(n):
next = n
count = 0
while next != 1:
next = collatz_step(next)
count += 1
return count
def solve(n):
start = time.time()
stepcache = [0] * n
max_step_count = 0
max = 0
for i in range(2, n):
if stepcache[i] != 0:
current_step_count = stepcache[i]
else:
current_step_count = stepcount(i)
stepcache[i] = current_step_count
if current_step_count > max_step_count:
max = i
max_step_count = current_step_count
end = time.time()
print(end - start, 'seconds')
return max |
import math
import sympy
def isPalindrome(n):
list = [int(x) for x in str(n)]
for i in range(0, len(list)):
if i < len(list) / 2:
if list[i] != list[len(list) - 1 - i]:
return False
return True
palindromes = []
for i in range(100,999):
for j in range(100,999):
product = i*j
if isPalindrome(product):
palindromes.append(product)
|
def sum_of_squares(n):
sum = 0
for i in range(1, n + 1):
sum += i*i
return sum
def square_of_sum(n):
sum = 0
for i in range(1, n + 1):
sum += i
return sum*sum
|
import math
#42 spaces. Will print introduction header.
def introduction_header():
print("*" * 42)
print("{title:^42}".format(title = "CURVED GRADE CALCULATOR"))
print("*" * 42)
#42 spaces. Will print course header for average printing.
def course_header():
print("{title: ^42}".format(title = "*Course Final Grades Report*"))
print("{name:<14}{average:^14}{grade:>14}".format(name = "Name", average = "Average", grade = "Grade"))
print("-" * 42)
print()
#26 spaces, prints the summary heading
def summary_header():
print("{summary:^26}".format(summary = "Summary"))
print("-" * 26)
#Finding the mean by dividing the total averages scores to the amount of accumulated averages.
def find_mean(tot_averages,accum_averages):
mean = tot_averages / len(accum_averages)
return mean
#Median
#Will find the median. Copying the list, avoiding referencing the object. Then sort the copied list, and finding the middle value for the median.
#If it is an odd list, then we take the two middle values in the list, add them and divide by two to find the median.
def find_median(accum_averages):
if len(accum_averages) % 2 == 1:
copy_list = list(accum_averages)
copy_list.sort()
median = copy_list[int(len(copy_list)) // 2]
return median
else:
copy_list = list(accum_averages)
copy_list.sort()
position = len(copy_list) // 2
high = copy_list[position]
low = copy_list[position-1]
median = (high + low) / 2
return median
#Variance
def find_variance(vals):
mean = find_mean(tot_averages,accum_averages)
total = 0
for val in vals:
total = total + (val-mean)**2
variance = total / len(vals)
return variance
#Find population standard deviation
def find_stdev(vals):
return math.sqrt(find_variance(vals))
#finds min by sorting a copy of the accum_averages
def find_min(accum_averages):
copy = list(accum_averages)
copy.sort()
minimum = copy[0]
return minimum
#Finds max by sorting a copy of the accum_averages
def find_max(accum_averages):
copy = list(accum_averages)
copy.sort()
maximum = copy[-1]
return maximum
#Obtaining grade letter to print and appending letter lists with the respected letter grades.
def find_letter_grade(accum_averages,stdev,mean):
letters = []
for val in accum_averages:
if val >= mean + (1.25 * stdev):
letters.append("A")
elif val >= mean + (0.25 * stdev):
letters.append("B")
elif val >= mean - (1 * stdev):
letters.append("C")
elif val >= mean - (2 * stdev):
letters.append("D")
elif val < mean - (2 * stdev):
letters.append("F")
return letters
#Gets the letter frequencies using a libary.
def get_letter_frequencies(letters):
freqs = {}
for letter in letters:
if letter in freqs:
freqs[letter] = freqs[letter] + 1
else:
freqs[letter] = 1
return freqs
#find mode in the letters list
def find_mode(letters):
mode = []
freqs = {}
most = 0
for letter in letters:
if letter in freqs:
freqs[letter] = freqs[letter] + 1
else:
freqs[letter] = 1
if freqs[letter] > most:
most = freqs[letter]
for letter in freqs:
if freqs[letter] == most:
mode.append(letter)
return mode[0]
#Code that prints the output of final results. This will take all values in parameters after the end of the program when all
#variables are found.
def summary_header(mean,median,stdev,minimum,maximum,mode,frequencies):
print("\n{summary:^20}".format(summary = "Summary"))
print("-" * 20)
print("{Mean:<10}{mean:>10.2f}".format(Mean = "Mean", mean = mean))
print("{Median:<10}{median:>10.2f}".format(Median = "Median", median = median))
print("{StDev:<10}{stdev:>10.2f}".format(StDev = "StDev", stdev = stdev))
print("{Minimum:<10}{minimum:>10.2f}".format(Minimum = "Minimum", minimum = minimum))
print("{Maximum:<10}{maximum:>10.2f}".format(Maximum = "Maximum", maximum = maximum))
print("{common:<10} {mode}".format(common = "Most common grade:", mode = mode))
print("{number_of:<10}{frequencies:>10}".format(number_of = "# of A's", frequencies = frequencies['A']))
print("{number_of:<10}{frequencies:>10}".format(number_of = "# of B's", frequencies = frequencies['B']))
print("{number_of:<10}{frequencies:>10}".format(number_of = "# of C's", frequencies = frequencies['C']))
print("{number_of:<10}{frequencies:>10}".format(number_of = "# of D's", frequencies = frequencies['D']))
print("{number_of:<10}{frequencies:>10}".format(number_of = "# of F's", frequencies = frequencies['F']))
print("Thank you for using this program.")
#print introduction header
introduction_header()
file = input("Enter name of test scores file: ")
print("test_scores.txt\n")
course_header()
myfile = open(file,"r")
first_line = True #initialize this variable and set it to true, but will change to flase after first iteration.
accum_students = []#List to hold all students
average = 0 #Initializing average
accum_averages = [] #List that holds the averages of all students
tot_averages = 0 #variable that will iterate through a for loop to obtain the total number of the accumalated average scores.
mean = 0 #variable that after obtaining the total_averages, will find the mean by tot_averages / len(accum_averages)
median = 0 #Initializing median
for line in myfile: #looping through file.
if first_line == False:
line = line.strip()
parts = line.split("\t") #will contain the part seperated by a tab.
#Get all student_num, averages, and grade letters
#This if statement will determine the data line without "F10" being present on parts[5], which is the last test score.
#The elif statement will determine the data line with the "F10" being present on parts[5] to remove the "F10" and keep the score only.
if "Student_" in parts[0] and "F10" not in parts[5] : #This will check if parts begin with row "Student_" to seperate data with title.
students = parts[0]
accum_students.append(students)
scores = [int(i) for i in parts[1:]]
average = float(scores[0] + scores[1] + scores[2] + scores[3] + scores[4]) / 5 #Getting the average by dividing the scores in list by how many elements (test scores).
accum_averages.append(average) #Will append the average to the accum_average list to later find the mean.
elif "Student_" in parts[0] and "F10" in parts[5]:
students = parts[0]
accum_students.append(students)
scores = [int(i) for i in parts[1:5]]
score_with_letter = parts[5][0:2] #Accessing student_9 because of elif condition, then retrieving the first two string characters, removing "F10."
scores.append(int(score_with_letter)) #Appending the score after removing "F10" and then converting the first two digits "87" into an integer to append to scores.
average = float(scores[0] + scores[1] + scores[2] + scores[3] + scores[4]) / 5 #Getting the average by dividing the scores in list by how many elements (test scores)
accum_averages.append(average) #Will append the average to the accum_average list to later find the mean.
first_line = False
myfile.close()
#This will obtain the total number of averages in the loop stored into tot_averages.
for i in accum_averages:
tot_averages += i
#Mean
mean = find_mean(tot_averages,accum_averages)
#Median
median = find_median(accum_averages)
#Variance
variance = find_variance(accum_averages)
stdev = find_stdev(accum_averages)
#Minimum
minimum = find_min(accum_averages)
#Maximum
maximum = find_max(accum_averages)
#Obtaining grade letter to print and appending letter lists with the respected letter grades.
letters = find_letter_grade(accum_averages,stdev,mean)
#Printing the student columns and rows. Will print the student, average for student and letter grade received for each student.
for index in range(len(accum_students)):
print(f"{accum_students[index]:<14}{accum_averages[index]:^14.2f}{letters[index]:>14}")
#Frequency
frequencies = get_letter_frequencies(letters)
#Most common grade
mode = find_mode(letters)
#Print the summary
summary_header(mean,median,stdev,minimum,maximum,mode,frequencies)
|
from datetime import datetime
current_date = datetime.now()
print(str(current_date))
print("Day: " + str(current_date.day))
print("Month: " + str(current_date.month))
print("Year: " + str(current_date.year))
|
# asal sayi olup olmadigini bulan program
sayi = int(input("Bir sayi giriniz:"))
# 1'den buyuk olup olmadigini kontrol etme
if sayi > 1:
for i in range(2,sayi):
if (sayi % i) == 0:
print(sayi,"asal sayi degildir.")
print(i, " x ", sayi//i, " = " , sayi)
break
else:
print(sayi,"asal sayidir.")
#Eger girilen sayi 1 yada 1'den kucukse
else:
print(sayi,"asal sayi degildir.") |
sayilar = [1,3,5,7,9,12,19,21]
# Sayıların 3'ün katı durumu?
# for ucKati in sayilar:
# if ucKati %3 == 0:
# print(ucKati)
# Sayıların toplamı
# toplam = 0
# for sayi in sayilar:
# toplam += sayi
# print(toplam)
# Tek Sayıların karelerini alma
# for sayi in sayilar:
# if sayi%2 == 1:
# sayi = sayi ** 2
# print(sayi)
# Karakter sayıs 10'un altında olan şehirler yazdırma
# sehirler = ["bern","atina","moscow","tokyo","manila","jakarta"]
# for sehir in sehirler:
# if len(sehir) < 10:
# print(sehir)
#fiyat toplamı yazdırma
# urunler = [
# {"name":"iPhone SE","price":"400"},
# {"name":"iPhone 11","price":"1000"},
# {"name":"iPhone 11 Pro","price":"1100"},
# {"name":"iPhone 12","price":"950"},
# {"name":"iPhone 8","price":"350"},
# {"name":"iPhone XR","price":"420"}
# ]
# toplam = 0
# for phones in urunler:
# fiyat = int(phones["price"])
# toplam += fiyat
# print(toplam)
|
q=1
dizi=[]
while True:
try:
a=int(input(f'{q}. kenari giriniz: '))
if a<0:
print("Lütfen pozitif sayi girin")
continue
dizi.append(a)
q=q+1
if len(dizi)==3:
break
except Exception:
print("Lütfen bir sayi girin")
x=dizi[0]
y=dizi[1]
z=dizi[2]
if (abs(x+y)>z and abs(x+z)>y and abs(y+z)>x):
if (x==y and x==z and y==z):
print("Bu bir eskenar ucgendir.")
elif (x==y or x==z or y==z):
print("Bu bir ikizkenar ucgendir.")
else:
print("Bu bir cesitkenar ucgendir.")
else:
print("Ucgen olma kosullarını saglamıyor!")
|
#!/usr/bin/python3
import argparse
import random
import math
import sys
def entropy(words, n):
return n * math.log(len(words), 2)
def make_password(words, n):
rand = random.SystemRandom()
return ' '.join(rand.choice(words) for _ in range(n))
def main():
argparser = argparse.ArgumentParser()
argparser.add_argument('words', nargs='?', default='/usr/share/dict/words')
argparser.add_argument('n')
args = argparser.parse_args()
with open(args.words) as f:
words = [w.strip() for w in f]
n = int(args.n)
print('theoretical maximum entropy: {} bits'.format(entropy(words, n)),
file=sys.stderr)
print('continue? [y/N] ', end='', file=sys.stderr)
if input() in ('y', 'Y', 'yes', 'Yes'):
print(make_password(words, n))
if __name__ == '__main__':
main()
|
# Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.
# Example 1:
# Input:nums = [1,1,1], k = 2
# Output: 2
# Note:
# The length of the array is in range [1, 20,000].
# The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].
# O(n) time
# O(n) space, worst case
class Solution:
def subarraySum(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
dic = {0:1}
res = cursum = 0
for num in nums:
cursum += num
if cursum - k in dic:
res += dic[cursum - k]
dic[cursum] = dic.get(cursum, 0) + 1
return res
"""
suppose running sum 0:j = cursum
then sum of i:j = k if some running sum 0:i-1 = cursum - k exists for (multiple) i
0_____i_____j_____
"""
|
def check_prime(number):
for divisor in range(2,int(number**0.5)+1): # square root of a number + 1
if number%divisor == 0:
return False
#divisor += 1
return True
class Primes():
def __init__(self,max):
self.max = max
self.number = 1
def __iter__(self):
return self
def __next__(self):
self.number+=1
if self.number >= self.max:
raise StopIteration
elif check_prime(self.number):
return self.number
else:
return self.__next__()
prime = Primes(10)
for x in prime:
print(x)
#same logic using generator
def Primes_gen(max):
number = 1
while number < max:
number+=1
if check_prime(number):
yield number
prime_gen = Primes_gen(10)
for x in prime_gen:
print(x)
|
#!/usr/local/bin/python
from dataclasses import dataclass
from typing import List
import os
import sys
@dataclass
class Photo:
position: str
tagsCount: int
tags: List[str]
def AddTag(self,tag):
self.tags.append(tag)
class Slide:
def __init__(self,slide):
self.slide = slide
def CheckPosition(self):
pass
def AverageTagsPerPhoto(photosList):
return allTagsCount/len(photosList)
photosList = []
allTagsCount = 0
pathToFile = os.getcwd() + "/QualificationRound2019.in/" + sys.argv[1]
with open(pathToFile) as fileObject:
photosCount = int(fileObject.readline())
#print(photosCount)
for i in range(photosCount):
photo = fileObject.readline().rstrip().split(' ')
tagsCount = int(len(photo[2:]))
position = photo[0]
photosList.append(Photo(position,tagsCount,[]))
allTagsCount += tagsCount
# print(f'Tags count: {tagsCount}')
for j in range(tagsCount):
tag = photo[j+2].rstrip()
#print(f'Tag: {tag}', end= " ")
photosList[i].AddTag(tag)
#for x in photosList:
#print(f'Tags count: {x.tagsCount}')
#print(f'Tags list: {x.tags}')
print(f'Photos count: {len(photosList)}')
print(f'Average tags per photo: {AverageTagsPerPhoto(photosList)}')
print(f'All tags: {allTagsCount}')
|
# Implementation of classic arcade game Pong
import simplegui
import random
# initialize globals - pos and vel encode vertical info for paddles
WIDTH = 600
HEIGHT = 400
BALL_RADIUS = 20
PAD_WIDTH = 8
PAD_HEIGHT = 80
HALF_PAD_WIDTH = PAD_WIDTH / 2
HALF_PAD_HEIGHT = PAD_HEIGHT / 2
ball_pos = [WIDTH//2, HEIGHT//2]
ball_vel = [0,0]
paddle1_pos = HEIGHT//2
paddle2_pos = HEIGHT//2
paddle1_vel = 0
paddle2_vel = 0
score1 = 0
score2 = 0
total_score = "0 / 0"
# helper function that spawns a ball by updating the
# ball's position vector and velocity vector
# if right is True, the ball's velocity is upper right, else upper left
def ball_init(right):
global ball_pos, ball_vel # these are vectors stored as lists
ball_pos = [WIDTH//2, HEIGHT//2]
hor = random.randrange(120, 240)
ver = -random.randrange(60, 180)
if not right:
hor *=-1
ball_vel[0] = hor/60
ball_vel[1] = ver/60
# define event handlers
def new_game():
global paddle1_pos, paddle2_pos, paddle1_vel, paddle2_vel # these are floats
global score1, score2 # these are ints
score1, score2 = 0, 0
ball_init(True)
paddle1_pos = HEIGHT//2
paddle2_pos = HEIGHT//2
def update_paddle(paddle_pos, vel):
if paddle_pos + vel >= HALF_PAD_HEIGHT and paddle_pos + vel <= HEIGHT - HALF_PAD_HEIGHT:
paddle_pos += vel
return paddle_pos
def draw(c):
global total_score, score1, score2, paddle1_pos, paddle2_pos, ball_pos, ball_vel, paddle1_vel, paddle2_vel
# update paddle's vertical position, keep paddle on the screen
paddle1_pos = update_paddle(paddle1_pos, paddle1_vel)
paddle2_pos = update_paddle(paddle2_pos, paddle2_vel)
# draw mid line and gutters
c.draw_line([WIDTH / 2, 0],[WIDTH / 2, HEIGHT], 1, "White")
c.draw_line([PAD_WIDTH, 0],[PAD_WIDTH, HEIGHT], 1, "White")
c.draw_line([WIDTH - PAD_WIDTH, 0],[WIDTH - PAD_WIDTH, HEIGHT], 1, "White")
# draw paddles
c.draw_line([HALF_PAD_WIDTH, paddle1_pos - HALF_PAD_HEIGHT], [HALF_PAD_WIDTH, paddle1_pos + HALF_PAD_HEIGHT], PAD_WIDTH, "White")
c.draw_line([WIDTH - HALF_PAD_WIDTH, paddle2_pos - HALF_PAD_HEIGHT], [WIDTH - HALF_PAD_WIDTH, paddle2_pos + HALF_PAD_HEIGHT], PAD_WIDTH, "White")
c.draw_text(str(score1), (WIDTH//2-120, HEIGHT//2 - 100), 50, "Red", "serif")
c.draw_text(str(score2), (WIDTH//2+100, HEIGHT//2 - 100), 50, "Red", "serif")
# update ball
if ball_pos[1] <= BALL_RADIUS or ball_pos[1] >= HEIGHT - BALL_RADIUS - 1:
ball_vel[1] *=-1
if ball_pos[0] <= BALL_RADIUS + PAD_WIDTH:
if abs(ball_pos[1] - paddle1_pos) <= HALF_PAD_HEIGHT:
ball_vel[0] *= -1.1
ball_vel[1] *= 1.1
else:
score2 += 1
ball_init(True)
elif ball_pos[0] >= WIDTH - BALL_RADIUS - PAD_WIDTH:
if abs(ball_pos[1] - paddle2_pos) <= HALF_PAD_HEIGHT:
ball_vel[0] *= -1.1
ball_vel[1] *= 1.1
else:
score1 += 1
ball_init(False)
total_score = str(score1) + " - " + str(score2)
ball_pos[0] += ball_vel[0]
ball_pos[1] += ball_vel[1]
# draw ball and scores
c.draw_circle(ball_pos, BALL_RADIUS, 2, "White", "White")
def keydown(key):
global paddle1_vel, paddle2_vel
acc = 5
if key==simplegui.KEY_MAP["w"]:
paddle1_vel -= acc
elif key==simplegui.KEY_MAP["s"]:
paddle1_vel += acc
elif key==simplegui.KEY_MAP["up"]:
paddle2_vel -= acc
elif key==simplegui.KEY_MAP["down"]:
paddle2_vel += acc
def keyup(key):
global paddle1_vel, paddle2_vel
acc = 5
if key==simplegui.KEY_MAP["w"]:
paddle1_vel += acc
elif key==simplegui.KEY_MAP["s"]:
paddle1_vel -= acc
elif key==simplegui.KEY_MAP["up"]:
paddle2_vel += acc
elif key==simplegui.KEY_MAP["down"]:
paddle2_vel -= acc
# create frame
frame = simplegui.create_frame("Pong", WIDTH, HEIGHT)
frame.set_draw_handler(draw)
frame.set_keydown_handler(keydown)
frame.set_keyup_handler(keyup)
button2 = frame.add_button("Restart", new_game, 50)
# start frame
frame.start()
new_game()
# http://www.codeskulptor.org/#user13_wan0gCdD3GFk857.py |
import os
import subprocess
import glob
import string
def format_filename(filename):
'''
Changes filenames and gets rid of any characters that might break the code.
'''
valid_chars = "-_. %s%s" % (string.ascii_letters, string.digits)
filename = ''.join(char for char in filename if char in valid_chars)
return filename
def clean_folder(client_folder):
'''
Goes through each folder and checks if the filenames are acceptable.
ex: clean_folder('/Users/matthewwong/Desktop/A1')
'''
for folder in os.listdir(client_folder):
filepath = client_folder + '/' + folder
if not folder.startswith('.'):
for filename in os.listdir(filepath):
os.rename(filepath + '/' + filename, \
filepath + '/' + format_filename(filename))
def decrypt_pdf(filename):
'''
Decrypts a PDF so they can be run through PDFminer to extract the text.
Also makes folders for client if none exists.
ex: decrypt_pdf('/Users/matthewwong/Desktop/Insurance.pdf')
Subprocess example:
subprocess.call(["qpdf", "--password=''", "--decrypt", "input_file", "output_file"])
'''
decrypted_file = "/Users/matthewwong/dsi-capstone/PDFs/decrypted_test/"
client_folder = filename.split('/')[-3]
folder = filename.split('/')[-2]
pdf = filename.split('/')[-1]
if not os.path.exists(decrypted_file + client_folder):
os.makedirs(decrypted_file + client_folder)
if not os.path.exists(decrypted_file + client_folder + '/' + folder):
os.makedirs(decrypted_file + client_folder + '/' + folder)
lst = ["qpdf", "--password=''", "--decrypt", filename, \
decrypted_file + client_folder + '/' + folder + '/' + pdf]
subprocess.call(' '.join(map(lambda x: x.replace(' ', '\ '), lst)),
shell=True)
def decrypt_folder(client_folder):
'''
Decrypts a folder so the PDFs can be run through PDFminer to extract text.
ex: decrypt_folder('/Users/matthewwong/Desktop/A1')
'''
# looks at all the folders in the client folder
for folder in os.listdir(client_folder):
filepath = str(client_folder) + '/' + folder
if not folder.startswith('.'):
# looks at the files in those folders
for filename in os.listdir(filepath):
# list of all the pdfs
pdfs = glob.glob(filepath + '/' + '*.pdf')
# adds files ending with caps
if filename.endswith('PDF'):
pdfs.append(filepath + '/' + filename)
for pdf in pdfs:
decrypt_pdf(pdf)
def decrypt(client_folder):
'''
Decrypts a client's entire folder.
ex: decrypt('/Users/matthewwong/Desktop/A1')
'''
clean_folder(client_folder)
decrypt_folder(client_folder)
|
import sys
def y_d(x):
list=["Jan","Feb","Mar","Apr","may","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
c=31
v=x/c
w=x%c
if w>30:
b=w/30
w=w%30
a=v+b
else:
a=v
if a>12:
a = a-12
return (str(w)+list[a-1])
def main():
x = input("Enter your numbers:" )
print y_d(x)
if __name__ == '__main__':
main()
|
'''
利用parse模块模拟post请求
分析百度词典
分析步骤:
1、打开F12
2、
'''
from urllib import request,parse
import json
if __name__ == '__main__':
baseurl = 'http://fanyi.baidu.com/sug'
#存放用来模拟form的数据一定是dict格式
data = {
'kw':'girl'
}
#需要使用parse模块对data进行编码
data = parse.urlencode(data).encode("utf-8")
#我们需要构造一个请求头,请求头应该至少包含传入的数据长度
headers = {
#因为用post请求,至少应该包含content-length字段
'Content-Length':len(data)
}
req = request.Request(url=baseurl,data=data,headers=headers)
#因为已经构造了一个Request请求实例,则所有的请求信息都可以封装在Request里面
rsp = request.urlopen(req)
json_data = rsp.read().decode()
#把json字符串转换成字典
json_data=json.load(json_data)
print(json_data)
for item in json_data['data']:
print(iten['k'],"--",item['v']) |
import sys
import os
if __name__ == '__main__':
try:
class node(object):
def __init__(self):
self.data = None
self.pointers = []
class tree(object):
Z = 0
clild=[]
def __init__(self):
self.root = None
def insert_root(self,data):
if (self.root == None):
nnode = node()
nnode.data = data
self.root = nnode
#elif not self.root.pointers:
else:
nnode = node()
nnode.data = data
#input_search = input('Enter search element')
self.root.pointers.append(nnode)
#else:
# print('E')
def insert(self,data,list_node,search_element):
# if self.root == None:
# nnode =node()
# nnode.data = data
# self.root = nnode
# return True
# elif not self.root.pointers:
# nnode = node()
# nnode.data = data
# self.root.pointers.append(nnode)
# return True
self.list_node_list = []
if not list_node:
print('Not found that element')
return False
else:
for leafNode in list_node:
#condition
if leafNode.data == search_element:
print('Found')
nnode = node()
nnode.data = data
leafNode.pointers.append(nnode)
return True
else:
for subs in leafNode.pointers:
self.list_node_list.append(subs)
return self.insert(data,self.list_node_list,search_element)
def root_leaf_list(self):
self.leaf_list = []
leaf_len=len(self.root.pointers)
for i in range(0,leaf_len):
self.leaf_list.append(self.root.pointers[i])
return self.leaf_list
def leafs(self,return_list):
if not return_list:
print('Empty list')
return False #cause there is no leaf node left
else:
self.gather_ton_of_leaf_node = []
for leafNode in return_list:
#print(leafNode.data)
for sub in leafNode.pointers:
self.gather_ton_of_leaf_node.append(sub)
print('====')
for i in self.gather_ton_of_leaf_node:
print(i.data)
print('====')
return self.leafs(self.gather_ton_of_leaf_node)
#def traversalPos(self):
#will start from here
obj = tree()
obj.insert_root(4)
obj.insert_root(10)
obj.insert_root(20)
X = obj.root_leaf_list()
obj.insert(30,X,10)
obj.insert(40,X,20)
obj.insert(50,X,10)
obj.insert(60,X,10)
#obj.printt(hhead)
# if not X[2].pointers:
# print('None')
# else:
# print('have elements')
# for i in X:
# print(i.data)
obj.leafs(X)
except KeyboardInterrupt:
try:
print('\n')
sys.exit(0)
except SystemExit:
print('\n')
os._exit(0)
#output
# Not found that element
# 10
# 20
# 40
# 50
# 60
# Empty list
# ➜ src git:(master) ✗ python3 tree.py
# Not found that element
# Found
# Found
# Found
# 10
# 20
# 40
# 50
# 60
# Empty list
# ➜ src git:(master) ✗ python3 tree.py
# Not found that element
# Not found that element
# Found
# Found
# 10
# 20
# 50
# 60
# Empty list
# ➜ src git:(master) ✗ python3 tree.py
# Not found that element
# Not found that element
# Not found that element
# Found
# 10
# 20
# 60
# Empty list
|
import json
from difflib import get_close_matches
dictionary = json.load(open("dictionary.json"))
def get_definition(target_word):
# Convert target to lower case to eliminate case sensitivity
target_word = target_word.lower()
# If the target is contained within the dict
if target_word in dictionary:
# Retrieve the definition from the dict
definition = dictionary[target_word]
# Return a formatted string of the word (key) and definition (value)
return f"{target_word}: {definition}"
else:
# Using the sequence comparison module difflib to find close matches
close_matches = get_close_matches(target_word, dictionary.keys())
# If any close matches are found, present the to the user and ask them to select one
if len(close_matches) > 1:
print(
f"Your word was not found. Here are up to 3 close matches for your original input: {close_matches}. ", end='')
user_selection_index = int(
input("Type 1-3 to select a word. \n")) - 1
# Change the target to the newly selected word from close matches
corrected_target_word = close_matches[user_selection_index]
# Retrieve the definition of the new target
definition = dictionary[corrected_target_word]
# Return a formatted string of the new word (key) and definition (value)
return f"{corrected_target_word}: {definition}"
# If no close matches are found, tell the user the word nor any close matches were found
else:
return f"{target_word} not found. No similar words found either. Please try another word!"
user_word = input("Please enter a word to search the dictionary for: \n")
print(get_definition(user_word))
|
def prob_10 (p1, p2, p3):
p1 = ()
p2 = ()
p3 = ()
n1x=int(input("ingrese el punto x: "))
p1.append(n1x)
n1y=int(input("ingrese el punto y: "))
p1.append(n1y)
return (p1) |
class Vehicle():
def __init__(self,model,color,price):
self.model=model
self.color=color
self.price=price
def print(self):
print("Model:",self.model,"Color:",self.color,"Price",self.price)
def __str__(self): #method is the string representation of object,to work when we call print(objec)
return self.model+str(self.price) # return takes only one value, and --str method return only striong so conactenation applied
car=Vehicle("Xuv","Black","10l")
car.print()
print(car) |
str=input("Enter the string to check palindrome:")
rev=str[::-1]
if str==rev:
print("The string is paliandrome")
else:
print("The string is not paliandrome") |
s1=set()
limit=int(input("Enter the limit for your set:"))
for i in range(limit):
num=input("Enter the element:")
s1.add(num)
print(s1) |
# to separate odd and even numbers from one set to another two sets
set1={0,23,25,45,67,68,86,44,34,25,69,70,98,100}
odd=set()
even=set()
for i in set1:
if i%2==0:
odd.add(i)
else:
even.add(i)
print("The set with odd num is:",odd)
print("The set with even num is:",even) |
# num1=int(input("Enter the number:"))
# num2=int(input("Enter the number:"))
# print(num1/num2)
# in this if yoy give num2 as 0 you will get a zero division error. To handle this kind of errors we have to do exception handling
#EXCEPTION HANDLING HAS THREE block
# try .... to write the code that can cause exception. it will work all time
# except ..... solving code
# finally .... anything
num1=int(input("Enter the number:"))
num2=int(input("Enter the number:"))
try:
print(num1/num2)
except Exception as e: # From module get the exception error to e variable
print("exception occured",e)
finally:
print("Done")
|
#The __str__ method is useful for a string representation of the object,
# either when someone codes in str(your_object), or even when someone might do print(your_object).
class Employee:
compnay="ABC"
def __init__(self,name,id,salar,exp):
self.name=name
self.id=id
self.salary=salar
self.exp=exp
def printval(self):
print("Name:",self.name,"ID:",self.id)
def __str__(self):
return self.name+" "+str(self.exp)
emp=Employee("Anju",1234,3.5,4)
print(emp) # calls the object and then it will pass to __str__ method and returns the value from there |
# TWO TYPES OF VARIABLES
# Static variable: related to class ... access using class name
# instance variable..... related to method ... access using self
class Book:
category="Fiction" #Static variable
def setval(self,name,author,nopages):
self.name=name
self.author=author
self.pages=nopages
def printinfo(self):
print("Book name:",self.name)
print("author:",self.author)
print("category:",Book.category) # printing static variable
print("No of pages:",self.pages)
book1=Book()
book1.setval("Shages of twilight","Linda Howard",456)
book1.printinfo()
book2=Book()
book2.setval("Alchemist","paolo coehlo",560)
book2.printinfo()
|
import re
file=open("phone num","r")
rule="[+][9][1][\d]{10}"
for i in file:
num=i.rstrip()
match=re.fullmatch(rule,num)
if match is not None:
print(num,":Valid")
else:
print(num,":Not valid") |
class Calculator:
def __init__(self,num1,num2):
self.num1=num1
self.num2=num2
def add(self):
print("The sum is:",self.num1+self.num2)
def diif(self):
print("The difference is :", self.num1-self.num2)
def div(self):
print("The division result is:",self.num1/self.num2)
def mul(self):
print("The product is:",self.num1*self.num2)
calc1=Calculator(12,23)
calc1.add()
calc1.diif()
calc1.div()
calc1.mul() |
class College:
def setval(self,clgname,place,nodept):
self.clgname=clgname
self.place=place
self.nodept=nodept
def printinfo(self):
print("College Name:",self.clgname)
print("Place:",self.place)
print("No of Departments:",self.nodept)
class Employee(College):
def emp(self,name,id,job):
self.name=name
self.id=id
self.job=job
print("Employee Details are:",self.name,self.id,self.job)
class Teachers(Employee):
def std(self,dept):
self.dept=dept
print("Department:",self.dept)
# Single Inheritance
print("Single inheritance")
emp1=Employee()
emp1.setval("VJEC","Kannur",7)
emp1.printinfo()
emp1.emp("Sneha",23,"Teacher")
# Multilevel Inheritance
print("Multilevel inheritance")
t1=Teachers()
t1.setval("Ajec","Thrissur",6)
t1.printinfo()
t1.emp("Anju","1234","Librarian")
t1.std("CSE")
class Department():
def dept(self,dep):
self.dep=dep
print("Department:",self.dep)
class Student(College,Department):
def info(self,name,id):
self.name=name
self.id=id
print(self.name,self.id)
print("Multiple iheritance")
std1=Student()
std1.setval("Ajec","Thrissur",6)
std1.printinfo()
std1.dept("Cse")
std1.info("Akhil",17)
|
# constructor to intialize instance variables
# constructor automatically invoke when object creates
class Person:
def __init__(self,name,age):
self.name=name
self.age=age
def info(self):
print("Name:",self.name)
print("Age:",self.age)
person1=Person("Abc",25)
person1.info()
|
# # List comprehensions are used for creating new lists from other iterables.
# # As list comprehensions return lists, they consist of brackets containing the expression,
# # which is executed for each element along with the for loop to iterate over each element.
a=[1,23,34,43,65,13,6733,66,87,25,6,6,23]
# b=[]
# for i in a:
# b.append(i*5)
# print(b)
b=[i*5 for i in a] #list comprehension create another list from an exising list
print(b)
|
def add():
num1 = float(input("enter the first number1:"))
num2 = float(input("enter the second number:"))
print("The result is:",num1+num2)
def sub():
num1 = float(input("enter the first number1:"))
num2 = float(input("enter the second number:"))
print("The result is:",num1-num2)
def mul():
num1 = float(input("enter the first number1:"))
num2 = float(input("enter the second number:"))
print("The result is:",num1*num2)
def div():
num1 = float(input("enter the first number1:"))
num2 = float(input("enter the second number:"))
print("The result is:",num1/num2)
a=False
print("Select operation:\n 1.addition \n 2.subtraction \n 3.multiplication \n 4.division \n 5.exit")
while not a:
choice=int(input("enter your choice:"))
if choice==1:
add()
elif choice==2:
sub()
elif choice==3:
mul()
elif choice==4:
div()
else:
a=True |
class Bank:
def setval(self,name,accountno):
self.name=name
self.accountno=accountno
self.balance=5000
def withdraw(self):
c=int(input ("enter the amount to withdraw:"))
if c<self.balance:
self.balance=self.balance-c
print("amount withdraw done: your current balance is:",self.balance)
def deposit(self):
a=int(input("Enter the amount to deposit:"))
self.balance=self.balance+a
print("Your balance is:",self.balance)
custom1=Bank()
custom1.setval("anju",12345)
custom1.deposit()
custom1.withdraw()
|
users={
1000:{"acconu_num":1000,"password":"user1","balance":3000},
1001: {"acconu_num": 1001, "password": "user2", "balance": 4000},
1002: {"acconu_num": 1002, "password": "user2", "balance": 5000},
1003: {"acconu_num": 1003, "password": "user3", "balance": 6000}
}
# Check for username and password
def validate(**kwargs):
accno=kwargs["accno"]
passw=kwargs["password"]
if accno in users:
if passw==users[accno]["password"]:
print("Succes")
else:
print("Wrong password")
else:
print("Invalid accountno")
user=int(input("Enter the account number:"))
passw=input("Enter the password:")
validate(accno=user,password=passw) |
from enum import *
class Color(Enum):
blue = "blue"
green = "green"
yellow = "yellow"
red = "red"
class TypeOfDecorations(Enum):
garland = "garland"
wreath = "wreath"
toys = "toys"
lighting = "lighting"
class Decoration:
def __init__(self, decoration_place, type_of_decoration, color):
self.decoration_place = decoration_place
self.type_of_decoration = type_of_decoration
self.color = color
def __str__(self):
return "Type of decorations " + str(self.type_of_decoration) + ", decoration place " + \
str(self.decoration_place) + ", color " + str(self.color) + ", "
|
people = {'football','messi','barcelona','football'}
print(people)
#sets will automatically remove duplicate value
number1 = {1,2,3,4,5}
number2 = {4,5,6,7,8}
#do an operation or union
print(number1 | number2)
|
import unbreakable
class Person:
""" Superclass for the classes Sender and Receiver"""
def __init__(self):
self.cipher = None
self.key = ""
self.encoded_message = ""
def set_key(self, key):
self.key = key
def get_key(self):
return self.key
def set_cipher(self, cipher):
self.cipher = cipher
def get_cipher(self):
return self.cipher
def set_encoded_message(self, encoded_message):
self.encoded_message = encoded_message
def get_encoded_message(self):
return self.encoded_message
def operate_cipher(self):
""" Encodes or decodes a message """
class Sender(Person):
""" Encrypts a chosen message """
def __init__(self):
self.receiver = None
self.message = ""
super().__init__()
def set_receiver(self, receiver):
self.receiver = receiver
def get_receiver(self):
return self.receiver
def get_message(self):
return self.message
def operate_cipher(self):
self.message = input("Write which message you want to send...")
encoded_message = self.get_cipher().encode(self.message)
self.receiver.set_encoded_message(encoded_message)
return encoded_message
class Receiver(Person):
""" Decrypts an encoded message sent from the Sender class """
def operate_cipher(self):
decoded_message = self.get_cipher().decode(self.get_encoded_message())
return decoded_message
|
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 28 05:14:57 2020
Author: Sai Madhav Kasam.
Data Programming Assignment-1.
"""
# Georgian Calendar starts from 1582.
isLeap=False;
year=eval(input("Give the year"));
day=eval(input("Give the day of the First date of the year"));
if(year%4==0):
isLeap=True;
if(year%100==0):
if(year%400==0):
isLeap=True;
else:
isLeap=False;
else:
isLeap=False;
monthDays=[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
weekDays=["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
months=["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
if(isLeap):
monthDays[1]=29;
for i in range(12):
print(months[i], " 1", year, "is: ", weekDays[day%7]);
day+=monthDays[i];
|
'''
Author: Sai Madhav Kasam.
Data Programming Assignment-1.
'''
import datetime;
# currTime= datetime.datetime.now();
# print(currTime.hour);
class Time:
def __init__(self):
self.__hour=datetime.datetime.now().hour;
self.__minute=datetime.datetime.now().minute;
self.__second=datetime.datetime.now().second;
####################################Getter Methods.####################################
def getHour(self):
return self.__hour;
def getMinute(self):
return self.__minute;
def getSecond(self):
return self.__second;
def setTime(self, elapsedTime):
todaySeconds=elapsedTime%86400;
self.__hour=todaySeconds//3600;
todaySeconds=todaySeconds%3600;
self.__minute=todaySeconds//60;
todaySeconds=todaySeconds%60;
self.__second=todaySeconds;
def main():
obj=Time();
print("Current hour is: ", obj.getHour());
print("Current Minute is: ", obj.getMinute());
print("Curent Second is: ", obj.getSecond());
elapsedTime=eval(input("Give the elapsedTime: "));
obj.setTime(elapsedTime);
print("Elapsed Time's hour is: ", obj.getHour());
print("Elapsed Time's Minute is: ", obj.getMinute());
print("Elapsed Time's Second is: ", obj.getSecond());
main();
|
'''
Author: Sai Madhav Kasam
Data Programming Assignment-1.
'''
def main():
str=input("Enter the numbers separated by spaces in a line");
lt=str.split();
numList=[eval(x) for x in lt];
# numList.reverse();
i=0;
j=len(numList)-1;
while(i<j):
numList[i], numList[j]=numList[j], numList[i];
i+=1;
j-=1;
print(numList);
main();
|
'''
Author: Sai Madhav Kasam
Data Programming Assignment-1.
'''
def main():
side1, side2, side3=eval(input("Enter the three sides of the triangle: "));
# triObject1=Triangle();
try:
triObject=Triangle(side1, side2, side3);
except TriangleError as ex:
print("These sides: ", ex.getSide1(), ex.getSide2(), ex.getSide3(), "don't satisfy Triangle inequality theorem.")
print("side1: ", triObject.getSide3());
triObject.setColor(input("Enter the color for the triangle: "));
triObject.setFilledState(eval(input("Enter 0 for empty or 1 for filled: ")));
print("The area is: ", triangle.getArea());
print("The perimeter is: ", triangle.getPerimeter());
print("The color is: ", triangle.getColor());
print("The Filled state is: ";, triangle.getFilledState());
class GeometricObject:
def __init__(self, color="black", filled=True):
self.__color=color;
self.__filled=filled;
#####################################Getter Methods.####################################
def getColor(self):
return self.__color;
def getFilledState(self):
return self.__filled;
#####################################Setter Methods.###################################
def setColor(self, color):
self.__color=color;
def setFilledState(self, filled):
self.__filled=filled;
def __str__(self):
print("color: "+self.__color+" and filled: "+str(self.__filled));
class TriangleError(RuntimeError):
def __init__(self, side1, side2, side3):
super().__init__();
self.__side1=side1;
self.__side2=side2;
self.__side3=side3;
##########################Getter Methods.################################
def getSide1(self):
return self.__side1;
def getSide2(self):
return self.__side2;
def getSide3(self):
return self.__side3;
class Triangle(GeometricObject):
def __init__(self, side1=1.0, side2=1.0, side3=1.0):
# super().__init__(color, filled);
# if(side1+side2<=side3):
# raise RuntimeError("Triangle can't be formed as these sides dont' satisfy The Triangle Inequality Theorem.")
# if(side2+side3<=side1):
# raise RuntimeError("Triangle can't be formed as these sides dont' satisfy The Triangle Inequality Theorem.")
# if(side1+side3<=side2):
# raise RuntimeError("Triangle can't be formed as these sides dont' satisfy The Triangle Inequality Theorem.")
self.__side1=side1;
self.__side2=side2;
self.__side3=side3;
GeometricObject.__init__(self);
if not self.isValid():
raise TriangleError(side1, side2, side3);
##########################Getter Methods.################################
def getSide1(self):
return self.__side1;
def getSide2(self):
return self.__side2;
def getSide3(self):
return self.__side3;
def isValid(self):
if(self.__side1+self.__side2<=self.__side3 or self.__side2+self.__side3<=self.__side1 or self.__side1+self.__side3<=self.__side2):
return False;
return True;
def getPerimeter(self):
return self.__side1+self.__side2+self.__side3;
def getArea(self):
avg=(self.__side1+self.__side2+self.__side3)/2;
return math.sqrt(avg*(avg-self.__side1)*(avg-self.__side2)*(avg-self.__side3));
def __str__(self):
return "Triangle: side1="+str(self.__side1)+" side2="+str(self.__side2)+" side3="+str(self.__side3);
# def main():
# side1, side2, side3=eval(input("Enter the three sides of the triangle: "));
# # triObject1=Triangle();
# try:
# triObject=Triangle(side1, side2, side3);
# except TriangleError as ex:
# print("These sides: ", ex.getSide1(), ex.getSide2(), ex.getSide3(), "don't satisfy Triangle inequality theorem.")
# print("side1: ", triObject.getSide3());
main(); |
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 19 05:23:56 2020
Author: Sai Madhav Kasam.
Data Programming Assignment-1.
"""
import random;
import math;
randNumber=random.randint(100, 999);
# temp=randNumber;
thirdDigit=randNumber%10;
randNumber//=10;
secondDigit=randNumber%10;
randNumber//=10;
firstDigit=randNumber;
guessNumber=eval(input("Give a random 3 digit number: "));
# print("Generated random number is: ", temp);
guessedThirdDigit=guessNumber%10;
guessNumber//=10;
guessedSecondDigit=guessNumber%10;
guessNumber//=10;
guessedFirstDigit=guessNumber;
prize=0;
if(guessNumber==randNumber):
prize=10000;
elif((thirdDigit==guessedThirdDigit and secondDigit==guessedFirstDigit and firstDigit==guessedSecondDigit)
or (thirdDigit==guessedSecondDigit and secondDigit==guessedFirstDigit and firstDigit==guessedThirdDigit)
or (thirdDigit==guessedSecondDigit and secondDigit==guessedThirdDigit and firstDigit==guessedFirstDigit)
or (thirdDigit==guessedFirstDigit and secondDigit==guessedThirdDigit and firstDigit==guessedSecondDigit)
or (thirdDigit==guessedFirstDigit and secondDigit==guessedSecondDigit and firstDigit==guessedThirdDigit)):
prize=3000;
elif((thirdDigit==guessedFirstDigit or thirdDigit==guessedSecondDigit or thirdDigit==guessedThirdDigit)
or (secondDigit==guessedFirstDigit or secondDigit==guessedSecondDigit or secondDigit==guessedThirdDigit)
or (firstDigit==guessedFirstDigit or firstDigit==guessedSecondDigit or firstDigit==guessedThirdDigit)):
prize=1000;
print("The prize money is: ", prize); |
'''
Author: Sai Madhav Kasam
Data Programming Assignment-1.
'''
import os;
def main():
# fileName="testFile.txt";
fileName=input("Give the filename.");
# print("filename is: ", fileName);
try:
fileObject=open(fileName, "r");
except:
print("No such filename exists.");
# print(fileObject.readlines());
vowels={'A':0, 'E':0, 'I':0, 'O':0, 'U':0};
totalChars=0;
for line in fileObject:
for word in line.split():
# totalChars+=len(word);
for i in range(len(word)):
if(word[i]>='a' and word[i]<='z'):
totalChars+=1;
if(word[i]>='A' and word[i]<='Z'):
totalChars+=1;
if(word[i]=='a' or word[i]=='A'):
vowels['A']+=1;
elif(word[i]=='e' or word[i]=='E'):
vowels['E']+=1;
elif(word[i]=='i' or word[i]=='I'):
vowels['I']+=1;
elif(word[i]=='o' or word[i]=='O'):
vowels['O']+=1;
elif(word[i]=='u' or word[i]=='U'):
vowels['U']+=1;
totalVowels=vowels['A']+vowels['E']+vowels['I']+vowels['O']+vowels['U'];
consonents=totalChars-totalVowels;
print("Number of Vowels: ", totalVowels)
print("Number of Consonents: ", consonents);
fileObject.close();
main(); |
'''
Author: Sai Madhav Kasam
Data Programming Assignment-1.
'''
def isSorted(lt):
if(len(lt)<=1):
return True;
prev=lt[0];
for i in range(1, len(lt)):
if(prev>lt[i]):
return False;
prev=lt[i];
return True;
def main():
str=input("Give the numbers between 1 and 100 separated by spaces.");
strList=str.split();
lt=[eval(x) for x in strList];
if(isSorted(lt)):
print("The list is already sorted.");
else:
print("The list is not sorted.");
main(); |
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 15 20:38:58 2020
@author: Administrator
"""
# -*- coding: utf-8 -*-
import math;
currentPopulation=312032486;
secondsPerBirth=7;
secondsPerDeath=13;
secondsPerImmigrant=45;
secondsPerYear=365*24*60*60;
birthsPerYear=secondsPerYear/secondsPerBirth;
deathsPerYear=secondsPerYear/secondsPerDeath;
immigrantsPerYear=secondsPerYear/secondsPerImmigrant;
changePerYear=birthsPerYear-deathsPerYear+immigrantsPerYear;
yearsElapsed=eval(input("Enter the number of years: "));
#print("Population at end of First Year: ", currentPopulation+changePerYear);
#print("Population at end of Second Year: ", currentPopulation+2*changePerYear);
#print("Population at end of Third Year: ", currentPopulation+3*changePerYear);
#print("Population at end of Fourth Year: ", currentPopulation+4*changePerYear);
#print("Population at end of Fifth Year: ", currentPopulation+5*changePerYear);
print("The population in", yearsElapsed," years is: ", math.ceil(currentPopulation+yearsElapsed*changePerYear));
|
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 15 20:43:43 2020
Author: Sai Madhav Kasam
Data Programming Assignment 1.
"""
import turtle;
pointX=eval(input("Give the x coordinate center of the rectangle."));
pointY=eval(input("Give the y coordinate center of the rectangle."));
length=eval(input("Give the length"));
breadth=eval(input("Give the breadth"));
turtle.home();
turtle.penup();
turtle.goto(pointX,pointY-breadth//2);
turtle.pendown();
turtle.forward(length//2);
turtle.left(90);
turtle.forward(breadth);
turtle.left(90);
turtle.forward(length);
turtle.left(90);
turtle.forward(breadth);
turtle.left(90);
turtle.forward(length//2);
turtle.done(); |
'''
Author: Sai Madhav Kasam
Data Programming Assignment-1.
'''
def main():
str1=input("Enter the first sorted list1.");
lt=str1.split();
nums1=[eval(x) for x in lt];
str2=input("Enter the Second sorted list");
lt2=str2.split();
nums2=[eval(x) for x in lt2];
i=0;
j=0;
res=[];
while(i<len(nums1) or j<len(nums2)):
if(i<len(nums1) and j<len(nums2)):
if(nums1[i]<=nums2[j]):
res.append(nums1[i]);
i+=1;
else:
res.append(nums2[j]);
j+=1;
elif(i<len(nums1)):
res.append(nums1[i]);
i+=1;
else:
res.append(nums2[j]);
j+=1;
print("The merged list is: ", end="");
for num in res:
print(num,"", end="");
print("");
main(); |
import math
class Parallelogram:
def __init__(self, width, height, angle):
self.width = width
self.height = height
self.angle = angle
@property
def area(self):
return self.width * self.height * math.sin(math.radians(self.angle))
@area.setter
def area(self, value):
ratio = (value / self.area) ** 0.5
self.width = self.width * ratio
self.height = self.height * ratio
class Rectangle(Parallelogram):
def __init__(self, width, height):
super().__init__(width, height, 90)
class Square(Rectangle):
def __init__(self, side):
super().__init__(side, side)
s = Square(10)
print(s.area)
s.area = 9
print(s.width)
print(isinstance(s, Square))
print(isinstance(s, Rectangle))
print(isinstance(s, Parallelogram))
print(isinstance(s, object))
print()
print(type(s) == Square)
print(type(s) == Rectangle)
print(type(s) == Parallelogram) |
from abc import ABC, ABCMeta, abstractmethod
class Animal(metaclass=ABCMeta):
def __init__(self, name):
self.name = name
@abstractmethod
def make_sound(self):
raise NotImplemented
class Horse(Animal):
pass
class Cat(Animal):
def make_sound(self):
print("meow")
class Dog(Animal):
def make_sound(self):
print("woof")
|
# fact_check = int(input('Please Enter #: '))
# for
# fact_check -= 1
def fact(n):
for i in range(1, n+1)
# This code prints "Hellow World" followed by number 1-50, 10 times satisfying the "if counter == 10" statement
#counter = 0
#while True:
# counter += 1
# print("Hellow World")
# for index in range(1,100):
# print(index)
# if index == 50:
break
# if counter == 10:
# break |
'''Program created by Akul Umamageswaran.'''
'''NOTE:
This program finds either the principal, rate, time, or
interest.
It solves for one of the above given the other three values.
It does this using the simple interest formula:
i = prt
The program will prompt you for integer values.
During those prompts, please ONLY ENTER integers.
Otherwise, the program WILL NOT WORK!
'''
choice = input("What are you solving for? Enter 'p' for principal, 'r' for rate, 't' for time, or 'i' for interest")
if choice == "p":
r = int(input("What is the rate? Type an integer."))
t = int(input("What is the time? Type an integer."))
i = int(input("What is the interest? Type an integer."))
p = i / (r * t)
print "the principal is", p, "dollars"
elif choice == "r":
p = int(input("What is the principal? Type an integer."))
t = int(input("What is the time? Type an integer."))
i = int(input("What is the interest? Type an integer."))
r = i / (p * t)
print "the rate is", r
elif choice == "t":
p = int(input("What is the principal? Type an integer."))
r = int(input("What is the rate? Type an integer."))
i = int(input("What is the interest? Type an integer."))
t = i / (p * r)
print "the time is", t
else:
p = int(input("What is the principal? Type an integer."))
r = int(input("What is the rate? Type an integer."))
t = int(input("What is the time? Type an integer."))
i = p * r * t
print "the interest is", i, "dollars"
|
#Two Sum
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
container = {}
for i, num in enumerate(nums):
if target - num in container:
return [container[target - num], i]
container[num] = i
return |
import RPi.GPIO as GPIO
ledPin = 11
buttonPin = 12
def setup():
print('Program is starting...')
GPIO.setmode(GPIO.BOARD)
GPIO.setup(ledPin, GPIO.OUT)
# With the circuite provided in the lab, the program still works
# even without specifying the pull_up_down value becaused we actually
# create a pull_up_down circuit with
# 3.3V -> R2 (10k Ohm) -> GPIO18
# -> Switch
# However, we are seeing in many gpiozero tutorials we do not need to
# create this pull down circuit with rpi and we can directly connect
# a switch to a GPIO port and ground.
# This is because, internally, if we tell rpi that this GPIO.IN port
# is used as -> pull_up_down=GPIO.PUD_UP, rpi will automatically
# connect this GPIO port with a VCC (3.3V?) and a resistor which is
# basically a pull up circuit.
# Hence, directly connect a switch to a GPIO port and a ground will
# work in this case but we need to ensure that pull_up_down=GPIO.PUD_UP
# is specified.
# I tried removing pull_up_down from the setup and it turns out that
# the LED will always be ON in this case because this IN port will
# always receive GPIO.LOW in this case regardless of whether the switch
# is pressed or not (it will always connect to Ground since rpi does not
# turn on the pull up for you)
# You will not need to worry about all of this if you are using
# the Button class of the gpiozero package since the pull_up setting
# will be used as a default setting but it is at least good to know
# what it is done behinde the seen :)
# pull_up_down must be set if switch is directly connect to the port
GPIO.setup(buttonPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# This will also work for the circuit provided in Tutorial.pdf since
# we also create a pull up circuit outside rpi
# GPIO.setup(buttonPin, GPIO.IN)
def loop():
while True:
if GPIO.input(buttonPin) == GPIO.LOW:
GPIO.output(ledPin, GPIO.HIGH)
print('led on....')
else:
GPIO.output(ledPin, GPIO.LOW)
print('led off...')
def destroy():
GPIO.output(ledPin, GPIO.LOW)
GPIO.cleanup()
if __name__ == '__main__':
print('Hello WOLRD!')
setup()
try:
loop()
except KeyboardInterrupt:
destroy() |
# -*- coding: utf-8 -*-
"""
Github Project
@author: mremreozcelik
"""
######## ENGLİSH LANGUAGE #########
money = int(0)
while True:
print("Money : ", int(money)," $")
print("1-) To deposit money (1) \n2-) Withdraw (2) \n3-) My Bank Status (3)")
x = input("Enter the action you want to do ?\n")
if x=="1":
yatir = int(input("How Many Money You Want to Deposit ? (Ex: 25)\n"))
money = int(money) + int(yatir)
print("Congratulations " , int(yatir) , " you deposit.")
print("Returning to the beginning...")
elif x =="2":
cek = int(input("How Many Money Do You Want ? (Ex: 25)\n"))
money = int(money) - int(cek)
print("Congratulations " , int(cek) , " you took.")
print("Returning to the beginning...")
elif x=="3":
print("Instant Money :", int(+money) )
else:
print("You made an incorrect entry!") |
import csv
file = open("data_file/record.csv", "r")
with file:
read = csv.reader(file)
for row in read:
print(row)
print("--------\n")
file = open("data_file/record_pipe.csv", "r")
with file:
read = csv.reader(file)
for row in read:
print(row)
print("--------\n")
file = open("data_file/record_pipe.csv", "r")
with file:
read = csv.reader(file, delimiter="|")
for row in read:
print(row)
print("--------\n")
file = open("data_file/record_tab.csv", "r")
with file:
read = csv.reader(file, delimiter="\t")
for row in read:
print(row)
print("--------\n")
file = open("data_file/record.csv", "r")
with file:
read = csv.DictReader(file)
for row in read:
print(dict(row))
print("--------\n")
file = open("data_file/record.csv", "r")
with file:
read = csv.DictReader(file)
for row in read:
print(row)
names = [["First Name", "Last Name"],
["Sofia", "Reyes"],
["Jerome", "Jackson"],
["Jia", "Zhong"]]
# file = open("data_file/names.csv", "w")
# with file:
# file_writer = csv.writer(file)
# for row in names:
# file_writer.writerow(row)
nums = [[10, 20, 30],
[40, 50, 60],
[70, 80, 90]]
# file = open("data_file/numbers.csv", "w")
# with file:
# write = csv.writer(file)
# write.writerows(nums)
# file = open("data_file/names.csv", "w")
# with file:
# fnames = ["First Name", "Last Name"]
# writer = csv.DictWriter(file, fieldnames=fnames)
# writer.writeheader()
# writer.writerow(({"First Name" : "Sofia", "Last Name": "Reyes"}))
# writer.writerow(({"First Name" : "Jerome", "Last Name": "Jackson"}))
# writer.writerow(({"First Name" : "Jia", "Last Name": "Zhong"}))
# csv.register_dialect("tab", delimiter="\t")
# with open("data_file/record_tab.csv", "r") as f:
# reader = csv.reader(f, dialect = "tab")
# for row in reader:
# print(row)
csv.register_dialect("plus", delimiter="+", lineterminator="\n\r")
file = open("data_file/names_dialect.csv", "w")
with file:
file_writer = csv.writer(file, dialect="plus")
for row in names:
file_writer.writerow(row) |
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 29 18:21:13 2020
@author: Dillons PC
"""
import sys
def Encrypt(key, file):
counter = 0
if isinstance(key, str) and isinstance(file, str):
f = open(file)
text = f.readlines()
newList = []
for x in text:
line = list(x)
for i in line:
if(i.isalpha()):
if(i.isupper()):
encryptedtext = ord(i) - ord('A')
keytext = ord(key[counter%len(key)]) - ord('A')
newList.append( chr(((encryptedtext - keytext)%26) + ord('A')) )
else:
encryptedtext = ord(i) - ord('a')
keytext = ord(key[counter%len(key)]) - ord('a')
newList.append( chr(((encryptedtext - keytext)%26) + ord('a')) )
else:
newList.append(i)
counter += 1
f = open("VigenereDecrypted.txt", "w" )
for i in newList:
f.write(i)
else :
print("give me a string that will be your key and then the name of your file ")
Encrypt(sys.argv[1],sys.argv[2]) |
tc=int(input())
for i in range(tc):
x=input()
j='LUCKY'
for k in x:
if k!='7' and k!='3':
j='BETTER LUCK NEXT TIME'
break
print(j)
|
"""
mapping
~~~~~~~
Performs projection functions. Map tiles are projected using the
https://en.wikipedia.org/wiki/Web_Mercator projection, which does not preserve
area or length, but is convenient. We follow these conventions:
- Coordinates are always in the order longitude, latitude.
- Longitude varies between -180 and 180 degrees. This is the east/west
location from the Prime Meridian, in Greenwich, UK. Positive is to the east.
- Latitude varies between -85 and 85 degress (approximately. More extreme
values cannot be represented in Web Mercator). This is the north/south
location from the equator. Positive is to the north.
Once projected, the x coordinate varies between 0 and 1, from -180 degrees west
to 180 degrees east. The y coordinate varies between 0 and 1, from (about) 85
degrees north to -85 degrees south. Hence the natural ordering from latitude
to y coordinate is reversed.
Web Mercator agrees with the projections EPSG:3857 and EPSG:3785 up to
rescaling and reflecting in the y coordinate.
For more information, see for example
http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames
Typical workflow is to use one of the `extent` methods to construct an
:class:`Extent` object. This stores details of a rectangle of web mercator
space. Then construct a :class:`Plotter` object to actually draw the tiles.
This object can then be used to plot the basemap to a `matplotlib` axes object.
"""
from __future__ import print_function, absolute_import
from six.moves import map
import numpy as np
import math as _math
from .distanceCalculator import translate_lonlat
_EPSG_RESCALE = 20037508.342789244
def _to_3857(x, y):
return ((x - 0.5) * 2 * _EPSG_RESCALE,
(0.5 - y) * 2 * _EPSG_RESCALE)
def _from_3857(x, y):
xx = 0.5 + (x / _EPSG_RESCALE) * 0.5
yy = 0.5 - (y / _EPSG_RESCALE) * 0.5
return xx, yy
def to_web_mercator(longitude, latitude):
"""Project the longitude / latitude coords to the unit square.
:param longitude: In degrees, between -180 and 180
:param latitude: In degrees, between -85 and 85
:return: Coordinates `(x,y)` in the "Web Mercator" projection, normalised
to be in the range [0,1].
"""
xtile = (longitude + 180.0) / 360.0
lat_rad = _math.radians(latitude)
ytile = (1.0 - _math.log(_math.tan(lat_rad) + (1 / _math.cos(lat_rad))) / _math.pi) / 2.0
return (xtile, ytile)
def to_lonlat(x, y):
"""Inverse project from "web mercator" coords back to longitude, latitude.
:param x: The x coordinate, between 0 and 1.
:param y: The y coordinate, between 0 and 1.
:return: A pair `(longitude, latitude)` in degrees.
"""
longitude = x * 360 - 180
latitude = _math.atan(_math.sinh(_math.pi * (1 - y * 2))) * 180 / _math.pi
return (longitude, latitude)
class _BaseExtent(object):
"""A simple "rectangular region" class."""
def __init__(self, xmin, xmax, ymin, ymax):
self._xmin, self._xmax = xmin, xmax
self._ymin, self._ymax = ymin, ymax
if not (xmin < xmax):
raise ValueError("xmin < xmax.")
if not (ymin < ymax):
raise ValueError("ymin < ymax.")
@property
def xmin(self):
"""Minimum x value of the region."""
return self.project(self._xmin, self._ymin)[0]
@property
def xmax(self):
"""Maximum x value of the region."""
return self.project(self._xmax, self._ymax)[0]
@property
def width(self):
"""The width of the region."""
return self.xmax - self.xmin
@property
def xrange(self):
"""A pair of (xmin, xmax)."""
return (self.xmin, self.xmax)
@property
def ymin(self):
"""Minimum y value of the region."""
return self.project(self._xmin, self._ymin)[1]
@property
def ymax(self):
"""Maximum y value of the region."""
return self.project(self._xmax, self._ymax)[1]
@property
def height(self):
"""The height of the region."""
return self.ymax - self.ymin
@property
def yrange(self):
"""A pair of (ymax, ymin). Inverted so as to work well with
`matplotib`.
"""
return (self.ymax, self.ymin)
@staticmethod
def from_center(x, y, xsize=None, ysize=None, aspect=1.0):
"""Helper method to aid in constructing a new instance centered on the
given location, with a given width and/or height. If only one of the
width or height is specified, the aspect ratio is used.
:return: `(xmin, xmax, ymin, ymax)`
"""
if xsize is None and ysize is None:
raise ValueError("Must specify at least one of width and height")
x, y, aspect = float(x), float(y), float(aspect)
if xsize is not None:
xsize = float(xsize)
if ysize is not None:
ysize = float(ysize)
if xsize is None:
xsize = ysize * aspect
if ysize is None:
ysize = xsize / aspect
xmin, xmax = x - xsize / 2, x + xsize / 2
ymin, ymax = y - ysize / 2, y + ysize / 2
return (xmin, xmax, ymin, ymax)
def _to_aspect(self, aspect):
"""Internal helper method. Return a new bounding box.
Shrinks the rectangle as necessary."""
width = self._xmax - self._xmin
height = self._ymax - self._ymin
new_xrange = height * aspect
new_yrange = height
if new_xrange > self.width:
new_xrange = width
new_yrange = width / aspect
midx = (self._xmin + self._xmax) / 2
midy = (self._ymin + self._ymax) / 2
return (midx - new_xrange / 2, midx + new_xrange / 2,
midy - new_yrange / 2, midy + new_yrange / 2)
def _with_scaling(self, scale):
"""Return a new instance with the same midpoint, but with the width/
height divided by `scale`. So `scale=2` will zoom in."""
midx = (self._xmin + self._xmax) / 2
midy = (self._ymin + self._ymax) / 2
xs = (self._xmax - self._xmin) / scale / 2
ys = (self._ymax - self._ymin) / scale / 2
return (midx - xs, midx + xs, midy - ys, midy + ys)
class Extent(_BaseExtent):
"""Store details about an area of web mercator space. Can be switched to
be projected in EPSG:3857 / EPSG:3785. We allow the x range outside of
[0,1] to allow working across the "boundary" as 1 (i.e. we treat the
coordinates as being topologically a cylinder and identify (0,y) and (1,y)
for all y).
:param xmin:
:param xmax: The range of the x coordinates, between 0 and 1. (But see
note above).
:param ymin:
:param ymax: The range of the y coordinates, between 0 and 1.
:param projection_type: Internal use only, see :meth:`to_project_3857`
and :meth:`to_project_web_mercator` instead.
"""
def __init__(self, xmin, xmax, ymin, ymax, projection_type="normal"):
super(Extent, self).__init__(xmin, xmax, ymin, ymax)
if ymin < 0 or ymax > 1:
raise ValueError("Need 0 < ymin < ymax < 1.")
if projection_type == "normal":
self.project = self._normal_project
elif projection_type == "epsg:3857":
self.project = self._3857_project
else:
raise ValueError()
self._project_str = projection_type
@staticmethod
def from_center(x, y, xsize=None, ysize=None, aspect=1.0):
"""Construct a new instance centred on the given location in Web
Mercator space, with a given width and/or height. If only one of the
width or height is specified, the aspect ratio is used.
"""
xmin, xmax, ymin, ymax = _BaseExtent.from_center(x, y, xsize, ysize, aspect)
xmin, xmax = max(0, xmin), min(1.0, xmax)
ymin, ymax = max(0, ymin), min(1.0, ymax)
return Extent(xmin, xmax, ymin, ymax)
@staticmethod
def from_center_lonlat(longitude, latitude, xsize=None, ysize=None, aspect=1.0):
"""Construct a new instance centred on the given location with a given
width and/or height. If only one of the width or height is specified,
the aspect ratio is used.
"""
x, y = to_web_mercator(longitude, latitude)
return Extent.from_center(x, y, xsize, ysize, aspect)
@staticmethod
def from_center_3857(x, y, xsize=None, ysize=None, aspect=1.0):
"""Construct a new instance centred on the given location with a given
width and/or height. If only one of the width or height is specified,
the aspect ratio is used.
"""
x, y = _from_3857(x, y)
ex = Extent.from_center(x, y, xsize, ysize, aspect)
return ex.to_project_3857()
@staticmethod
def from_lonlat(longitude_min, longitude_max, latitude_min, latitude_max):
"""Construct a new instance from longitude/latitude space."""
xmin, ymax = to_web_mercator(longitude_min, latitude_min)
xmax, ymin = to_web_mercator(longitude_max, latitude_max)
return Extent(xmin, xmax, ymin, ymax)
@staticmethod
def from_3857(xmin, xmax, ymin, ymax):
"""Construct a new instance from longitude/latitude space."""
xmin, ymin = _from_3857(xmin, ymin)
xmax, ymax = _from_3857(xmax, ymax)
ex = Extent(xmin, xmax, ymin, ymax)
return ex.to_project_3857()
@staticmethod
def from_trajectory(longitudes, latitudes):
coordinates_web_mercator = np.array(list(map(to_web_mercator, longitudes, latitudes)))
xmin, ymin = np.min(coordinates_web_mercator, axis=0)
xmax, ymax = np.max(coordinates_web_mercator, axis=0)
return Extent(xmin, xmax, ymin, ymax)
def get_lonlat_extent(self):
min_lon, max_lat = to_lonlat(self._xmin, self._ymin)
max_lon, min_lat = to_lonlat(self._xmax, self._ymax)
return (min_lon, max_lon, min_lat, max_lat)
def __repr__(self):
return "Extent(({},{})->({},{}) projected as {})".format(self.xmin, self.ymin,
self.xmax, self.ymax, self._project_str)
def clone(self, projection_type=None):
"""A copy."""
if projection_type is None:
projection_type = self._project_str
return Extent(self._xmin, self._xmax, self._ymin, self._ymax, projection_type)
def _normal_project(self, x, y):
"""Project from tile space to coords."""
return x, y
def _3857_project(self, x, y):
return _to_3857(x, y)
def to_project_3857(self):
"""Change the coordinate system to conform to EPSG:3857 / EPSG:3785
which can be useful when working with e.g. geoPandas (or other data
which is projected in this way).
:return: A new instance of :class:`Extent`
"""
return self.clone("epsg:3857")
def to_project_web_mercator(self):
"""Change the coordinate system back to the default, the unit square.
:return: A new instance of :class:`Extent`
"""
return self.clone("normal")
def to_square(self):
x_width = (self._xmax - self._xmin)
y_width = (self._ymax - self._ymin)
x_margin = y_width - x_width
y_margin = x_width - y_width
if x_margin > 0:
return Extent(self._xmin - x_margin/2., self._xmax + x_margin/2., self._ymin, self._ymax)
elif y_margin > 0:
return Extent(self._xmin, self._xmax, self._ymin - y_margin/2. , self._ymax + y_margin/2.)
else:
return Extent(self._xmin, self._xmax, self._ymin, self._ymax)
def with_center(self, xc, yc):
"""Create a new :class:`Extent` object with the centre moved to these
coordinates and the same rectangle size. Clips so y is in range [0,1].
"""
oldxc = (self._xmin + self._xmax) / 2
oldyc = (self._ymin + self._ymax) / 2
ymin = self._ymin + yc - oldyc
ymax = self._ymax + yc - oldyc
if ymin < 0:
ymax -= ymin
ymin = 0
if ymax > 1:
ymin -= (ymax - 1)
ymax = 1
return Extent(self._xmin + xc - oldxc, self._xmax + xc - oldxc,
ymin, ymax, self._project_str)
def with_margin_km(self, margin):
"""Create a new :class:'Extent` object with additional margin
"""
coords = np.zeros((2,2))
coords[0,:] = to_lonlat(self._xmin, self._ymin)
coords[1,:] = to_lonlat(self._xmax, self._ymax)
longitude_min, latitude_min = np.min(coords, axis=0)
longitude_max, latitude_max = np.max(coords, axis=0)
new_longitude_min, new_latitude_min = translate_lonlat(longitude_min, latitude_min, -1*margin)
new_longitude_max, new_latitude_max = translate_lonlat(longitude_max, latitude_max, margin)
return Extent.from_lonlat(new_longitude_min, new_longitude_max, new_latitude_min, new_latitude_max)
def with_center_lonlat(self, longitude, latitude):
"""Create a new :class:`Extent` object with the centre the given
longitude / latitude and the same rectangle size.
"""
xc, yc = to_web_mercator(longitude, latitude)
return self.with_centre(xc, yc)
def to_aspect(self, aspect):
"""Return a new instance with the given aspect ratio. Shrinks the
rectangle as necessary."""
output = self._to_aspect(aspect)
return Extent(output[0],output[1],output[2],output[3], self._project_str)
def with_absolute_translation(self, dx, dy):
"""Return a new instance translated by this amount. Clips `y` to the
allowed region of [0,1].
:param dx: Amount to add to `x` value (on the 0 to 1 scale).
:param dy: Amount to add to `y` value (on the 0 to 1 scale).
"""
ymin, ymax = self._ymin + dy, self._ymax + dy
if ymin < 0:
ymax -= ymin
ymin = 0
if ymax > 1:
ymin -= (ymax - 1)
ymax = 1
return Extent(self._xmin + dx, self._xmax + dx, ymin, ymax, self._project_str)
def with_translation(self, dx, dy):
"""Return a new instance translated by this amount. The values are
relative to the current size, so `dx==1` means translate one whole
rectangle size (to the right).
:param dx: Amount to add to `x` value relative to current width.
:param dy: Amount to add to `y` value relative to current height.
"""
dx = dx * (self._xmax - self._xmin)
dy = dy * (self._ymax - self._ymin)
return self.with_absolute_translation(dx, dy)
def with_scaling(self, scale):
"""Return a new instance with the same midpoint, but with the width/
height divided by `scale`. So `scale=2` will zoom in."""
output = self._with_scaling(scale)
return Extent(output[0],output[1],output[2],output[3], self._project_str)
|
#Fundametos de Python
#C++
# private int numero = 0;
#cout
#JS
# var,let,const numero = 0;
# console.log("numero es:" + numero)
#Python
nombre = "Rodrigo"
VoF = True
#double o float o decimal es con el "."
altura = 1.75
n,n2, n3 = 5,4,7
numero_complejo = 2.1 + 7.8j
""" Tipo de datos"""
tipo_variable = type(n)
print("La variable con valor " + str(n) + " es de tipo: " + str(tipo_variable))
tipo_variable = type(nombre)
print("La variable con valor " +str(nombre) + " es de tipo: " + str(tipo_variable))
tipo_variable = type(numero_complejo)
print("La variable con valor " +str(numero_complejo) + " es de tipo: " + str(tipo_variable))
#Simbolos
suma = n2 + n3
print("Suma: " + str(suma))
resta = n2 - n3
print("Resta: " + str(resta))
multi = n2*n3
print("Multiplicación: " + str(multi))
divi = n2/n3
print("Division: " + str(divi))
potencia = 10 ** 4
print("Potencia: " + str(potencia))
division_entera = 100 // 3
print("Division Entera: " + str(division_entera))
residuo = 24 % 7
print("Residuo: " + str(residuo))
incremento_de_dos = 10
incremento_de_dos += 5
print(str(incremento_de_dos))
decremento_de_cinco = 10
decremento_de_cinco -= 5
print(str(decremento_de_cinco))
#Condicionales
print("Software Base")
variable = input("Ingrese un numero positivo: ")
number = int(variable)
if number < 0:
print("El numero no es positivo")
else:
print("El numero es positivo")
variable = input("Ingrese una edad: ")
edad = int(variable)
if edad > 17 :
print("Es mayor de edad")
elif edad < 0:
print("Edad no es valida")
else:
print("Es menor de edad")
variable = input("Ingrese una edad para entrar a los juegos mecanicos: ")
edad = int(variable)
if edad>17 and edad <60: #&&
print("Esta apto")
else:
print("No esta apto")
variable = input("Ingrese su codigo de admin: ")
codigo = int(variable)
if codigo == 1 or codigo == 2: #||
print("Tiene acceso")
else:
print("No tiene acceso")
#Arrays
lista = ['pera','papaya','lucuma','palta']
print(lista)
#Añado un elemento a la lista
lista.append('limon')
print(lista)
#Añadir en posicion
lista.insert(1,'uva')
print(lista)
#Añadir una lista a la lista
lista2 = ['fresa', 'toronja', 'lechuga']
lista.extend(lista2)
print(lista)
#Eliminar por valor o dato
lista.remove('toronja')
print(lista)
#Eliminar por posición
lista.pop(1)
print(lista)
#Segunda manera de eliminar por posición
del lista[5]
print(lista)
#Eliminar ultimo elemento de la lista
lista.pop()
print(lista)
#Contar repeticion de un valor en la lista
veces = lista.count('pera')
print('Veces que se repite palta :' + str(veces))
#Encontrar la posicion de la primera coincidencia
posicion = lista.index('lucuma')
print("Indice de la primera coincidencia al buscar Lucuma: " + str(posicion))
#Revertir el orden
lista.reverse()
print(lista)
#Ordenamiento ascendente
lista.sort()
print(lista)
#ordenamiento de manera descendente
lista.sort(reverse=True)
print(lista)
#Eliminar todos los datos
lista.clear()
print(lista)
#Matriz, Tuplas
matriz = [
[1,2,[2,3],4],
[1,2,3,4,5,6],
[1,2],
['Rodrigo']
]
print(matriz)
#tupla = (10,30)
#print(str(type(tupla)))
matriz_de_tupla = [
(40,80),
(4,10),
(21,70)
]
print(matriz_de_tupla)
print(" ----------------- ")
#Bucles, Ciclos, Repetitivas
#Bucle FOR
for elemento in lista:
print(elemento)
for number in range(2,6): ##Secuancia incrementa cada 1
print(number)
for number in range(2,6,3): ##Secuancia incrementa cada 3
print(number)
else:
print("Termino!")
for elemento in range(len(lista)):
print(elemento)
for elemento in matriz:
print(elemento)
for j in elemento:
print(j)
for (edad,peso) in matriz_de_tupla:
print("La edad es : " + str(edad))
print("Y el peso es : " + str(peso))
#Bucle While:
a,b = 0,5
while a < b:
print(a)
a += 5
#Funciones
#Funcion simple
def imprimir_hola_mundo():
print('Hola mundo!')
imprimir_hola_mundo()
#Funciones con paramteros
def imprimir_msg_bienvenida(nombre,apellido):
print('Hola {} {}'.format(nombre,apellido))
imprimir_msg_bienvenida('Liliana','Yanqui')
#Palabras clave como parametros
def imprimir_msg_general(str):
print(str)
return;
imprimir_msg_general(str = 'Mi cadena')
def imprimir_invitacion_cumpleaños(direccion, nombre):
print('Hola {} estas invitado a mi fiesta que se envunetra en {}. Te espero!'.format(nombre,direccion))
imprimir_invitacion_cumpleaños(nombre = 'Max', direccion = 'Av. Los proceres 123')
#Parametros con valores por defecto
def imprimir_informacion(name, edad = 0):
print('Nombre : ' + name)
if edad != 0:
print('Edad : ' + str(edad))
imprimir_informacion('Pedro')
#Manipulacion de cadenas
palabra = "Hola Mundo"
#Concatenacion
print(palabra + "!")
#Multiplicacion
print(palabra * 3)
#Tamaño de la palabra
print(len(palabra))
#Recorrer la cadena
for l in palabra:
print(l)
#Acceder a posiciones
print(palabra[3])
#Obtener un segmento de cadena
print(palabra[5:])
#Formateo
print("¡ {} !".format(palabra))
#Metodos
#Mayusculas
print(palabra.upper())
#Minuscula
print(palabra.lower())
#Confirmaciones
print(palabra.isupper())
print(palabra.islower())
print(palabra.startswith('Hola'))
print(palabra.endswith('o'))
#Metodos join() y split()
mi_lista = ['gato','perro','loro']
texto_unido = "-".join(mi_lista)
print(texto_unido)
texto_final = "SmartFitABCBodytechABCGoldGym"
gym_lista = texto_final.split('ABC')
print(gym_lista)
#Diccionarios
#Definicion
diccionario = {
'frio' : 'cold',
'caliente' : 'hot'
}
print(diccionario)
#Acceder a un valor por clave
print(diccionario['caliente'])
#Metodos para recorrer diccionario: keys(), values() y items()
print("\nMetodos para recorrer diccionario :")
print("Por llaves :")
for k in diccionario.keys():
print(k)
print("Por Valor :")
for v in diccionario.values():
print(v)
print("Por Item :")
for i in diccionario.items():
print(i)
#Comprobar si el valor existe en una clave, valor o item
print('frio' in diccionario.keys())
print('hot' in diccionario.values())
print('caliente' in diccionario)
#Metodo GET
print(diccionario.get('caliente'))
#Añadir datos
diccionario.setdefault('Llave', 'Valor')
print(diccionario)
#Clases
class Evento():
id = None
titulo = None
descripcion = None
imagenURL = None
def __init__(self, titulo):
self.titulo = titulo
print("Este es el constructor")
def setTitulo(self, value):
self.titulo = value
def setDescripcion(self, value):
self.descripcion = value
def getId(self):
return self.id
def printInformation(self):
print(self.titulo)
print(self.descripcion)
evento = Evento('Musica Electro')
print(evento.titulo)
evento.setDescripcion('Esta es la descripcion')
print(evento.descripcion)
print(evento.getId())
class ClaseHija(Evento): #definicion de la clase hija
def __init__(self):
print("Se inicio el constructor de la clase hija")
claseH = ClaseHija()
print(claseH.getId())
claseH.setTitulo('Titulo 2')
claseH.setDescripcion('Esta es la descripcion 2')
claseH.printInformation()
def getInformation():
try:
print(10/0)
except ZeroDivisionError:
print("OPS! No se puede dividr entre 0")
print(ZeroDivisionError)
finally:
print("La funcion se termino")
getInformation()
|
#ANN
# ----- PREPROCESADO DE DATOS -----
# Cargar Librerias
import numpy as np
import matplotlib as plt
import pandas as pd
# Cargar de Dataset
dataset = pd.read_csv('Churn_Modelling.csv')
X = dataset.iloc[:, 3:13].values
y = dataset.iloc[:,13].values
#Variables Dummys
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
# Tranformacion para "Country"
labelencoder_X_1 = LabelEncoder()
X[:, 1] = labelencoder_X_1.fit_transform(X[:, 1])
#Trnasformacion para "Gender"
labelencoder_X_2 = LabelEncoder()
X[:, 2] = labelencoder_X_2.fit_transform(X[:, 2])
onehotencoder = OneHotEncoder(categorical_features = [1])
X = onehotencoder.fit_transform(X).toarray()
X = X[:,1:]
# Dvidir Entrenamiento y Testing
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X,y, test_size = 0.2, random_state = 0)
#Escalado de Variables
from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()
X_train = sc_X.fit_transform(X_train)
X_test = sc_X.transform(X_test)
# ----- CONSTRUIR ANN -----
# Importar Librerias para ANN
import keras
from keras.models import Sequential
from keras.layers import Dense
# Inicializar la ANN
classifier = Sequential()
# Capa de Entrada y Primera Capa Oculta
classifier.add(Dense(units = 6, kernel_initializer = "uniform",
activation = "relu", input_dim = 11))
# Segunda Capa Oculta
classifier.add(Dense(units = 6, kernel_initializer = "uniform",
activation = "relu"))
# Capa de Salida
classifier.add(Dense(units = 1, kernel_initializer = "uniform",
activation = "sigmoid"))
#Compilar ANN
classifier.compile(optimizer = "adam", loss = "binary_crossentropy",
metrics = ["accuracy"])
# Ajustar ANN al Conjunto de Entrenamiento
classifier.fit(X_train, y_train, batch_size =10, epochs = 100)
# ----- EVALUACION DE MODELO Y CALCULO DE PREDICCIONES -----
#Prediccion de Resultados del Conjunto Testing
y_pred = classifier.predict(X_test)
y_pred = (y_pred>0.5)
#Matriz de Confusion
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test,y_pred)
|
l=input("Input a letter of the alphabet:")
if l in ('a','e','i','o','u'):
printf("%s is vowel." %l)
elif l=='y':
printf("sometimes letter y stand for vowel,sometimes stand for consonant")
else:
printf("%s is a consonant."%l)
|
from utils import (
is_palindrome,
print_matrix,
rebuild_words,
assert_checking,
)
def palindrome_subsequences(word):
# precalculate dinamic programming N x N of characters coicidences
n = len(word)
# length 1
dp = [[0 for x in range(n)] for y in range(n)]
for i in range(n):
dp[i][i] = 1
palindromes = list(word)
# length 2
pos = 0
while pos < n - 1:
if word[pos] == word[pos + 1]:
for i in range(n):
dp[pos][pos + 1] = 1
dp[pos + 1][pos] = 1
palindromes.append(word[pos] + word[pos + 1])
pos = pos + 1
# print_matrix(dp)
# check words greater > 2
for k in range(3, n + 1):
for i in range(n):
for j in range(i, n):
# check
if is_palindrome(word, i, j, j - i):
dp[i][j] = 1
dp[j][i] = 1
# print_matrix(dp)
# reconstruct words
for i in range(1, n - 1):
if dp[i][i + 1] == 1: # even words
x1 = i
y1 = i + 1
palindromes = rebuild_words(x1, y1, word, '', palindromes, dp)
if i - 1 > 0 and dp[i - 1][i + 1] == 1: # odd words
x1 = i - 1
y1 = i + 1
palindromes = rebuild_words(x1, y1, word, word[i], palindromes, dp)
return palindromes
if __name__ == '__main__':
exit_condition = "!e"
string = 'afoolishconsistencyisthehobgoblinoflittlemindsadoredbylittlestatesmenandphilosophersanddivineswithconsistencyagreatsoulhassimplynothingtodohemayaswellconcernhimselfwithhisshadowonthewallspeakwhatyouthinknowinhardwordsandtomorrowspeakwhattomorrowthinksinhardwordsagainthoughitcontradicteverythingyousaidtodayahsoyoushallbesuretobemisunderstoodisitsobadthentobemisunderstoodpythagoraswasmisunderstoodandsocratesandjesusandlutherandcopernicusandgalileoandnewtonandeverypureandwisespiritthatevertookfleshtobegreatistobemisunderstood'
print(f"\n*********************************************")
print(f"Executing exercise 3. ")
print(f"The result will be an array with all ")
print(f"string subsequences palindromes.")
print(f"\nExecuting algorithm with input: \"{string}\"")
print("Please wait...")
subseq = palindrome_subsequences(string)
print("\nAll subsequences found: ", subseq)
assert_checking(subseq, string)
str_input = input(f"Enter other example, be gentle ;), I think recommended less than 600 chrs (Type \"{exit_condition}\" to exit): ")
while str_input != exit_condition:
subseq = palindrome_subsequences(str_input)
print("\nAll subsequences found: ", subseq)
str_input = input(f"Enter other example, be gentle ;), I think recommended less than 600 chrs (Type \"{exit_condition}\" to exit): ")
print("Finish.")
|
# Given an object/dictionary with keys and values that consist of both strings and integers, design an algorithm to calculate and return the sum of all of the numeric values.
# For example, given the following object/dictionary as input:
# {
# "cat": "bob",
# "dog": 23,
# 19: 18,
# 90: "fish"
# }
# Your algorithm should return 41, the sum of the values 23 and 18.
# You may use whatever programming language you'd like.
# Verbalize your thought process as much as possible before writing any code. Run through the UPER problem solving framework while going through your thought process.
# d = {
# "cat": "bob",
# "dog": 23,
# 19: 18,
# 90: "fish"
# }
# total = 0
# for value in d.values():
# if type(value) is int:
# total += value
# print(total)
# function compareTwoArrays(arr1, arr2) {
# # compare the two arrays and if they have the same numbers return true otherwise
# for(let i = 0; i > arr1.length; i++){
# if (length(arr1) != length(arr2)){
# return false
# }
# else if (arr1[i] === arr2[i]) {
# return true
# }
# }
# }
# // Test cases to verify
# console.log(compareTwoArrays([1,2,3], [1,2,3])); // true
# console.log(compareTwoArrays([3,3,3], [1,2,3])); // false
# console.log(compareTwoArrays([1,2,3,4], [1,2,3])); // false
# console.log(compareTwoArrays([1,2,3], [1,2,3,4])); // false
# // If you decide to attempt nested arrays
# const a = [1,['a', 'b'],3,4];
# const b = [1,['a', 'b'],3,4];
# console.log(compareTwoArrays(a, b)); // true
# const a = [1,[‘z', ‘z'],3,4];
# const b = [1,['a', 'b'],3,4];
# console.log(compareTwoArrays(a, b)); // false
|
from collections import Counter
def isBeautifulString(s):
a = "abcdefghijklmnopqrstuvwxyz"
for i in range(1,len(a)):
if s.count(a[i-1]) >= s.count(a[i]):
continue
return False
return True |
def alphabeticShift(input):
letters = "abcdefghijklmnopqrstuvwxyz"
input = list(input)
for i in range(len(input)):
if input[i] == 'z':
input[i] = 'a'
else:
index = letters.index(input[i])
input[i] = letters[index + 1]
return "".join(input) |
def palindromeRearranging(inputString):
counter = 0
# if len(inputString) % 2 != 0:
# return False
for char in inputString:
input_count = inputString.count(char)
if len(inputString) % 2 == 0:
if input_count % 2 != 0:
return False
else:
if input_count == 1:
counter += 1
if counter > 1:
return False
return True |
#Derivative
#In this exercise, we will calculates a derivative.
#For that purpose, keep in mind the mathematical definition of a derivative is
# dfdx=lim(δx→0)((f(x+δx)−f(x))/δx)
#Write a script that calculate the derivative of f(x)=x2 on 101 points between 0 and 10 for δx=10−2.
#Plot the error curve (i.e. expected value – computed value) over the 101 points.
#Do the same for different values of different values on δx ranging from 10−2 to 10−14.
#How does the error vary with the δx?
#Derivative
import matplotlib.pyplot as plt
i=0
i_values = []
delta = 0.01
y = []
while i<=100:
y.append(((i+delta)**2 - i**2)/delta)
i_values.append(i)
i = i+delta
plt.plot(i_values, y)
plt.xlabel("X")
plt.ylabel("Y")
plt.show() |
from lib import abstractstrategy
from math import inf
class AlphaBetaSearch:
def __init__(self, strategy, maxplayer, minplayer, maxplies=3,
verbose=False):
""""alphabeta_search - Initialize a class capable of alphabeta search
problem - problem representation
maxplayer - name of player that will maximize the utility function
minplayer - name of player that will minimize the uitlity function
maxplies- Maximum ply depth to search
verbose - Output debugging information
"""
self.maxplayer = maxplayer
self.minplayer = minplayer
self.strategy = strategy
self.maxplies = maxplies
def alphabeta(self, state):
"""
Conduct an alpha beta pruning search from state
:param state: Instance of the game representation
:return: best action for maxplayer
"""
""" Look at potential captures """
available_actions = state.get_actions(self.maxplayer)
if len(available_actions) <= 0:
return None
max_p_capture_action = available_actions[0]
max_p_can_capture = (len(max_p_capture_action[1]) == 3)
if max_p_can_capture:
return max_p_capture_action
""" Enter alpha-beta pruning """
return self.maxvalue(state, -inf, inf, 1)[1]
def cutoff(self, state, ply):
"""
cutoff_test - Should the search stop?
:param state: current game state
:param ply: current ply (depth) in search tree
:return: True if search is to be stopped (terminal state or cutoff
condition reached)
"""
return state.is_terminal()[0] or ply >= self.maxplies
def maxvalue(self, state, alpha, beta, ply):
"""
maxvalue - - alpha/beta search from a maximum node
Find the best possible move knowing that the next move will try to
minimize utility.
:param state: current state
:param alpha: lower bound of best move max player can make
:param beta: upper bound of best move max player can make (at most)
:param ply: current search depth
:return: (value, maxaction)
"""
max_action = None
if self.cutoff(state, ply):
v = self.strategy.evaluate(state)
else:
v = -inf
# checks each available action and passes it to min
for action in state.get_actions(self.maxplayer):
new_v_value = max(v, self.minvalue(state.move(action), alpha, beta, ply + 1)[0])
# if our new value is less than v, assign it to v and update the action and alpha
if new_v_value > v:
v = new_v_value
alpha = max(alpha, v)
max_action = action
# check if we can prune
if alpha >= beta:
break
if max_action is None:
pass
return v, max_action
def minvalue(self, state, alpha, beta, ply):
"""
minvalue - alpha/beta search from a minimum node
:param state: current state
:param alpha: lower bound on best move for min player
:param beta: upper bound on best move for max player
:param ply: current depth
:return: (v, minaction) Value of min action and the action that
produced it.
"""
min_action = None
if self.cutoff(state, ply):
v = self.strategy.evaluate(state)
else:
v = inf
# checks each available action and passes it to max
for action in state.get_actions(self.minplayer):
new_v_value = min(v, self.maxvalue(state.move(action), alpha, beta, ply + 1)[0])
# if our new value is less than v, assign it to v and update the action and alpha
if new_v_value < v:
v = new_v_value
alpha = min(alpha, v)
min_action = action
# check if we can prune
if alpha <= beta:
break
# if we do not have an action, end the function call
if min_action is None:
pass
return v, min_action
class Strategy(abstractstrategy.Strategy):
"""Your strategy, maybe you can beat Tamara Tansykkuzhina,
2019 World Women's Champion
"""
def __init__(self, *args):
"""
Strategy - Concrete implementation of abstractstrategy.Strategy
See abstractstrategy.Strategy for parameters
"""
super(Strategy, self).__init__(*args)
self.search = \
AlphaBetaSearch(self, self.maxplayer, self.minplayer,
maxplies=self.maxplies, verbose=False)
def play(self, board):
"""
play(board) - Find best move on current board for the maxplayer
Returns (newboard, action)
"""
action = self.search.alphabeta(board)
if action is None:
return board, None
return board.move(action), action
def evaluate(self, state, turn=None):
"""
evaluate - Determine utility of terminal state or estimated
utility of a non-terminal state
:param state: Game state
:param turn: Optional turn (None to omit)
:return: utility or utility estimate based on strength of board
(bigger numbers for max player, smaller numbers for
min player)
Takes a CheckerBoard and turn and determines the strength
related to the maxplayer given in the constructor. For example,
a strong red board should return a high score if the constructor
was invoked with ‘r’, and a low score with ‘b’. The optional argument
turn may be used to enhance your evaluation function for a specific
player’s turn, but may be ignored if you do not want to create a turn
specific evaluation function.
"""
player_diff = []
""" Weights """
weight_num_pawn = 40
weight_num_king = 60
weight_edge_piece = 3
weight_moves_available = 3
weight_goalie = 4
weight_king_in_last_row = -4
""" Amount of moves available """
max_p_moves = len(state.get_actions(self.maxplayer))
min_p_moves = len(state.get_actions(self.minplayer))
player_diff.append(max_p_moves * weight_moves_available)
player_diff.append(-(min_p_moves * weight_moves_available))
""" Pawn Differences """
# pawn_dif= red pawns - black pawns
pawn_diff = state.get_pawnsN()[0] - state.get_pawnsN()[1]
# Since get_pawnsN() returns red first, if maxplayer is black we
# must invert the value of the difference between the two
if self.maxplayer is 'b':
pawn_diff = -pawn_diff
player_diff.append(pawn_diff * weight_num_pawn)
# king_dif= red kings - black kings
king_diff = state.get_kingsN()[0] - state.get_kingsN()[1]
# Since get_kingsN() returns red first, if maxplayer is black we
# must invert the value of the difference between the two
if self.maxplayer is 'b':
king_diff = -king_diff
player_diff.append(king_diff * weight_num_king)
""" Edge Pieces, Goalies, Kings in far row """
for r, c, piece in state:
# Test if any 'goalies' (back row pieces that prevent enemy from king-ing)
if self.is_goalie(r, state.edgesize, self.maxplayer):
player_diff.append(weight_goalie)
""" If this piece:
- belongs to maxplayer
- is a King
- is in the far row/other player's row """
# If piece belongs to maxplayer
if state.isplayer(self.maxplayer, piece):
# If piece is a king
if state.isking(piece):
# If in other player's row (we can just pass in the
# other player into is_goalie() to check this)
if self.is_goalie(r, state.edgesize, self.minplayer):
player_diff.append(weight_king_in_last_row)
# Test if piece is on edge of the board
if self.is_edge_piece(r, c, state.edgesize):
player_diff.append(weight_edge_piece)
# Return sum of each aspect of our evaluation
return sum(player_diff)
@staticmethod
def is_edge_piece(r, c, board_size):
"""
Determines if the given piece is on the edge of the board
:param r: row of the piece
:param c: column of the piece
:param board_size: total size (in r and c) of the board
:return: True if in the first or last row/column
"""
in_first_row = (r - 1) < 0
in_first_col = (c - 1) < 0
in_last_row = (r + 1) > (board_size - 1)
in_last_col = (c + 1) > (board_size - 1)
return in_first_row or in_first_col \
or in_last_row or in_last_col
@staticmethod
def is_goalie(r, board_size, player):
"""
Determines if the given row value satisfies the requirement for a "goalie".
A goalie is a piece that resides in the furthest back row, which prevents the enemy from
kinging their pieces.
:param r: row index to evaluate
:param board_size: total number of rows on the board
:param player: player that we're evaluating with respect to
:return: True if the piece is in the furthest row from your opponent.
"""
in_black_row = (r - 1) < 0
in_red_row = (r + 1) > (board_size - 1)
if player == 'r':
return in_red_row
if player == 'b':
return in_black_row
|
import numpy as np
def stereographicProjection(alt, az):
"""Project stars onto a 2D plane stereographically.
Parameters
----------
alt : np.ndarray
The altitude of a star, relative to an observer.
Values are processed as radians.
az : np.ndarray
The azimuth of a star, relative to an observer.
Values are processed as radians.
Returns
-------
(np.ndarray, np.ndarray)
The (x, y) coordinates of each star, projected onto a 2D plane
stereographically.
"""
x = np.cos(alt) * np.sin(az)
y = np.cos(alt) * np.cos(az)
z = np.sin(alt)
return x/(1+z), y/(1+z)
def cylindricalProjection(alt, az):
"""Project stars onto an equirectangular plan.
Parameters
----------
alt : np.ndarray
The altitude of a star, relative to an observer.
Values are processed as radians.
az : np.ndarray
The azimuth of a star, relative to an observer.
Values are processed as radians.
Returns
-------
(np.ndarray, np.ndarray)
The (x, y) coordinates of each star, calculated using an
equirectangular projection, to maintain equal areas.
"""
x = np.interp(az, [0, 2*np.pi], [-1, +1])
y = np.sin(alt)
return x, y
|
#-*-coding:utf-8-*-
import numpy as np
import pandas as pd
from datetime import datetime
from datetime import timedelta
from dateutil.parser import parse
from pandas import DataFrame,Series
now=datetime.now()
#print(now)
#print(now.year,now.month,now.day)
#datetime以毫秒形式存储日期和时间.
# datetime.timedelta表示两个datetime对象之间的时间差
delta=datetime(2011,1,7)-datetime(2008,6,24,8,15)
#print(delta)
#print(delta.days)
#print(delta.seconds)
#给datetime对象加上一个或多个timedelta,这样会产生一个新对象
start=datetime(2011,1,7)
a=start+timedelta(12)
#print(a)
#利用str或strftime方法
# datetime对象和pandas的Timestamp对象可以被格式化为字符串
stamp=datetime(2011,1,3)
#print(str(stamp))#默认格式转换
#print(stamp.strftime("%Y-%m-%d"))#指定格式转换
value='2011-01-03'
a=datetime.strptime(value,'%Y-%m-%d')
print(a)
datestrs=['7/6/2011','8/6/2011']
|
#-*-coding:utf-8-*-
from datetime import datetime
from datetime import timedelta
from dateutil.parser import parse
from pandas import DataFrame,Series
import pandas as pd
stamp=datetime(2011,1,3)
print(str(stamp))#默认格式切换
#print(stamp.strftime('%Y-%m-%d'))#指定转换格式
value='2011-01-03'
#print(datetime.strptime(value,'%Y-%m-%d'))
datestrs=['7/6/2011','8/6/2011']
data=[datetime.strptime(x,'%m/%d/%Y') for x in datestrs]
print(data)
#datetime.strptime是通过已知格式进行日期解析的最佳方式.但是每次都要编写格式定义是很麻烦的事情,尤其是对于一些常见的日期格式.
# 这种情况下,你可以用dateutil这个第三方包中的parser.parse方法
parse('2011-01-03')#自动解析,默认月在前
#dateutil可以解析几乎所有人类能够理解的日期表示形式
print(parse('Jan 31,1997 10:45 PM'))
#在国际通用的格式中,日通常出现在月的前面
#传入dayfirst=True即可解决这个问题
print(parse('6/12/2011',dayfirst=True))#日在月前
#pandas通常是用于处理成组日期的,不管这些日期是DataFrame的轴索引还是
#列,to_datetime方法可以解析多种不同的日期表示形式.对标准日期格式的
#解析非常快
print(datestrs)
a=pd.to_datetime(datestrs)
print(a)#变成时间索引对象
#它还可以处理缺失值
idx=pd.to_datetime(datestrs+[None])
print(idx)
print(idx[2])
b=pd.isnull(idx)
print(b)
|
#-*-coding:utf-8-*-
from pandas import DataFrame,Series
import numpy as np
import pandas as pd
tips=pd.read_csv('/home/jethro/文档/pydata-book-master/data/tips.csv')
#添加‘小费占总额百分比’的列
tips['tip_pct']=tips['tip']/tips['total_bill']
#print(tips[:6])
grouped=tips.groupby('smoker')
#grouped_pct=grouped['tip_pct']
#print(grouped_pct.agg('mean'))
#如果传入的是一个由(name,function)元组组成的列表
# ,则各元组的第一个元素就会被用作DataFrame的列名
functions=['count','mean','max']
result=grouped['tip_pct','total_bill'].agg(functions)
#print(result['tip_pct'])
ftuples=[('Durchschnitt','mean'),('Abweichung',np.var)]
#print(grouped['tip_pct','total_bill'].agg(ftuples))
#print(grouped.agg({'tip':np.max,'size':'sum'}))
print(grouped.agg({'tip_pct':['min','max','mean','std'],'size':sum})) |
#!/bin/python3
# Write a Python program to iterate over two lists simultaneously.
num = [1, 2, 3]
color = ['red', 'while', 'black']
for (a,b) in zip(num, color):
print(a, b)
|
import math
'''
While statement repeats body of code as long as a condition is true.
'''
# counter = 1
# while counter <=5:
# print ("Hello World")
# counter += 1
'''
While fragment where both conditions are satisfied
'''
# counter = 1
# done = False
# while counter <=10 and not done:
# print("Hello World")
# counter +=1
'''
for statement can be used to iterate over the members of a collection,
so long as the collection is a sequence (list, tuples, and strings).
'''
# for item in [1,2,3,4,5,6,7]:
# print(item)
'''
A common use of the for statement is to implement
definite iteration over a range of values.
'''
# for item in range(5):
# print(item **2)
'''
The following code fragment iterates over a list of strings and for each string
processes each character by appending it to a list. The result is a list of all
the letters in all of the words.
'''
# wordlist = ['cat','dog','rabbit']
# letterlist = [ ]
# for aword in wordlist:
# for aletter in aword:
# letterlist.append(aletter)
# print(letterlist)
'''
if and ifelse statement
'''
# num = input("Please enter value: ")
# n = int(num)
# if n<0:
# print ("Sorry , value is negative")
# else:
# print(math.sqrt(n))
'''
Selection constructs, as with any control construct, can be nested so that the
result of one question helps decide whether to ask the next.
'''
# num = input("Please enter your score: ")
# score = int(num)
# if score>=90:
# print('A')
# else:
# if score>=80:
# print('B')
# else:
# if score>=70:
# print('C')
# else:
# if score>60:
# print('D')
# else:
# print('You have a BIG FAT "F"')
'''
Refactored with "elif"
'''
# num = input("Please enter your score: ")
# score = int(num)
# if score>=90:
# print('A')
# elif score>=80:
# print('B')
# elif score>=70:
# print('C')
# elif score>60:
# print('D')
# else:
# print('You have a BIG FAT "F"')
'''
A single way selection construct, the if statement.
With this statement, if the condition is true, an action is performed. In the
case where the condition is false, processing simply continues on to the next
statement after the if
'''
# n=20
# if n<0:
# n = abs(n)
# print(math.sqrt(n))
|
__author__ = 'albertfougy'
import time
from random import randrange
"""
Test function with random string size and time alloted to perform comparisons
"""
# exponential version == O(n**2)
# def findMin(a_list):
# overallMin = a_list[0]
# for i in a_list: # 1st loop
# is_smallest = True
# for j in a_list: # 2nd loop = O(n^2)
# if j > i:
# is_smallest = False
# if is_smallest:
# overallMin == i
# return overallMin
# linear version == O(n)
def findMin(a_list):
minsofar= a_list[0]
for i in a_list:
if i < minsofar:
minsofar == i
return minsofar
some_list = [1,44,77,200,32]
print(findMin(some_list))
for listSize in range(1000, 10001,1000):
a_list = [randrange(100000) for x in range(listSize)]
start = time.time()
print(findMin(a_list))
end = time.time()
# print("size: %d time: %f" % (listSize, end-start))
print(f'size: {listSize} time: {end-start}')
|
import psycopg2
conn = psycopg2.connect(host="127.0.0.1",port="5432",database="employeedb",user="test",password="password")
print("Connected to employeedb")
cursor = conn.cursor()
cursor.execute("select * from employee")
rows = cursor.fetchall()
print("Total Numbers of records",cursor.rowcount)
for row in rows:
print(row)
cursor.close()
conn.close() |
#Please put your code for Step 2 and Step 3 in this file.
# Alex Bazyk
import numpy as np
import matplotlib.pyplot as plt
import random
# FUNCTIONS
#takes no parameters. returns glucose, hemo, class numpy arrays based on
# the the data stored in the file.
def openckdfile():
glucose, hemoglobin, classification = np.loadtxt('ckd.csv', delimiter=',', skiprows=1, unpack=True)
return glucose, hemoglobin, classification
#normalizes the data of glucose, hemo, class numpy arrays as a value from 0-1.
#does this through an equation
#returns the new normalized data in numpy arrays
def normalizeData(glucose, hemoglobin, classification):
g_max = np.amax(glucose)
g_min = np.amin(glucose)
h_max = np.amax(hemoglobin)
h_min = np.amin(hemoglobin)
c_max = np.amax(classification)
c_min = np.amin(classification)
for i in range(len(glucose)):
normalized = (glucose[i]-g_min)/(g_max-g_min)
glucose[i] = normalized
for h in range(len(hemoglobin)):
normalized = (hemoglobin[h]-h_min)/(h_max-h_min)
hemoglobin[h] = normalized
for j in range(len(glucose)):
normalized = (classification[j]-c_min)/(c_max-c_min)
classification[j] = normalized
return glucose , hemoglobin, classification
#graphs the data stored in the glucose, hemoglobin, classification numpy arrays
#returns nothing but prints out the graph
def graphData(glucose,hemoglobin,classification):
plt.figure()
plt.plot(hemoglobin[classification==1],glucose[classification==1], "k.", label = "Class 1")
plt.plot(hemoglobin[classification==0],glucose[classification==0], "r.", label = "Class 0")
plt.xlabel("Hemoglobin")
plt.ylabel("Glucose")
plt.title("Glucose vs. Hemoglobin")
plt.legend()
plt.show()
#Parameters: glucose and hemoglobin numpy arrays not normalized
#Creates test points by creating random numbers between 0 and 1 which is
#the bounds for the normalized data
#Also creates variables using min and max and the random numbers which are
#values that are those random numbers scaled to the non normalized data
#Returns all 4 of those numbers just in case either of them are ever needed.
def createTestCase(glucose,hemoglobin):
g_max = np.amax(glucose)
g_min = np.amin(glucose)
h_min = np.amin(hemoglobin)
h_max = np.amax(hemoglobin)
newglucose = np.random.rand(1)
normg = newglucose
newglucose = np.multiply(newglucose,g_max-g_min)
newglucose = np.add(newglucose,g_min)
newhemoglobin = np.random.rand(1)
normh = newhemoglobin
newhemoglobin = np.multiply(newhemoglobin,h_max-h_min)
newhemoglobin = np.add(newhemoglobin,h_min)
return newglucose, newhemoglobin, normg, normh
#takes in the test point(numpy arrays) and glucose, hemoglobing numpy arrays
#calculates the distance between the test case and every point in the
#gluc and numpy arrays
#returns a distance numpy array that holds all those distances
def calculateDistanceArray(newglucose, newhemoglobin, glucose, hemoglobin):
Distance = np.zeros(len(glucose))
for i in range(len(Distance)):
d1 = (newglucose[0] - glucose[i])**2
d2 = (newhemoglobin[0] - hemoglobin[i])**2
Distance[i] = np.add(d1,d2)
Distance = np.sqrt(Distance)
return Distance
#parameters: glucose, hemoglobin, classification numpy arrays as well as the test cases in numpy arrays
#Calls upon calculate distance function and stores that in a distance numpy array
#Use np.argmin(distance) to find the minimum index
#Get the classification of that minimum distance
#Return that classification
def nearestNeighborClassifier(newglucose, newhemoglobin, glucose, hemoglobin, classification):
Distance = calculateDistanceArray(newglucose, newhemoglobin, glucose, hemoglobin)
MinIndex = np.argmin(Distance)
TheClassification = classification[MinIndex]
return TheClassification
#takes in test point, gluc, hemo, classification numpy arrays and the class for the test point
#graphs all of that data on a graph
#returns nothing.
def graphTestCase(newglucose, newhemoglobin, glucose, hemoglobin, classification, newclass):
plt.figure()
plt.plot(hemoglobin[classification==1],glucose[classification==1], "k.", label = "Class 1")
plt.plot(hemoglobin[classification==0],glucose[classification==0], "r.", label = "Class 0")
if(newclass == 1):
plt.scatter(newhemoglobin,newglucose,c = "black", s = 100)
else:
plt.scatter(newhemoglobin,newglucose, c= "red", s = 100)
plt.xlabel("Hemoglobin")
plt.ylabel("Glucose")
plt.title("Glucose vs. Hemoglobin with Test Point")
plt.legend()
plt.show()
#parameters: k points to observe, test case hemoglobin and glucose, and numpy arrays of
#glucose and hemoglobin and classification
#Calls upon distance function created earlier for test case and real cases and stores
#that in a numpy array
#Sorts the distance function using np.argsort
#Grabs the k classifications from that. This new variable is a numpy array that
#stores the k nearest point’s classifications.
#From there, the average classification of array is found and if the average is above
#.5 it is treated as 1 and below is 0. This value is then returned.
def kNearestNeighborClassifier(k, newglucose, newhemoglobin, glucose, hemoglobin, classification):
Distance = calculateDistanceArray(newglucose, newhemoglobin, glucose, hemoglobin)
sorted_indices = np.argsort(Distance)
#print("sorted ind", sorted_indices)
k_indices = sorted_indices[:k]
#print("hemos: ", hemoglobin[k_indices], " \nglucos: ", glucose[k_indices])
k_classifications = classification[k_indices]
print(k_classifications)
#print(k_classifications.size)
sum = 0
for i in range(k):
sum +=k_classifications[i]
sum = sum/k
print("Average classification is: ", sum)
if(sum > .5):
return 1
else:
return 0
# MAIN SCRIPT
glucose, hemoglobin, classification = openckdfile()
plt.figure()
plt.plot(hemoglobin[classification==1],glucose[classification==1], "k.", label = "Class 1")
plt.plot(hemoglobin[classification==0],glucose[classification==0], "r.", label = "Class 0")
plt.xlabel("Hemoglobin")
plt.ylabel("Glucose")
plt.legend()
plt.show()
#original script is above new script is below this comment
newg, newh, normnewg, normnewh = createTestCase(glucose,hemoglobin)
print(newg,newh, normnewg, normnewh)
gnorm,hnorm,cnorm = normalizeData(glucose,hemoglobin,classification)
ClassForNewPoint = nearestNeighborClassifier(normnewg,normnewh,gnorm,hnorm,cnorm)
print(ClassForNewPoint)
graphTestCase(normnewg,normnewh,gnorm,hnorm,cnorm,ClassForNewPoint)
#graphData(gnorm,hnorm,cnorm)
k = int(input("How many nearest points should be taken into consideration?: "))
k_classes = kNearestNeighborClassifier(k, normnewg, normnewh, glucose, hemoglobin, classification)
graphTestCase(normnewg,normnewh,gnorm,hnorm,cnorm,k_classes)
|
#time O(nlog) space is O(n)
def sortedSquaredArray(array):
# Write your code here.
sqarr=[]
for num in array:
sqnum=num*num
sqarr.insert(-1,sqnum)
sqarr.sort()
return sqarr
#O(n) S O(n)
def sortedSquaredArray(array):
# Write your code here.
sortsquared=[0 for _ in array]
left = 0
right= len(array)-1
for i in reversed(range(len(array))):
smallvalue=array[left]
largervalue=array[right]
if abs(smallvalue)>abs(largervalue):
sortsquared[i]=smallvalue*smallvalue
left=left+1
else:
sortsquared[i]=largervalue* largervalue
right=right-1
return sortsquared
|
# This is an input class. Do not edit.
class LinkedList:
def __init__(self, value):
self.value = value
self.next = None
def removeDuplicatesFromLinkedList(linkedList):
# Write your code here.
# passing in the top only
current = linkedList
while current is not None:
distinct = current.next
# a none value will also not have a property and that is why we have to perform a check heres
# this will always be true and we should only keep iterating until we are not the same anymore
while distinct is not None or distinct.value == current.value:
distinct = distinct.next
current.next = distinct
current = distinct
return linkedList
|
# This is an input class. Do not edit.
class BinaryTree:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
class TreeInfo:
def __init__(self, isBalanced, height):
self.isBalanced=isBalanced
self.height=height
def getTreeInfo(tree):
if tree ==None:
return TreeInfo(True, 0)
l=getTreeInfo(tree.left)
r=getTreeInfo(tree.right)
isBalanced=l.isBalanced and r.isBalanced and abs(l.height-r.height)<=1
height=1+max(l.height,r.height)
return TreeInfo(isBalanced,height)
def heightBalancedBinaryTree(tree):
# Write your code here.
return getTreeInfo(tree).isBalanced
|
#AVG O(logn) time and space O(1)
#worst o(n) and space O(1)
def findClosestValueInBst(tree, target):
# Write your code here.
return helper(tree, target, tree.value)
def helper(tree, target, closest):
current=tree
while current is not None:
if abs(closest-target)>abs(target-current.value):
closest=current.value
if target< current.value:
current=current.left
elif target> current.value:
current=current.right
else:
break
return closest
# This is the class of the input tree. Do not edit.
class BST:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 23 08:53:04 2019
@author: erik
"""
import math
def binarySearch(target, listOfNumbers, start,end):
index = math.floor( (end+start) /2)
if(target < listOfNumbers[index] and (index > start)):
index = binarySearch(target,listOfNumbers,start,index-1)
elif (listOfNumbers[index] < target) and (end > index ):
index = binarySearch(target,listOfNumbers,index + 1,end)
if(listOfNumbers[index] == target and index != -1):
return index
else:
return -1
listOfNumbers = list(range(0,21,2))
target = 0
index = binarySearch(target, listOfNumbers, 0 , len(listOfNumbers) )
print(target)
if(index != -1):
print(listOfNumbers[index])
else:
print("didnt find") |
# color circle areas
from math import pi
total = int(raw_input())
numbers = []
ratios = total
while ratios > 0:
numbers.append(int(raw_input()))
ratios -= 1
numbers.sort()
signal = 'tasu'
area = 0
while total > 0:
ratio = float(numbers.pop())
if signal == 'tasu':
area += pi * ratio * ratio
signal = 'minus'
elif signal == 'minus':
area -= pi * ratio * ratio
signal = 'tasu'
total -= 1
print area
|
# from StringIO import StringIO
import lxml.etree as etree
data = """
<root>
<person>
<name>John</name>
<address>
<street>Hill Street</street>
</address>
</person>
<person>
<name>Jeff</name>
<address>
<street>Bay Street</street>
</address>
</person>
</root>
"""
root = etree.fromstring(data)
first_person = root[0]
print 'Print the street of the address of the first person in xml'
print first_person.xpath('address/street')[0].text
import lxml.etree as etree
import io
data = """
<root xmlns="http://my-xmlns.com/foo">
<person>
<name>John</name>
<address>
<home>
<street>Hill Street</street>
</home>
<office>
<street>Wall Street</street>
</office>
</address>
</person>
<person>
<name>Jeff</name>
<address>
<home>
<street>Bay Street</street>
</home>
<office>
<street>Water Street</street>
</office>
</address>
</person>
</root>
"""
xslt='''<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="no"/>
<xsl:template match="/|comment()|processing-instruction()">
<xsl:copy>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
<xsl:template match="*">
<xsl:element name="{local-name()}">
<xsl:apply-templates select="@*|node()"/>
</xsl:element>
</xsl:template>
<xsl:template match="@*">
<xsl:attribute name="{local-name()}">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>
'''
print 'Using xslt to get rid of namespaces'
xslt_doc=etree.parse(io.BytesIO(xslt))
transform=etree.XSLT(xslt_doc)
dom = etree.parse(io.BytesIO(data))
root = transform(dom)
# first_person = root[0]
print 'Print the street of the office address of the first person in xml'
print root.find('.//home/street').text
|
def check_value(mapping,cell):
row=cell[0]
column=cell[1]-1
already_played=True
if(mapping[row][column]!=' '):
print("cell already played")
return already_played
else:
already_played=False
return already_played
def check_full_board(mapping):
for item in mapping.values():
for i in item:
if i!=' ':
pass
else:
return False
return True
def win_check(board,marks):
for mark in marks:
if((board['1'][0]==board['1'][1]==board['1'][2]==mark)or(board['1'][0]==board['2'][1]==board['3'][2]==mark)or(board['1'][0]==board['2'][0]==board['3'][0]==mark)or(board['1'][1]==board['2'][1]==board['3'][1]==mark)or(board['1'][2]==board['2'][2]==board['3'][2]==mark)or(board['2'][0]==board['2'][1]==board['2'][2]==mark)or(board['3'][0]==board['3'][1]==board['3'][2]==mark)or(board['1'][2]==board['2'][1]==board['3'][0]==mark)):
win=True
print(f'{mark} is the winner')
return win
else:
win=False
return win
if __name__=="__main__":
print("This module is tested") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.