text
stringlengths 37
1.41M
|
---|
#!/usr/bin/python3
# Filename: super.py
class Bird(object):
def chirp(self):
print("make sound")
class Chicken(Bird):
def chirp(self):
super().chirp()
print("ji")
bird = Bird()
bird.chirp()
summer = Chicken()
summer.chirp()
|
#!/usr/bin/python3
# Filename: residual.py
i = 0
residual = 500000.0
interest_tuple = (0.01, 0.02, 0.03, 0.035)
repay = 30000.0
while residual> 0:
i = i + 1
print("The ",i , "year need to pay debt")
if i <= 4:
interest = interest_tuple[i - 1]
else:
interest = 0.05
residual = residual * (interest + 1) -repay
print("The residual is pay off at ",i ,"year.")
|
#!/usr/bin/python3
# Filename: inheritance.py
class Bird(object):
feather = True
reproduction = "egg"
def chirp(self, sound):
print(sound)
class Chicken(Bird):
how_to_move = "walk"
edible = True
class Swan(Bird):
how_to_move = "swim"
edible = False
summer = Chicken()
print(summer.feather)
summer.chirp("ji")
|
#!/usr/bin/python3
# Filename: function_timer.py
import time
def function_timer(old_function):
def new_function(*arg, **dict_arg):
t1 = time.time()
result = old_function(*arg, **dict_arg)
t2 = time.time()
print("The run time is:" + t + "s.")
return result
return new_function
|
# 함수 funtions 간략하고 보기쉽게 짜는 기법, 여러개를 수정해야할때 중복을 단순하게 바꿔준다
# 입력값 parameters, 반환값 return
def hello_friends(name):
print("hello, {}".format(name))
name1 = "marco"
name2 = "jane"
name3 = "john"
name4 = "tom"
name5 = "marco"
name6 = "jane"
name7 = "john"
name8 = "tom"
# print("hi, {}".format(name1))
# print("hi, {}".format(name2))
# print("hi, {}".format(name3))
# print("hi, {}".format(name4))
# print("hi, {}".format(name5))
# print("hi, {}".format(name6))
# print("hi, {}".format(name7))
# print("hi, {}".format(name8))
hello_friends(name1)
hello_friends(name2)
hello_friends(name3)
hello_friends(name4)
hello_friends(name5)
hello_friends(name6)
hello_friends(name7)
hello_friends(name8)
# 1)입력값 o 반환값 o #반환값이 있다는건 return이 있다는거 ,반환값이 있다는건 변수를 다룰수 있다
def sum(a, b):
return a + b
# 2)입력값 o 반환값 x
def hello_friends(name):
print("hello, {}".format(name))
#3)입력값 x 반환값 o
def return_1():
return 1
num_1 = return_1()
print(num_1)
#4) 입력값 x 반환값 x
def hello_world():
print("hello world")
|
# Enter your code here. Read input from STDIN. Print output to STDOUT
a=int(input())
b=int(input())
m=int(input())
power=pow(a,b)
print power
module=pow(a,b,m)
print module
|
#有一个已经排好序的数组。现输入一个数,要求按原来的规律将它插入数组中。
'''
#!/usr/bin/python
# -*- coding: UTF-8 -*-
if __name__ == ' __main__ '
# 方法一 : 0 作为加入数字的占位符
a = [ 1 , 4 , 6 , 9 , 13 , 16 , 19 , 28 , 40 , 100 , 0 ]
print ' 原始列表: '
for i in range ( len ( a ) )
print a [ i ]
number = int ( raw_input ( " \n 插入一个数字: \n " ) )
end = a [ 9 ]
if number > end
a [ 10 ] = number
else
for i in range ( 10 )
if a [ i ] > number
temp1 = a [ i ]
a [ i ] = number
for j in range ( i + 1 , 11 )
temp2 = a [ j ]
a [ j ] = temp1
temp1 = temp2
break
print ' 排序后列表: '
for i in range ( 11 )
print a [ i ] ,
'''
|
#打印出杨辉三角形(要求打印出10行如下图)。
'''
#!/usr/bin/python
# -*- coding: UTF-8 -*-
if __name__ == ' __main__ '
a = [ ]
for i in range ( 10 )
a . append ( [ ] )
for j in range ( 10 )
a [ i ] . append ( 0 )
for i in range ( 10 )
a [ i ] [ 0 ] = 1
a [ i ] [ i ] = 1
for i in range ( 2 , 10 )
for j in range ( 1 , i )
a [ i ] [ j ] = a [ i - 1 ] [ j - 1 ] + a [ i - 1 ] [ j ]
from sys import stdout
for i in range ( 10 )
for j in range ( i + 1 )
stdout . write ( str ( a [ i ] [ j ] ) )
stdout . write ( ' ' )
print
'''
|
#判断101-200之间有多少个素数,并输出所有素数。
'''
#!/usr/bin/python
# -*- coding: UTF-8 -*-
h = 0
leap = 1
from math import sqrt
from sys import stdout
for m in range ( 101 , 201 )
k = int ( sqrt ( m + 1 ) )
for i in range ( 2 , k + 1 )
if m % i == 0
leap = 0
break
if leap == 1
print ' %-4d ' % m
h += 1
if h % 10 == 0
print ' '
leap = 1
print ' The total is %d ' % h
'''
def IsPrimeNumber(num):
for i in range(2, num - 1):
if (num % i == 0):
return False
return True
for i in range(101, 201):
if IsPrimeNumber(i):
print(i)
|
print("hello world")
print(2 + 2)
num1 = 2
num2 = 4
print(num1 * num2)
name = "Mj"
print(name)
name1, name2, name3 = "Mj", "Jm", "MJJM"
print(name1, name2, name3)
s = "123456"
print(s[1])
print(s[1:5])
print(s * 2)
print(s + "789")
print(s[1:5:2])
list = ['runoob', 786, 2.23, 'john', 70.2]
print(list)
print(list[1])
print(list[1:3])
print(list[2:])
tuple = ('runoob', 786, 2.23, 'john', 70.2)
print(tuple)
print(tuple[1])
print(tuple[1:3])
print(tuple[2:])
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
print(dict['one'])
print(dict[2])
print(dict.keys())
print(dict.values())
a = 10
if a > 5:
print("ok")
else:
print("haha")
a = 1
while a < 10:
print(a)
a += 1
|
#有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的前20项之和。
a = [2, 3]
b = [1, 2]
for i in range(18):
a.append(a[-2] + a[-1])
b.append(b[-2] + b[-1])
c = 0
for i in range(len(a)):
c = c + a[i] / b[i]
print(c)
|
#统计 1 到 100 之和。
'''
#!/usr/bin/python
# -*- coding: UTF-8 -*-
tmp = 0
for i in range ( 1 , 101 )
tmp += i
print ' The sum is %d ' % tmp
'''
|
num=int(input("Enter a number: "))
a = 0
while(num > 0):
a=a+num
num=num-1
print("The sum of number is",a)
|
# Sum square difference
'''
The sum of the squares of the first ten natural numbers is,
12 + 22 + ... + 102 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)2 = 552 = 3025
Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
'''
# Answer: 25164150
sumOfSquares = 0
squareOfSums = 0
for x in range(1,101):
sumOfSquares += x**2
squareOfSums += x
squareOfSums **= 2
print(squareOfSums-sumOfSquares)
|
#!/usr/bin/env python3
# encoding: utf-8
nums = [x for x in range(30) ]
for num in nums:
print(num)
strs = [m + n for m in "ABC" for n in "XYZ"]
for str in strs:
print(str)
|
# -*- coding: utf-8 -*-
'''
This file containing utilities to assist in processing the xml file.
'''
import codecs
import re
import urllib
'''
Following is the regular expression match differenct kinds of strings.
'''
two_colons_reg = re.compile(r'^([a-z]|_|[0-9])*:([a-z]|_|[0-9])*:([a-z]|_|[0-9])*$')
lower_reg = re.compile(r'^([a-z]|_|[0-9])*$')
colon_reg = re.compile(r'^([a-z]|_|[0-9])*:([a-z]|_|[0-9])*$')
WAY_NAME_FILE = '../way_names'
NODE_NAME_FILE = '../node_names'
pinyin_reg = re.compile(r'^[\da-z A-Z]+$')
def download_file(url, file_out):
'''
This function download a file contained in a url to a local file
'''
urllib.urlretrieve (url, file_out)
def read_mapping(filename):
'''
This function read a mapping file and output a corresponding dictionary.
The input file contains a key value pair in each line. The key value pair
is separated by ':'. See file 'node_names' for example.
'''
f = codecs.open(filename, encoding='utf-8', mode='r')
result = dict()
for line in f:
key = line.split(':')[0]
value = line.split(':')[1].strip()
result[key] = value
f.close()
return result
def lower_filter(string):
'''
This function transform a string into its lower case form.
'''
return string.lower()
def replace_hyphen_filter(string):
'''
This function replace hyphen(-) in a string with a underscore(_).
'''
if re.search('-',string):
return re.sub('-', '_', string)
else:
return string
def replace_second_colon_filter(string):
'''
This function replace the second colon(:) with underscore(_) in a string.
'''
if re.search(two_colons_reg, string):
string_list = list(string)
string_list[[m.start() for m in re.finditer(r":",string)][1]] = '_'
return ''.join(string_list)
else:
return string
def is_match_reg(regex, string):
'''
This function test if a string containing a given regular expression.
'''
if re.search(regex, string):
return True
else:
return False
def mapping_name(string, name_mapping):
'''
This function transform a string to a new string. This tranform is defined
in a dictionary in which keys are original string and corresponding value
is the new string. If the string is not included in the dictionary.
Original string is returned.
'''
if string in name_mapping:
return name_mapping[string]
else:
return string
def read_word_list(filename):
with codecs.open(filename, "r") as fo:
result = [string.strip() for string in fo]
return result
def count_map(regex, string_list):
return sum([1 for string in string_list if re.search(regex, string)])
|
def listSum(numList):
theSum = 0
for i in numList:
theSum += i
return theSum
def listSumRecursion(numList):
if len(numList) == 1:
return numList[0]
else:
return numList[0] + listSumRecursion(numList[1:])
if __name__ == '__main__':
a = [1, 3, 5, 7, 9]
print("Loop: {}; Recursion: {}".format(listSum(a), listSumRecursion(a)))
|
#lists
subba = [216, "Reddy", True, False]
print(subba[0])
print(type(subba))
print(subba[-1])
# syntax to retuurn multiple values from list
#list[start:end:step]
print(subba[1:3])
#list can have a list inside the list
reddy = ["Garem",subba,"kanna"]
print(reddy[1])
#syntax to return values list withing the list is list[masterindex][childindex]
print(reddy[1][1:3:2])
# we can add list with another list
a = [1, 2, 3]
print(a+[1])
print(list("ABC"))
#insert will be used to add te item in the list at a particular position
a = a.insert(1,4)
print(a)
|
let = input("Please enter the wor")
vowels = 0
consonants = 0
for letter in let:
if letter.lower() in "aeiou":
vowels = vowels+1
elif letter =="":
pass
else:
consonants = consonants+1
print("there are {} vowels".format(vowels))
print("there are {} consonants".format(consonants))
friends = {
"male":["shiv","praveen","nitheesh"]
"female":["sukan","kasi","ramya"]
}
for key in friends.keys():
print(friends.key)
|
""" Recalls the method or class property used as an input parameter by the calling frame"""
import inspect
import re
def arcane_recall(calling_frame, target_argument_pos=0):
"""
This is some super sneaky shit.
And I know! I know! "You're not supposed to mess with the stack, it's a bad idea, there be dragons!!!"
Blah blah blah.
Look! If you're not willing to push some limits while being as mindful as you can be, you're never going
to get ahead in life. You already know this, so stop being such a baby! We have frontiers to cross and
dragons to slay!
With that said, here's what I'm doing (currently).
Let's say that you're calling a method which is taking another method as an input parameter.
The return value of the input parameter method is acquired first and then passed into the scope of
the calling method.
Once the returned value of the input parameter method is calculated and passed into the calling method's
scope, it is it's own thing in memory. Whatever that value is, that's the only value it will ever be and
it does not contain within it any knowledge of what originally created (returned) it ancestrally.
So, one might ask, how can you find out what created/returned the value that was passed in to the calling
method from the input parameter method?
And, more importantly, how can you re-call/re-access the object which gave us the value passed into our
calling function?
Yes, you could simply pass in the pointer to the method which you might want to re-call and that would be easy,
BUT, that only really works for functions. It doesn't work for class instance properties, not in any way that
is clean, intuitive to use, and doesn't require the user to do more work than they should have to.
What we really want is something that can be completely dynamic and figure out everything for us.
That's what this method is for. It does all of the magic for you of determining the if what we need to recall
is a class method (which needs to be called using parentheses), or a class instance property.
Furthermore, if what we want to recall is at the end of a dot-notation chain, this method will do what it
needs to do to traverse the objects in this notation chain within the calling frames' local scope until it
gets to the bottom of the chain in order to call/access the target.
Args:
calling_frame (Any):
target_argument_pos (int):
Returns:
The a new return value of the argument passed in the method from the calling frame.
"""
arguments = re.compile('\\(.*\\)')
# The setup to gain access to the calling frames method call.
calling_code = calling_frame.code_context[0].strip('\n')
calling_locals = calling_frame.frame.f_locals
target_call = arguments.search(calling_code)[0].strip('\\(').strip('\\)').split(', ')[target_argument_pos]
# Get a list of the complete dot notation call chain from the calling frames method argument list
target_call_attrs = target_call.split('.')
# Reverse the call chain so we can work from the logical start point since we will never have any idea of what to expect
target_call_attrs.reverse()
# Get a copy of primary target that we want to eventually call/access (removing it from the call chain list)
prime_target_id = target_call_attrs.pop(0).strip('()')
# We'll store the string "id" of the top most level object here later
top_level_target_id = ''
# Our eventual dot notation call chain that we might need to iterate through.
dot_notation_chain = []
# Check to see if our primary target is a callable method within calling frames locals before making this more complicated than it has to be.
if prime_target_id in calling_locals and callable(calling_locals[prime_target_id]):
return calling_locals[prime_target_id]()
else:
# If we're here, we need to loop through each of the target call attributes to find the top most level object we need to access first
for attribute in target_call_attrs:
if attribute.strip('()') in calling_locals:
top_level_target_id = attribute.strip('()')
break
else:
# Until we find the top most level, we need to construct a chain of attributes between the top most level object and our target so we can drill down to access it.
dot_notation_chain.append(attribute.strip('()'))
# Store the reference to the top level object that we need to access
top_level_object = calling_frame.frame.f_locals[top_level_target_id]
# Reverse the dot.notation chain so it's in the correct order after processing.
dot_notation_chain.reverse()
# If we've gotten this far we now need to traverse dot notation chain to drill down into the object references
current_level_object = top_level_object
for index, command in enumerate(dot_notation_chain):
# Is the command a class or a callable object within the current level object we're inspecting?
if inspect.isclass(type(getattr(current_level_object, command))) or callable(getattr(current_level_object, command)):
# If so, store the reference to the command as the new current level object and keep digging.
current_level_object = getattr(current_level_object, command)
else:
# Than the current level object must be the parent to our prime target, return the value.
return getattr(current_level_object, prime_target_id)
# If we're here then we've drilled down to the bottom and we can recall the original calling frames argument.
if callable(getattr(current_level_object, prime_target_id)):
return getattr(current_level_object, prime_target_id)()
else:
return getattr(current_level_object, prime_target_id)
|
# https://www.hackerrank.com/challenges/python-arithmetic-operators/problem
# cambiar a f"{}" - f-string
#Opcion 1 - Con funcion
def run(a,b):
print("""{}
{}
{}""".format(a+b,a-b,a*b))
if __name__ == '__main__':
a = int(input())
b = int(input())
run(a,b)
#opcion 2 *******
a = 4
b = 2
print(a + b)
print(a - b)
print(a * b)
#Opcion 2 - .format()
a = 4
b = 2
print("""{}
{}
{}""".format(a+b,a-b,a*b))
"""
Instrucciones:
Vas a recibir dos valores (a, b)
y vas a retornar el resultado de 3 operaciones en tres lineas diferentes
suma
resta
multiplicacion
Ejemplo:
a = 4
b = 2
Resultado:
6
2
8
"""
|
def repitiendo(text, n):
if n == 0:
return
print(n, text)
repitiendo(text, n-1)
text = "recursividad"
n = 10
repitiendo(text, n)
|
#Opcion 1
name = input("Cual es tu nombre: ")
print("Hola ", name)
#Opcion 2
name = input("Cual es tu nombre: ")
saludo = "Hola "
print(saludo, name)
"""
Instrucciones:
Pregunta el nombre a tu usuario y muestra en pantalla su nombre con un saludo
Ejemplo
Cual es tu nombre llamas: Juan
Resultado
"hola, juan!!!"
"""
|
n=int(input("enter a number"))
if(n%4==0):
print("leap year:")
else:
print("not leap year:")
|
'''
Exceptions are the errors which being break by the program or user.
We have to handle the exception to excecute our program or software smoothly.
In exception handling we have 3 main blocks.
1. Try block
2. Except block / Catch block
3. Finally block
Keywords to use in Exceptional Handling.
try, except, finally, raise
'''
try:
raise IOError('sadad')
open('f1.txt')
print (5 + str(5))
raise RuntimeError('Sir! Something went wrong.')
except ZeroDivisionError as e:
print (str(e))
except RuntimeError as e:
print (str(e))
except AttributeError as e:
print (str(e))
except TypeError as e:
print (str(e))
except FileNotFoundError as e:
print (str(e))
except Exception as e:
print (str(e))
try:
f = open('file.txt', 'w+')
f.append('asdas')
f.close()
except Exception as e:
print (str(e))
finally:
f.close()
print (f)
'''
Task:
'''
try:
f = open('nmn.txt','w+')
f.append('aaaaaa')
f.close()
except Exception as e:
print (str(e))
finally:
f.close()
print (f)
|
#factorial
#using for loop
n=int(input("enter a number:"))
total = 1
for i in range(n,0,-1):
total += total*i
print("factorial of",n,"is",total)
#using while loop
n=int(input("enter a number:"))
total=1
i=1
while i<=n-1:
total += total*i
i += 1
print("factorail of",n,"is",total)
|
import pandas as pd
import numpy as np
ddf=pd.read_excel(open('k-nnalgo.xlsx','rb'))
x=ddf.iloc[:,0:-1]
y=ddf.iloc[:,-1]
x=np.array(x)
y=np.array(y)
i=int()
j=int()
result=[]
us=[]
z=[]
a=int(input("enter the quality of cottan-"))
b=int(input("enter the price of cottan-"))
#for getting list only for distance elements
for i in range(len(x)):
d=np.sqrt((abs(x[i][0]-a)**2)+(abs(x[i][1]-b)**2))
result.append(d)
us.append(d)
result=np.sort(result)
for i in range(3):
for j in range(len(us)):
if(result[i]==us[j]):
z.append(j)
B=G=0
for i in range(len(z)):
if(z[i]>=3):
B=B+1
else:
G=G+1
if(G>B):
print("samplde is good")
else:
print("sample is bad")
|
import sqlite3
conn = sqlite3.connect('employee.db')
cur = conn.cursor()
##query = 'create table employee (id integer primary key, first_name varchar(20),last_name varchar(20))'
##
##cur.execute(query)
##insert_query = 'insert into employee (id, first_name, last_name) values (?, ?, ?)'
##cur.execute(insert_query, (10, 'Ritik', 'Jain'))
## Delete the rows
#query = '''create table person (first_name varchar(20) not null, last_name varchar(20),
#id varchar(20) primary key, age integer not null, gender varchar(1) not null, phone integer(10) not null, address text)'''
##query = 'create table employee (email varchar(20) primary key, pwd varchar(20), name varchar(30))'
##cur.execute(query)
def insert_data(cur):
insert_query = 'insert into employee (email, pwd, name) values (?, ?, ?)'
name = input('Enter your name: ')
email = input('Enter the email id: ')
pwd = input('Enter the password: ')
try:
cur.execute(insert_query, (email, pwd, name))
print ('You are allowed to login!')
except sqlite3.OperationalError as e:
print (e)
except Exception as e:
print (e)
finally:
conn.commit()
def update_pwd(cur):
update = 'update employee set pwd = ? where email = ?'
email = input('Enter the email id:')
pwd = input('Enter the password: ')
try:
cur.execute(update, (pwd, email))
print ('Your password has been updated!')
except sqlite3.DatabaseError as e:
print(e)
except sqlite3.OperationalError as e:
print(e)
except Exception as e:
print(e)
finally:
conn.commit()
def login(cur):
select_query = 'select * from employee where email = ? and pwd = ?'
email = input('Enter the email id: ')
pwd = input('Enter the password: ')
try:
cur.execute(select_query, (email, pwd))
data = cur.fetchall()
if (len(data) > 0):
print ('You have been successfully logged in!')
print('Welcome' + data[0][2] + ' in the application!')
else:
print ('Sorry you are not an application User!')
except sqlite3.OperationalError as e:
print (e)
except sqlite3.DatabaseError as e:
print (e)
except Exception as e:
print(e)
query = 'delete from employee where email = ?'
|
from typing import TypeVar, Generic, Callable, Optional
T = TypeVar('T')
U = TypeVar('U')
class ImmutableList(Generic[T]):
"""
Immutable list is data structure that doesn't allow to mutate instances
"""
def __init__(self, head: T = None, tail: 'ImmutableList[T]' = None, is_empty: bool = False) -> None:
self.head = head
self.tail = tail
self.is_empty = is_empty
def __eq__(self, other: object) -> bool:
return isinstance(other, ImmutableList) \
and self.head == other.head\
and self.tail == other.tail\
and self.is_empty == other.is_empty
def __str__(self) -> str: # pragma: no cover
return 'ImmutableList{}'.format(self.to_list())
def __add__(self, other: 'ImmutableList[T]') -> 'ImmutableList[T]':
"""
If Maybe is empty return new empty Maybe, in other case
takes mapper function and returns result of mapper.
:param mapper: function to call with Maybe.value
:type mapper: Function(A) -> Maybe[B]
:returns: Maybe[B | None]
"""
if not isinstance(other, ImmutableList):
raise ValueError('ImmutableList: you can not add any other instace than ImmutableList')
if self.tail is None:
return ImmutableList(self.head, other)
return ImmutableList(
self.head,
self.tail.__add__(other)
)
def __len__(self):
if self.head is None:
return 0
if self.tail is None:
return 1
return len(self.tail) + 1
@classmethod
def of(cls, head: T, *elements) -> 'ImmutableList[T]':
if len(elements) == 0:
return ImmutableList(head)
return ImmutableList(
head,
ImmutableList.of(elements[0], *elements[1:])
)
@classmethod
def empty(cls):
return ImmutableList(is_empty=True)
def to_list(self):
if self.tail is None:
return [self.head]
return [self.head, *self.tail.to_list()]
def append(self, new_element: T) -> 'ImmutableList[T]':
"""
Returns new ImmutableList with elements from previous one
and argument value on the end of list
:param new_element: element to append on the end of list
:type fn: A
:returns: ImmutableList[A]
"""
return self + ImmutableList(new_element)
def unshift(self, new_element: T) -> 'ImmutableList[T]':
"""
Returns new ImmutableList with argument value on the begin of list
and other list elements after it
:param new_element: element to append on the begin of list
:type fn: A
:returns: ImmutableList[A]
"""
return ImmutableList(new_element) + self
def map(self, fn: Callable[[Optional[T]], U]) -> 'ImmutableList[U]':
"""
Returns new ImmutableList with each element mapped into
result of argument called with each element of ImmutableList
:param fn: function to call with ImmutableList value
:type fn: Function(A) -> B
:returns: ImmutableList[B]
"""
if self.tail is None:
return ImmutableList(fn(self.head))
return ImmutableList(fn(self.head), self.tail.map(fn))
def filter(self, fn: Callable[[Optional[T]], bool]) -> 'ImmutableList[T]':
"""
Returns new ImmutableList with only this elements that passed
info argument returns True
:param fn: function to call with ImmutableList value
:type fn: Function(A) -> bool
:returns: ImmutableList[A]
"""
if self.tail is None:
if fn(self.head):
return ImmutableList(self.head)
return ImmutableList(is_empty=True)
if fn(self.head):
return ImmutableList(self.head, self.tail.filter(fn))
return self.tail.filter(fn)
def find(self, fn: Callable[[Optional[T]], bool]) -> Optional[T]:
"""
Returns first element of ImmutableList that passed
info argument returns True
:param fn: function to call with ImmutableList value
:type fn: Function(A) -> bool
:returns: A
"""
if self.head is None:
return None
if self.tail is None:
return self.head if fn(self.head) else None
if fn(self.head):
return self.head
return self.tail.find(fn)
def reduce(self, fn: Callable[[U, T], U], acc: U) -> U:
"""
Method executes a reducer function
on each element of the array, resulting in a single output value.
:param fn: function to call with ImmutableList value
:type fn: Function(A, B) -> A
:returns: A
"""
if self.head is None:
return acc
if self.tail is None:
return fn(acc, self.head)
return self.tail.reduce(fn, fn(acc, self.head))
|
import re
"""
parsed data structure
0 => first number
1 => operator
2 => second number
3 => answers (None if display_answers=False)
4 => length of the largest number
"""
def arithmetic_arranger(problems, display_answers=False):
parsed = parse_data(problems)
if type(parsed) != list:
return parsed
parsed = calculate_answers(parsed)
parsed = calculate_lengths(parsed)
output = ""
spacer = " " * 4
for i,problem in enumerate(parsed):
if i:
output += spacer;
output += format_number(problem[0], problem[4] + 2)
output += "\n"
for i,problem in enumerate(parsed):
if i:
output += spacer
output += problem[1] + " " + format_number(problem[2], problem[4])
output += "\n"
for i,problem in enumerate(parsed):
if i:
output += spacer
output += "-" * (problem[4] + 2)
if display_answers:
output += "\n"
for i,problem in enumerate(parsed):
if i:
output += spacer
output += format_number(problem[3], problem[4] + 2)
return output
def calculate_answers(parsed):
for problem in parsed:
if problem[1] == "+":
problem.append(problem[0] + problem[2])
if problem[1] == "-":
problem.append(problem[0] - problem[2])
return parsed
def calculate_lengths(parsed):
for problem in parsed:
problem.append(len(str(max(problem[0], problem[2], problem[3]))));
return parsed
def format_number(number, length):
if(len(str(number)) < 0):
number = number - 1
spaces = " " * (length - len(str(number)))
return spaces + str(number)
def parse_data(problems):
if len(problems) > 5:
return "Error: Too many problems."
ret = []
for problem in problems:
splits = re.split("\s", problem)
if(splits[1] != "+" and splits[1] != "-"):
return "Error: Operator must be '+' or '-'."
if(len(splits[0]) > 4 or len(splits[2]) > 4):
return "Error: Numbers cannot be more than four digits."
try:
el = [int(splits[0]), splits[1], int(splits[2])]
except ValueError:
return "Error: Numbers must only contain digits."
ret.append(el)
return ret
|
def elefantes(n):
if n <= 0: return ""
if n == 1: return "1 elefante incomoda muita gente"
return elefantes(n - 1) + str(n) + " elefantes " + incomodam(n) + ("muita gente" if n % 2 > 0 else "muito mais")
def incomodam(n):
if n <= 0: return ""
if n == 1: return "incomodam "
return "incomodam " + incomodam(n - 1)
|
class Employee:
def __init__(self, first,last, pay):
self.first = first
self.last = last
self.email = first + '.' + last + '@company.com'
self.pay = pay
def full_name(self):
return '{} {}'.format(self.first,self.last)
emp1= Employee('Corey','Schafer',500000)
emp2 = Employee('Test','User',60000)
print(emp1.full_name())
print(Employee.full_name(emp2))
|
#!/usr/bin/python3
def uniq_add(my_list=[]):
if my_list:
summ = 0
uniq_list = list(set(my_list))
for x in uniq_list:
summ += x
return summ
else:
return 0
|
#!/usr/bin/python3
"""
Write an empty class BaseGeometry
"""
class MyInt(int):
"""a class as subclass of int"""
def __eq__(self, other):
if int(self) == int(other):
return False
else:
return True
def __ne__(self, other):
if int(self) != int(other):
return False
else:
return True
|
import unittest
from movies import Movies
class MoviesTest(unittest.TestCase):
def setUp(self):
self.m = Movies()
def test_movies_sort_by_one_column_year(self):
sql = """SELECT TITLE, YEAR FROM MOVIES ORDER BY YEAR DESC """
query = self.m.query_db(sql)
self.assertEqual(self.m.sort_by('Year'), query)
def test_movies_sort_by_two_columns(self):
sql = """SELECT TITLE, GENRE, BOX_OFFICE FROM MOVIES
ORDER BY GENRE ASC, BOX_OFFICE DESC"""
query = self.m.query_db(sql)
self.assertEqual(self.m.sort_by('Genre', 'box_office'), query)
def test_movies_filter_by_director(self):
query = self.m.filter_by('director', 'Fincher')
self.assertEqual(len(query), 3)
def test_movies_filter_by_actor(self):
query = self.m.filter_by('actors', 'DiCaprio')
self.assertEqual(len(query), 5)
def test_movies_filter_by_oscar_only_nominated(self):
query = self.m.filter_by('awards', 'nominated')
self.assertEqual(len(query), 30)
def test_movies_filter_by_awards_won_more_than_percent_nominations(self):
query = self.m.filter_by('awards', '80')
self.assertEqual(len(query), 41)
def test_movies_filter_by_language(self):
query = self.m.filter_by('language', 'spanish')
self.assertEqual(len(query), 17)
def test_movies_compare_by_rating(self):
query = self.m.compare('imdb_rating', 'Seven Pounds', 'Memento')
self.assertEqual(query, ('Memento', 8.4))
def test_movies_compare_by_box_office(self):
query = self.m.compare('box_office', 'Seven Pounds', 'Memento')
self.assertEqual(query, ('Seven Pounds', 69951824))
def test_movies_compare_by_numbers_awards_won(self):
query = self.m.compare('awards', 'Seven Pounds', 'Memento')
self.assertEqual(query, ('Memento', 56))
def test_movies_compare_by_runtime(self):
query = self.m.compare('runtime', 'Seven Pounds', 'memento')
self.assertEqual(query, ('Seven Pounds', 123))
def test_highsores(self):
highscore_query = [
('Runtime', 'Gone with the Wind', '3h58m'),
('Box Office', 'The Dark Knight', '$533,316,061'),
('IMDB Rating', 'The Shawshank Redemption', 9.3),
('Oscars', 'Ben Hur', 11),
('Awards Won', 'Boyhood', 171),
('Nominations', 'Boyhood', 209),
]
self.assertEqual(self.m.highscores(), highscore_query)
if __name__ == '__main__':
unittest.main()
|
from random import randint, choice, choices
from tile import Tile
from copy import deepcopy
from gridStack import GridStack
class Grid:
def __init__(self, arrays=None, cols=4, rows=4):
"""
Creates the Grid object
:arrays: 2d array that will populate the grid
:cols: number of columns in the grid
:rows: number of rows in the grid
:raises AssertionError: raises error when array is not rectangular
:TODO: fix undo
"""
self.score = 0
# self.stack = GridStack()
# Creates a random grid with 2 random tiles
if not arrays:
self.grid = [[Tile(0) for x in range(cols)] for y in range(rows)]
self.addTile()
self.addTile()
# Create a predetermined grid
else:
assert(isinstance(arrays[0], list)), 'Creating game with array failed. Must pass 2D array.'
self.grid = []
width = len(arrays[0])
for r in arrays:
assert(width == len(r)), 'Rows must have same lengths'
row = []
width = len(r)
for num in r:
row.append(Tile(num))
self.grid.append(row)
self.num_rows = len(self.grid)
self.num_cols = len(self.grid[0])
def __str__(self):
ret = ''
for row in self.grid:
for t in row:
if t.val != 0:
ret += '{: ^6}'.format(str(t.val))
else:
ret += '{: ^6}'.format('_')
ret += '\n\n'
return ret
def __repr__(self):
return self.__str__()
def __eq__(self, other):
for r in range(self.num_rows):
for c in range(self.num_cols):
if self.grid[r][c] != other.grid[r][c]:
return False
return True
def checkGameOver(self):
"""Returns True if there are no more moves to make, else False"""
directions = ['UP', 'DOWN', 'LEFT', 'RIGHT']
counter = 0
# Try all moves and count non-moves
for direction in directions:
test_grid = deepcopy(self)
test_grid.slide(direction)
if test_grid == self:
counter += 1
return counter == 4
def slide(self, direction):
"""
Slides all the tiles in the direction of the key press
:direction: str representing where the tiles will slide
:return: None
"""
def slideTiles(r, c):
"""Helper function to slide the tiles and merge. Helps reduce redundant code"""
global merged
currTile = self.grid[r][c]
if currTile.val != 0:
if len(shifted) > 0:
if shifted[-1] == currTile and not merged:
merged = True
shifted.pop()
shifted.append(Tile(currTile.val*2))
self.score += currTile.val * 2
else:
shifted.append(currTile)
merged = False
else:
shifted.append(currTile)
merged = False
if direction == 'UP':
# Loop through grid in opp dir and collect non-zero tiles
for c in range(self.num_cols):
shifted = []
merged = False
for r in range(self.num_rows):
slideTiles(r, c)
# Copy over new column
for i in range(self.num_rows - len(shifted)):
shifted.append(Tile(0))
for i, new in enumerate(shifted):
self.grid[i][c] = new
elif direction == 'RIGHT':
# Loop through grid in opp dir and collect non-zero tiles
for r in range(self.num_rows):
shifted = []
merged = False
for c in range(self.num_cols-1, -1, -1):
slideTiles(r, c)
# Copy over new row
for i in range(self.num_cols - len(shifted)):
shifted.append(Tile(0))
self.grid[r] = list(reversed(shifted))
elif direction == 'DOWN':
# Loop through grid in opp dir and collect non-zero tiles
for c in range(self.num_cols):
shifted = []
merged = False
for r in range(self.num_rows-1, -1, -1):
slideTiles(r, c)
# Copy over new column
for i in range(self.num_rows - len(shifted)):
shifted.append(Tile(0))
for i, new in enumerate(reversed(shifted)):
self.grid[i][c] = new
elif direction == 'LEFT':
# Loop through grid in opp dir and collect non-zero tiles
for r in range(self.num_rows):
shifted = []
merged = False
for c in range(self.num_cols):
slideTiles(r, c)
# Copy over new row
for i in range(self.num_cols - len(shifted)):
shifted.append(Tile(0))
self.grid[r] = list(shifted)
def addTile(self):
"""
Randomly adds a 2 or a 4 tile into an open space
:return: None, adds tile to grid
"""
loc = [] # Possible locations for new tiles
nums = [2, 4] # The values of tiles
# Loop through grid and compile empty tiles
for i, r in enumerate(self.grid):
for j, c in enumerate(r):
if c.val == 0:
loc.append((i,j))
# Choose a location and add a random value
coord = choice(loc)
newVal = choices(nums, weights=[.9, .1], k=1)[0]
self.grid[coord[0]][coord[1]].setVal(newVal)
def checkWin(self):
"""
Checks grid to see if there is a 2048 tile
:return: True if there is a 2048 tile, else False
"""
# Loop through all tiles and check for 2048
for r in range(self.num_rows):
for c in range(self.num_cols):
if self.grid[r][c].val == 2048:
return True
return False
# def undo(self):
# """
# Uses a stack to undo moves and reflects changes on the grid
# :return: None, grid itself is edited
# """
# if self.stack.top():
# self.grid = self.stack.pop()
# def rememberGrid(self):
# self.stack.push(deepcopy(self.grid))
# print(self.stack)
|
#!/usr/bin/python3
# to concatenate strings and numbers
s = 'aaa' + 'bbb' + 'ccc'
print(s)
s1 = 'aaa'
s2 = 'bbb'
s3 = 'ccc'
s4 = 'ddd'
s = s1 + s2 + s3 + s4
print(s)
s = s1 + '.' + s2 + '.' + s3 + '.' + s4
print(s)
|
#!C:\Python3\python.exe
import nourrisson_normes
# Fonction pour valider que la valeur val est un entier
def isInteger(val):
try:
int(val)
return True
except ValueError:
return False
# Fonction pour valider que la valeur val est un décimal
def isFloat(val):
try:
float(val)
return True
except ValueError:
return False
# Fonction pour valider le genre entré
def entrer_genre():
# Demande le genre à l'utilisateur une 1ère fois
genre = input("Entrez le genre de votre nourrisson ('g' pour garçon, 'f' pour fille) : ")
# Tant que l'entrée n'est pas 'g' ou 'f' on redemande une nouvelle entrée
while genre != 'g' and genre != 'f':
# Affichage du message d'erreur de saisie en rappeleant l'entrée
print(f"Erreur de saisie : {genre} ne fait pas partie des choix possibles !")
genre = input("Entrez le genre de votre nourrisson ('g' pour garçon, 'f' pour fille) : ")
# Renvoi de l'entrée validée
return genre
# Fonction pour valider l'age entré
def entrer_age():
# Demande l'age à l'utilisateur une 1ère fois
age = input("Veuillez entrer l'age de votre nourrisson en mois (entre 0 et 60 mois) : ")
# Tant que l'entrée n'est pas un entier compris entre 0 et 60 on redemande une nouvelle entrée
while not isInteger(age) or int(age) < 0 or int(age) > 60:
# Affichage du message d'erreur de saisie en rappeleant l'entrée
print(f"Erreur de saisie : {age} ne fait pas partie des choix possibles !")
age = input("Veuillez entrer l'age de votre nourrisson en mois (entre 0 et 60 mois) : ")
# Renvoi de l'entrée validée converti en entier
return int(age)
# Fonction pour valider le poids entré
def entrer_poids():
# Demande le poids à l'utilisateur une 1ère fois
poids = input("Veuillez entrer le poids de votre nourrisson en kg : ")
# Tant que l'entrée n'est pas un float ou un entier et qu'il n'est pas positif on redemande l'entrée
while not (isFloat(poids) or isInteger(poids)) or float(poids) < 0:
# Affichage du message d'erreur de saisie en rappeleant l'entrée
print(f"Erreur de saisie : {poids} ne fait pas partie des choix possibles !")
poids = input("Veuillez entrer le poids de votre nourrisson en kg : ")
# Renvoi de l'entrée validée converti en décimal
return float(poids)
# Fonction pour valider la taille entrée
def entrer_taille():
# Demande la taille à l'utilisateur une 1ère fois
taille = input("Veuillez entrer la taille de votre nourrisson en cm : ")
# Tant que l'entrée n'est pas un float ou un entier et qu'il n'est pas positif on redemande l'entrée
while not (isFloat(taille) or isInteger(taille)) or float(taille) < 0:
# Affichage du message d'erreur de saisie en rappeleant l'entrée
print(f"Erreur de saisie : {taille} ne fait pas partie des choix possibles !")
taille = input("Veuillez entrer la taille de votre nourrisson en cm : ")
# Renvoi de l'entrée validée converti en décimal
return float(taille)
# Fonction pour valider le tour du crane entré
def entrer_crane():
# Demande le tour du crane à l'utilisateur une 1ère fois
crane = input("Veuillez entrer le périmètre cranien de votre nourrisson en cm : ")
# Tant que l'entrée n'est pas un float ou un entier et qu'il n'est pas positif on redemande l'entrée
while not (isFloat(crane) or isInteger(crane)) or float(crane) < 0:
# Affichage du message d'erreur de saisie en rappeleant l'entrée
print(f"Erreur de saisie : {crane} ne fait pas partie des choix possibles !")
crane = input("Veuillez entrer le périmètre cranien de votre nourrisson en cm : ")
# Renvoi de l'entrée validée converti en décimal
return float(crane)
# Fonction pour afficher la réponse du poids normé
def message_norme_genre(genre):
# Choix d'une partie variable du message en fonction du genre
if genre == 'g':
message_genre = "un garçon de"
else:
message_genre = "une fille de"
# Renvoi du message en clair
return message_genre
# Fonction pour afficher la réponse normé ou non
def message_norme_ou_pas(valeur, valeur_mini, valeur_maxi):
# Choix d'une partie variable du message en fonction de son emplacement dans la norme
if valeur > valeur_mini and valeur < valeur_maxi:
message_norme = "est dans la norme !"
else:
message_norme = "n'est pas dans la norme !"
# Renvoi du message en clair
return message_norme
# Fonction pour afficher la réponse du poids normé
def message_norme_poids(genre, age, poids, poids_mini, poids_maxi):
# Choix d'une partie variable du message en fonction du genre
message_genre = message_norme_genre(genre)
# Choix d'une partie variable du message en focntion de son emplacement dans la norme
message_norme = message_norme_ou_pas(poids, poids_mini, poids_maxi)
# Définition des lignes complètes des messages
ligne_1 = f"La norme de poids pour {message_genre} {age} mois est située entre {poids_mini} kg et {poids_maxi} kg"
ligne_2 = f"Le poids de votre nourrisson ({poids} kg) {message_norme}"
# Concatenation des 2 lignes
message = ligne_1 + '\n' + ligne_2
# Renvoi du message en clair
return message
# Fonction pour afficher la réponse de la taille normée
def message_norme_taille(genre, age, taille, taille_mini, taille_maxi):
# Choix d'une partie variable du message en fonction du genre
message_genre = message_norme_genre(genre)
# Choix d'une partie variable du message en focntion de son emplacement dans la norme
message_norme = message_norme_ou_pas(taille, taille_mini, taille_maxi)
# Définition des lignes complètes des messages
ligne_1 = f"La norme de taille pour {message_genre} {age} mois est située entre {taille_mini} cm et {taille_maxi} cm"
ligne_2 = f"Le taille de votre nourrisson ({taille} cm) {message_norme}"
# Concatenation des 2 lignes
message = ligne_1 + '\n' + ligne_2
# Renvoi du message en clair
return message
# Fonction pour afficher la réponse du tour de crane normé
def message_norme_crane(genre, age, crane, crane_mini, crane_maxi):
# Choix d'une partie variable du message en fonction du genre
message_genre = message_norme_genre(genre)
# Choix d'une partie variable du message en focntion de son emplacement dans la norme
if poids > poids_mini and poids < poids_maxi:
message_norme = "est dans la norme !"
else:
message_norme = "n'est pas dans la norme !"
# Définition des lignes complètes des messages
ligne_1 = f"La norme du périmètre cranien pour {message_genre} {age} mois est située entre {crane_mini} cm et {crane_maxi} cm"
ligne_2 = f"Le périmètre cranien de votre nourrisson ({crane} cm) {message_norme}"
# Concatenation des 2 lignes
message = ligne_1 + '\n' + ligne_2
# Renvoi du message en clair
return message
# Affichage du message d'accueil
print("Bienvenue dans ce programme de vérification des constantes de votre nourisson !")
# Définition des différentes variable par l'utilisateur
genre = entrer_genre()
age = entrer_age()
poids = entrer_poids()
taille = entrer_taille()
crane = entrer_crane()
# Récupération des valeurs dans les tableaux de référence à l'index correspond à l'age en mois
if genre == 'g':
poids_mini = nourrisson_normes.low_weights_boys[age]
poids_maxi = nourrisson_normes.high_weights_boys[age]
taille_mini = nourrisson_normes.low_heights_boys[age]
taille_maxi = nourrisson_normes.high_heights_boys[age]
crane_mini = nourrisson_normes.low_skulls_boys[age]
crane_maxi = nourrisson_normes.high_skulls_boys[age]
else:
poids_mini = nourrisson_normes.low_weights_girls[age]
poids_maxi = nourrisson_normes.high_weights_girls[age]
taille_mini = nourrisson_normes.low_heights_girls[age]
taille_maxi = nourrisson_normes.high_heights_girls[age]
crane_mini = nourrisson_normes.low_skulls_girls[age]
crane_maxi = nourrisson_normes.high_skulls_girls[age]
# Affiche une ligne vide
print()
# Affichage des différents messages re réponse
print(message_norme_poids(genre, age, poids, poids_mini, poids_maxi))
print()
print(message_norme_taille(genre, age, taille, taille_mini, taille_maxi))
print()
print(message_norme_crane(genre, age, crane, crane_mini, crane_maxi))
|
import sqlite3, hashlib
def buildDB(): #builds a database with three tables
data="data.db"
db=sqlite3.connect(data)
c=db.cursor()
command="CREATE TABLE if not EXISTS Story_List(ID INTEGER PRIMARY KEY, Title TEXT, Story TEXT)"
c.execute(command)
command="CREATE TABLE if not EXISTS Edits(ID INTEGER,Edit TEXT,Timestamp TIMESTAMP, Username TEXT)"
c.execute(command)
command="CREATE TABLE if not EXISTS Accounts(Username TEXT,Password TEXT)"
c.execute(command)
db.commit()
db.close()
def verifyUser(user): #searches database if user exists
data="data.db"
db=sqlite3.connect(data)
c=db.cursor()
command = "SELECT count(*) FROM Accounts WHERE Username=\"{}\";"
countWithUser = c.execute( command.format(user) )
data = c.fetchone()[0]
return(data)
db.commit()
db.close()
def rightLogin(user,givenPass): #searches database to match username and password
data="data.db"
db=sqlite3.connect(data)
c=db.cursor()
command='''
Select Password
From Accounts
Where Username=\"{}\"
'''
c.execute(command.format(user))
info=c.fetchone()
if not info is None and (hashlib.md5((givenPass.encode('utf-8')))).hexdigest()==info[0]:
return 1 #correct
else:
return 2 #incorrect
db.commit()
db.close()
def addUser(user,p): #adds user name and pass into database
data="data.db"
db=sqlite3.connect(data)
c=db.cursor()
command="INSERT INTO Accounts VALUES(\"{}\",\"{}\")"
c.execute( command.format(user,(hashlib.md5(p.encode('utf-8'))).hexdigest()) )
db.commit()
db.close()
def getStory(storyID): #returns row requested
db = sqlite3.connect('data.db')
c = db.cursor()
command = '''
select
Story_List.Title,
Edits.Edit,
Edits.Timestamp,
Edits.Username
from
Story_List
left join
Edits using (ID)
where Story_List.ID={}
order by Edits.Timestamp desc;
'''
c.execute(command.format(storyID,storyID))
result = c.fetchone()
db.commit()
db.close()
return result
def userStories(user): #list of stories user has contributed to
data="data.db"
db=sqlite3.connect(data)
c=db.cursor()
command='''
SELECT
ID,Title
FROM
Story_List
WHERE
EXISTS (
SELECT Username
FROM Edits
WHERE
Username==\'{}\' AND ID=Story_List.ID
);
'''
c.execute( command.format(user) )
results = c.fetchall()
print(results)
db.commit()
db.close()
return results
def otherStories(user): #list of stories user has not contributed to
print('get other stories for {}'.format(user))
data="data.db"
db=sqlite3.connect(data)
c=db.cursor()
command = '''
SELECT
ID,Title
FROM
Story_List
WHERE
NOT EXISTS (
SELECT Username
FROM Edits
WHERE
Username==\'{}\' AND ID=Story_List.ID
);
'''
c.execute( command.format(user) )
results = c.fetchall()
db.commit()
db.close()
return results
def addEdit(username,id,editText): #adds contribution to database
db = sqlite3.connect('data.db')
c = db.cursor()
command = 'select count(*) from Edits where id=\"{}\" and username=\"{}\"'
c.execute(command.format(id,username))
if(c.fetchone()[0] > 0):
db.commit()
db.close()
return 'You have already contributed to this story!'
else:
command = '''
insert into Edits
(ID,Edit,Timestamp,Username)
values
('{}','{}',datetime('now'),'{}');
'''
c.execute(command.format(id,editText,username))
db.commit()
db.close()
return 'Submission successfully added.'
def story(id): #gets the content of the stories
db = sqlite3.connect('data.db')
c = db.cursor()
command='''Select Story, Title
From Story_List
Where ID={}
'''
c.execute(command.format(id))
result=c.fetchone()
db.commit()
db.close()
return result
def update(text,story_id): #updates full story
db=sqlite3.connect('data.db')
c=db.cursor()
command='''
Select Story
From Story_List
Where ID=\"{}\"
'''
c.execute(command.format(story_id))
info=c.fetchone()[0]
info=info+" "+text
command='''
UPDATE Story_List
SET Story=\"{}\"
WHERE ID=\"{}\"
'''
c.execute(command.format(info,story_id))
db.commit()
db.close()
def addStory(title,story): #adds a new story to database
data="data.db"
db=sqlite3.connect(data)
c=db.cursor()
# determine how many stories already exist
command = "SELECT count(*) FROM Story_List;"
c.execute(command)
newID = c.fetchone()[0]
print(newID)
command="INSERT INTO Story_List VALUES(\"{}\",\"{}\",\"{}\")"
c.execute( command.format(newID,title,story) )
db.commit()
db.close()
return newID
def userHasEdited(username,id): # checks whether story should be visible to user
db = sqlite3.connect('data.db')
c = db.cursor()
command="select count(*) from Edits where ID={} and Username=\'{}\'"
c.execute(command.format(id,username))
countEdits = c.fetchone()[0]
db.commit()
db.close()
return countEdits == 1
|
# -*- coding: utf-8 -*-
"""Exercise 3.
Split the dataset based on the given ratio.
"""
import numpy as np
def split_data(x, y, ratio, seed=1):
"""split the dataset based on the split ratio."""
# set seed
np.random.seed(seed)
# ***************************************************
# INSERT YOUR CODE HERE
# split the data based on the given ratio: TODO
# ***************************************************
indices = np.random.permutation(x.size)
train_size = int(np.floor(ratio*x.size))
train_indices = indices[:train_size]
test_indices = indices[train_size:]
x_train, y_train = x[train_indices], y[train_indices]
x_test, y_test = x[test_indices], y[test_indices]
return x_train, y_train, x_test, y_test
|
"""
재귀 용법(Recursive Call, 재귀호출)
- 함수 안에서 동일한 함수를 호출하는 형태
"""
"""
예제) 팩토리얼
2! = 1 x 2
3! = 1 x 2 x 3
4! = 1 x 2 x 3 x 4
...
n! = 1 x 2 x 3 x ... x n
~> 규칙
if n > 1:
return n * function(n-1)
else:
return n
>> 시간 복잡도 & 공간 복잡도
= factorial(n) 함수는 n-1번의 factorial() 함수를 호출한다.
- 일종의 n-1번 반복문을 호출한 것과 동일
- factorial() 함수를 호출할 때마다, 지역 변수 n이 생성된다.
따라서, 시간 복잡도 / 공간 복잡도 = O(n-1) = O(n)
>> 일반적인 형태 1.
def function(입력):
if 입력 > 일정값: # 입력이 일정 값 이상이면
return 입력 * function(입력 - 1)
else:
return 일정값, 입력값, 또는 특정값 # 재귀 호출 종료
>> 일반적인 형태 2.
def function(입력):
if 입력 <= 일정값: # 입력이 일정 값보다 작으면
return 일정값, 입력값, 또는 특정값 # 재귀 호출 종료
else:
return 입력 * function(입력 - 1)
> 재귀 호출은 '스택'처럼 관리된다.
> 파이썬에서 재귀호출은 '1000회 이하'이어야 한다.
"""
import random
random.seed(428)
# 일반적인 형태 1.
def factorial_1(num):
if num > 1:
return num * factorial_1(num - 1)
else:
return num
# 일반적인 형태 2.
def factorial_2(num):
if num <= 1:
return num
else:
return num * factorial_2(num - 1)
"""
예제 1. 다음 함수를 재귀 함수를 활용해서 완성해서 1부터 num까지의 곱이 출력되게 만드세요
def muliple(data):
if data <= 1:
return data
return -------------------------
multiple(10)
"""
def muliple(data):
if data <= 1:
return data
else:
return data * muliple(data - 1)
"""
예제 2. 숫자가 들어 있는 리스트가 주어졌을 때, 리스트의 합을 리턴하는 함수를 만드세요
"""
def sum(list):
total = 0
for i in list:
total += i
return total
"""
예제 2-1. 숫자가 들어 있는 리스트가 주어졌을 때, 리스트의 합을 리턴하는 함수를 만드세요 (재귀함수를 써보세요)
def sum_recur(list):
if len(list) == 1:
return list[0]
return --------------------------------
"""
def sum_recur(list):
if len(list) <= 1:
return list[0]
else:
return list[0] + sum_recur(list[1:])
"""
예제 3.
회문(palindrome)은 순서를 거꾸로 읽어도 제대로 읽은 것과 같은 단어와 문장을 의미함
회문을 판별할 수 있는 함수를 리스트 슬라이싱을 활용해서 만드세요
"""
def palindrome(str):
return str == str[::-1]
# [::-1] ~> 처음부터 끝까지 -1칸 간격으로 역순
# 즉, 거꾸로 하나씩 문자를 가져와 처음부터 차려대로 문자와 비교
# 결과는 True or False
"""
예제 3-1.
회문(palindrome)은 순서를 거꾸로 읽어도 제대로 읽은 것과 같은 단어와 문장을 의미함
회문을 판별할 수 있는 함수를 재귀함수를 활용해서 만드세요.
"""
def palindrome_rucur(str):
if len(str) == 1:
return True
if str[0] == str[-1]:
return palindrome(str[1:-1])
else:
return False
"""
예제 4.
정수 n에 대해 n이 홀수이면 3 X n + 1 을 하고, n이 짝수이면 n 을 2로 나눕니다.
이렇게 계속 진행해서 n 이 결국 1이 될 때까지 2와 3의 과정을 반복합니다.
예를 들어 n에 3을 넣으면,
3
10
5
16
8
4
2
1
이 됩니다.
이렇게 정수 n을 입력받아, 위 알고리즘에 의해 1이 되는 과정을 모두 출력하는 함수를 작성하세요.
"""
def func(n):
print(n)
if n == 1:
return n
if n % 2 == 1: # 홀수라면
return func((3 * n) + 1) # 계산하고 다시 func() 함수를 호출해 반복하며 'n == 1'이 되면 리턴하며 종료
else: # 짝수라면
return func((n / 2)) # 계산하고 다시 func() 함수를 호출해 반복하며 'n == 1'이 되면 리턴하며 종료
"""
예제 5.
문제: 정수 4를 1, 2, 3의 조합으로 나타내는 방법은 다음과 같이 총 7가지가 있음
1+1+1+1
1+1+2
1+2+1
2+1+1
2+2
1+3
3+1
정수 n이 입력으로 주어졌을 때, n을 1, 2, 3의 합으로 나타낼 수 있는 방법의 수를 구하시오
힌트: 정수 n을 만들 수 있는 경우의 수를 리턴하는 함수를 f(n) 이라고 하면,
f(n)은 f(n-1) + f(n-2) + f(n-3) 과 동일하다는 패턴 찾기
출처: ACM-ICPC > Regionals > Asia > Korea > Asia Regional - Taejon 2001
~>
N[1] = 1
N[2] = 2 (1+1, 2)
N[3] = 4 (1+1+1, 1+2, 2+1, 3)
그렇다면 N[4]는
1) 맨 앞에 1을 놓으면 뒤에는 3이 되어야 함
1 + {합이 3이 되는 조합} = 1 + (1+1+1), 1 + (1+2, 2+1), 1 + (3) ---> N[3] = 4
2) 맨 앞에 2를 놓으면 뒤에는 2가 되어야 함
2 + {합이 2가 되는 조합} = 2 + (1+1), 2 + (2) ---> N[2] = 2
3) 맨 앞에 3을 놓으면 뒤에는 1이 되어야 함
3 + {1이 되는 조합} = 3 + (1) ---> N[1] = 1
따라서 N[4] = N[3] + N[2] + N[1] = 1 + 2 + 4 = 7
이를 N[i]로 확장하면, 아래와 같은 점화식으로 표현 가능
N[i] = N[i-1] + N[i-2] + N[i-3] 이때 4 <= i <= n
"""
def combination(n):
if n < 0:
return 0 # 단, 정수 0과 음수는 나타낼수 없으므로 그대로 0을 리턴한다.
if n == 0:
return 0
elif n == 1: # N[1]
return 1
elif n == 2: # N[2]
return 2
elif n == 3: # N[3]
return 4
# N[i] = N[i-1] + N[i-2] + N[i-3]
return combination(n-1) + combination(n-2) + combination(n-3)
if __name__ == '__main__':
for num in range(10):
print(factorial_1(num))
for num in range(10):
print(factorial_2(num))
print(muliple(10))
n = random.sample(range(100), 10)
print(n)
print(sum(n))
n2 = random.sample(range(100), 10)
print(n2)
print(sum_recur(n2))
str = "abcde1edcba"
print(palindrome(str)) # True
print(palindrome_rucur(str)) # True
print(func(3))
print(func(4))
print(combination(4), "개 입니다.") # 7 개 입니다.
|
import numpy as np
def CalculatePearson(x, y):
mean_of_x = np.mean(x)
mean_of_y = np.mean(y)
x_n = x - mean_of_x
y_n = y - mean_of_y
return np.mean(x_n * y_n)/(np.std(x) * np.std(y))
def test():
x = [15, 12, 8, 8, 7, 7, 7, 6, 5, 3]
y = [10, 25, 17, 11, 13, 17, 20, 13, 9, 15]
value = CalculatePearson(x, y)
print("%.3f" %value)
def main():
test()
if __name__ == "__main__":
main()
|
'''
Created on Jan 6, 2017
@author: stephenkoh
'''
import mingus.core.intervals as intervals
key = str(input('Please enter a key: '))
note = str(input('Please enter a note: '))
third = intervals.third(note, key)
fifth = intervals.fifth(note, key)
print(note, third, fifth)
|
x = str(input("enter the value:"))
x =x.casefold()
rev = x[::-1]
print (rev)
if rev==x:
print("this is palindrome")
else:
print("this is not palindrome")
|
def allFibs(n):
fibs = [None] * n
for i in range(n):
print "{}th fib {}".format(i+1, fib(i, fibs))
def fib(n, fibs):
if n == 0:
return 0
elif n == 1:
return 1
elif fibs[n] is not None:
return fibs[n]
fibs[n] = fib(n-1, fibs) + fib(n-2, fibs)
return fibs[n]
allFibs(15)
|
#! /usr/bin/env python
def fib(n):
a, b = 0, 1
while a<n:
print a,
a, b=b, a+b
fib(2000)
def fib2(n):
result = []
a, b = 0, 1
while a<n:
result.append(a)
a, b= b, a+b
return result
print 'next line: '
for x in fib2(1000):
print x
def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
print "--This parrot wouldn't", action,
print "if you put", voltage, "volts through it."
print "--Lovely plumage, the", type
print "--It's", state, "!"
parrot (1000)
parrot (voltage=1000)
parrot(voltage=1000000, action='VOOOOOM')
def cheeseshop(kind, *arguments, **keywords):
print "--Do you have any", kind, "?"
print "--I'm sorry, we're all out of", kind
for arg in arguments:
print arg
print "-"*40
keys = sorted(keywords.keys())
for kw in keys:
print kw, ":", keywords[kw]
cheeseshop(
"Limburger", "It's very runny, sir.",
"It's really very, VERY runny, sir.",
shopkeeper="Michael Palin",
client="John Cleese",
sketch="Cheese Shop Sketch"
)
d = {"voltage" : "xxx", "state":"yyy", "action":"VOOOOOOOOOM"}
parrot(**d)
|
#! /usr/bin/env python
def fib(n):
result=[]
a, b=0, 1
while a<n:
result.append(a)
a, b=b, a+b
return result
def fib2(n):
result = []
a, b=0, 1
while b<n:
result.append(b)
a, b=b, a+b
return result
|
import tweepy # best Twitter API (in my opinion!)
import random # for selecting a random sentence
from nltk.corpus import wordnet
# wordnet is a word database and has so many capabilities! We use it for finding if a word a usually a noun, adjective, verb
# wordnet does not have some words, including swear words :(
from keys import CONSUMER_KEY, CONSUMER_SECRET, ACCESS_KEY, ACCESS_SECRET
# authenticating with tweepy
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth)
# mentions_timeline gets all the tweets you are mentioned in on Twitter
# count = 1 takes only one, the most recent one
mentions = api.mentions_timeline(count=1)
# we make it all lowercase so we can remove the @ tag
mention = str(mentions[0].text).lower().replace("@220madlibs ", "")
# this wordnet function gets the types (noun/adj/verb) and selects the first
# print(wordnet.synsets(mention))
type_of_word = wordnet.synsets(mention)[0].pos()
# sentences to put our word into
# the 'f' in front makes it a string literal, allowing us to do {mention}
noun_sentences = [
f"Hey {mention} how are you?",
f"One day a {mention} was walking down the road. 'This is nice' said the {mention}.",
f"Don't you dare look at the {mention}, it will destroy you.",
f"I really love the {mention}. The {mention} is great.",
f"Like they always say, too many cooks spoil the {mention}."
]
verb_sentences = [
f"You should {mention}",
f"Whenever I {mention}, I'm happy.",
f"{mention} is my favourite thing to do in the world.",
f"Have you tried {mention}? It's so relaxing.",
f"My boyfriend was {mention} last night, so gross."
]
adjective_sentences = [
f"I am so {mention}",
f"Stop trying to make {mention} happen. {mention} will never happen.",
f"The drama teacher told me I was too {mention}",
f"I can't believe you'd do that. That's so {mention}!",
f"I'm a sentient bot. I'm {mention}."
]
# update_status posts a tweet, selecting a random sentence with the word from the mention
if type_of_word == "n":
api.update_status(random.choice(noun_sentences))
elif type_of_word == "v":
api.update_status(random.choice(verb_sentences))
elif type_of_word == "a":
api.update_status(random.choice(adjective_sentences))
|
import sys
class AugmentationType:
def __init__(self, aug_type, sigma=0.1):
self.type = aug_type
self.sigma = 0
self.noise=False
if aug_type == 0:
self.type_text = "Augmentation Type: No Augmentation"
elif aug_type == 1:
self.type_text = "Augmentation Type: Duplication"
elif aug_type == 2:
self.type_text = "Augmentation Type: Duplication with Noise (Sigma = " + str(sigma) + ")"
self.noise=True
self.sigma=sigma
elif aug_type == 3:
self.type_text = "Augmentation Type: SMOTE"
else:
print("Incorrect augmentation type given as input, only 0-3 is accepted")
sys.exit()
|
# read the input
char = input()
List = ["a","e","i","o","u","A","E","I","O","U"]
# solve the problem
count = 0
for i in char:
if i in List:
count += 1
# output the result
print(count)
|
import sys
import random
def read_restaurant(restaurants):
"""Restaurant rating lister."""
# restaurant_roster = open(filename)
# for each line
# right strip
# split @ colon
# put right into dictionary
# index[0] will be key
# index[1] will be value!
for establishment, rating in sorted(restaurants.items()):
print "{} is rated at {}.".format(establishment, rating)
def add_restaurant(restaurants):
new_restaurant = raw_input("Is there a restaurant we're missing? \n"
"Add it for Ratings Points! \n"
"Restaurant name: ")
while True:
new_restaurant_rating = raw_input("Your rating: ")
if 0 < int(new_restaurant_rating) < 6:
restaurants[new_restaurant] = new_restaurant_rating
break
else:
print "Please enter a number rating between 1 and 5"
return restaurants
# restaurant_roster.close()
def edit_rating_rand(restaurants):
"""Allow user to edit rating of random restaurant in restaurants{}"""
random_restaurant = random.choice(restaurants.keys())
print random_restaurant
while True:
user_rating = raw_input("What should the rating be for {}?".format(random_restaurant))
if 0 < int(user_rating) < 6:
restaurants[random_restaurant] = user_rating
print "Rating updated!"
break
else:
print "Please enter a number rating between 1 and 5"
return restaurants
def edit_rating(restaurants):
"""Allow user to select a restaurant and edit its rating"""
chosen_restaurant = raw_input("Please select a restaurant rating to update!")
undercase_restaurants = [k.lower() for k in restaurants]
while True:
# FIXME - need to check using .get() whether key exists to update
if chosen_restaurant.lower() in undercase_restaurants:
new_rating = raw_input("New rating: ")
if 0 < int(new_rating) < 6:
restaurants[chosen_restaurant] = new_rating
break
else:
print "That's not in our system. Would you like to add it?"
user_choice = raw_input("Yes or no: ")
if user_choice.lower() == 'yes':
add_restaurant(restaurants)
else:
break
return restaurants
def start_restaurant_rater():
filename = sys.argv[1]
restaurants = {}
with open(filename) as restaurant_roster:
for line in restaurant_roster:
establishment, rating = line.rstrip().split(":")
restaurants[establishment] = rating
print ("Hello! Welcome to the Restaurant Rater. Type 'a' to see all ratings. \n"
"Type 'b' to add a new restaurant and rate it. \n"
"Type 'c' to edit a random restaurant's rating. \n"
"Type 'd' to edit a selected restaurant's rating \n"
"Type 'q' to quit. \n")
while True:
user_choice = raw_input("type 'a', 'b', c, or 'q': ")
if user_choice.lower() == 'q':
break
elif user_choice.lower() == 'a':
read_restaurant(restaurants)
elif user_choice.lower() == 'b':
restaurants = add_restaurant(restaurants)
elif user_choice.lower() == 'c':
restaurants = edit_rating_rand(restaurants)
elif user_choice.lower() == 'd':
restaurants = edit_rating(restaurants)
else:
print "Please enter a letter from the menu."
start_restaurant_rater()
|
#!/usr/bin/python
import sys;
import matplotlib.pyplot as plt
from matplotlib.patches import Ellipse
import numpy as np
samples = []
for line in sys.stdin:
fields = line.split( ' ' )
delay, throughput = float(fields[ 0 ]), float(fields[ 1 ])
samples.append( [ delay, throughput ] )
samples = np.matrix( samples )
# taken from https://github.com/joferkington/oost_paper_code/blob/master/error_ellipse.py
def get_ellipse(points, nstd=1):
def eigsorted(cov):
vals, vecs = np.linalg.eigh(cov)
order = vals.argsort()[::-1]
return vals[order], vecs[:,order]
cov = np.cov(points, rowvar=False)
vals, vecs = eigsorted(cov)
theta = np.degrees(np.arctan2(*vecs[:,0][::-1]))
# Width and height are "full" widths, not radius
# width, height = 2 * nstd * np.sqrt(vals)
width, height = nstd * np.sqrt(vals)
return [ width, height, theta ]
def get_ellipse_coords(a=0.0, b=0.0, x=0.0, y=0.0, angle=0.0, k=2):
""" Draws an ellipse using (360*k + 1) discrete points; based on pseudo code
given at http://en.wikipedia.org/wiki/Ellipse
k = 1 means 361 points (degree by degree)
a = major axis distance,
b = minor axis distance,
x = offset along the x-axis
y = offset along the y-axis
angle = clockwise rotation [in degrees] of the ellipse;
* angle=0 : the ellipse is aligned with the positive x-axis
* angle=30 : rotated 30 degrees clockwise from positive x-axis
"""
pts = np.zeros((360*k+1, 2))
beta = -angle * np.pi/180.0
sin_beta = np.sin(beta)
cos_beta = np.cos(beta)
alpha = np.radians(np.r_[0.:360.:1j*(360*k+1)])
sin_alpha = np.sin(alpha)
cos_alpha = np.cos(alpha)
pts[:, 0] = x + (a * cos_alpha * cos_beta - b * sin_alpha * sin_beta)
pts[:, 1] = y + (a * cos_alpha * sin_beta + b * sin_alpha * cos_beta)
return pts
means = np.mean( samples, axis=0 )
center_x = means[ 0, 0 ]
center_y = means[ 0, 1 ]
width, height, theta = get_ellipse( samples )
#print center_x, center_y
#print width, height, theta
for i in get_ellipse_coords(width, height, center_x, center_y, -theta ):
print i[ 0 ], i[ 1 ]
|
import random
class TheVote:
def __init__(self):
pass
def findMajority(self, voteLyst):
'''returns eliminated person based on votes'''
votes = {}
highestVotes = []
highestVoteCount = 0
for vote in voteLyst:
votes[vote] = votes.get(vote, 0) + 1
if votes[vote] > highestVoteCount:
highestVotes = [vote]
highestVoteCount = votes[vote]
elif votes[vote] == highestVoteCount:
highestVotes.append(vote)
if len(highestVotes) == 1:
#non-tie case
return highestVotes[0]
else:
#tie case
return self.tieBreaker(highestVotes)
def tieBreaker(self, voteLyst):
'''in the event of a tie, one of the tied people are randomly eliminated'''
return random.choice(voteLyst)
|
def func(n, A, B, C):
if n == 1:
print(A + " -- >" + B)
else:
func(n - 1, A, C, B)
print(A + " -- >" + B)
func(n - 1, C, B, A)
func(3, A='A', B='B', C='C')
|
def check_0_max(value, max_value):
"""
Check if the value in range(0, max_value) and if it is not change to closest(0 or max_value)
:param value: integer or float
:param max_value: integer or float
:return: 0 or max_value or value
"""
if value not in range(0, max_value):
if value <= 0:
return 0
else:
return max_value
return value
|
#Organizza con un dizionario la rubrica con i nomi delle persone e i rispettivi numeri telefonici.
#Fornito poi il nome della persona, il programma visualizza il suo numero di telefono oppure un messaggio nel caso la persona non sia presente nella rubrica.
rubrica = {"Marco":"343 897 3922",
"Filippo":"375 542 9054",
"Alberto":"366 738 0394",
"Riccardo":"329 489 3829",
"Lorenzo":"334 789 5692",
"Fausto":"329 239 1348",
"Luca":"390 687 2645"}
contatto = input("Inserire il nome del contatto della quale si vuole sapere il numero: ")
if contatto in rubrica:
print("Il numero del contatto", contatto,"è:", rubrica[contatto])
else:
print("Il contatto", contatto,"non è salvato nella rubrica.")
|
a=10
b=20
m=15
y=a+b
print(y)
m +=10
print(m)
m -=10
print(m)
m *=10
print(m)
m /=10
print(m)
m %=10
print(m)
m **=10
print(m)
m //=10
print(m)
|
# Accessing 2D Array using While Loop
from numpy import *
a = array([[10, 20, 30, 40], [50, 60, 70, 80]])
n = len(a)
i = 0
while i<n:
j=0
while j<len(a[i]):
print('index',i,j,"=",a[i][j])
j+=1
i+=1
print()
|
#!/bin/python3
# go to https://trinket.io/embed/python/33e5c3b81b#.W56BiV5KjIV
alphabet = 'abcdefghijklmnopqrstuvwxyz'
key = int(input('Please enter a key number: ')) #you can use negative numbers to go in reverse
newmessage = ''
message = input('Please enter a message: ') #the message that is created
for character in message:
if character in alphabet:
position = alphabet.find(character)
newposition = (position + key) % 26
newcharacter = alphabet[newposition]
newmessage += newcharacter
else:
newmessage += character
print('The new message is: ', newmessage)
|
fruit_list = ["apple", "orange", "grape", "banana", "avocado"]
if "grape" in fruit_list:
print("Yes, grape is in the fruit list.")
else:
print("No, grape is not in the fruit list.")
if "strawberry" in fruit_list:
print("strawberry is in the fruit list.")
elif "orange" in fruit_list:
print("orange is in the fruit list.")
else:
print("Both strawberry and orange are not in the fruit list.")
if fruit_list[1] == "orange":
print("True")
else:
print("False")
if fruit_list[4] == "avocado":
print("Yes, avocado is at the fourth index.")
print("Replacing avocado with strawberry at the fourth index.")
fruit_list[4] = "strawberry"
print(fruit_list)
else:
print("avocado is not at the fourth index.")
car_tuple = ["Toyota Camry", "Honda Accord", "Honda Civic", "Toyota Corolla"]
if "Honda Accord" in car_tuple:
print("Honda Accord is present in our car tuple.")
else:
print("Honda Accord is not present in our car tuple.")
if "Ducati monster" in car_tuple:
print("Ducati Monster is a car.")
else:
print("ducati Monster is not a car.")
if "Ducati Monster" in car_tuple and "Honda Accord" in car_tuple:
print("Ducati Monster and Honda Accord are both cars.")
else:
print("At least one of Ducati Monster and Honda Accord is not a car.")
if "Ducati Monster" in car_tuple or "Honda Accord" in car_tuple:
print("At least one of Ducati Monster and Honda Accord is a car.")
else:
print("Neither Ducati Monster nor Honda Accord is a car.")
salary_details = {"Lisa": 25000,
"Jason": 45000,
"Cooper": 35000,
"Elias": 23000,
"Jordan": 77000}
print(salary_details)
if "Lisa" in salary_details:
print("We have the salary details for Lisa.")
else:
print("We don`t have the salary details for Lisa.")
if "Cora" in salary_details:
print("We have the salary detail for Cora.")
else:
salary_details["Cora"] = 31000
print("Cora`s annual income is %s."%salary_details["Cora"])
print(salary_details)
age_details = {"Lisa": 25, "Jason": 30, "Cooper": 29, "Sarah": 22}
print(age_details)
if age_details["Lisa"] < age_details["Jason"]:
print("Json is older than Lisa.")
if age_details["Jason"] > age_details["Cooper"]:
print("Json is older than Cooper.")
if age_details["Cooper"] < age_details["Sarah"]:
print("Cooper is younger than Sarah.")
elif age_details["Cooper"] > age_details["Sarah"]:
print("Json is the oldest person in the given dictionary.")
else:
print("Jason is not the oldest person in the given dictionary.")
details = [["Jane", "Amanda", "Emma"],
[35, 30, 50],
[20000, 50000, 40000]]
print(details)
max_sal = max(details[2])
if (details[2][1] == max_sal):
if details[1][1] > 30:
print(details[0][1], "has the highest salary and her age is greater than 30.")
elif details[1][1] == 30:
print(details[0][1], "has the highest salary and she is 30 years old.")
else:
print("Amanda has the highest salary and her age is less than 30.")
else:
print("Amanda is not highest paid employee.")
|
a = 23
b = -23
def abs(n):
if n < 0:
n = -n
return n
if abs(a) == abs(b):
print("The absolute value of", a, "and", b, "are equal")
else:
print("The absolute value of", a, "and", b, "are not equal")
|
username = input("Username: ")
password = input("Password: ")
command = str()
name = str()
code = str()
while command != "lock":
command = input("Command: ")
while name != username:
name = input("Username: ")
while code != password:
code = input("Password: ")
print("Unlocked")
|
# Import os and cvs
import csv
import os
import numpy as np
budget_csv = os.path.join("Resources", "budget_data.csv")
# Open and read csv
with open(budget_csv, "r") as csv_file:
csv_reader = csv.reader(csv_file, delimiter = ",")
# Skip the header
csv_header = next(csv_reader)
# Find the total number of months
# Count number of rows
file = open(budget_csv)
csv_reader = csv.reader(csv_file, delimiter = ",")
num_rows = -1
for row in open(budget_csv):
num_rows = num_rows + 1
# Print total months
# print("Total months: ", num_rows)
# * The net total amount of "Profit/Losses" over the entire period
date = []
profit_losses = []
for row in csv_reader:
date.append(row[0])
profit_losses.append(int(row[1]))
profit_losses_total = (sum(profit_losses))
## print(f'Total: ${profit_losses_total}')
# * Calculate the changes in "Profit/Losses" over the entire period, then find the average of those changes
avg_change = []
for i in range(len(profit_losses)-1):
avg_change.append(profit_losses[i+1]-profit_losses[i])
# print(f'Average Change ${round(sum(avg_change)/len(avg_change),2)}')
# avg_change = round((profit_loses[-1] - profit_loses[0])/num_rows, 2)
# print (f'Average Change ${avg_change}')
# * The greatest increase in profits (date and amount) over the entire period
greatest_increase = max(avg_change)
increase_indexing = avg_change.index(greatest_increase)
profit_increase = date[increase_indexing + 1]
# print(f'Greatest Increase in Profits: {profit_increase} (${greatest_increase})')
# * The greatest decrease in profits (date and amount) over the entire period
greatest_decrease = min(avg_change)
decrease_indexing = avg_change.index(greatest_decrease)
profit_decrease = date[decrease_indexing + 1]
# print(f'Greatest Decrease in Profits: {profit_decrease} (${greatest_decrease})')
print ("----------------------------")
print ("Financial Analysis")
print ("----------------------------")
print ("Total Months: ", num_rows)
print ("----------------------------")
print (f'Total: ${profit_losses_total}')
print ("----------------------------")
print (f'Average Change ${round(sum(avg_change)/len(avg_change),2)}')
print ("----------------------------")
print (f'Greatest Increase in Profits: {profit_increase} (${greatest_increase})')
print ("----------------------------")
print(f'Greatest Decrease in Profits: {profit_decrease} (${greatest_decrease})')
print ("----------------------------")
# * As an example, your analysis should look similar to the one below:
# ```text
# Financial Analysis
# ----------------------------
# Total Months: 86
# Total: $38382578
# Average Change: $-2315.12
# Greatest Increase in Profits: Feb-2012 ($1926159)
# Greatest Decrease in Profits: Sep-2013 ($-2196167)
# ```
# In addition, your final script should both print the analysis to the terminal and export a text file with the results
export_to_terminal = os.path.join("analysis", "bank.budget.txt")
f = open (export_to_terminal, "w")
f.write ("----------------------------")
f.write ("\n")
f.write ("Financial Analysis")
f.write ("\n")
f.write ("Total months: {num_rows}")
f.write ("\n")
f.write ((f'Total: ${profit_losses_total}'))
f.write ("\n")
f.write (f'Average Change ${avg_change}')
f.write ("\n")
f.write (f'Greatest Increase in Profits: {profit_increase} (${greatest_increase})')
f.write ("\n")
f.write (f'Greatest Decrease in Profits: {profit_decrease} (${greatest_decrease})')
f.write ("\n")
f.write ("----------------------------")
|
class Problem(object):
"""Representation of a problem"""
def __init__(self, initial, goal):
self.initial = list(initial)
self.goal = list(goal)
def actions(self, state):
"""Returns possible actions on current state"""
actions_list = []
index_of_blank_space = state.index("0")
# The four possible actions Up, Down, Left and Right
# can only be done if the blank space is in a certain space
if index_of_blank_space == 0 or index_of_blank_space == 1 \
or index_of_blank_space == 2 or index_of_blank_space == 3 \
or index_of_blank_space == 4 or index_of_blank_space == 5:
actions_list.append("U")
if index_of_blank_space == 3 or index_of_blank_space == 4 \
or index_of_blank_space == 5 or index_of_blank_space == 6 \
or index_of_blank_space == 7 or index_of_blank_space == 8:
actions_list.append("D")
if index_of_blank_space == 7 or index_of_blank_space == 6 \
or index_of_blank_space == 4 or index_of_blank_space == 3 \
or index_of_blank_space == 1 or index_of_blank_space == 0:
actions_list.append("L")
if index_of_blank_space == 8 or index_of_blank_space == 7 \
or index_of_blank_space == 5 or index_of_blank_space == 4 \
or index_of_blank_space == 2 or index_of_blank_space == 1:
actions_list.append("R")
return actions_list
def result(self, state, action):
"""Returns resulting state after a certain action"""
# Has not taken in account false moves
wState = list(state)
index_of_blank_space = state.index("0")
if action == "L":
wState[index_of_blank_space], wState[index_of_blank_space + 1] \
= wState[index_of_blank_space + 1], wState[index_of_blank_space]
if action == "R":
wState[index_of_blank_space], wState[index_of_blank_space - 1] \
= wState[index_of_blank_space - 1], wState[index_of_blank_space]
if action == "U":
wState[index_of_blank_space], wState[index_of_blank_space + 3] \
= wState[index_of_blank_space + 3], wState[index_of_blank_space]
if action == "D":
wState[index_of_blank_space], wState[index_of_blank_space - 3] \
= wState[index_of_blank_space - 3], wState[index_of_blank_space]
return wState
def path_cost(self,cost):
return cost + 1
def goal_test(self, state):
"""Returns boolean whether the goal state has been reached"""
if state == self.goal:
return True
else:
return False
|
def fibbo(n):
a = 0
b = 1
for i in range(n):
a = b
b = b + a
print(a, '/n')
return b
num = int(input('enter the number value-->')
print(fibbo(num))
|
import sys
from sys import stdout as std
"""
Minimax algorithm to build an tic tac toe AI
-----------------------------------------------
computer represents X and the player is O
so, we are maximiser and the player is minimiser
"""
class board:
def __init__(self):
self.positions = []
self.movesLeft = 9
def Start(self):
for i in range(9):
self.positions.append(0);
#position value 0 indicates empty space
#position value 1 indicates X
#position value -1 indicates O
def PrintTable(self):
i = 0;
for j in range(3):
for k in range(3):
if(self.positions[i] == 0):
std.write('_ ') #to print without a newline
elif(self.positions[i] == 1):
std.write('X ')
else:
std.write('O ')
i+=1
print ('\n')
def NextMove(self,filled):
self.PrintTable()
while(True):
a = input('Enter a number between 0-8')
if(a > 8 or a < 0):
continue
if(not(a in filled)):
break
filled.append(a)
self.positions[a] = -1
self.movesLeft -= 1
def GameState(self):
for row in range (3): #checking for a match in a row
if( ( self.positions[row*3] == self.positions[row*3+1]) and (self.positions[row*3+1] == self.positions[row*3+2] ) ):
if(self.positions[row*3] == 1):
return 10
elif(self.positions[row*3] == -1):
return -10
for column in range(3): #match in column
if((self.positions[column] == self.positions[column + 3]) and (self.positions[column +3] == self.positions[column + 6])):
if(self.positions[column] == 1):
return 10
elif(self.positions[column] == -1):
return -10
#condition for 2 diagonals
if((self.positions[0] == self.positions[4]) and (self.positions[4] == self.positions[8])):
if(self.positions[0] == 1):
return 10
elif(self.positions[0] == -1):
return -10
if((self.positions[2] == self.positions[4]) and (self.positions[4] == self.positions[6])):
if(self.positions[2] == 1):
return 10
elif(self.positions[2] == -1):
return -10
#if none of the above is true
return 0
#This function return the best move possible for the given state by the maximiser
def BestMove(self):
if(self.movesLeft == 0):
return -1
current = -sys.maxint
for i in range(9):
if(self.positions[i] == 0):
self.positions[i] = 1
if(self.MiniMax(10-self.movesLeft,False) > current):
current = self.MiniMax(10-self.movesLeft,False)
bestMove = i
self.positions[i] = 0
return bestMove
#This is a recrsive function used to check all posibilities
def MiniMax(self,depth,MaximisingPlayer):
#base cases
score = self.GameState()
if(score == 10): #we return score - depth so as to make
# that selection which has minimum number of moves
return (score - depth)
elif(score == -10):
return (score + depth)
elif(depth == 9): #moves finished
return 0
#deciding best move from the point of maximising player
if(MaximisingPlayer):
curr = -1000
for i in range(9):
if(self.positions[i] == 0):
self.positions[i] = 1
curr = max(curr,self.MiniMax(depth+1,False))
self.positions[i] = 0
return curr
#Best move from the point of view of minimiser
else:
curr = 1000
for i in range(9):
if(self.positions[i] == 0):
self.positions[i] = -1
curr = min(curr,self.MiniMax(depth+1,True))
self.positions[i] = 0
return curr
game = board()
game.Start()
filled = [] #list that stores position occupied
while(game.movesLeft >= 0):
print (game.movesLeft)
game.NextMove(filled)
a = game.BestMove()
filled.append(a)
game.positions[a] = 1
game.movesLeft -= 1
b = game.GameState()
if(b == 10):
game.PrintTable()
print ('You lose!\ntry again')
break
elif(b == -10):
game.PrintTable()
print ('You win!\n')
break
if(game.movesLeft == -1): #in case of draw
game.PrintTable()
|
def Main():
print "\nFor loop counting up"
for x in range(1,5):
print "%d" % (x)
print "\nWhile loop counting down"
while x != 0:
print "%d" % (x)
x -= 1
if __name__ == "__main__":
Main()
|
f=open('form1.txt','a')
f.write("\t\t\t\t\tWelcome To Form Registration\n")
f.write("\t\t\t\t\t----------------------------\n")
f.write("\t\t\t\t\t----------------------------\n\n\n")
n=int(input("Enter no of Students :"))
for i in range(1,n+1) :
print("Enter The student Detail : ",i)
f.write("Student Details :");
f.write(str(i))
name=input("\nEnter a name\n")
f.write("\n")
f.write(name)
f.write("\n")
place=input("Enter a place\n")
f.write(place)
f.write("\n")
college=input("Enter a college \n")
f.write(college)
f.write("\n--------------------------------------------------------------\n")
f.write("\n")
f.write("\n")
print("Print Succefully")
|
class Test:
def __init__(self,a,b):
self.a=a
self.b=b
def add(self,a,b):
c=self.a+self.b
return c
p=Test(10,20)
print(p.a)
print(p.b)
q=p.add(p.a,p.b)
print("sum =" ,q)
|
'''n=int(input())
for i in range(n):
s=input()
for i in range(s):
p=set(s)
print(p)
'''
d= int(input())
a=[]
for i in range(d):
b=input().split()
a.append(b)
for i in range(d):
print(set(a[i]))
|
with open('abc.txt','w') as f:
f.write("\nAnji\n")
f.write("Aj\n")
f.write("AWS")
# print(10/0) if exception occurs then also file is closed automatically;
print("Is Closed :",f.closed)
print("Is Closed :",f.closed)
""" o/p: Using With Statement:
Is Closed : False
Is Closed : True
"""
|
p1=int(input("enter a no 1\n"))
p2=int(input("enter a no 2\n"))
p3=int(input("enter a no 3\n"))
p4=int(input("enter a no 4\n"))
p5=int(input("enter a no 5\n"))
i=(p1+p2+p3+p4+p5)/5
if(i>=60):
print("first division\n")
elif(i>45 and i<60):
print("second division")
elif(i<45 and i>33):
print("thrid division\n")
else:
print("Fail")
|
from collections import defaultdict
d=defaultdict(str)
d['e']=1
d['b']=2
d['c']=3
d['d']=4
print(d)
'''
o/p:
defaultdict(<class 'float'>, {'a': 1, 'b': 2, 'c': 3, 'd': 4})
'''
|
d= int(input())
a=[]
for i in range(d):
b=input().split()
a.append(b)
for i in range(d):
print(a[i])
'''
d= int(input())
a=[]
b=input().split()
#a.append(b)
print(b)
0/p:-=
1 2 3 4
1 2 3 5
132 4 4
4 5 5 6
['1', '2', '3', '4']
['1', '2', '3', '5']
['132', '4', '4']
['4', '5', '5', '6']
anji
'''
print("{}".format("anji"))
|
print("Enter an age not less tha 10")
a=int(input(""))
if a>=10 :
raise NameError("Not Valid")
#//Error hai pta nahi
|
from collections import deque
q=int(input())
d=deque()
for i in range(q):
m,n=input().split()
if(m=='append'):
d.append(int(n))
print(d[i])
elif(m=='pop'):
d.pop(int(n))
print(d[i])
elif(m=='appendleft'):
d.appendleft(int(n))
print(d[i])
elif(m=='popleft'):
d.popleft(int(n))
print(d[i])
'''
o=int(input())
d.append(d[1])
q=int(input())
d.append(int(input()))
e=int(input())
d.appendleft(int(input()))
d.pop()
d.popleft()
'''
|
'''def swap_case(s):
l=len(s)
for i in range(l) :
if(s[i]>='a' and s[i]<='z'):
s[i]=chr(ord(s[i]) - 32);
elif(s[i]>='A' and s[i]<='Z'):
s[i]=chr(ord(s[i])+32);
str = ''.join(s)
return str
if __name__ == '__main__':
s = input()
result = swap_case(s)
print(result)
'''
def swap_case(s): return s.swapcase()
if __name__ == '__main__':
s = input()
result = swap_case(s)
print(result)
|
str1=input("Enter a string ")
n=len(str1); # string lenght= lenght(string)
str=list(str1)
for i in range(n) :
if(str[i]>='a' and str[i]<='z'):
str[i]=chr(ord(str[i]) - 32);
elif(str[i]>='A' and str[i]<='Z'):
str[i]=chr(ord(str[i])+32);
str = ''.join(str)
print(str)
|
'''
def print_formatted(n):
for i in range(1,n+1):
print(i,end=' ')
print(oct(i).lstrip('0o'),end=' ')
print(hex(i).lstrip('0x'),end=' ')
print(bin(i).lstrip('0b'),end='\n')
if __name__ == '__main__':
n = int(input())
print_formatted(n)
'''
#DCS hai
def print_formatted(n):
for i in range(1, n+1):
print('{0:>{w}d} {0:>{w}o} {0:>{w}X} {0:>{w}b}'.format(i, w=len(bin(n))-2))
if __name__ == '__main__':
n = int(input())
print_formatted(n)
|
class ArrayQueue:
DEFAULT_CAPACITY = 10
def __init__ (self):
self._data = [None] * ArrayQueue.DEFAULT_CAPACITY
self._size = 0
self._front = 0
self._back = 0
def len (self):
return self._size
def is_empty(self):
return self._size == 0
def first(self):
if self.is_empty():
raise Empty( "Queue is empty" )
return self._data[self._front]
def dequeue(self):
if self.is_empty():
raise Empty( "Queue is empty" )
answer = self._data[self._front]
self._data[self._front] = None
self._front = (self._front + 1) % len(self._data)
self._size -= 1
self._back = (self._front + self._size - 1) % len(self._data)
return answer
def dequeue1(self):
if self.is_empty():
raise Empty('Queue is empty')
back = (self._front + self._size - 1) % len(self._data)
answer = self._data[back]
self._data[back] = None
self._front = self._front
self._size -= 1
self._back = (self._front + self._size - 1) % len(self._data)
return answer
def enqueue(self, e):
if self._size == len(self._data):
self._resize(2 * len(self._data))
avail = (self._front + self._size) % len(self._data)
self._data[avail] = e
self._size += 1
self._back = (self._front + self._size - 1) % len(self._data)
def enqueue1(self, e):
if self._size == len(self._data):
self._resize(2 * len(self._data))
self._front = (self._front - 1) % len(self._data)
avail = (self._front + self._size) % len(self._data)
self._data[self._front] = e
self._size += 1
self._back = (self._front + self._size - 1) % len(self._data)
def _resize(self, cap):
old = self._data
self._data = [None] * cap
walk = self._front
for k in range(self. size):
self._data[k] = old[walk]
walk = (1 + walk) % len(old)
self._front = 0
self._back = (self._front + self._size - 1) % len(self._data)
queue = ArrayQueue()
queue.enqueue1(1)
print(f"First Element: {queue._data[queue._front]}, Last Element: {queue._data[queue._back]}")
queue._data
queue.enqueue1(2)
print(f"First Element: {queue._data[queue._front]}, Last Element: {queue._data[queue._back]}")
queue._data
queue.dequeue1()
print(f"First Element: {queue._data[queue._front]}, Last Element: {queue._data[queue._back]}")
queue.enqueue1(3)
print(f"First Element: {queue._data[queue._front]}, Last Element: {queue._data[queue._back]}")
queue.enqueue1(4)
print(f"First Element: {queue._data[queue._front]}, Last Element: {queue._data[queue._back]}")
queue.dequeue1()
print(f"First Element: {queue._data[queue._front]}, Last Element: {queue._data[queue._back]}")
queue.enqueue1(5)
print(f"First Element: {queue._data[queue._front]}, Last Element: {queue._data[queue._back]}")
queue.dequeue()
print(f"First Element: {queue._data[queue._front]}, Last Element: {queue._data[queue._back]}")
queue.enqueue(6)
print(f"First Element: {queue._data[queue._front]}, Last Element: {queue._data[queue._back]}")
|
import abc
from itertools import chain
class RollingObject(metaclass=abc.ABCMeta):
"""
Baseclass for rolling iterator objects.
The __new__ method here sets appropriate magic
methods for the class (__iter__ and __init__)
depending on window_type.
All iteration logic is handled in this class.
Subclasses just implement methods manipulating
any attributes needed to compute the value of
the rolling window as values are added and removed.
Subclasses *must* implement the following methods
with the following parameters:
_init_fixed(self, iterable, window_size, **kwargs)
_init_variable(self, iterable, window_size, **kwargs)
_update_window(self, new)
_add_new(self, new)
_remove_old(self)
current_value(self) # this is a @property
Variable-length instances must also have a self._obs
attribute returning the current size of the window.
"""
def __new__(cls, iterable, window_size, window_type="fixed", **kwargs):
if window_type == "fixed":
cls.__init__ = cls._init_fixed
cls.__next__ = cls._next_fixed
elif window_type == "variable":
cls.__init__ = cls._init_variable
cls.__next__ = cls._next_variable
else:
raise ValueError("Unknown window_type '{}'".format(window_type))
self = super().__new__(cls)
self.window_type = window_type
self.window_size = _validate_window_size(window_size)
self._iterator = iter(iterable)
if self.window_type == "variable":
self._filled = False
return self
def __repr__(self):
return "Rolling(operation='{}', window_size={}, window_type='{}')".format(
self.__class__.__name__, self.window_size, self.window_type
)
def __iter__(self):
return self
def _next_fixed(self):
"""
Return the next value for fixed-length windows
"""
new = next(self._iterator)
self._update_window(new)
return self.current_value
def _next_variable(self):
"""
Return the next value for variable-length windows
"""
# while the window size is not reached, add new values
if not self._filled and self._obs < self.window_size:
new = next(self._iterator)
self._add_new(new)
if self._obs == self.window_size:
self._filled = True
return self.current_value
# once the window size is reached, update window until the iterator finishes
try:
new = next(self._iterator)
self._update_window(new)
return self.current_value
# if the iterator finishes, remove the oldest values one at a time
except StopIteration:
if self._obs == 1:
raise
else:
self._remove_old()
return self.current_value
def extend(self, iterable):
"""
Extend the iterator being consumed with a new iterable.
The extend() method may be called at any time (even after
StopIteration has been raised). The most recent values from
the current iterator are retained and used in the calculation
of the next window value.
For "variable" windows which are decreasing in size, extending
the iterator means that these windows will grow towards their
maximum size again.
"""
self._iterator = chain(self._iterator, iterable)
if self.window_type == "variable":
self._filled = False
@property
@abc.abstractmethod
def current_value(self):
"""
Return the current value of the window
"""
pass
@abc.abstractmethod
def _init_fixed(self):
"""
Intialise as a fixed-size window
"""
pass
@abc.abstractmethod
def _init_variable(self):
"""
Intialise as a variable-size window
"""
pass
@abc.abstractmethod
def _remove_old(self):
"""
Remove the oldest value from the window, decreasing window size by 1
"""
pass
@abc.abstractmethod
def _add_new(self, new):
"""
Add a new value to the window, increasing window size by 1
"""
pass
@abc.abstractmethod
def _update_window(self, new):
"""
Add a new value to the window and remove the oldest value from the window
"""
pass
def _validate_window_size(k):
"""
Check if k is a positive integer
"""
if not isinstance(k, int):
raise TypeError(
"window_size must be integer type, got {}".format(type(k).__name__)
)
if k <= 0:
raise ValueError("window_size must be positive")
return k
|
#count of number of words and letters
wc ={}
ltr = {}
'''this code list the count of number words and letters in the goven text file'''
with open("test.txt", 'r') as fout:
output = fout.read().lower()
#print(output)
new = output.split()
def wl_count():
#number of words
for words in new:
if words not in wc:
wc[words]=1
else:
wc[words]+=1
for w in wc:
print(wc[w],w)
# number of letter
def l_count():
for words in new:
for l in words:
if l not in ltr:
ltr[l]= 1
else:
ltr[l]+= 1
for k in ltr:
print(ltr[k], k)
if __name__=='__main__':
wl_count()
l_count()
|
def PigLatin(s):
vowels = ['a', 'e', 'i', 'o', 'u']
output = []
count = 1
new = s.lower().split()
print(new)
for word in new:
if word[0] not in vowels:
#case 1: remove first letter and add "ma"
word = word[1:]
new_word = word + "ma"
else:
# case 2: if word begins with vowel
new_word = word + "ma"
#case 3: increment and append j after each word
string_to_append = "j"*count
word = "%s%s" %(new_word,string_to_append)
count+=1
output.append(word)
print(" ".join(output))
if __name__ == "__main__":
s ="I am a pig latin"
PigLatin(s)
|
import pygame
#se crea la clase para los button para los botones
class button(pygame.sprite.Sprite):#se crea la clase para los botones
def __init__(self,pic1,pic2,x,y):#se define cada boton con dos imagenes y las coordenadas
self.unselected_pic=pic1#se define como se vera la imagen sin seleccionar
self.selected_pic=pic2 #se define como se vera la imagen seleccionada
self.basic_pic=self.unselected_pic #se define una imagen bacica qie inicia como la no seleccionada
self.rect=self.basic_pic.get_rect()
self.rect.left,self.rect.top=(x,y)
def update(self,screen,cursor):#se actializa el boton
if cursor.colliderect(self.rect):#se define la condicion cuando el cursor se pocisione sobre el bot
self.basic_pic=self.selected_pic
else: self.basic_pic=self.unselected_pic #condicion del boton en stand by
screen.blit(self.basic_pic,self.rect)#que se actualiza la pantalla dependiendo de la accion condicional
|
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 6 18:42:31 2015
@author: zhihuixie
"""
import pandas as pd
def ranks(rate_dict):
"""
input as a dictornary, key as movie id and name, values as calculated
parameters of rating
"""
sorted_dict = sorted(rate_dict, key = lambda x: rate_dict[x], reverse = True)
return sorted_dict
def mean_rate(df):
"""
input a pandas dataframe, return mean of rate for each movie
"""
mean_of_rate = dict(df.mean())
return mean_of_rate
def count_rate(df):
"""
input a pandas dataframe, return number of rate for each movie
"""
number_of_rate = dict(df.count())
return number_of_rate
def positive_rate(df):
"""
Calculate the percentage of ratings for each movie that are 4 or higher.
"""
pos_rate_percentages = {}
movies = df.columns.values
nrows, ncols = df.shape[0], df.shape[1]
for i in range(ncols):
pos_rate = [df.iloc[j, i] for j in range(nrows) if df.iloc[j, i] >= 4]
pos_rate_percentage = len(pos_rate)*1.0/df.iloc[:, i].count()
pos_rate_percentages[movies[i]] = pos_rate_percentage
return pos_rate_percentages
def similarity_rate(target_movie, df):
"""
Use (x&y)/x to compute similarity — that is,
compute the probability that the user rated movie i given that they
also rated 260: Star Wars: Episode IV - A New Hope (1977).
"""
nrows, ncols = df.shape[0], df.shape[1] #number of users and movies
common_rates = {} #define a dictornary for user who rate both target movie and another movie
movies = df.columns.values #names of movies
is_not_rate_target = df[target_movie].isnull() #True for rate, False for not rate
num_of_target_rate = df[target_movie].count()# count number of total rate
for i in range(ncols):
is_not_rate = df.iloc[:, i].isnull()#True for rate, False for not rate
#calculate number of common rate
common_rate = len([n for n in range(nrows) if not is_not_rate_target[n] \
and is_not_rate_target[n] == is_not_rate[n]])
#calculate the percentage of target raters who also rated that movie
common_rates[movies[i]] = common_rate * 1.0 / num_of_target_rate
return common_rates
if __name__ == "__main__":
df = pd.read_csv("A1Ratings.csv", usecols = range(1,21))
#Quiz Part I - mean of rate
mean_of_rate = ranks(mean_rate(df))
print "The top5 mean of rate:"
print mean_of_rate[:5], "\n"
#Quiz Part II - number of rate
number_of_rate = ranks(count_rate(df))
print "The top5 number of rate:"
print number_of_rate[:5], "\n"
#Quiz Part III - fraction of positive ratings
pos_rate_percentages = ranks(positive_rate(df))
print "The top5 positive percentage of rate:"
print pos_rate_percentages[:5], "\n"
#Quiz Part VI - fraction of positive ratings
target_movie = "260: Star Wars: Episode IV - A New Hope (1977)"
common_rates = ranks(similarity_rate(target_movie, df))
print "The top5 common_rates:"
print common_rates[1:6], "\n"
|
#import smbus for i2c communications
import smbus
import time
#import the chip library
import bme280
# Get I2C bus, this is I2C Bus 1
bus = smbus.SMBus(1)
#kwargs is a Python set that contains the address of your device as well as desired range and bandwidth
#refer to the chip's datasheet to determine what values you should use to suit your project
#The default address for this chip is 0x76, this simply allows you to manually set it for multi-board chains.
kwargs = {'address': 0x76, 'humidity_sampling_rate': 0x01, 'pressure_sampling_rate': 0x04, 'temperature_sampling_rate': 0x20, 'mode': 0x03, 'standby_time': 0xA0, 'filter': 0x00}
#create the BME280 object from the BME280 library and pass it the kwargs and com bus.
#the object requires that you pass it the bus object so that it can communicate and share the bus with other chips/boards if necessary
bme280 = bme280.BME280(bus, kwargs)
while True :
#print out the readings.
#the readings will be return in a set keyed as pressure, temperature, and humidity for the corresponding values
#read the temperature back in fahrenheit
print bme280.get_readings('f')
#read the temperature back in kelvin
print bme280.get_readings('k')
#read the temperature back in celsius (this is also the default value so () would work
print bme280.get_readings('c')
#this sleep is not required
time.sleep(.25)
|
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 23 21:42:35 2020
@author: Siddharth
"""
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
from math import sqrt
#import os
#x=os.getcwd()
rf_data=pd.read_csv(r'C:\Users\Siddharth\Desktop\BITS\3 2\DM\project\Sub_Division_IMD_2017.csv')
###Calculate Mean of a column
def cal_mean(readings):
readings_total = sum(readings)
number_of_readings = len(readings)
mean = readings_total / float(number_of_readings)
return mean
###Calculate variance of a column
def cal_variance(readings):
# To calculate the variance we need the mean value
# Calculating the mean value from the cal_mean function
readings_mean = cal_mean(readings)
# mean difference squared readings
mean_difference_squared_readings = [pow((reading - readings_mean), 2) for reading in readings]
variance = sum(mean_difference_squared_readings)
return variance / float(len(readings) - 1)
###Calculate Covariance of a column
def cal_covariance(readings_1, readings_2):
readings_1_mean = cal_mean(readings_1)
readings_2_mean = cal_mean(readings_2)
readings_size = len(readings_1)
covariance = 0.0
for i in xrange(0, readings_size):
covariance += (readings_1[i] - readings_1_mean) * (readings_2[i] - readings_2_mean)
return covariance / float(readings_size - 1)
###Calculate the linear regression coefficients
def lin_reg(df):
# Calculating the mean of the years and the annual rainfall
years_mean = cal_mean(df['YEAR'])
rainfall_mean = cal_mean(df['value'])
# Calculating the variance of the years and the annual rainfall
years_variance = cal_variance(df['YEAR'])
# Calculating the regression
covariance_of_rainfall_and_years = df.cov()['YEAR']['value']
w1 = covariance_of_rainfall_and_years / float(years_variance)
w0 = rainfall_mean - (w1 * years_mean)
return [w0, w1]
###Calculate rmse for given dataframe
def cal_rmse(df):
soe = 0
n = len(df['value'])
for x in range (n):
actual = test_vals['value'].iloc[x]
predicted = test_vals['Predicted_Rainfall'].iloc[x]
soe = soe + ((actual-predicted)**2)/n
return sqrt(soe)
###Load the data
x = rf_data.SUBDIVISION
states=[]
for i in range(len(x)):
if x[i] not in states:
states.append(x[i])
###list of state dataframes
l_state_dfs = []
for i in range(len(states)):
n=states[i]
x=rf_data[rf_data.SUBDIVISION == n]
l_state_dfs.append(x)
###create list of columns to drop
months = ['SUBDIVISION', 'JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC', 'JF', 'MAM', 'JJAS', 'OND']
###drop the columns for all dataframes and melt
for i in range(len(states)):
l_state_dfs[i]=l_state_dfs[i].drop(months, axis=1)
l_state_dfs[i] = l_state_dfs[i].melt('YEAR').reset_index()
###Remove nans (loop through states and replace with annual mean)
for i in range(len(states)):
mean_of_state=l_state_dfs[i].value.mean()
l_state_dfs[i].value = l_state_dfs[i].value.fillna(mean_of_state)
'''
###normalize annual rainfall
na=[]
for i in range(len(states)):
a=min(l_state_dfs[i].value)
b=max(l_state_dfs[i].value)
for j in range(len(l_state_dfs[i].value)):
u = (l_state_dfs[i]['value'][j]-a)/(b -a)
na.append(u)
l_state_dfs[i].drop(['value'],axis=1)
l_state_dfs[i]['value'] = na
na = []
'''
###Use functions defined to perform linear regression
errors = [] #list of RMSE for each state
for i in range(len(states)):
#full contains original dataframe [i]
full=l_state_dfs[i]
#l_state_df[i] contains first 70% of dataframe
l_state_dfs[i]=l_state_dfs[i].head(int(len(l_state_dfs[i])*(70/100)))
#get coefficients using linear regression function
coeffs = lin_reg(l_state_dfs[i])
w0 = coeffs[0]
w1 = coeffs[1]
# Predictions
full['Predicted_Rainfall'] = w0 + w1 * full['YEAR']
#RMSE calculation
test_vals = full.tail(int(len(l_state_dfs[i])*(30/100))+1)
rmse = cal_rmse(test_vals)
errors.append(rmse)
###plot
plt.figure()
plt.plot(full['YEAR'], full['value'])
plt.plot(full['YEAR'], full['Predicted_Rainfall'])
plt.title(states[i])
plt.xlabel('YEAR')
plt.ylabel('Annual Rainfall in mm')
'''
###convert annual rainfall back to mm
na=[]
for j in range(len(l_state_dfs[i].value)):
u=l_state_dfs[i]['Predicted_Rainfall'][j]*(b -a)+a
na.append(u)
l_state_dfs[i].drop(['Predicted_Rainfall'],axis=1)
l_state_dfs[i]['Predicted_Rainfall'] = na
'''
|
## Question 1
## What would be the output of the following code?
my_dict = {'a':[0, 1, 2, 3], 'b':[0, 1, 2, 3], 'c':[0, 1, 2, 3], 'd':[0, 1, 2, 3]}
i = 0
output = []
for key in my_dict:
output.append(my_dict[key][i])
i += 1
print(output) # [0,1,2,3]
## Practice Exercise 1 Solution
def smallest_positive(in_list):
# Define a control structure that finds the smallest positive
# number in in_list and returns the correct smallest number.
if len(in_list) == 1:
return None
smallest = max(in_list)
for num in in_list:
if all([num < smallest, num > 0]):
smallest = num
return smallest
# Test cases
print(smallest_positive([4, -6, 7, 2, -4, 10]))
# Correct output: 2
print(smallest_positive([.2, 5, 3, -.1, 7, 7, 6]))
# Correct output: 0.2
## Practice Exercise 2 Solution
numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9) # Declaring the tuple
count_odd = 0
count_even = 0
for x in numbers:
if not x % 2:
count_even+=1
else:
count_odd+=1
print("Number of even numbers : ",count_even)
print("Number of odd numbers : ",count_odd)
## Number of even numbers : 4
## Number of odd numbers : 5
|
#!/usr/bin/env jython
"""
This script is a helper tool for taking a group of ciphertexts, guessing what
the plaintext is, and checking to see if any of the ciphertexts match that
plaintext.
"""
import argparse
import vigenere
def main():
# Get arguments from the command-line.
parser = argparse.ArgumentParser(
description="Check one or more ciphertexts against a plaintext fragment.",
)
parser.add_argument('-p', '--plaintext', required=True)
parser.add_argument(
'ciphertext_file',
nargs='+',
)
arguments = parser.parse_args()
for filename in arguments.ciphertext_file:
print "--- " + filename + " " + ("-" * (79 - len(filename) - 5))
with open(filename) as file:
print vigenere.decrypt(
file.read(),
arguments.plaintext,
)
print
if __name__ == '__main__':
main()
|
# SORT function sorts the data permanently
cars =['bmw','audi','toyota','subaru','Audi','BMW']
cars.sort()
print(cars)
cars.sort(reverse = True)
print(cars)
# Sorting a List Temporarily with sorted() Function
cars =['bmw','audi','toyota','subaru','Audi','BMW']
print("Here is the original list:")
print(cars)
print("\nHere is the sorted list:")
print(sorted(cars))
print("\nHere is the sorted list in reverse:")
print(sorted(cars, reverse=True))
print("Here is the original list:")
print(cars)
# Original list
cars =['bmw','audi','toyota','subaru','Audi','BMW']
print("Here is the original list:")
print(cars)
# Reverse original cars list
print("Sorted on cars list")
cars.reverse()
print (cars)
print (f"Length of car is {len(cars)}")
|
# -*- coding: utf-8 -*-
import numpy as np
class Punto():
"""Almacena la posicion (x,y,z) en un tiempo t de una particula.
"""
def __init__(self,x,y,z,t):
self.x=x
self.y=y
self.z=z
self.t=t
def imprimir(self):
print(int(self.t)+' ('+str(self.x)+','+str(self.y)+','+str(self.z)+')')
class Track():
def __init__(self,nombre=''):
self.puntos=[]
self.nombre=nombre
#Inserta una particula (x,y,z) en el tiempo t.
def agregar(self,x,y,z,t):
punto=Punto(x,y,z,t)
if (len(self.puntos)==0) or (self.puntos[len(self.puntos)-1].t<t):
self.puntos.append(punto)
else:
puntosAux=[]
i=0
while self.puntos[i].t<t:
puntosAux.append(self.puntos[i])
i+=1
puntosAux.append(punto)
while i<len(self.puntos):
puntosAux.append(self.puntos[i])
i+=1
self.puntos=puntosAux
def imprimir(self):
#print
print(self.nombre)
#print(len(self.puntos))
for p in self.puntos:
p.imprimir()
def posicion(self,tiempo):
puntos=self.puntos
if (puntos[len(puntos)-1].t >= tiempo):
i=0
while puntos[i].t < tiempo:
i+=1
if puntos[i].t==tiempo:
return puntos[i].x,puntos[i].y,puntos[i].z
return None,None,None
def siguiente(self,tiempo):
puntos=self.puntos
if (puntos[len(puntos)-1].t >= tiempo+1):
i=0
while puntos[i].t < tiempo+1:
i+=1
if puntos[i].t==tiempo+1:
return puntos[i].x,puntos[i].y,puntos[i].z
return None,None,None
def longitud(self):
return len(self.puntos)
class Tracks():
def __init__(self,datos):
self.tracks=[]
self.xMin= np.inf
self.xMax= -np.inf
self.yMin= np.inf
self.yMax= -np.inf
for i in range(len(datos)):
r=Track()
if i%100==0:
print i,'/',len(datos)
for vals in datos[i]:
x=float(vals[0])
y=float(vals[1])
z=float(vals[2])
t=int(vals[3])
#print(t)
r.agregar(x,y,z,t)
if x<self.xMin:
self.xMin=x
if x>self.xMax:
self.xMax=x
if y<self.yMin:
self.yMin=y
if y>self.yMax:
self.yMax=y
self.tracks.append(r)
self.duracion=max(track.puntos[len(track.puntos)-1].t for track in self.tracks)
#Retorna una la lista de trayectorias ordenada de acuerdo al tiempo en que terminan
def getSortedTracks(self):
resultado=[]
tmax=0
for track in self.tracks:
finTrack=track.puntos[len(track.puntos)-1].t#Tiempo final de la trayectoria
if tmax<=finTrack:#Insertar al final
resultado.append(track)
tmax=track.puntos[len(track.puntos)-1].t
else:#Insertar en otra parte
aux=[]
i=0
while (finTrack>=resultado[i].puntos[len(resultado[i].puntos)-1].t):
aux.append(resultado[i])
i+=1
aux.append(track)
for j in range(i,len(resultado)):
aux.append(resultado[j])
resultado=aux
return resultado
def imprimir(self):
for t in self.tracks:
t.imprimir()
print
def guardar(self,ruta):
f = file(ruta,'w')
f.write('t')
for track in self.tracks:
f.write(',x,y,z,')
for t in range(self.duracion+1):
f.write('\n'+str(t))
for track in self.tracks:
x,y,z=track.posicion(t)
if x:
f.write(','+str(x)+','+str(y)+','+str(z)+',')
else:
f.write(',,,,')
f.close()
def puntos(self,tiempo,lmin):
x2=[]
y2=[]
z2=[]
for i in range(len(self.tracks)):
track=self.tracks[i]
x1,y1,z1=track.posicion(tiempo)
x3,y3,z3=track.siguiente(tiempo)
if x1 and x3 and lmin<=track.longitud():
x2.append(x1)
y2.append(y1)
z2.append(z1)
return x2,y2,z2
def vectores(self,tiempo,lmin):
x=[]
y=[]
z=[]
u=[]
v=[]
w=[]
for track in self.tracks:
x1,y1,z1=track.posicion(tiempo)
x2,y2,z2=track.siguiente(tiempo)
if x1 and x2 and lmin<=track.longitud():
u1=x2-x1
v1=y2-y1
w1=z2-z1
x.append(x1)
y.append(y1)
z.append(z1)
u.append(u1)
v.append(v1)
w.append(w1)
return x,y,z,u,v,w
def sentidos(self,xc,yc,lmin):
def sentidosT(tiempo):
def determinarSentido(x3,y3,z3,x4,y4,z4):
distActual=(x3-xc)**2+(y3-yc)**2#Distancia actual al centro
distSiguiente=(x4-xc)**2+(y4-yc)**2#Dist. siguiente al centro
deltaRadial=distSiguiente-distActual#Desplazamiento radial
deltaZ = z4-z3#Desplazamiento z
if deltaRadial>0:
return 1
else:
return 0
resultado=[]
for i in range(len(self.tracks)):
track=self.tracks[i]
x3,y3,z3=track.posicion(tiempo)
x4,y4,z4=track.siguiente(tiempo)
if x3 and x4 and lmin<=track.longitud():
resultado.append(determinarSentido(x3,y3,z3,x4,y4,z4))
return resultado
return [sentidosT(t) for t in range(self.duracion)]
"""
def vectoresSeparados(self,xc,yc,tiempo,lmin):
"Retorna los vectores separados por su sentido (centro, fuera, arriba, abajo)"
x1=[]
y1=[]
z1=[]
u1=[]
v1=[]
w1=[]
x2=[]
y2=[]
z2=[]
u2=[]
v2=[]
w2=[]
for track in self.tracks:
x3,y3,z3=track.posicion(tiempo)
x4,y4,z4=track.siguiente(tiempo)
if x3 and x4 and lmin<=track.longitud:
hypOrigen=(x3-xc)**2+(y3-yc)**2
hypDest=(x4-xc)**2+(y4-yc)**2
u3=x4-x3
v3=y4-y3
w3=z4-z3
if (hypOrigen>hypDest):#Si se acerca al centro...
x1.append(x3)
y1.append(y3)
z1.append(z3)
u1.append(u3)
v1.append(v3)
w1.append(w3)
else:
x2.append(x3)
y2.append(y3)
z2.append(z3)
u2.append(u3)
v2.append(v3)
w2.append(w3)
return x1,y1,z1,u1,v1,w1,x2,y2,z2,u2,v2,w2"""
|
from collections import Counter
def count_words_fast(text): #counts word frequency using Counter from collections
text = text.lower()
skips = [".", ", ", ":", ";", "'", '"']
for ch in skips:
text = text.replace(ch, "")
word_counts = Counter(text.split(" "))
return word_counts
# >>>count_words_fast(text) You can check the function
def read_book(title_path): #read a book and return it as a string
with open(title_path, "r", encoding ="utf8") as current_file:
text = current_file.read()
text = text.replace("\n", "").replace("\r", "")
return text
def word_stats(word_counts): # word_counts = count_words_fast(text)
num_unique = len(word_counts)
counts = word_counts.values()
return (num_unique, counts)
word_counts = count_words_fast(text)
(num_unique, counts) = word_stats(word_counts)
print(num_unique, sum(counts))
|
class Node:
def __init__(self,data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.start = None
def insertLast(self,value):
newNode = Node(value)
if self.start == None:
self.start = newNode
else:
temp = self.start
while temp.next!=None:
temp = temp.next
temp.next = newNode
def deleteFirst(self):
if self.start == None:
print('linked list is empty!')
else:
self.start = self.start.next
# def insertFirst(self,value):
# newNode = Node(value)
# newNode.data = self.start
# self.start = newNode
def deleteLast(self):
temp2 = self.start
while temp2.next != None:
temp2 = temp2.next
temp2.data = None
def viewList(self):
if self.start == Node:
print('list is empty')
else:
temp3 = self.start
while temp3!=None:
print(temp3.data)
temp3=temp3.next
myList = LinkedList()
myList.insertLast(6)
myList.insertLast(88)
myList.viewList()
myList.deleteFirst()
print('sssss')
myList.viewList()
print('--------------')
myList.insertLast(7777)
myList.insertLast(6675)
myList.viewList()
myList.deleteLast()
myList.deleteLast()
|
class Node:
def __init__(self,data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def printList(self):
cur_node = self.head
while cur_node != None :
print(cur_node.data)
cur_node = cur_node.next
def append(self,data):
new_node = Node(data)
if self.head == None:
self.head = new_node
return
last_node = self.head
while last_node.next != None:
last_node = last_node.next
last_node.next = new_node
def prepend(self,data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
def insert_after_node(self,prev_node,data):
if not prev_node:
print('previous node is not in the list')
return
new_node = Node(data)
new_node.next = prev_node.next
prev_node.next = new_node
def deleteNode(self,key):
cur_node = self.head
if cur_node !=None and cur_node.data==key:
self.head = cur_node.next # for deleting the head
cur_node = None
# deleting the given node
prev = None
while cur_node != None and cur_node.data != key:
prev = cur_node
cur_node = cur_node.next
if cur_node is None: # if element is not in the list
print('element is not in the list')
else:
prev.next = cur_node.next
cur_node = None
#deleting thr last node
def deleteLast(self):
prev = None
cur_node = self.head
while cur_node.next != None:
prev = cur_node
cur_node = cur_node.next
prev.next = None
L = LinkedList()
L.append('A')
L.append('B')
L.append('C')
L.append('D')
#L.prepend('E')
#L.insert_after_node(L.head.next,'E')
#L.printList()
#L.deleteNode('B')
#print()
#L.printList()
L.deleteLast()
L.printList()
|
# -*- coding: utf-8 -*-
## THESE PROGRAMS ALLOW YOU TO CALCULATE
## THE ENERGY OF A LIQUID, PARTICULE
## AND MAYBE SOME OTHERS THINGS NOT CODED YET
##LICENSE : DO WHAT THE FUCK YOU WANT
## ./particle.py argv1 argv2 --> argv1: speed particle && argv2: particle's mass
import sys,math
args=len(sys.argv)
if args != 3:
print("There isn't enough or too much arguments.\
\nYou have to give exactly two arguments.\n\n\
The first argument is the speed of the particle\n\
And the second argument is the mass of the particle.\
\nExiting...")
sys.exit()
pass
def lorentzian_factor(v, c):
y=1/(((1-v*2)/(c*2))*0.5)
return float(y)
pass
def impulsion(y,m,v):
p=y*m*v
return float(p)
pass
def energy_computing(m, c, p):
m=math.pow(m, 2)
cc=math.pow(c, 4)
pp=math.pow(p, 2)
c=math.pow(c, 2)
EE=((m*cc)+pp*c)
EE=float(EE)
return EE
pass
v=float(sys.argv[1]) #v is the speed of the particle
m=float(sys.argv[2]) #mass of the particle
c=float(299792458) #Fiat lux!
y=lorentzian_factor(v,c)
y=float(y)
print("The lorentzian factor is : " + str(y))
p=impulsion(y,m,v)
print("The impulsion is : " + str(p))
energy=energy_computing(m,c,p)
print("E²=" + str(energy) + "")
print("Therefore, we have :\n\
E="+ str(math.sqrt(float(energy))))
sys.exit()
|
# -*-coding:utf-8-*-
import sys
#για την επανάληψη του προγράμματος
play = True
while play == True:
import math
num = 1000001
#πλήθος φορών που ο αριθμός διαιρείται με το 2:
pl2 = 0
#έλεγχος
while num > 1000000 or num < 1:
num = int(raw_input("Δώστε έναν αριθμό απο το 1 μέχρι το 1000000: "))
#Εκτυπώνει πόσες φορές ο αριθμός είναι διαιρέσιμος με το 2
while num % 2 == 0:
pl2 += 1
num = num // 2
if pl2 > 0:
print "(2 ** %d)" % (pl2)
#δημιουργία λίστας (ilist) στην οποία θα προσθέτονται οι αριθμοί που διαπιστώνουμε
#οτι διαιρούν τέλεια τον num, οσο διαιρείται με αυτούς.
ilist = [0]
for i in range(3, int(math.sqrt(num))+1, 2):
while num % i == 0:
ilist.append(i)
num = num / i
ilist.remove(0)
i = 0
#παραμετροποιούμε το μήκος της λίστας ωστε να λαμβάνουμε υπ΄οψιν το 0
#σαν αρχή στην επανάληψη
ilen = int(len(ilist)) - 1
#για την εμφάνιση των αριθμών που βρίσκονται μία μόνο φορά στη λίστα
while i < ilen:
if ilist[i] <> ilist[i+1] and ilist[i] <> ilist[i-1]:
print "(%d)" % (ilist[i])
i = i + 1
else:
i = i + 1
if ilen >= 2:
if ilist[ilen] <> ilist[ilen-2]:
print "(%d)" % (ilist[len(ilist)-1])
#ελέγψει αν οποιοςδίποτε αριθμός υπάρχει στην λίστα τουλάχιστον δύο φορές
#και τον εκτυπώνει κατάλληλα
for x in range(1, 500000):
if ilist.count(x) > 1:
print "(%d ** %d)" % (x, ilist.count(x))
#όταν δεν γίνεται παραπάνω απλοποίηση εκτυπώνει το "υπόλοιπο" του αρχικού αριθμού
if num > 2:
print num
#για επανάληψη η παύση του προγράμματος
stop = raw_input("Πατήστε R για επανάληψη ή X για έξοδο: ").capitalize()
if stop == "R":
play = True
elif stop == "X":
play = False
if stop == "X":
print("Αντίο.")
sys.exit(-1)
|
class LoanCaculator():
def __init__( loan, time):
self.loan = loan
if time = "1":
self.time = 3
elif time = "2":
self.time = 5
else time = "3":
self.time = 20
def get_total_interests():
total_interests = self.loan * self.get_interests_rate()
def get_interests_rate():
if self.time == 3:
return 0.0603
elif self.time == 5:
return 0.0612
else self.time == 20:
return 0.0639
def get_monthly_payment():
monthly_payment = (self.loan + self.get_total_interests()) / (self.time * 12)
loan = int(input("请输入贷款金额:"))
time =int(input("请选择贷款年限:1.3年(36个月) 2.5年(60个月) 3.20年(240个月)"))
loan_caculate = LoanCaculator(loan, time)
print("月供为:%f" % loan_caculate.get_monthly_payment())
|
Python 3.8.8 (tags/v3.8.8:024d805, Feb 19 2021, 13:18:16) [MSC v.1928 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> a=int(input("Enter integer 1:"))
b=int(input("ENTER INTEGER 2 :"))
print("Addition of integers : ",a+b)
print("Subtraction of integers : ",a-b)
print("Multiplication of integers : ",a*b)
print("Division of integers : ",a/b) #question2 def covid():
a=str(input("Enter Patient Name : "))
b=float(input("Enter body temperature : "))
b=98
|
#!/usr/bin/env python3
import sys
import os
# prvo sistemskite i se ostava 2 mesta megju import od razlicen tip
def main():
if len(sys.argv) > 1:
for filename in sys.argv[1:]:
text_stats = stats(filename)
try:
print(" {} {} {} {}".format(*text_stats))
except:
print("")
else:
content = sys.stdin.read()
text_stats = content_stats(content)
text_stats.append(" - ")
try:
print(" {} {} {} {}".format(*text_stats))
except:
print("")
def content_stats(content):
lines = content.splitlines()
words = content.split()
lines_count = len(lines)
words_count = len(words)
chars_count = len(content)
return [lines_count, words_count, chars_count]
def stats(filename):
"""This function returns three values:
- lines in the passed string,
- words in the passed string,
- size of the passed string,
"""
try:
with open(filename, "r") as file:
content = file.read()
stats = content_stats(content)
stats.append(file.name)
return stats
except FileNotFoundError as fnf_error:
error = "{}: {}\n".format(fnf_error.args[1], fnf_error.filename)
sys.stderr.write(error)
exit(fnf_error.errno)
except PermissionError as perm_error:
error = "{}: {}\n".format(perm_error.args[1], perm_error.filename)
sys.stderr.write(error)
exit(perm_error.errno)
if __name__ == "__main__":
main()
|
#!/usr/bin/env python3
import sys
import os
for i in range(1,len(sys.argv)):
filename = sys.argv[i]
with open(filename, "r") as file:
book = file.read()
lines = book.splitlines()
words = book.split()
chars = os.path.getsize(filename)
print(len(lines), len(words), chars, filename)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.