text stringlengths 37 1.41M |
|---|
# message = input('Tell me something, and I will repeat it back to you:')
# print(message)
#
# name = input('Please enter your name:')
# print('Hello,' + name + '!')
#
# age = input('How old are you?')
# print(age)
#
# age = int(age)
#
# if age >= 18:
# print('you are more than 18th')
print('\n')
print(4 % 3)
print(5 % 3)
print(6 % 3)
print(7 % 3)
print('\n')
# current_num = 1
# while current_num <= 5:
# print(current_num)
# current_num += 1
#
# prompt = '\nTell me something, and I will repeat it back to you:'
# prompt += '\nEnter quit to end the program'
# message = ''
# while message != 'quit':
# message = input(prompt)
# print(message)
#
# active = True
# while active:
# message = input(prompt)
# if message == 'quit':
# active = False
# else:
# print(message)
#
#
# prompt = '\nPlease enter the name of a city you have visited'
# prompt += '\nEnter quit to end the program'
#
# while True:
# city = input(prompt)
#
# if city == 'quit':
# break
#
# print(city)
print('\n')
current_number = 0
while current_number < 10:
current_number += 1
if current_number % 2 == 0:
continue
print(current_number)
print('\n')
unconfirmed_users = ['alice','brain','candac']
confirmed_users = []
while unconfirmed_users:
current_user = unconfirmed_users.pop()
print('Verifying user:' + current_user.title())
confirmed_users.append(current_user)
print(confirmed_users)
print('\n')
pets = ['dog','cat','bird','rabbit','fish']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)
print('\n')
responses = {}
polling_active = True
while polling_active:
name = input('Please enter your name')
response = input('which book would you like to read')
responses[name] = response
repeat = input('Would you like to let another person respond?(y/n)')
if repeat == 'n':
polling_active = False
print(responses)
for name,book in responses.items():
print(name.title() + '--' + book.title())
|
import sqlite3
# Create table
# c.execute(''' CREATE TABLE person (
# first_name TEXT,
# last_name TEXT,
# age SMALLINT,
# email TEXT)
# ''')
# Inserting values
# persons = [
# ('John', 'Smith', 32, 'john@gmail.com'),
# ('Jane', 'Doe', 28, 'jane@gmail.com'),
# ('Luke', 'Brown', 31, 'luke@gmail.com'),
# ('Corie', 'Chase', 29, 'chase@gmail.com'),
# ('Michael', 'Prince', 27, 'mike@gmail.com')
# ]
# c.executemany('INSERT INTO person VALUES(?,?,?,?)', persons)
# db.commit()
# Create a fxn for easier execution
# Query db and return all records
def show_all():
# Create and connect to db
db = sqlite3.connect('appdbase.db')
c = db.cursor()
# Select and print items in tablel
c.execute('SELECT rowid, * FROM person')
fetch = c.fetchall()
for i in fetch:
print(i)
db.close()
# add new record to table
def add_one(first, last, age, email):
# Create and connect to db
db = sqlite3.connect('appdbase.db')
c = db.cursor()
c.execute('INSERT INTO person VALUES (?,?,?,?)', (first, last, age, email))
db.commit()
db.close()
# adding many records
def add_many(record):
db = sqlite3.connect('appdbase.db')
c = db.cursor()
c.executemany('INSERT INTO person VALUES (?,?,?,?)', record)
db.commit()
db.close()
# delete record
def delete_one(id):
# Create and connect to db
db = sqlite3.connect('appdbase.db')
c = db.cursor()
c.execute('DELETE FROM person WHERE rowid = (?)', id)
db.commit()
db.close()
|
"""
定义函数
函数function,通常接受输入参数,并有返回值。
它负责完成某项特定任务,而且相较于其他代码,具备相对的独立性。
In [1]:
def add(x, y):
""Add two numbers""
a = x + y
return a
函数通常有一下几个特征:
使用 def 关键词来定义一个函数。
def 后面是函数的名称,括号中是函数的参数,不同的参数用 , 隔开, def foo(): 的形式是必须要有的,参数可以为空;
使用缩进来划分函数的内容;
docstring 用 "" 包含的字符串,用来解释函数的用途,可省略;
return 返回特定的值,如果省略,返回 None 。
使用函数
使用函数时,只需要将参数换成特定的值传给函数。
Python并没有限定参数的类型,因此可以使用不同的参数类型:
In [2]:
print add(2, 3)
print add('foo', 'bar')
5
foobar
在这个例子中,如果传入的两个参数不可以相加,那么Python会将报错:
In [3]:
print add(2, "foo")
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-3-6f8dcf7eb280> in <module>()
----> 1 print add(2, "foo")
<ipython-input-1-e831943cfaf2> in add(x, y)
1 def add(x, y):
2 ""Add two numbers""
----> 3 a = x + y
4 return a
TypeError: unsupported operand type(s) for +: 'int' and 'str'
如果传入的参数数目与实际不符合,也会报错:
In [4]:
print add(1, 2, 3)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-4-ed7bae31fc7d> in <module>()
----> 1 print add(1, 2, 3)
TypeError: add() takes exactly 2 arguments (3 given)
In [5]:
print add(1)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-5-a954233d3b0d> in <module>()
----> 1 print add(1)
TypeError: add() takes exactly 2 arguments (1 given)
传入参数时,Python提供了两种选项,第一种是上面使用的按照位置传入参数,另一种则是使用关键词模式,显式地指定参数的值:
In [6]:
print add(x=2, y=3)
print add(y="foo", x="bar")
5
barfoo
可以混合这两种模式:
In [7]:
print add(2, y=3)
5
设定参数默认值
可以在函数定义的时候给参数设定默认值,例如:
In [8]:
def quad(x, a=1, b=0, c=0):
return a*x**2 + b*x + c
可以省略有默认值的参数:
In [9]:
print quad(2.0)
4.0
可以修改参数的默认值:
In [10]:
print quad(2.0, b=3)
10.0
In [11]:
print quad(2.0, 2, c=4)
12.0
这里混合了位置和指定两种参数传入方式,第二个2是传给 a 的。
注意,在使用混合语法时,要注意不能给同一个值赋值多次,否则会报错,例如:
In [12]:
print quad(2.0, 2, a=2)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-12-101d0c090bbb> in <module>()
----> 1 print quad(2.0, 2, a=2)
TypeError: quad() got multiple values for keyword argument 'a'
接收不定参数
使用如下方法,可以使函数接受不定数目的参数:
In [13]:
def add(x, *args):
total = x
for arg in args:
total += arg
return total
这里,*args 表示参数数目不定,可以看成一个元组,把第一个参数后面的参数当作元组中的元素。
In [14]:
print add(1, 2, 3, 4)
print add(1, 2)
10
3
这样定义的函数不能使用关键词传入参数,要使用关键词,可以这样:
In [15]:
def add(x, **kwargs):
total = x
for arg, value in kwargs.items():
print "adding ", arg
total += value
return total
这里, **kwargs 表示参数数目不定,相当于一个字典,关键词和值对应于键值对。
In [16]:
print add(10, y=11, z=12, w=13)
adding y
adding z
adding w
46
再看这个例子,可以接收任意数目的位置参数和键值对参数:
In [17]:
def foo(*args, **kwargs):
print args, kwargs
foo(2, 3, x='bar', z=10)
(2, 3) {'x': 'bar', 'z': 10}
不过要按顺序传入参数,先传入位置参数 args ,在传入关键词参数 kwargs 。
返回多个值
函数可以返回多个值:
In [18]:
from math import atan2
def to_polar(x, y):
r = (x**2 + y**2) ** 0.5
theta = atan2(y, x)
return r, theta
r, theta = to_polar(3, 4)
print r, theta
5.0 0.927295218002
事实上,Python将返回的两个值变成了元组:
In [19]:
print to_polar(3, 4)
(5.0, 0.9272952180016122)
因为这个元组中有两个值,所以可以使用
r, theta = to_polar(3, 4)
给两个值赋值。
列表也有相似的功能:
In [20]:
a, b, c = [1, 2, 3]
print a, b, c
1 2 3
事实上,不仅仅返回值可以用元组表示,也可以将参数用元组以这种方式传入:
In [21]:
def add(x, y):
""Add two numbers""
a = x + y
return a
z = (2, 3)
print add(*z)
5
这里的*必不可少。
事实上,还可以通过字典传入参数来执行函数:
In [22]:
def add(x, y):
""Add two numbers""
a = x + y
return a
w = {'x': 2, 'y': 3}
print add(**w)
5
map 方法生成序列
可以通过 map 的方式利用函数来生成序列:
In [23]:
def sqr(x):
return x ** 2
a = [2,3,4]
print map(sqr, a)
[4, 9, 16]
其用法为:
map(aFun, aSeq)
将函数 aFun 应用到序列 aSeq 上的每一个元素上,返回一个列表,不管这个序列原来是什么类型。
事实上,根据函数参数的多少,map 可以接受多组序列,将其对应的元素作为参数传入函数:
In [24]:
def add(x, y):
return x + y
a = (2,3,4)
b = [10,5,3]
print map(add,a,b)
[12, 8, 7]
""" |
"""
Python 自1.5以后增加了re的模块,提供了正则表达式模式
re模块使Python语言拥有了全部的正则表达式功能
正则表达式,又称规则表达式。(英语:Regular Expression,在代码中常简写为regex、regexp或RE),计算机科学的一个概念。正则表达式通常被用来检索、替换那些符合某个模式(规则)的文本。
许多程序设计语言都支持利用正则表达式进行字符串操作。例如,在Perl中就内建了一个功能强大的正则表达式引擎。正则表达式这个概念最初是由Unix中的工具软件(例如sed和grep)普及开的。正则表达式通常缩写成“regex”,单数有regexp、regex,复数有regexps、regexes、regexen。
""" |
"""
break 语句
作用:跳出for和while循环
注意:只能跳出距离他最近的那一层循环
"""
for i in range(10):
print(i)
if i == 5:
break
num = 1
while num <= 10:
print(num)
num += 1
if num ==3:
break
#循环语句可以有else语句,break导柱循环截止,不会执行else下面的语句
else:
print("sunck is a good man")
|
"""
认识函数:在一个完整的项目中,某些功能会反复的使用,那么我们会将功能封装成函数,当我们要使用功能时直接调用函数
本质:函数就是对功能的封装
优点:
1.简化代码结构:增加了代码的复用度(重复使用的程度)
2.如果想修改某些功能或者T调试某个BUG,只需要修改对应的函数即可
"""
"""
定义函数:
格式:
def 函数名(参数列表--参数1,参数2,....参数n):
语句
return表达式
def:函数代码块以得分关键字开始
函数名:遵循标识符规则
():参数列表的开始和结束
参数列表(参数1,参数2,....参数n):任何传入函数的参数和变量必须
放在圆括号之间,用逗号分隔,函数从函数的调用者那里获取的信息
冒号:函数内容(封装的功能)以冒号开始,并且缩进
语句;函数封装的功能
return:一般用于结束函数,并返回信息给函数的调用者
表达式:即为要返回给函数的调用者的信息
注意:最后的return表达式,可以不写,相当于return None
"""
# 凯 = "帅"
# print(凯)
"""无参数无返回值
def myprint():
print("sunck is a good man")
print("sunck is a nice man")
print("sunck is a handsome man")
"""
"""
函数的调用
格式:函数名(参数列表)
函数名:是要使用的功能的函数名字
参数列表:函数的调用者给函数传递的信息,如果没有参数,小括号也不能省略
函数调用的本质:实参给形参赋值的过程
""" |
"""
简单的数学运算
整数相加,得到整数:
In [1]:
2 + 2
Out[1]:
4
浮点数相加,得到浮点数:
In [2]:
2.0 + 2.5
Out[2]:
4.5
整数和浮点数相加,得到浮点数:
In [3]:
2 + 2.5
Out[3]:
4.5
变量赋值
Python使用<变量名>=<表达式>的方式对变量进行赋值
In [4]:
a = 0.2
字符串 String
字符串的生成,单引号与双引号是等价的:
In [5]:
s = "hello world"
s
Out[5]:
'hello world'
In [6]:
s = 'hello world'
s
Out[6]:
'hello world'
三引号用来输入包含多行文字的字符串:
In [7]:
s = """hello
world"""
print s
hello
world
In [8]:
s = '''hello
world'''
print s
hello
world
字符串的加法:
In [9]:
s = "hello" + " world"
s
Out[9]:
'hello world'
字符串索引:
In [10]:
s[0]
Out[10]:
'h'
In [11]:
s[-1]
Out[11]:
'd'
In [12]:
s[0:5]
Out[12]:
'hello'
字符串的分割:
In [13]:
s = "hello world"
s.split()
Out[13]:
['hello', 'world']
查看字符串的长度:
In [14]:
len(s)
Out[14]:
11
列表 List
Python用[]来生成列表
In [15]:
a = [1, 2.0, 'hello', 5 + 1.0]
a
Out[15]:
[1, 2.0, 'hello', 6.0]
列表加法:
In [16]:
a + a
Out[16]:
[1, 2.0, 'hello', 6.0, 1, 2.0, 'hello', 6.0]
列表索引:
In [17]:
a[1]
Out[17]:
2.0
列表长度:
In [18]:
len(a)
Out[18]:
4
向列表中添加元素:
In [19]:
a.append("world")
a
Out[19]:
[1, 2.0, 'hello', 6.0, 'world']
集合 Set
Python用{}来生成集合,集合中不含有相同元素。
In [20]:
s = {2, 3, 4, 2}
s
Out[20]:
{2, 3, 4}
集合的长度:
In [21]:
len(s)
Out[21]:
3
向集合中添加元素:
In [22]:
s.add(1)
s
Out[22]:
{1, 2, 3, 4}
集合的交:
In [23]:
a = {1, 2, 3, 4}
b = {2, 3, 4, 5}
a & b
Out[23]:
{2, 3, 4}
并:
In [24]:
a | b
Out[24]:
{1, 2, 3, 4, 5}
差:
In [25]:
a - b
Out[25]:
{1}
对称差:
In [26]:
a ^ b
Out[26]:
{1, 5}
字典 Dictionary
Python用{key:value}来生成Dictionary。
In [27]:
d = {'dogs':5, 'cats':4}
d
Out[27]:
{'cats': 4, 'dogs': 5}
字典的大小
In [28]:
len(d)
Out[28]:
2
查看字典某个键对应的值:
In [29]:
d["dogs"]
Out[29]:
5
修改键值:
In [30]:
d["dogs"] = 2
d
Out[30]:
{'cats': 4, 'dogs': 2}
插入键值:
In [31]:
d["pigs"] = 7
d
Out[31]:
{'cats': 4, 'dogs': 2, 'pigs': 7}
所有的键:
In [32]:
d.keys()
Out[32]:
['cats', 'dogs', 'pigs']
所有的值:
In [33]:
d.values()
Out[33]:
[4, 2, 7]
所有的键值对:
In [34]:
d.items()
Out[34]:
[('cats', 4), ('dogs', 2), ('pigs', 7)]
数组 Numpy Arrays
需要先导入需要的包,Numpy数组可以进行很多列表不能进行的运算。
In [35]:
from numpy import array
a = array([1, 2, 3, 4])
a
Out[35]:
array([1, 2, 3, 4])
加法:
In [36]:
a + 2
Out[36]:
array([3, 4, 5, 6])
In [37]:
a + a
Out[37]:
array([2, 4, 6, 8])
画图 Plot
Python提供了一个很像MATLAB的绘图接口。
In [38]:
%matplotlib inline
from matplotlib.pyplot import plot
plot(a, a**2)
Out[38]:
[<matplotlib.lines.Line2D at 0x9fb6fd0>]
循环 Loop
In [39]:
line = '1 2 3 4 5'
fields = line.split()
fields
Out[39]:
['1', '2', '3', '4', '5']
In [40]:
total = 0
for field in fields:
total += int(field)
total
Out[40]:
15
Python中有一种叫做列表推导式(List comprehension)的用法:
In [41]:
numbers = [int(field) for field in fields]
numbers
Out[41]:
[1, 2, 3, 4, 5]
In [42]:
sum(numbers)
Out[42]:
15
写在一行:
In [43]:
sum([int(field) for field in line.split()])
Out[43]:
15
文件操作 File IO
In [44]:
cd ~
d:\Users\lijin
写文件:
In [45]:
f = open('data.txt', 'w')
f.write('1 2 3 4\n')
f.write('2 3 4 5\n')
f.close()
读文件:
In [46]:
f = open('data.txt')
data = []
for line in f:
data.append([int(field) for field in line.split()])
f.close()
data
Out[46]:
[[1, 2, 3, 4], [2, 3, 4, 5]]
In [47]:
for row in data:
print row
[1, 2, 3, 4]
[2, 3, 4, 5]
删除文件:
In [48]:
import os
os.remove('data.txt')
函数 Function
Python用关键词def来定义函数。
In [49]:
def poly(x, a, b, c):
y = a * x ** 2 + b * x + c
return y
x = 1
poly(x, 1, 2, 3)
Out[49]:
6
用Numpy数组做参数x:
In [50]:
x = array([1, 2, 3])
poly(x, 1, 2, 3)
Out[50]:
array([ 6, 11, 18])
可以在定义时指定参数的默认值:
In [51]:
from numpy import arange
def poly(x, a = 1, b = 2, c = 3):
y = a*x**2 + b*x + c
return y
x = arange(10)
x
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
Out[51]:
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In [52]:
poly(x)
Out[52]:
array([ 3, 6, 11, 18, 27, 38, 51, 66, 83, 102])
In [53]:
poly(x, b = 1)
Out[53]:
array([ 3, 5, 9, 15, 23, 33, 45, 59, 75, 93])
模块 Module
Python中使用import关键词来导入模块。
In [54]:
import os
当前进程号:
In [55]:
os.getpid()
Out[55]:
4400
系统分隔符:
In [56]:
os.sep
Out[56]:
'\\'
- 类 Class
用class来定义一个类。 Person(object)表示继承自object类; __init__函数用来初始化对象; self表示对象自身,类似于C Java里面this。
In [57]:
class Person(object):
def __init__(self, first, last, age):
self.first = first
self.last = last
self.age = age
def full_name(self):
return self.first + ' ' + self.last
构建新对象:
In [58]:
person = Person('Mertle', 'Sedgewick', 52)
调用对象的属性:
In [59]:
person.first
Out[59]:
'Mertle'
调用对象的方法:
In [60]:
person.full_name()
Out[60]:
'Mertle Sedgewick'
修改对象的属性:
In [61]:
person.last = 'Smith'
添加新属性,d是之前定义的字典:
In [62]:
person.critters = d
person.critters
Out[62]:
{'cats': 4, 'dogs': 2, 'pigs': 7}
网络数据 Data from Web
In [63]:
url = 'http://ichart.finance.yahoo.com/table.csv?s=GE&d=10&e=5&f=2013&g=d&a=0&b=2&c=1962&ignore=.csv'
处理后就相当于一个可读文件:
In [64]:
import urllib2
ge_csv = urllib2.urlopen(url)
data = []
for line in ge_csv:
data.append(line.split(','))
data[:4]
Out[64]:
[['Date', 'Open', 'High', 'Low', 'Close', 'Volume', 'Adj Close\n'],
['2013-11-05', '26.32', '26.52', '26.26', '26.42', '24897500', '24.872115\n'],
['2013-11-04',
'26.59',
'26.59',
'26.309999',
'26.43',
'28166100',
'24.88153\n'],
['2013-11-01',
'26.049999',
'26.639999',
'26.030001',
'26.540001',
'55634500',
'24.985086\n']]
使用pandas处理数据:
In [65]:
ge_csv = urllib2.urlopen(url)
import pandas
ge = pandas.read_csv(ge_csv, index_col=0, parse_dates=True)
ge.plot(y='Adj Close')
Out[65]:
<matplotlib.axes._subplots.AxesSubplot at 0xc2e3198>
""" |
"""
循环可以用来生成列表:
In [1]:
values = [10, 21, 4, 7, 12]
squares = []
for x in values:
squares.append(x**2)
print squares
[100, 441, 16, 49, 144]
列表推导式可以使用更简单的方法来创建这个列表:
In [2]:
values = [10, 21, 4, 7, 12]
squares = [x**2 for x in values]
print squares
[100, 441, 16, 49, 144]
还可以在列表推导式中加入条件进行筛选。
例如在上面的例子中,假如只想保留列表中不大于10的数的平方:
In [3]:
values = [10, 21, 4, 7, 12]
squares = [x**2 for x in values if x <= 10]
print squares
[100, 16, 49]
也可以使用推导式生成集合和字典:
In [4]:
square_set = {x**2 for x in values if x <= 10}
print(square_set)
square_dict = {x: x**2 for x in values if x <= 10}
print(square_dict)
set([16, 49, 100])
{10: 100, 4: 16, 7: 49}
再如,计算上面例子中生成的列表中所有元素的和:
In [5]:
total = sum([x**2 for x in values if x <= 10])
print(total)
165
但是,Python会生成这个列表,然后在将它放到垃圾回收机制中(因为没有变量指向它),这毫无疑问是种浪费。
为了解决这种问题,与xrange()类似,Python使用产生式表达式来解决这个问题:
In [6]:
total = sum(x**2 for x in values if x <= 10)
print(total)
165
与上面相比,只是去掉了括号,但这里并不会一次性的生成这个列表。
比较一下两者的用时:
In [7]:
x = range(1000000)
In [8]:
%timeit total = sum([i**2 for i in x])
1 loops, best of 3: 3.86 s per loop
In [9]:
%timeit total = sum(i**2 for i in x)
1 loops, best of 3: 2.58 s per loop
""" |
"""
对应于元组(tuple)与列表(list)的关系,对于集合(set),Python提供了一种叫做不可变集合(frozen set)的数据结构。
使用 frozenset 来进行创建:
In [1]:
s = frozenset([1, 2, 3, 'a', 1])
s
Out[1]:
frozenset({1, 2, 3, 'a'})
与集合不同的是,不可变集合一旦创建就不可以改变。
不可变集合的一个主要应用是用来作为字典的键,例如用一个字典来记录两个城市之间的距离:
In [2]:
flight_distance = {}
city_pair = frozenset(['Los Angeles', 'New York'])
flight_distance[city_pair] = 2498
flight_distance[frozenset(['Austin', 'Los Angeles'])] = 1233
flight_distance[frozenset(['Austin', 'New York'])] = 1515
flight_distance
Out[2]:
{frozenset({'Austin', 'New York'}): 1515,
frozenset({'Austin', 'Los Angeles'}): 1233,
frozenset({'Los Angeles', 'New York'}): 2498}
由于集合不分顺序,所以不同顺序不会影响查阅结果:
In [3]:
flight_distance[frozenset(['New York','Austin'])]
Out[3]:
1515
In [4]:
flight_distance[frozenset(['Austin','New York'])]
Out[4]:
1515
""" |
"""
列表是可变的(Mutable)
In [1]:
a = [1,2,3,4]
a
Out[1]:
[1, 2, 3, 4]
通过索引改变:
In [2]:
a[0] = 100
a
Out[2]:
[100, 2, 3, 4]
通过方法改变:
In [3]:
a.insert(3, 200)
a
Out[3]:
[100, 2, 3, 200, 4]
In [4]:
a.sort()
a
Out[4]:
[2, 3, 4, 100, 200]
字符串是不可变的(Immutable)
In [5]:
s = "hello world"
s
Out[5]:
'hello world'
通过索引改变会报错:
In [6]:
s[0] = 'z'
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-6-83b06971f05e> in <module>()
----> 1 s[0] = 'z'
TypeError: 'str' object does not support item assignment
字符串方法只是返回一个新字符串,并不改变原来的值:
In [7]:
print s.replace('world', 'Mars')
print s
hello Mars
hello world
如果想改变字符串的值,可以用重新赋值的方法:
In [8]:
s = "hello world"
s = s.replace('world', 'Mars')
print s
hello Mars
或者用 bytearray 代替字符串:
In [9]:
s = bytearray('abcde')
s[1:3] = '12'
s
Out[9]:
bytearray(b'a12de')
数据类型分类:
可变数据类型 不可变数据类型
list, dictionary, set, numpy array, user defined objects integer, float, long, complex, string, tuple, frozenset
字符串不可变的原因
其一,列表可以通过以下的方法改变,而字符串不支持这样的变化。
In [10]:
a = [1, 2, 3, 4]
b = a
此时, a 和 b 指向同一块区域,改变 b 的值, a 也会同时改变:
In [11]:
b[0] = 100
a
Out[11]:
[100, 2, 3, 4]
其二,是字符串与整数浮点数一样被认为是基本类型,而基本类型在Python中是不可变的。
""" |
class Person(object):
#这里的属性实际上是属于类属性(用类名来调用)
name = "person"
def __inir__(self,name):
#对象属性:无,默认“person”
self.name = name
print(Person.name)
per = Person("tom")
#对象属性的优先级高于类属性
#动态的给对象添加对象属性
per.age = 18#只针对与当前对象生效,对于类创建的其他对象没有作用
#print(per.name) #tom 无法运行???
per3 = Person("lilei")
#print(per2.age) 没有age属性
#删除对象中的某个属性,再调用会使用到同名的类属性
del per.name
print(per.name)
#注意:以后千万不要将对象属性与类属性重名,因为对象属性会屏蔽掉类属性,但是当删除对象属性后,再使用又能使用类属性了。
|
from types import MethodType
#用MethodType将方法绑定到类,并不是将这个方法直接写到类内部,而是在内存中创建一个link指向外部的方法,在创建实例的时候这个link也会被复制
#创建一个空类
class Person(object):
__slots__ = ("name","age","speak")
#添加属性
per = Person()
#动态添加属性。,这体现了动态语言的特点(灵活)
per.name = "tom"
print(per.name)
#动态添加方法
"""
def say(self):
print("mu name is " + self.name)
per.speak = say
per.speak()
"""
def say(self):
print("my name is " + self.name)
per.speak = MethodType(say,per)
per.speak()
#思考:如果我们想要限制实例的属性怎么办??
#比如:只允许给对象添加name,age,height,weight属性
#per.height = 170
#print(per.height)
|
import tkinter
from tkinter import ttk
#创建主窗口
win = tkinter.Tk()
#设置标题
win.title("sunck")
#设置大小和位置
win.geometry("600x600+200+200")
tree = ttk.Treeview(win)
tree.pack()
#定义列
tree["columns"] =("姓名","年龄","身高","体重")
#设置列,列不显示
tree.column("姓名",width = 100)
tree.column("年龄",width = 100)
tree.column("身高",width = 100)
tree.column("体重",width = 100)
#设置表头
tree.heading("姓名",text = "姓名-name")
tree.heading("年龄",text = "年龄-age")
tree.heading("身高",text = "身高-height")
tree.heading("体重",text = "体重-weight")
#添加数据
# 添加行数【】
tree.insert("",0,text = "line1",values = ("施易人","28","175","70"))
tree.insert("",1,text = "line2",values = ("**","25","180","80"))
win.mainloop()
|
import itertools
import time
#myList = list(itertools.product([1,2,3,4,5,6,7,8,9,0],repeat = 3))
#print(myList)
password = ("".join(x) for x in itertools.product("1234567890",repeat = 3))
#print(len(myList))
while True:
try:
str = next(password)
print(str)
except StopIteration as e:
break
|
"""
基本用法
判断,基于一定的条件,决定是否要执行特定的一段代码,例如判断一个数是不是正数:
In [1]:
x = 0.5
if x > 0:
print "Hey!"
print "x is positive"
Hey!
x is positive
在这里,如果 x > 0 为 False ,那么程序将不会执行两条 print 语句。
虽然都是用 if 关键词定义判断,但与C,Java等语言不同,Python不使用 {} 将 if 语句控制的区域包含起来。Python使用的是缩进方法。同时,也不需要用 () 将判断条件括起来。
上面例子中的这两条语句:
print "Hey!"
print "x is positive"
就叫做一个代码块,同一个代码块使用同样的缩进值,它们组成了这条 if 语句的主体。
不同的缩进值表示不同的代码块,例如:
x > 0 时:
In [2]:
x = 0.5
if x > 0:
print "Hey!"
print "x is positive"
print "This is still part of the block"
print "This isn't part of the block, and will always print."
Hey!
x is positive
This is still part of the block
This isn't part of the block, and will always print.
x < 0 时:
In [3]:
x = -0.5
if x > 0:
print "Hey!"
print "x is positive"
print "This is still part of the block"
print "This isn't part of the block, and will always print."
This isn't part of the block, and will always print.
在这两个例子中,最后一句并不是if语句中的内容,所以不管条件满不满足,它都会被执行。
一个完整的 if 结构通常如下所示(注意:条件后的 : 是必须要的,缩进值需要一样):
if <condition 1>:
<statement 1>
<statement 2>
elif <condition 2>:
<statements>
else:
<statements>
当条件1被满足时,执行 if 下面的语句,当条件1不满足的时候,转到 elif ,看它的条件2满不满足,满足执行 elif 下面的语句,不满足则执行 else 下面的语句。
对于上面的例子进行扩展:
In [4]:
x = 0
if x > 0:
print "x is positive"
elif x == 0:
print "x is zero"
else:
print "x is negative"
x is zero
elif 的个数没有限制,可以是1个或者多个,也可以没有。
else 最多只有1个,也可以没有。
可以使用 and , or , not 等关键词结合多个判断条件:
In [5]:
x = 10
y = -5
x > 0 and y < 0
Out[5]:
True
In [6]:
not x > 0
Out[6]:
False
In [7]:
x < 0 or y < 0
Out[7]:
True
这里使用这个简单的例子,假如想判断一个年份是不是闰年,按照闰年的定义,这里只需要判断这个年份是不是能被4整除,但是不能被100整除,或者正好被400整除:
In [8]:
year = 1900
if year % 400 == 0:
print "This is a leap year!"
# 两个条件都满足才执行
elif year % 4 == 0 and year % 100 != 0:
print "This is a leap year!"
else:
print "This is not a leap year."
This is not a leap year.
值的测试
Python不仅仅可以使用布尔型变量作为条件,它可以直接在if中使用任何表达式作为条件:
大部分表达式的值都会被当作True,但以下表达式值会被当作False:
False
None
0
空字符串,空列表,空字典,空集合
In [9]:
mylist = [3, 1, 4, 1, 5, 9]
if mylist:
print "The first element is:", mylist[0]
else:
print "There is no first element."
The first element is: 3
修改为空列表:
In [10]:
mylist = []
if mylist:
print "The first element is:", mylist[0]
else:
print "There is no first element."
There is no first element.
当然这种用法并不推荐,推荐使用 if len(mylist) > 0: 来判断一个列表是否为空。
""" |
#排序:冒泡排序,选择排序, 快速排序,插入法,计数器排序
#普通排序
list1 = [4,7,2,6,3]
list2 = sorted(list1)#默认升序排序
print(list1)
print(list2)
#按绝对值大小排序
list3 = [4,-7,2,-6,3]
#key接受函数来实现自定义排序规则
list4 = sorted(list3,key = abs)
print(list3)
print(list4)
#按降序
list5 = [4,7,2,6,3]
list6 = sorted(list5,reverse= True)
print(list5)
print(list6)
#按长短--函数可以自己写
def myLine(str):
return len(str)
list7 = ["a111","b222","c33","d7854"]
list8 = sorted(list7,key = myLine)
print(list7)
print(list8)
|
"""
概述:
目前代码比较少,写在一个文件中还体现不出什么缺点,但是随着代码量越来越多,代码就越来越难以维护
为了解决难以维护问题,我们把很多相似功能的函数分组,分别放到不同文件中去,这样每个文件所包含的内容相对较少
而且对于每一个文件的大致功能可用文件名来体现,很多编程语言都是这么来组织代码结构,一个py文件就是一个模块
优点:
1.提高代码的可维护性
2.提高代码的服用度,当一个模块完毕,可以被多个地方应用
3.引用其他的模块(内置模块和三方模块和自定义模块)
4.避免函数名和变量名的冲突
"""
|
'''
elena corpus
program 11
csci 161
merge short
'''
def mergeSort(myList):
if len(myList) > 1:
#splitting the list
mid = len(myList) // 2
#left half
lefthalf = myList[:mid]
#right half
righthalf = myList[mid:]
mergeSort(lefthalf)
mergeSort(righthalf)
i = 0
j = 0
k = 0
#comparing lists to decipher which is greater than or less than
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
myList[k] = lefthalf[i]
i = i + 1
else:
myList[k] = righthalf[j]
j = j + 1
k = k + 1
#determining if i from the left side is less than what is in the left side
while i < len(lefthalf):
myList[k] = lefthalf[i]
i = i + 1
k = k + 1
#determining if
while j < len(righthalf):
myList[k] = righthalf[j]
j = j + 1
k = k + 1
myList = [22, 64, 11, 34, 25, 90, 12]
mergeSort(myList)
print("Sorted:", myList)
|
from datetime import datetime
from time import mktime
__all__ = (
'TimeStamp',
)
class TimeStamp:
"""
TimeStamp
~~~~~~~~~
>>> ts = TimeStamp(1578302868) # Monday, January 6, 2020 12:27:48 PM GMT+03:00
>>> ts.to_datetime()
datetime.datetime(2020, 1, 6, 12, 27, 48)
>>> ts.to_epoch()
1578302868
>>> ds = TimeStamp(datetime(year=2011, month=7, day=14, hour=6, minute=43, second=35))
>>> ds.to_datetime()
datetime.datetime(2011, 7, 14, 6, 43, 35)
>>> ds.to_epoch()
1310615015
"""
def __init__(self, timestamp: (int, float, datetime) = None):
"""
Timestamp helpers
:param timestamp: timestamp in shape of epoch or datetime object
"""
if timestamp is None:
timestamp = datetime.now()
if isinstance(timestamp, datetime):
self._timestamp = timestamp
else:
# noinspection PyTypeChecker
self._timestamp = datetime.fromtimestamp(timestamp)
def to_datetime(self) -> datetime:
"""Datetime representation of given timestamp"""
return self._timestamp
def to_epoch(self) -> int:
"""Epoch time representation of given timestamp"""
return int(mktime(self._timestamp.timetuple()))
|
import requests, json
cached_currencies = []
def get_currency(currency_code):
global cached_currencies
currency_code = currency_code.lower()
currency_data = dict(eval(requests.get(f'http://www.floatrates.com/daily/{currency_code}.json').text))
new_currency = {currency_code: currency_data}
with open(f'{currency_code}.json', 'w', encoding='utf-8') as currency:
json.dump(new_currency, currency, indent=4)
cached_currencies.append(currency_code)
get_currency("usd")
get_currency("eur")
def exchange(sell_currency, buy_currency, amount):
sell_currency = sell_currency.lower()
buy_currency = buy_currency.lower()
print("Checking the cache...")
if sell_currency not in cached_currencies:
get_currency(sell_currency)
if buy_currency not in cached_currencies:
print("Sorry, but it is not in the cache!")
get_currency(buy_currency)
else:
print("Oh! It is in the cache!")
with open(f"{sell_currency}.json", 'r') as file:
currencies = json.load(file)
result = round(amount * currencies[sell_currency][buy_currency]['rate'], 2)
return result
sell_currency = input().upper()
buy_currency = input().upper()
amount = float(input())
while True:
print(f"You received {exchange(sell_currency, buy_currency, amount)} {buy_currency}.")
buy_currency = input().upper()
if buy_currency == "":
break
amount = float(input())
if amount == "":
break
|
if __name__ == '__main__':
your_name = input("What is your name?")
their_name = input("What is their name?")
combined_name = your_name + their_name
t_count = combined_name.lower().count('t')
r_count = combined_name.lower().count('r')
u_count = combined_name.lower().count('u')
e_count = combined_name.lower().count('e')
true_count = t_count + r_count + u_count + e_count
l_count = combined_name.lower().count('l')
o_count = combined_name.lower().count('o')
v_count = combined_name.lower().count('v')
e_count = combined_name.lower().count('e')
love_count = l_count + o_count + v_count + e_count
print(str(true_count) + str(love_count))
|
lst = []
size = int(input("Enter size of array "))
for n in range(size):
number = int(input("Enter Elements "))
lst.append(number)
x = int(input("Enter number to be searched "))
result = -1
for i in range(len(lst)):
if x == lst[i]:
result = i
break
print(result) |
numero = int (input("Informe número a ser fatorado: "))
if numero == 1 or numero == 0:
fatorial = 1
else:
fatorial=1
for i in range (1,numero+1):
fatorial = fatorial* i
print("Fatorial de",numero,"é: ",fatorial) |
x=0
soma=0
while x < 4:
notas = float (input("Informe notas: "))
soma += notas
x+=1
media = soma/4
print("%.2f" %media) |
from sys import argv, exit
from cs50 import get_string
# Check if user has provided any command line arg
if (len(argv) != 2):
print("Usage: python caeser.py key")
exit(1)
# Convert the command line arg into an int
key = int(argv[1])
#print(key)
plaintext = get_string("plaintext: ")
print("ciphertext: ", end="")
for c in plaintext:
# if c is a letter
if c.isalpha():
# if c is an uppercase letter
if c.isupper():
base = ord(c) - 65 # 0,1,2
index = (base + key) % 26 # new index
new_char = chr(65 + index)
print(new_char, end="")
# if c is a lowercase letter
else:
base = ord(c) - 97 # 0,1,2
index = (base + key) % 26 # new index
new_char = chr(97 + index)
print(new_char, end="")
# if c is some other char
else:
print(c, end="")
print()
|
from cs50 import get_int
# Validating input
while True:
height = get_int("Height: ")
if (height > 0 and height <= 8):
break
space = height - 1
star = 1
for i in range(height):
# Left side
print(" " * space, end="")
space -= 1
print("#" * star, end="")
star += 1
# Spaces - Middle side
print(" " * 2, end="")
# Right side
print("#" * (i + 1)) |
#!/usr/bin/python3
"""
Take a list, say for example this one:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
and write a program that prints out all the elements of the list that are less than 5.
Extras:
Instead of printing the elements one by one, make a new list that has all the elements
less than 5 from this list in it and print out this new list.
Write this in one line of Python.
Ask the user for a number and return a list that contains only elements from the original
list a that are smaller than that number given by the user.
"""
from helpers import user_data_validation
number_list = [0, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
def main():
create_new_list()
create_user_generated_list()
def create_new_list():
new_number_list = []
for number in number_list:
if number < 5:
print('index: {} value: {}'.format(number_list.index(number), number))
new_number_list.append(number)
print('original list: {}'.format(number_list))
print('new list with values less than 5: {}'.format(new_number_list))
def create_user_generated_list():
user_generated_list = []
user_input_value = int(user_data_validation(input('Please provide a value: ')))
for number in number_list:
if number < user_input_value:
user_generated_list.append(number)
print('original list: {}'.format(number_list))
print('user generated list: {}'.format(user_generated_list))
if __name__ == '__main__': main()
|
#!/usr/bin/python3
def user_data_validation(user_data, message='You must specify a number to continue:'):
while user_data == '':
try:
raise ValueError(message)
except ValueError as err:
print(err)
user_data = input()
if user_data == "exit":
quit()
return user_data
def turn_checker(user_data, message='You must specify a valid turn, Please enter either Rock, Paper or Scissors:'):
while user_data not in ['Rock', 'Paper' 'Scissors']:
try:
raise NameError(message)
except NameError as err:
print(err)
user_data = input()
|
import random
user_wins = 0
comp_wins = 0
options = ['rock', 'paper', 'scissors']
def play():
while True:
# user = input("Type Rock/Paper/Scissors or Q to quit.").lower()
user = input("rock/paper/scissors: ").lower()
if user == 'q':
break
if user not in options:
continue
comp = random.randint(0, 2)
comp_guess = options[comp]
# print(f'Computer chose {comp_guess}.')
print(f'Troll chose {comp_guess}.')
if user == 'rock' and comp_guess == 'scissors':
print("You win!")
# user_wins += 1
# continue
return True
elif user == 'paper' and comp_guess == 'rock':
print("You win!")
# user_wins += 1
# continue
return True
elif user == 'scissors' and comp_guess == 'paper':
print("You win!")
# user_wins += 1
# continue
return True
elif user == 'rock' and comp_guess == 'rock':
print("Tie. Go again.")
continue
elif user == 'paper' and comp_guess == 'paper':
print("Tie. Go again.")
continue
elif user == 'scissors' and comp_guess == 'scissors':
print("Tie. Go again.")
continue
else:
print("You lost!")
# comp_wins += 1
return False
|
import queue
def is_connected(str1, str2):
N = len(str1)
diff = 0
for i in range(N):
if str1[i] != str2[i]:
diff += 1
if diff == 2:
return False
return True
def solution(begin, target, words):
if target not in words:
return 0
N = len(words) + 1
nvs = [[] for _ in range(N)]
for i, word in enumerate(words):
if is_connected(begin, word):
nvs[0].append(i + 1)
for i in range(N - 1):
for j in range(N - 1):
if is_connected(words[i], words[j]) and i != j:
nvs[i + 1].append(j + 1)
target_v = words.index(target) + 1
q = queue.Queue()
distance = [-1 for _ in range(N)]
q.put(0)
distance[0] = 0
while q.qsize() > 0:
v = q.get()
for nv in nvs[v]:
if distance[nv] == -1:
q.put(nv)
distance[nv] = distance[v] + 1
if distance[target_v] == -1:
return 0;
else:
return distance[target_v] |
def solution(N):
D = [0 for _ in range(N + 1)]
D[1] = 1
D[2] = 1
for i in range(3, N + 1):
D[i] = D[i - 1] + D[i - 2]
return D[N] * 2 + (D[N] + D[N - 1]) * 2 |
def binary_search(budgets, M, start, end):
if start == end:
return start
mid = (start + end + 1) // 2
total_budget = sum([min(budget, mid) for budget in budgets])
if total_budget == M:
return mid
elif total_budget < M:
return binary_search(budgets, M, mid, end)
else:
return binary_search(budgets, M, start, mid - 1)
def solution(budgets, M):
N = len(budgets)
max_budget = max(budgets)
return binary_search(budgets, M, 0, max_budget) |
num=int(raw_input())
arr=raw_input()
arr=arr.split()
max=int(arr[0])
for i in range(1,num):
if int(arr[i])>max:
max=int(arr[i])
print max
|
number=int(input())
reverse=0
while number>0:
reminder=number%10
reverse=(reverse*10)+reminder
number=number//10
print(reverse)
|
a1=int(raw_input())
b1=int(raw_input())
c1=int(raw_input())
if (a1>=b1) and (a1>=c1):
largest=a1
elif (b1>=a1) and (b1>=c1):
largest=b1
else:
largest=c1
print int(largest)
|
list=['hai', 'jsdjh', 'shsh', 'dhsg', 'dksjhjsh']
for item in list:
print(item)
#2 range function: (start,stop,step size)
for i in range(1,8,2):
print(i)
else:
print('done with the loop') |
#1 maximum of 3 numbers:
def greatest(n1,n2,n3):
if(n1>n2 and n1>n3):
return n1
elif(n2>n1 and n2>n3):
return n2
else:
return n3
n1=int(input('enter the number: '))
n2=int(input('enter the number: '))
n3=int(input('enter the number: '))
print(greatest(n1,n2,n3))
#2 celcius to faherinhet:
# F=1.8c+32
def farenheit(c):
return ((1.8)*c)+32
c=int(input('enter the degree celcius: '))
f=farenheit(c)
print(f)
#3 sum of n natural numbers:
def addition(n):
add=0
for i in range(1,(n+1)):
add=add+i
i=i+1
return add
n=int(input('enter the number: '))
print(addition(n))
#4 sum of n natural numbers using recursion:
def sum(n):
add=0
for i in range(1,(n+1)):
add=add+i
return add
def sum_rec(n):
if n==0:
return 0
else:
return n+sum(n-1)
n=10
print(sum_rec(10))
#5 pattern:
def pattern(n):
for i in range(n):
print('*'*(n-i))
n=int(input('enter the number: '))
print(pattern(n))
#6 remove and strip:
string=' ajay is good '
def remove_strip(word):
new_string=string.replace(word,'')
return new_string.strip()
word=input('enter the word: ')
print(remove_strip(word))
#7 print table:
def table(n):
for i in range(1,11):
print(f"{n} X {i} = {n*i}")
n=int(input('enter the number: '))
print(table(n)) |
"""app/models.py: Tutorial IV - Databases.
database models: collection of classes whose purpose is to represent the
data that we will store in our database.
The ORM layer (SQLAlchemy) will do the translations required to map
objects created from these classes into rows in the proper database table.
- ORM: Object Relational Mapper; links b/w tables corresp. to objects.
"""
import bleach
from app import db
from flask import session, url_for, request, g
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import validates
from markdown import markdown
class User(db.Model):
"""A model that represents our users.
Jargon/Parameters:
- primary key: unique id given to each user.
- varchar: a string.
- db.Column parameter info:
- index=True: allows for faster queries by associating a given column
with its own index. Use for values frequently looked up.
- unique=True: don't allow duplicate values in this column.
Fields:
id: (db.Integer) primary_key for identifying a user in the table.
nickname: (str)
posts: (db.relationship)
"""
# Fields are defined as class variables, but are used by super() in init.
# Pass boolean args to indicate which fields are unique/indexed.
# Note: 'unique' here means [a given user] 'has only one'.
id = db.Column(db.Integer, primary_key=True)
nickname = db.Column(db.String(64), index=True, unique=True)
# Relationships are not actual database fields (not shown on a db diagram).
# They are typically on the 'one' side of a 'one-to-many' relationship.
# - backref: *defines* a field that will be added to the instances of
# Posts that point back to this user.
# - lazy='dynamic': "Instead of loading the items, return another query
# object which we can refine before loading items.
posts = db.relationship('Post', backref='author', lazy='dynamic')
@validates('nickname')
def convert_upper(self, key, value):
if not isinstance(value, str):
raise ValueError('convert_upper received {} as nickname'.format(
value))
return value.capitalize()
def __repr__(self):
return '<User {0} with {1} posts>'.format(
self.nickname, self.posts.count())
class Post(db.Model):
"""A model for posts that were created by a user.
Fields:
id: (db.Integer)
body: (db.String)
timestamp: (db.DateTime)
user_id: (db.Integer)
"""
id = db.Column(db.Integer, primary_key=True)
body = db.Column(db.Text)
# Cache the HTML code for the rendered (markdown) blog post.
body_html = db.Column(db.Text)
timestamp = db.Column(db.DateTime)
# Establish link bw foreign key (user_id) and 'id' field of
# table it refers to. One-to-many: one user writes many posts.
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
@staticmethod
def on_changed_body(target, value, oldvalue, initiator):
allowed_tags = [
'a', 'abbr', 'acronym', 'b', 'blockquote',
'code', 'em', 'i', 'li', 'ol', 'pre', 'strong',
'ul', 'h1', 'h2', 'h3', 'p']
target.body_html = bleach.linkify(bleach.clean(
markdown(value, output_format='html'),
tags=allowed_tags, strip=True))
def __repr__(self):
return '<Post %r>' % self.body
db.event.listen(Post.body, 'set', Post.on_changed_body)
|
domaci_zvirata = ["kráva", "pes", "kocka", "králík", "had", "andulka"]
domaci_zvirata2 = ["kráva", "pes", "lachtan", "králík", "had", "andulka", "tygr"]
def vytvor_seznamy(s1, s2):
s1ms2 = []
s2ms1 = []
union = []
intersection = []
for item in s1 + s2:
if item not in s1:
s2ms1.append(item)
elif item not in s2:
s1ms2.append(item)
elif item not in intersection:
intersection.append(item)
if item not in union:
union.append(item)
return s1ms2, s2ms1, intersection, union
def vrat_kratsi5(seznam):
res = []
for e in seznam:
if len(e) < 5:
res.append(e)
return res
def vrat_k(seznam):
res = []
for e in seznam:
if e[0].lower() == "k":
res.append(e)
return res
def je_v_seznamu(slovo, seznam=domaci_zvirata):
return slovo in seznam
def serad_abecedne(seznam):
return sorted(seznam)
def serad_special(seznam):
klice = [item[1:] for item in seznam]
dvojice = list(zip(klice, seznam))
return [item[1] for item in sorted(dvojice)]
# print(vytvor_seznamy(domaci_zvirata, domaci_zvirata2))
print(serad_abecedne(domaci_zvirata))
print(serad_special(domaci_zvirata))
|
"""
Inheritance examples from materials
https://naucse.python.cz/course/pyladies/beginners/inheritance/
"""
class Zviratko:
def __init__(self, jmeno):
self.jmeno = jmeno
def snez(self, jidlo):
print("{}: {} mi chutná!".format(self.jmeno, jidlo))
class Morcatko(Zviratko):
pass
lucinka = Morcatko("Lucinka")
lucinka.snez("mrkev")
class Kotatko(Zviratko):
def zamnoukej(self):
print("{}: Mňau!".format(self.jmeno))
class Stenatko(Zviratko):
def zastekej(self):
print("{}: Haf!".format(self.jmeno))
micka = Kotatko('Micka')
azorek = Stenatko('Azorek')
micka.zamnoukej()
azorek.zastekej()
micka.snez('myš')
azorek.snez('kost') |
"""
Created on Mon Dec 9 18:42:53 2019
@author: aaron
"""
'''
documentation
initialize() - starts the robot
end() - finishes the program
clear() - clears the file you wrote
button() - button function
clipboard() - copies program to clipboard for WIN
startmotor(distance) - moves forward in a specific distance in milimeters
startmotorslow1(distance) - same with startmotor but 25 power
startmotorslow2(distance) - same with startmotor but 12 power
nstartmotor(distance) - moves backward in a specific distance in milimeters
nstartmotorslow1(distance) - same with nstartmotor but 25 speed
nstartmotorslow1(distance) - same with nstartmotor but 12 speed
leftlineturn(lturnspeed) - turns left after detection by linefollow
rightlineturn(lturnspeed) - turns right after detection by linefollow
turnleft(degree) - turn to a specified degree to the left
turnright(degree) - turn to a specified degree to the right
leftturn(degree) - same with leftturn but only moves one wheel
rightturn(degree) - same with righturn but only moves one wheel
linefollow(inter=t,l,r) - detects either one of the three types of intersection
linefollowslow1(inter=t,l,r) - same with linefollow but with 25 power
linefollowslow2(inter=t,l,r) - same with linefollow but with 12 power
time(distance) - amount of distance it will follow the line
motor(motor,power) - motor = motor# - power = strength of motor
motorstrong1(motor=1,power=60)
wait(time) - amount of time the robot will remain not moving
stopmotor() - turn off all moving motors
motordeg(port, direction, degree) - turns the motor to a certiain degree
motordegstrong(port, direction, degree) - same with motor deg but stronger
'''
import pyperclip
import os
def initialize():
global name
f = open(name, "a+")
f.write(""" #include "ASEIO.h" \n""")
f.write("void main()\n")
f.write("{\n")
f.write(" WER_InitRobot_5(0,1.000000,1,1.000000,0,1,2,3,4,1);\n")
def startmotor(distance):
global name
f = open(name, "a+")
time = distance/475
f.write(' WER_SetMotor(50,50,\t')
f.write(str(time))
f.write(');\n')
def startmotorslow1(distance):
global name
f = open(name, "a+")
time = (distance/475)*2
f.write(' WER_SetMotor(25,25,\t')
f.write(str(time))
f.write(');\n')
def startmotorslow2(distance):
global name
f = open(name, "a+")
time = (distance/475)*4
f.write(' WER_SetMotor(12,12,\t')
f.write(str(time))
f.write(');\n')
def nstartmotor(distance):
global name
f = open(name, "a+")
time = distance/475
f.write(' WER_SetMotor(-50,-50,\t')
f.write(str(time))
f.write(');\n')
def nstartmotorslow1(distance):
global name
f = open(name, "a+")
time = (distance/475)*2
f.write(' WER_SetMotor(-25, -25,\t')
f.write(str(time))
f.write(');\n')
def nstartmotorslow2(distance):
global name
f = open(name, "a+")
time = (distance/475)*4
f.write(' WER_SetMotor(-12,-12,\t')
f.write(str(time))
f.write(');\n')
def leftlineturn():
global name
f = open(name, "a+")
f.write(" WER_Around(\t")
f.write(str(-30))
f.write(",\t")
f.write(str(30))
f.write(",\t")
f.write("0);\n")
def rightlineturn():
global name
f = open(name, "a+")
f.write(" WER_Around(\t")
f.write(str(30))
f.write(",\t")
f.write(str(-30))
f.write(",\t")
f.write("0);\n")
def turnleft(degree):
global name
f = open(name , "a+")
degree1 = 0.0067
time = degree1*degree
f.write(' WER_SetMotor(-30,30,\t')
f.write(str(time))
f.write(');\n')
def turnright(degree):
global name
f = open(name, "a+")
degree1 = 0.0067
time = degree1*degree
f.write(' WER_SetMotor(30,-30,\t')
f.write(str(time))
f.write(');\n')
def rightturn(degree):
global name
f = open(name, "a+")
if degree > 0:
degree1 = 1.09/90
time = degree1*degree
f.write(' WER_SetMotor(30,0,\t')
f.write(str(time))
f.write(');\n')
elif degree < 0:
degree = degree*-1
degree1 = 1.09/90
time = degree1*degree
f.write(' WER_SetMotor(-30,0,\t')
f.write(str(time))
f.write(');\n')
def leftturn(degree):
global name
f = open(name, "a+")
if degree > 0:
degree1 = 1.09/90
time = degree1*degree
f.write(' WER_SetMotor(0,30,\t')
f.write(str(time))
f.write(');\n')
elif degree < 0:
degree = degree*-1
degree1 = 1.09/90
time = degree1*degree
f.write(' WER_SetMotor(0,-30,\t')
f.write(str(time))
f.write(');\n')
def linefollow(inter):
global name
f = open(name, "a+")
if "t" in inter:
f.write(" WER_LineWay_C(50,15,0.2);\n")
elif "r" in inter:
f.write(" WER_LineWay_C(50,5,0.2);\n")
elif "l" in inter:
f.write(" WER_LineWay_C(50,1,0.2);\n")
def linefollowslow1(inter):
global name
f = open(name, "a+")
if "t" in inter:
f.write(" WER_LineWay_C(25,15,0.4);\n")
elif "r" in inter:
f.write(" WER_LineWay_C(25,5,0.4);\n")
elif "l" in inter:
f.write(" WER_LineWay_C(25,1,0.4);\n")
def linefollowslow2(inter):
global name
f = open(name, "a+")
if "t" in inter:
f.write(" WER_LineWay_C(12,15,0.8);\n")
elif "r" in inter:
f.write(" WER_LineWay_C(12,5,0.8);\n")
elif "l" in inter:
f.write(" WER_LineWay_C(12 ,1,0.8);\n")
def button():
global name
f = open(name, "a+")
f.write(" WER_next();\n")
def motor(motor=1,power=30):
global name
f = open(name , "a+")
f.write(" SetMoto(\t")
f.write(str(motor))
f.write(",\t")
f.write(str(power))
f.write(");\n")
def motorstrong1(motor=1,power=60):
global name
f = open(name , "a+")
f.write(" SetMoto(\t")
f.write(str(motor))
f.write(",\t")
f.write(str(power))
f.write(");\n")
def wait(time):
global name
f = open(name, "a+")
f.write(" wait(\t")
f.write(str(time))
f.write(");\n")
def stopmotor():
global name
f = open(name, "a+")
f.write(" SetMoto(1,0);\n")
f.write(" SetMoto(0,0);\n")
f.write(" SetMoto(2,0);\n")
f.write(" SetMoto(3,0);\n")
def time(distance):
time = distance/475
global name
f = open(name, "a+")
f.write(" WER_LineWay_T(50,\t")
f.write(str(time))
f.write(");\n")
def timeslow2(distance):
time = (distance/475)*4
global name
f = open(name, "a+")
f.write(" WER_LineWay_T(12,\t")
f.write(str(time))
f.write(");\n")
def motordeg(port, direction, degree):
global name
time = degree*(1/400)
f = open(name, "a+")
if direction == "r":
motor(port,30)
wait(time)
stopmotor()
elif direction =="l":
motor(port,-30)
wait(time)
stopmotor()
def motordegstrong(port, direction, degree):
global name
time = (degree*(1/400))/2
f = open(name, "a+")
if direction == "r":
motor(port,60)
wait(time)
stopmotor()
elif direction =="l":
motor(port,-60)
wait(time)
stopmotor()
def end():
global name
f = open(name , "a+")
f.write("}\n")
def clear():
global name
f = open(name, "w+")
f.write("")
def clipboard():
global name
f = open(name, "r")
content = f.read()
pyperclip.copy(content)
###############################################
def loc1():
global name
startmotor(100)
linefollow("l")
leftlineturn()
linefollow("r")
startmotor(200)
time(80)
leftlineturn()
time(200)
def loc2():
global name
startmotor(100)
linefollow("l")
leftlineturn()
linefollow("r")
turnleft(30)
startmotor(300)
time(400)
def loc3():
startmotor(100)
linefollow("l")
leftlineturn()
linefollow("r")
startmotor(200)
time(80)
time(240)
def loc4(): # start from back of the box
global name
startmotor(150)
linefollow("l")
leftlineturn()
linefollow("l")
leftlineturn()
linefollow("l")
time(230)
def loc5():
global name
startmotor(150)
linefollow("l")
leftlineturn()
linefollow("r")
rightlineturn()
linefollow("l")
def loc6():
global name
startmotor(150)
linefollow("l")
linefollow("l")
leftlineturn()
def loc7():
global name
startmotor(150)
linefollow("l")
linefollow("l")
linefollow("l")
leftlineturn()
time(110)
def loc8():
global name
startmotor(150)
linefollow("l")
linefollow("l")
linefollow("l")
linefollow("l")
leftlineturn()
def loc9():
global name
startmotor(150)
linefollow("l")
linefollow("l")
linefollow("l")
linefollow("l")
time(130)
def loc10back():
startmotor(100)
linefollow("l")
linefollow("l")
leftlineturn()
time(100)
turnleft(90)
wait(1)
turnleft(80)
startmotor(90)
end()
def loc10front():
global name
startmotor(150)
linefollow("l")
rightlineturn()
linefollow("t")
turnleft(90)
startmotor(350)
leftlineturn()
def loc10right():
global name
startmotor(150)
linefollow("l")
linefollow("l")
linefollow("l")
linefollow("l")
wait(0.3)
nstartmotor(50)
wait(0.3)
turnright(90)
startmotor(90)
name = 'stickslap.txt'
clear()
initialize()
button()
loc4()
time(60)
rightlineturn()
linefollow('r')
rightlineturn()
linefollow('r')
linefollow('r')
rightlineturn()
time(130)
time(150)
nstartmotorslow1(150)
timeslow2(160)
nstartmotor(55)
rightturn(220)
startmotor(600)
end()
clipboard()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
print "Welcome to potential energy calculation script..."
m = input("Put mass of object:")
g = 10
h = input("Put height of object:")
potential = m*g*h
print "Potential energy of object:%s Newton" %(potential)
|
print "Hi!"
x=raw_input('type Latin infinitive: ')
## кортеж: x=(1, 2, 3)
n=1
transitions={(1, 'a'):2, (1, 'e'):2, (1, 'i'):2, (2, 'a'):2, (2, 'e'):2, (2, 'i'):2, (2, 'r'):3, (3, 'e'):4, (4, 'a'):2, (4, 'i'):2, (4, 'e'):2}
for i in x:
if n==1 and i not in 'aei':
n=1
elif (n, i) in transitions:
n=transitions[(n, i)]
else:
n=1
if n==4:
print "Congratulations, you can type!"
else:
print 'No, I said "Latin infinitive"'
|
# -*- coding: utf-8 -*-
class OldString:
def __init__(self, text):
self.alphabet = u'абвгдежзиiклмнопрстуфхцчшщъыьѣэюяѳѵ'
self.d = {}
for i in self.alphabet:
self.d[i] = self.alphabet.index(i)
self.text = text.lower()
def __lt__(self, other):
i = 0
try:
while self.text[i] == other.text[i]:
i += 1
else:
return self.d[self.text[i]] < other.d[other.text[i]]
except:
return len(self.text) < len(other.text)
def __eq__(self, other):
return self.text == other.text
def __ne__(self, other):
return self.text != other.text
def __gt__(self, other):
return __lt__(self, other) == False and __eq__(self, other) == False
def __ge__(self, other):
return __lt__(self, other) == False
def __le__(self, other):
return __gt__(self, other) == False
s1 = OldString(u'бѣлый') # или сначала s1 = OldString(), а потом, например, s1.text = u'бѣлый'
s2 = OldString(u'бебебе')
s3 = OldString(u'Ѳедоръ')
array = [s1, s2, s3]
for s in sorted(array):
print s.text # слова должны распечататься в алфавитном порядке
|
f = open('long_poem.txt', 'r', encoding='utf-8')
text = f.read() # читаем текст
f.close()
text = text.split('\n') # разбиваем текст на строки
search = input('к чему надо подобрать рифму?\n')
for i in text:
lastword = i.split(' ')[-1] # последнее слово в строке
if lastword == search: # ищем строки, в которых последнее слово -- то, которое мы ищем
for n in range(-3, 3): # смотрим от нужной строки на 3 вверх и на 3 вниз
num = text.index(i) + n
if text[num][-2:] == search[
-2:]: # если последние 2 символа строки совпадают с последними 2 символами запроса,
print(text[num]) # то выводим строку
print('')
|
# -*- coding: utf-8 -*-
a=[]
b="0"
while b!="":
b=raw_input(u"Введите, пожалуйста, слово: ").decode("cp1251")
if b!="":
a.append(b)
else:
for i in range (0, 8):
for j in a:
n=len(j)
if n==i:
print j
|
def getSQCount(index):
#hard coded array of the arth sq totals within each hour... hard coded since this is known and is always constant
#assuming the clock is a normal LED clock
arrayOfArthSQInEachHour = [1, 5, 5, 4, 4, 3, 3, 2, 2, 1, 0, 1]
total = 0
#get total for all the hours that have passed since 12pm
for i in range(index):
total += arrayOfArthSQInEachHour[i]
return total
def getSumOfSQInHour(hour, minutesLeft, smallestCommonDiff, largestCommonDiff):
total = 0
#this check will get the last digit of the hour hand if 11, or 12 since the common difference is added to the last digit
if hour > 10:
hour = hour - 10
for i in range(smallestCommonDiff, largestCommonDiff +1):
firstDigit = hour + i
secondDigit = firstDigit + i
minuteCount = (firstDigit*10) + secondDigit
if minuteCount <= minutesLeft:
total += 1
else:
break
return total
def main(D):
hour = D//60 #the numbers of hours past 12pm
minutesLeft = D - (hour*60) #the number of minutes left in the hour
if hour > 0:
currentSumOfArthSQ = getSQCount(hour)
else: #if 0, then no hour has passed since 12pm so the current sum is 0
currentSumOfArthSQ = 0
smallestCommonDiff = 0
largestCommonDiff = 0
#determine what the max and min difference can be used for this hour so the "end time" is still a valid time
if hour < 10 and hour > 0:
smallestCommonDiffSetup = (hour-0)//2
smallestCommonDiff = 0-smallestCommonDiffSetup
largestCommonDiff = 5 - hour
else:
if hour == 0 or hour == 12:
smallestCommonDiff, largestCommonDiff = 1,1
if hour != 10:
sumOfArthSQInHour = getSumOfSQInHour(hour, minutesLeft, smallestCommonDiff, largestCommonDiff)
else:
sumOfArthSQInHour = 0
return currentSumOfArthSQ + sumOfArthSQInHour
#pick a number for D between 0 and 10^9
#link to question1: https://accessally.com/careers/coding-assessment/
print('Input number of minutes past 12pm: ')
D = int(input())
additionalSum = 0
totalSumPossibleIn12Hrs = 31
if D >= 720:
additionalSum = (D//720)*totalSumPossibleIn12Hrs #the total arth sq in 24 are known, so find out how many 12hours fit into minutes given and multiply by the known sum to get additional count
D = D%720 #get the leftover minutes
#D must be less than or equal to 720 before entering here
print('the total number of arithmetic sequences are: ')
print(main(D) + additionalSum)
|
sentence = raw_input("What word should be encrypted? ")
digi = False
while digi == False:
shift = raw_input("And how many steps? ")
if int(shift):
digi = True
i = 0
while i < len(sentence):
step = ord(sentence[i]) + int(shift)
if step > ord('z'):
step -= 26
elif step < ord('a'):
step += 26
print "\b" + chr(step),
i += 1
print |
#!/usr/bin/env python
from sys import argv
import random, string
def make_chains(corpus, num):
"""Takes an input text as a string and returns a dictionary of
markov chains."""
new_corpus = ""
for char in corpus:
# leave out certain kinds of punctuation
if char in "_[]*": # NOT WORKING DELETE THIS or char == "--":
continue
# put everything else in the new_corpus string
else:
new_corpus += char
list_of_words = new_corpus.split()
d = {}
for i in range( (len(list_of_words) - num) ):
prefix = []
for j in range(num):
prefix.append(list_of_words[i + j])
prefix = tuple(prefix)
# prefix = (list_of_words[i], list_of_words[i+1], list_of_words[i+2])
suffix = list_of_words[i+num]
if prefix not in d:
d[prefix] = [suffix] # initializes the suffix as a list
else:
d[prefix].append(suffix)
return d
def make_text(chains, num):
"""Takes a dictionary of markov chains and returns random text
based off an original text."""
# create a list of chain's keys, then return one of the keys at random
random_prefix = random.choice(chains.keys())
# from the list of values for the chosen key, return one value at random
random_suffix = random.choice(chains[random_prefix])
# initialize an empty string for our random text string
markov_text = ""
# iterate over prefix's tuple and add each word to the random text string
for word in random_prefix:
markov_text += word + " "
# then add the suffix
markov_text += random_suffix + " "
# rename random_prefix and random_suffix so that we can call them
# in a the following for loop
prefix = random_prefix
suffix = random_suffix
for i in range(1000):
# create a new prefix from the last items in the most recent prefix and
# the most recent suffix
newprefix = []
for j in range(1, num):
newprefix.append(prefix[j])
newprefix.append(suffix)
prefix = tuple(newprefix)
# choose a random suffix from the new prefix's values
suffix = random.choice(chains[prefix])
# add it all to the random text string
markov_text += "%s " % (suffix)
return markov_text
def main():
script, filename, num = argv
num = int(num)
fin = open(filename)
input_text = fin.read()
fin.close()
chain_dict = make_chains(input_text, num)
random_text = make_text(chain_dict, num)
print random_text
if __name__ == "__main__":
main() |
#! /usr/bin/env python3
# project euler #28
def make_corner_seq(n):
"""sequence of length n of corner numbers"""
seq = [1]
step_size = 2
while len(seq) < n:
for i in range(4):
seq.append(seq[-1] + step_size)
step_size += 2
return seq
def main():
seq = make_corner_seq(2 * 1001 - 1)
print(sum(seq))
if __name__ == "__main__":
main()
|
import heapq
from heapq import heappush , heappop
class Node :
def __init___(self, val) :
self.data = val
self.next =None
self.bottom = None
# this is useful during comparing two nodes
def __lt__(self, other):
return (self.data < other.data )
class Solution :
def flatten(self,root):
#Your code here
if not root :
return root
temp = root
pq = []
#push all the elements into heap
while temp :
heappush(pq , temp)
temp = temp.next
heapq.heapify(pq)
# get the newhead
newhead = heappop(pq)
# assign a temp variable
temp = newhead
if newhead.bottom :
heappush(pq,newhead.bottom )
while pq :
min = heappop(pq)
# extract and add the min node
temp.bottom = min
temp = temp.bottom
# add the bottom node of min
if min.bottom :
heappush(pq, min.bottom)
return newhead |
'''
You are given a singly linked list node and an integer k. Swap the value of the k-th (0-indexed) node from the end with the k-th node from the beginning.
Constraints
1 ≤ n ≤ 100,000 where n is the number of nodes in node
0 ≤ k < n
example :
Input:
node = [1, 2, 3, 4, 5, 6]
k = 1
Output :
[1, 5, 3, 4, 2, 6]
'''
# class LLNode:
# def __init__(self, val, next=None):
# self.val = val
# self.next = next
class Solution:
def solve(self, node, k):
front = node
back = node
back_fast = node
count = 0
while back_fast :
if count < k :
front = front.next
count += 1
else :
prev = back
back = back.next
back_fast = back_fast.next
prev.val , front.val = front.val , prev.val
return node
|
#question :
'''
You are given a list of integers piles and an integer k.
piles[i] represents the number of bananas on pile i.
On each hour, you can choose any pile and eat r number of bananas in that pile.
If you pick a pile with fewer than r bananas, it still takes an hour to eat the pile.
Return the minimum r required such that you can eat all the bananas in
less than or equal to k hours.
'''
#approach :
'''
-> The idea is to use binary-search .. let's first find the searh-space of the r
-> Min speed needed is 1
-> Whereas max_speed is max(piles).. because if it spends max time on it
-> Now let's write a check function, and do a binary-search.
'''
class Solution:
# check function with speed r
def isPossible(self, piles , r, k) :
hours = 0
for i in piles :
hours += i//r
if i%r :
hours += 1
# no need to check , if it croses k
if hours>k :
return False
return hours <= k
def solve(self, piles, k):
# set the limits
left = 1
right = max(piles)
INF = 9999999
min_speed = INF
# binary-search:
while left <= right :
mid = (left + right)//2
if self.isPossible(piles, mid , k) :
min_speed = min(mid , min_speed)
right = mid -1
else :
left = mid + 1
return min_speed
|
'''
Idea :
This is a variation of CoinChange problem ,
-> there , we found minimum number of coins to make change
Strategy : (for uniqueWaysOptimised )
-> we can choose any number of coins of same value
but once we move we cannot choose that coin .
-> the first loop handles ,when we can choose only coin of value 3 .
-> second loop for 5 and so on .
'''
class Solution :
def uniqueWaysNaive(n, arr):
# arr -> coins denominations array
dp = [[0 for i in range (len(arr)+1)] for j in range(n+1)]
#base cases
# Target_amount ==0 -> no.of ways = 1
# coin denominations ==0 -> no .of ways = 0
for i in range(len(arr) + 1):
for j in range (n+1) :
if j ==0 :
dp[i][j] = 1
elif i ==0 :
dp[i][j] = 0
elif arr[i] > j :
dp[i-1][j]
else :
dp[i][j] = dp[i-1][j] + dp[i-1][j-arr[i-1]]
return dp[len(arr)][n]
def uniqueWaysOptimised(n) :
dp = [0]*(n+1)
#base case
dp[0] = 1
# when we have only 3 value coins
for i in range (3, n+1) :
dp[i] += dp[i-3]
# when we have 3 qnd 5 value coins
for i in range(5, n+1) :
dp[i] = dp[i-5]
# when we have 3,5,10 coins .
for i in range(10, n+1) :
dp[i] = dp[i-10]
return dp[n] |
#question
'''
-> Given a matrix .. return the 90 deg clockwise rotation of the matrix
'''
#approach :
'''
-> The most simple approach is that 1)Reverse the matrix row-wise
-> 2) Transpose the matrix .
-> So simple right ;)
'''
from transpose import Solution
a = Solution()
def Rotate(matrix):
matrix = matrix[::-1]
a = Solution()
return a.transpose(matrix)
if __name__ == "__main__" :
a = [[1,2,3],
[4,5,6],
[7,8,9]]
print(Rotate(a)) |
'''
Algorithm :
The algorithm is pretty simple , It is called vertical scanning . ;)
'''
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
i = 0
s = strs[0]
lcp = ""
while i < len(strs[0]):
for j in range(1, len(strs)):
k = strs[j]
if i >= len(k) :
return lcp
elif k[i] != s[i] :
return lcp
else:
pass
lcp += s[i]
i += 1
return lcp |
'''
Min number of knight steps needed to reach the target position
'''
#aPPROACH :
'''
Same as flood fill algorithm , we inserted a null to keep track of the levels
count
'''
from collections import deque
class Solution:
# validates , whether a row and col valid or not
def validator(self, row , col , N ) :
if row >N-1 or row <0 or col >N-1 or col < 0 :
return False
return True
#Function to find out minimum steps Knight needs to reach target position.
def minStepToReachTarget(self, knightPos, targetPos, N):
dr = [2, 2, -2 , -2 , 1 , 1, -1, -1 ]
dc = [1 ,-1, 1, -1 , 2, -2, 2 ,-2 ]
visited =[[False for i in range(N+1)] for j in range(N+1)]
visited[knightPos[0]][knightPos[1]] = True
count = 1
null = (-1 , -1 )
q = deque()
q.append ((knightPos[0], knightPos[1]))
q.append(null)
while q :
(row , col ) = q.popleft()
if row ==-1 and col ==-1 :
count += 1
q.append(null)
continue
# we will take all the 8 steps possible for knight.
for i in range(8) :
row += dr[i]
col += dc[i]
if self.validator(row, col , N) and not visited[row][col] :
if row == targetPos[0] and col == targetPos[1] :
return count
q.append((row, col))
visited[row][col] = True
row -= dr[i]
col -= dc[i]
|
'''
Idea : three length palindromes must contains the first and last character .
-> So ,let's search for the characters from the front and from the back .
-> if front < back , then
-> number of palindromes are equal to numbber of unique letters between the
front and back indices .
'''
class Solution(object):
def countPalindromicSubsequence(self, s):
"""
:type s: str
:rtype: int
"""
n = len(s)
count = 0
l = set(s)
for i in l :
front = s.find(i)
back = s.rfind(i)
if front < back :
count += len(set(s[front+1 : back]))
return count
|
from collections import deque
class Solution:
# USING BFS STRATEGY :
def floodFill(self, image, sr: int, sc: int, newColor: int):
oldColor = image[sr][sc]
q = deque()
q.append((sr, sc))
while q :
(row ,col) = q.popleft()
if row <0 or row >= len(image) or col < 0 or col >= len(image[0]):
continue
if image[row][col] == newColor :
continue
if image[row][col] == oldColor :
image[row][col] = newColor
q.append((row-1 , col))
q.append((row+ 1, col))
q.append((row, col-1))
q.append((row , col +1 ))
return image
# USING DFS STRATEGY :
def floodFilldfs(self, image, sr, sc, newColor):
R, C = len(image), len(image[0])
color = image[sr][sc]
if color == newColor: return image
def dfs(r, c):
if image[r][c] == color:
image[r][c] = newColor
if r >= 1: dfs(r-1, c)
if r+1 < R: dfs(r+1, c)
if c >= 1: dfs(r, c-1)
if c+1 < C: dfs(r, c+1)
dfs(sr, sc)
return image |
#approach :
'''
-> k ... p*(p+1)//2
-> What is the min time --> k
-> What is the max time --> 8*k
-> these two are the limits for our search space ..
-> Suppose we want the mid value of both these limits as our answer
-> we have to make sure that no chef can get more time than this .
-> Allocate time to the first chef ..untill time is less than mid
-> if it had cross the mid .. start giving time to second chef
-> Finally , if the parata count >m return True
-> Else .. False
'''
class Solution:
#Function to find minimum number of pages.
def findPages(self,arr,p):
# function to check the possibility of division.
def allocationpossible(barrier ) :
paratas = 0
for i in range(len(arr)):
c = 0
time = mid
perparota = arr[i]
while time :
time -= perparota
c += 1
paratas += c
if paratas >= p :
break
if paratas >= p :
return True
return False
#defining search-space
k = p*(p+1)//2
left, right = k , 8*k
res = -1
#binary search ..
while left <= right :
mid = (left + right)>>1
#if allocation possible.. check with
# lower limits.
if allocationpossible(mid) :
res = mid
right = mid -1
else :
left = mid +1
return res |
'''
Given the head of a singly linked list and two integers left and right where left <= right,
reverse the nodes of the list from position left to position right, and return the reversed list.
'''
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseBetween(self, head: ListNode, left: int, right: int) -> ListNode:
if left == right :
return head
count = 1
temp , front = head , None
while count < left :
front = temp
temp = temp.next
count += 1
current , prev = temp , None
while count <= right :
next = current.next
current.next = prev
prev = current
current = next
count += 1
temp.next = current
if front:
front.next = prev
else :
return prev
return head
|
'''
k th largest / smallest element in the given array ..
Idea :: Selection-Sort
'''
class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
for i in range (k ) :
largest = i
for j in range (i+1, len(nums)) :
if nums[j] > nums[largest] :
largest = j
nums[largest] , nums[i] = nums[i] , nums[largest]
return nums[k-1]
|
#qUESTION :
'''
Given a binary matrix mat of size n * m, find out the maximum size square sub-matrix with all 1s.
'''
#iDEA :
'''
Let's think of the square matrix ending with (i,j)
-> Think , what can we derive abt (i,j) from (i-1, j) , (i,j-1) ,(i-1 , j-1 )
-> The answer is if the mat(i, j) is 1 , then we can make a square matrix
of size 1 + min(
( i-1 , j ),
( i , j-1 ),
( i-1 , j-1)
)
-> But How ? ... imagine we want to build a 3x3 matrix ,
0 1 1 1 0 1 1 1
1 1 1 1 ---------> 1 1 2 2
0 1 1 1 0 1 2 3
* the diagonal confirms that , we can form (n-1)x(n-1) matrix
* the top value confirms the right part (n-1)x(n-1)
* the left part confirms the bottom part (n-1)x(n-1)
* now we have to confirm the n*n by checking the (i,j) ;)
'''
class Solution:
def maxSquare(self, n, m, mat):
# code here
dp = [[0 for i in range(m)] for j in range(n)]
max_val = 0
#base cases
# if there is only single row or single coloumn ,
# we can just copy the same values of the matrix .
for i in range(n) :
dp[i][0] = mat[i][0]
max_val = max(max_val , dp[i][0])
for j in range(m) :
dp[0][j] = mat[0][j]
max_val = max(max_val , dp[0][j] )
for i in range(1,n) :
for j in range(1,m) :
if mat[i][j] :
dp[i][j] = 1 + min(dp[i-1][j-1] , dp[i][j-1] , dp[i-1][j])
else :
dp[i][j] = 0
max_val = max(max_val , dp[i][j])
return max_val
|
''' Node for linked list:
class Node:
def __init__(self, data):
self.data = data
self.next = None
'''
class Node :
def __init__(self, data ) :
self.data = data
self.next = None
class Solution:
#Function to add two numbers represented by linked list.
def addTwoLists(self, first, second):
# code here
# return head of sum list
def number (head ) :
temp = head
count = 0
while temp :
count *= 10
count += temp.data
temp = temp.next
return count
def reverse (head ) :
prev = None
curr = head
next = head.next
while curr :
next = curr.next
curr.next = prev
prev = curr
curr = next
return prev
num = number(first) + number(second)
newll = Node(num%10)
num = num//10
temp = newll
while num :
n = num%10
num = num//10
nextNode = Node(n)
temp.next = nextNode
temp = nextNode
return reverse(newll) |
'''
Idea :
the key takeaway from this question is that , if a string(s1) is rotation of
other(s2) , then the s1 must bbe substring of concatenation of s1 with itself .
We maintain a set to hold the values of concatenated strings ,and returns
it's length .
'''
class Solution:
def solve(self, words):
s = set()
for i in words :
found = 0
for j in s :
if i in j and len(i) == len(j)//2 :
found = 1
if not found :
s.add(i*2)
return len(s) |
'''
Algorithm :
So , the longest palindrome , will start in the middle . So , the key idea is to
to find the longest palindrome , with ith index as center . and to cover the even
length strings we , run the expand fundtion with ith index and i+1 th index as center
Note :
This approach is better than Dynamic programmming approach because , we don't use
extra space here .
'''
class Solution:
def expand (self, s, left, right ) :
n = len(s)
while left >= 0 and right < n and s[left] == s[right] :
left -= 1
right += 1
return s[left+1 : right ]
def longestPalin(self, S):
# code here
if S == "" :
return 0
longest = ""
for i in range(len(S)) :
p1 =self.expand(S, i-1 , i+1 )
if len(p1) > len(longest) :
longest = p1
p2 = self.expand(S, i , i +1 )
if len(p2) > len(longest):
longest = p2
return longest |
#question :
'''
Find the largest rectangular area possible in a given histogram where
the largest rectangle can be made of a number of contiguous bars.
For simpliFind the largest rectangular area possible in a given histogram
where the largest rectangle can be made of a number of contiguous bars.
For simplicity, assume that all bars have the same width and the width is
1 unit.city, assume that all bars have the same width and the width is 1 unit.
'''
#approach :
'''
-> Think .. what the max area can be find with the current element as height
-> What will be it's width .. ?
-> We need to find the immeddiate smaller element in it's right and left space
-> Now .. we have our height and width .. find the max_area ... by height as
the other bars in the histogram..
'''
class Solution:
#Function to find largest rectangular area possible in a given histogram.
def rightSmaller(self,arr,n):
#code here
stack = []
res = [0 for i in range(n)]
for i in reversed(range(n)):
while stack and arr[stack[-1]] >= arr[i]:
stack.pop()
if not stack :
res[i] = n-1
else :
res[i] = stack[-1] -1
stack.append(i)
return res
def leftSmaller(self, arr,n):
stack = []
res = [0 for i in range(n)]
for i in range(n):
while stack and arr[stack[-1]] >= arr[i] :
stack.pop()
if not stack :
res[i] = 0
else :
index = stack[-1]
res[i] = index + 1
stack.append(i)
return res
def getMaxArea(self,histogram):
#code here
l = self.leftSmaller(histogram , len(histogram))
r = self.rightSmaller(histogram , len(histogram))
max_area = -99999
for i in range(len(histogram)):
max_area = max(histogram[i] *(r[i] - l[i] + 1 ) , max_area )
return max_area |
'''
Algorithm :
It is used in kmp algorithm , for pattern matching . We maintain two pointers
l = 0 , i = 1
we traverse through the array :
if we found a match :
lps[i] = l+ 1
increment l and i
else :
if we already found some portion is same , i.e ( l != 0 ) :
move it to the previously matched portion
(matched portion length will be in lps[l -1 ])
else :
lps[i] = 0
increment i
'''
class Solution:
def lps(self, s):
# code here
lps = [0]*len(s)
i , l = 1, 0
while i < len(s) :
if s[i] == s[l] :
lps[i] = l + 1
l += 1
i += 1
else :
if l != 0 :
l = lps[l-1]
else :
lps[i] = 0
i += 1
return lps
|
#Boyer–Moore majority vote algorithm :
'''
-> MAJORITY-ELEMENT : element which occurs.. more than n//2 times in the array.
-> MAINTAIN A ELEMENT m AND ITERATOR i
-> for i in the nums.length :
# if i == 0 :
m = nums[i]
i = 1
elif nums[i] == m :
i += 1
else :
i -= 1
-> FINALLY ,WE WILL BE HAVING MAJORITY ELEMENT IN m .
'''
# EXTENDING IT TO N//3 (MAJORITY ELEMENT ) :
# --> Similarly we can extend it to any n//k maority element
class Solution:
def majorityElement(self, nums: list[int]) -> list[int]:
# a list of majority elements
majority = []
# threshold for majority validation and verification
threshold = len(nums) // 3
# Record for possible majority candidates, at most two majority elements is allowed by math-proof.
candidate = [0, 0]
# Voting for majority candidates
voting = [0, 0]
## Step_#1:
# Find possible majority candidates
for number in nums:
if number == candidate[0]:
# up vote to first candidate
voting[0] += 1
elif number == candidate[1]:
# up vote to second candidate
voting[1] += 1
elif not voting[0]:
# set first candidate
candidate[0] = number
voting[0] = 1
elif not voting[1]:
# set second candidate
candidate[1] = number
voting[1] = 1
else:
# down vote if mis-match
voting[0] -= 1
voting[1] -= 1
## Step_#2:
# Validation:
voting = [0, 0]
for number in nums:
if number == candidate[0]:
# update up vote for first candidate
voting[0] += 1
elif number == candidate[1]:
# update up vote for second candidate
voting[1] += 1
for i, vote in enumerate(voting):
# Verify majority by threshold
if vote > threshold:
majority.append( candidate[i] )
return majority
|
from collections import defaultdict , deque
class Graph :
def __init__(self, vertices):
self.v = vertices
self.adj = {i:[] for i in range(vertices)}
def addEdge (self, word1 , word2 ):
n = len(word1)
m = len(word2)
i = 0
while i < n and i < m :
a = word1[i]
b = word2[i]
if a == b :
i += 1
continue
if a != b :
k1 = ord(a) - ord('a')
k2 = ord(b) - ord('a')
if k2 not in self.adj[k1] :
self.adj[k1].append(k2)
break
def TopologicalSort(self, visited , finished , src , time ):
visited[src] = True
time += 1
for v in self.adj[src] :
if not visited[v] :
time = self.TopologicalSort(visited , finished , v , time )
finished[time] = src
time += 1
return time
def findOrder(dict, N, k):
g = Graph(k)
for i in range(N) :
for j in range(i+1, N) :
g.addEdge(dict[i] , dict[j])
visited =[False]*(k)
time = 0
finished = [-1]*(2*k)
for i in range(k) :
if not visited[i] :
time = g.TopologicalSort(visited , finished , i , time )
res = ""
for i in reversed(range(2*k)) :
if finished[i] != -1 :
res += chr(finished[i] + ord('a'))
return res
N = 5
K = 4
dict = ["baa","abcd","abca","cab","cad"]
print(findOrder(dict , N , K )) |
#! /usr/bin/python
#
# This is support material for the course "Learning from Data" on edX.org
# https://www.edx.org/course/caltechx/cs1156x/learning-data/1120
#
# The software is intented for course usage, no guarantee whatsoever
# Date: Sep 30, 2013
#
# Template for a LIONsolver parametric table script.
#
# Generates a table based on input parameters taken from another table or from user input
#
# Syntax:
# When called without command line arguments:
# number_of_inputs
# name_of_input_1 default_value_of_input_1
# ...
# name_of_input_n default_value_of_input_n
# Otherwise, the program is invoked with the following syntax:
# script_name.py input_1 ... input_n table_row_number output_file.csv
# where table_row_number is the row from which the input values are taken (assume it to be 0 if not needed)
#
# To customize, modify the output message with no arguments given and insert task-specific code
# to insert lines (using tmp_csv.writerow) in the output table.
import sys
import os
import random
import numpy as np
from numpy import arange, array, ones, linalg
#############################################################################
#
# Task-specific code goes here.
#
# The following function is a stub for the perceptron training function required in Exercise1-7 and following.
# It currently generates random results.
# You should replace it with your implementation of the
# perceptron algorithm (we cannot do it otherwise we solve the homework for you :)
# This functon takes the coordinates of the two points and the number of training samples to be considered.
# It returns the number of iterations needed to converge and the disagreement with the original function.
def YatX(x, m, b=0):
return m * x + b
def signF(xtotest, m, b):
val = m * xtotest + b
if val > 0:
return 1
elif val < 0:
return -1
else:
return 0
def targetFunction(x1,y1,x2,y2,x3,y3):
u = (x2-x1)*(y3-y1) - (y2-y1)*(x3-x1)
if u >= 0:
return 1
elif u < 0:
return -1
def plaG(w, x, y):
val = w[0] * 1 + w[1] * x + w[2] * y
if val > 0:
return 1
elif val < 0:
return -1
else:
return 0
def gen_points(num_data_points):
points = np.random.uniform(-1, 1, (num_data_points, 2))
x0 = np.ones((num_data_points, 1)) #add the artificial coordinate x0 = 1
points = np.append(x0, points, axis=1)
return points
def perceptron_training(x1, y1, x2, y2, training_size):
m = (y2 - y1) / (x2 - x1)
#y=mx +b; b = y-mx
b = y1 - m * x1
datapoints = gen_points(training_size)
ydatapoints = []
for datapoint in datapoints:
yn = targetFunction(x1, y1, x2, y2, datapoint[1], datapoint[2])
ydatapoints.append(yn)
ydatapoints = np.asarray(ydatapoints)
w = linalg.lstsq(datapoints, ydatapoints)[0]
#Lets find Ein
numwrong = 0
for datapoint in datapoints:
yn = targetFunction(x1, y1, x2, y2, datapoint[1], datapoint[2])
gyn = plaG(w, datapoint[1], datapoint[2])
if yn != gyn:
numwrong += 1
ein = float(numwrong) / training_size
#lets find Eout
numverify = 1000
verifypoints = []
numwrong = 0
for num in range(1, numverify + 1):
verifypoints.append((random.uniform(-1, 1), random.uniform(-1, 1)))
datapoint = verifypoints[num - 1]
yn = targetFunction(x1, y1, x2, y2, datapoint[0], datapoint[1])
gyn = plaG(w, datapoint[0], datapoint[1])
if yn != gyn:
numwrong += 1
eout = float(numwrong) / numverify
allgood = 0
numberIterations = 0
while allgood != 1:
random.shuffle(datapoints)
allgood = 1
for datapoint in datapoints:
yn = targetFunction(x1, y1, x2, y2, datapoint[1], datapoint[2])
gyn = plaG(w, datapoint[1], datapoint[2])
#print ("iteration %s: yn = %s , Gyn = %s") % (numberIterations, yn, gyn)
if (yn != gyn):
numberIterations += 1
allgood = 0
w[0] += yn * 1
w[1] += yn * datapoint[1]
w[2] += yn * datapoint[2]
break
#Ein Section
#return (int (random.gauss(100, 10)), random.random() / training_size)
return ein, eout, numberIterations
tests = 1000
points = 10
# Repeat the experiment n times (tests parameter) and store the result of each experiment in one line of the output table
totalEin = 0
totalEout = 0
totalNumIterations = 0
for t in range(1, tests + 1):
x1 = random.uniform(-1, 1)
y1 = random.uniform(-1, 1)
x2 = random.uniform(-1, 1)
y2 = random.uniform(-1, 1)
Ein, Eout, NumIterations = perceptron_training(x1, y1, x2, y2, points)
totalEin += Ein
totalEout += Eout
totalNumIterations += NumIterations
print "Average Ein: %s Average Eout: %s Average Iterations: %s" % ((totalEin/tests), (totalEout/tests), (totalNumIterations*1.0/tests))
|
# -*- coding:utf-8 -*-
class Solution:
def hasPath(self, matrix, rows, cols, path):
# write code here
if len(matrix) < 1 or rows <= 0 or cols <= 0 or not path: return False
# 对于python来说,set、list、dict都是可变对象,不能直接在上边操作防止重复遍历。
# 但如果输入是string是不可变对象,可以直接在上面操作。
for i in range(rows):
for j in range(cols):
if path[0] == matrix[i*cols+j]:
if self.find(list(matrix), rows, cols, path[1:], i, j):
return True
return False
def find(self, matrix, rows, cols, path, i, j):
if not path: return True
matrix[i*cols+j] ='0'
if j + 1 < cols and matrix[i*cols+j+ 1] == path[0]:
return self.find(matrix, rows, cols, path[1:], i, j + 1)
elif j - 1 >= 0 and matrix[i*cols+j- 1] == path[0]:
return self.find(matrix, rows, cols, path[1:], i, j - 1)
elif i + 1 < rows and matrix[(i+1)*cols+j] == path[0]:
return self.find(matrix, rows, cols, path[1:], i + 1, j)
elif i - 1 >= 0 and matrix[(i-1)*cols+j] == path[0]:
return self.find(matrix, rows, cols, path[1:], i - 1, j)
else:
return False
|
'''
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
'''
# -*- coding:utf-8 -*-
class Solution:
def MoreThanHalfNum_Solution(self, numbers):
if not numbers: return None
key, num = numbers[0], 1
for i in numbers[1:]:
if i == key:
num += 1
else:
num -= 1
if num == 0:
key = i
num = 1
num = 0
for i in numbers:
if i == key:
num += 1
return key if num * 2 > len(numbers) else 0
|
'''
给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{2,3,4,2,6,2,5,1}及滑动窗口的大小3,那么一共存在6个滑动窗口,他们的最大值分别为{4,4,6,6,6,5}; 针对数组{2,3,4,2,6,2,5,1}的滑动窗口有以下6个: {[2,3,4],2,6,2,5,1}, {2,[3,4,2],6,2,5,1}, {2,3,[4,2,6],2,5,1}, {2,3,4,[2,6,2],5,1}, {2,3,4,2,[6,2,5],1}, {2,3,4,2,6,[2,5,1]}。
'''
# -*- coding:utf-8 -*-
class Solution:
def maxInWindows(self, num, size):
# Approach one O(n) ~ O(kn)
# length = len(nums)
# if k > length or k <= 0: return []
# l , r = 0 , k-1
# res = [max(nums[l:r+1])]
# r += 1
# while r < length:
# if nums[r] >= res[-1]:
# res.append(nums[r])
# l += 1
# r += 1
# elif nums[l] == res[-1]:
# l += 1
# res.append(max(nums[l:r+1]))
# r += 1
# else:
# res.append(res[-1])
# l += 1
# r += 1
# return res
# Approch two 一个双向队列 O(n) , O(1)
res , tmp = [] , []
if size > len(num) or size <= 0 : return []
for i in range(len(num)):
if len(tmp) > 0 and tmp[0] <= i - size:
tmp.pop(0)
while len(tmp) > 0 and num[tmp[-1]] <= num[i]:
tmp.pop()
tmp.append(i)
if i >= size-1:
res.append(num[tmp[0]])
return res
|
# -*- coding:utf-8 -*-
class Solution:
def movingCount(self, threshold, rows, cols):
# write code here
if threshold < 0 or rows <= 0 or cols <= 0: return 0
visited = [[1 for _ in range(cols)] for _ in range(rows)]
return self.count(threshold, cols, rows, 0 ,0 ,visited)
def count(self,threshold, cols, rows, i , j ,visited):
if i >= rows or j >= cols or visited[i][j] == 0 or threshold < sum(map(int,str(i)+str(j))): return 0
visited[i][j] = 0
return 1 + self.count(threshold, cols, rows, i + 1 , j ,visited) + self.count(threshold, cols, rows, i , j + 1,visited)
|
'''
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
'''
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回构造的TreeNode根节点
def reConstructBinaryTree(self, pre, tin):
# write code here
if len(pre) == 0 or len(tin) == 0: return None
if len(pre) == 1 or len(tin) == 1: return TreeNode(pre[0])
root = TreeNode(pre[0])
for i, n in enumerate(tin):
if n == root.val:
root.left = self.reConstructBinaryTree(pre[1:i + 1], tin[:i])
root.right = self.reConstructBinaryTree(pre[i + 1:], tin[i + 1:])
return root
|
'''
汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务,就是用字符串模拟这个指令的运算结果。对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。是不是很简单?OK,搞定它!
'''
# -*- coding:utf-8 -*-
class Solution:
def LeftRotateString(self, s, n):
# write code here
return ''.join(list(s)[n:] + list(s)[:n])
|
from cs50 import get_int
h = 0
while not int(h) in range(1,9):
h = get_int("Height:")
j = 0
for i in range (h):
h -= 1
j += 1
print(" " * h + "#" * j + " " + "#" * j) |
from tkinter import *
valor = []
i = 0
control = 0
valor_real = [""]
resultado = 0
control2 = 0
operacao = []
app_calculadoura = Tk()
app_calculadoura.geometry("400x500+500+50")
app_calculadoura.title("Calculadoura Gráfica")
calculado = Frame(app_calculadoura,width = 400,height = 155,bd = 1,bg = "grey")
calculado.pack(side = TOP)
calculado1 = Label(calculado,width = 17,height = 3,bd = 0,bg= "grey")
calculado1.place(x=0,y=0)
def mostra_numero(button_id):
global i
global control
global resultado
global control2
global operacao
if button_id == 0:
valor.append("0")
calculado1["font"] = 'ariel',30,'bold'
elif button_id == 1:
valor.append("1")
calculado1["font"] = 'ariel',30,'bold'
elif button_id == 2:
valor.append("2")
calculado1["font"] = 'ariel',30,'bold'
elif button_id == 3:
valor.append("3")
calculado1["font"] = 'ariel',30,'bold'
elif button_id == 4:
valor.append("4")
calculado1["font"] = 'ariel',30,'bold'
elif button_id == 5:
valor.append("5")
calculado1["font"] = 'ariel',30,'bold'
elif button_id == 6:
valor.append("6")
calculado1["font"] = 'ariel',30,'bold'
elif button_id == 7:
valor.append("7")
calculado1["font"] = 'ariel',30,'bold'
elif button_id == 8:
valor.append("8")
calculado1["font"] = 'ariel',30,'bold'
elif button_id == 9:
valor.append("9")
calculado1["font"] = 'ariel',30,'bold'
elif button_id == "+":
valor.append("+")
calculado1["font"] = 'ariel',30,'bold'
elif button_id == "-":
valor.append("-")
calculado1["font"] = 'ariel',30,'bold'
elif button_id == "X":
valor.append("x")
calculado1["font"] = 'ariel',30,'bold'
elif button_id == "/":
valor.append("/")
calculado1["font"] = 'ariel',30,'bold'
elif button_id == ".":
valor.append(".")
calculado1["font"] = 'ariel',30,'bold'
elif button_id == "%":
valor.append("%")
control = 1
elif button_id == "igual":
control = 1
if control != 1:
calculado1["text"] = calculado1["text"] + valor[i]
i += 1
else:
for junt in range (len(valor)):
if valor[junt] != "+" and valor[junt] != "-" and valor[junt] != "x" and valor[junt] != "/" and valor[junt] != "%" :
valor_real[control2] = valor_real[control2] + valor[junt]
else:
if valor[junt] == "+":
operacao.append("+")
elif valor[junt] == "-":
operacao.append("-")
elif valor[junt] == "x":
operacao.append("x")
elif valor[junt] == "/":
operacao.append("/")
else:
operacao.append("%")
control2 += 1
valor_real.append("")
for I in valor_real:
for I2 in operacao:
if I2 == "+":
resultado = resultado + float(I)
break
elif I2 == "-":
if resultado == 0:
resultado = float(I)
break
else:
resultado = resultado - float(I)
break
elif I2 == "x":
if resultado == 0:
resultado = 1
resultado = resultado*float(I)
break
elif I2 == "/":
if resultado == 0:
resultado = float(I)
break
else:
resultado = resultado/float(I)
break
elif I2 == "%":
del valor_real[-1]
resultado = float(I)/100
break
calculado1["text"] = resultado
def bt_apaga(buttun_ok2):
global i
global control
global resultado
global control2
global operacao
if buttun_ok2 == "C":
del valor[:]
del valor_real[:]
valor_real.append("")
del operacao[:]
control = 0
resultado = 0
control2 = 0
i = 0
calculado1["text"] = ""
if buttun_ok2 == "<-":
i = i-1
del valor[-1]
calculado1["text"] = calculado1["text"][:-1]
bt_converte = Button(app_calculadoura,width = 8,height = 3,font =('ariel',14,'bold') ,text = "+/-", command = lambda: mostra_numero("+/-"))
bt_converte.place(x=0,y=430)
bt_0 = Button(app_calculadoura,width = 8,height = 3 ,font =('ariel',14,'bold'),text = "0", command = lambda: mostra_numero(0))
bt_0.place(x=101,y=430)
bt_ponto = Button(app_calculadoura,width = 8,height = 3 ,font =('ariel',14,'bold'),text = ".", command = lambda: mostra_numero("."))
bt_ponto.place(x=205,y=430)
bt_igual = Button(app_calculadoura,width = 7,height = 3 ,font =('ariel',14,'bold'),text = "=", command = lambda: mostra_numero("igual"))
bt_igual.place(x=308,y=430)
bt_1 = Button(app_calculadoura,width = 8,height =3 ,font =('ariel',14,'bold'),text = "1", command = lambda: mostra_numero(1))
bt_1.place(x=0,y=355)
bt_2 = Button(app_calculadoura,width = 8,height = 3 ,font =('ariel',14,'bold'),text = "2", command = lambda: mostra_numero(2))
bt_2.place(x=101,y=355)
bt_3 = Button(app_calculadoura,width = 8,height = 3 ,font =('ariel',14,'bold'),text = "3", command = lambda: mostra_numero(3))
bt_3.place(x=205,y=355)
bt_mais = Button(app_calculadoura,width = 7,height = 3 ,font =('ariel',14,'bold'),text = "+", command = lambda: mostra_numero("+"))
bt_mais.place(x=308,y=355)
bt_4 = Button(app_calculadoura,width = 8,height = 3 ,font =('ariel',14,'bold'),text = "4", command = lambda: mostra_numero(4))
bt_4.place(x=0,y=290)
bt_5 = Button(app_calculadoura,width = 8,height = 3 ,font =('ariel',14,'bold'),text = "5", command = lambda: mostra_numero(5))
bt_5.place(x=101,y=290)
bt_6 = Button(app_calculadoura,width = 8,height = 3 ,font =('ariel',14,'bold'),text = "6", command = lambda: mostra_numero(6))
bt_6.place(x=205,y=290)
bt_menos = Button(app_calculadoura,width = 7,height = 3 ,font =('ariel',14,'bold'),text = "-", command = lambda: mostra_numero("-"))
bt_menos.place(x=308,y=290)
bt_7 = Button(app_calculadoura,width = 8,height = 3 ,font =('ariel',14,'bold'),text = "7", command = lambda: mostra_numero(7))
bt_7.place(x=0,y=225)
bt_8 = Button(app_calculadoura,width = 8,height = 3 ,font =('ariel',14,'bold'),text = "8", command = lambda: mostra_numero(8))
bt_8.place(x=101,y=225)
bt_9 = Button(app_calculadoura,width = 8,height = 3 ,font =('ariel',14,'bold'),text = "9", command = lambda: mostra_numero(9))
bt_9.place(x=205,y=225)
bt_mult = Button(app_calculadoura,width = 7,height = 3 ,font =('ariel',14,'bold'),text = "X", command = lambda: mostra_numero("X"))
bt_mult.place(x=308,y=225)
bt_limpar_tudo = Button(app_calculadoura,width = 8,height = 3 ,font =('ariel',14,'bold'),text = "C", command = lambda: bt_apaga("C"))
bt_limpar_tudo.place(x=0,y=155)
bt_limpar = Button(app_calculadoura,width = 8,height = 3 ,font =('ariel',14,'bold'),text = "<-", command = lambda: bt_apaga("<-"))
bt_limpar.place(x=101,y=155)
bt_porcent = Button(app_calculadoura,width = 8,height = 3 ,font =('ariel',14,'bold'),text = "%", command = lambda: mostra_numero("%"))
bt_porcent.place(x=205,y=155)
bt_div = Button(app_calculadoura,width = 7,height = 3 ,font =('ariel',14,'bold'),text = "/", command = lambda: mostra_numero("/"))
bt_div.place(x=308,y=155)
app_calculadoura.mainloop()
|
print('Body-Mass-Index Calculator')
weight = int(input('Please enter your weight in kgs:'))
height = float(input('Please enter your height in m:'))
bmi = weight / height ** 2
print("Your BMI value is:", bmi) |
name = str(input("Enter name:"))
print("(H)ello")
print("(G)oodbye")
print("(Q)uit" )
choice = input("")
#import sys
while True:
if choice == 'Q' or choice == 'q':
print("Finished")
break
#MENU
elif choice == 'H' or choice == 'h':
print("Hello",name,"\n" )
print("(H)ello")
print("(G)oodbye")
print("(Q)uit\n" )
choice=input('\n ')
elif choice == 'G' or choice == 'g':
print("Goodbye", name)
print("(H)ello")
print("(G)oodbye")
print("(Q)uit\n" )
choice=input('\n ')
else:
print("Invalid Option")
print("(H)ello")
print("(G)oodbye")
print("(Q)uit\n" )
choice=input('\n ')
continue |
"""
Makes a list of random numbers of size n
random numbers are of range [0, n*2)
The program will output a file where the first line is the size of the list and
the next n lines will contain ranodm numbers.
run program with following format --
python3 GenList.py [size] [output_file_name]
"""
if __name__ == "__main__":
import random
import sys
if len(sys.argv) == 3:
try:
size = int(sys.argv[1])
except:
print("Size must be an integer")
sys.exit(1)
output = sys.argv[2]
with open(output, 'w') as file_out:
file_out.write(str(size) + "\n")
for _ in range(size):
file_out.write(str(random.randrange(size * 2)) + "\n")
file_out.close()
else:
print("Must specify file and size")
print("Use format")
print(" python3 GenList.py [size] [output_file_name]")
|
import struct
from pathlib import Path
def generate_filename(filename):
''' pass as argument the filename relative to the user home dir '''
home_path = Path.home()
filename_path = home_path / filename
return filename_path
def decode_bytes_from_file(file, size, output_list, d=False):
# TODO fare attenzione all'allineamento e dell'ordine in cui vengono letti i byte
bytes_to_float_parser = struct.Struct("f")
for i in range(0, size):
read_bytes = file.read(4)
if d:
print(read_bytes)
if len(read_bytes) < 4:
print("errore gravissimissimo ahahhaha")
print("l'indice è {i} mentre la dimesione è {d}".format(i=i, d=size))
# return the floating point representation
b = bytes_to_float_parser.unpack(read_bytes)
output_list.append(b[0])
|
# CCC Junior 2014 Problem 3
# Double Dice
def reduce_total(a_total, d_total, r):
a, d = r.split()
try:
a = int(a)
d = int(d)
except:
TypeError("not valid rolls")
if a < d:
a_total = a_total - d
return a_total, d_total
elif a > d:
d_total = d_total - a
return a_total, d_total
else:
return a_total, d_total
def main():
a_total = 100
d_total = 100
num_games = raw_input()
try:
num_games = int(num_games)
except:
TypeError("please enter an integer.")
rolls = ""
if num_games > 0:
for i in range(num_games):
rolls = raw_input()
a_total, d_total = reduce_total(a_total, d_total, rolls)
print a_total
print d_total
main() |
# CCC Senior 2013 Problem 1
# Given a year, find next year with distinct digits
def is_unique(year):
chars = []
for k in year:
if k not in chars:
chars.append(k)
else:
return False
if len(chars) == len(year):
return True
def increment_year(year):
# Create a marking array to indicate which of 10 digits are taken
nums = [False] * 10
done = False
# Iterate through the year's digits and mark them in nums
for i in range(0,len(year)):
print "year[%i] = " %i, year[i], "year = ", year
if nums[int(year[i])] == False:
nums[int(year[i])] = True
# Digit was taken, take the next available digit, and reset all succeeding digits
else:
k = int(year[i])
# If k = 9, set digit to zero, update preceding digit, and rerun function
if k == 9:
k = 0
preceding = year[0:i]
if preceding == "":
preceding = "1"
year = preceding + year # adds extra unit length of 1 when increasing digit length (i.e. 999 to 1000)
return year, done
else:
preceding = str(int(preceding) + 1)
print "check 1"
year = preceding + str(k) + str(0) * (len(year) - (i + 1)) # reset
increment_year(year)
while nums[k] == True:
k = k + 1
if k < len(year):
print "check 2"
year = year[0:i] + str(k) + str(0) * (len(year) - (i + 1)) # reset
else:
print "check 3"
year = year[0:i] + str(k)
nums[k] = True
done = is_unique(year)
return year, done
def main():
current_year = raw_input()
try:
int(current_year)
except:
TypeError("Please enter an integer value")
year = current_year
if int(current_year) >= 0 and int(current_year) <= 10000:
year, done = increment_year(year)
while done != True:
year, done = increment_year(year)
else:
print "Please enter a year greater than 0 and less than 10000 inclusively."
print year
main() |
### 단방향 연결리스트 ###
# 노드 클래스
class _Node:
def __init__(self, element=None, next=None):
self._element = element # 노드에 저장되는 element 값
self._next = next # 다음 노드로의 링크 (초기값은 None)
def __str__(self):
return str(self._element) # 출력 문자열 (print(node)에서 사용)
# 클래스 선언
class SinglyLinkedList:
def __init__(self):
self._head = None # 연결리스트의 가장 앞의 노드 (head)
self._size = 0 # 리스트의 노드 개수
def __len__(self):
return self._size # len(A) = A의 노드 개수 리턴
def print_list(self):
v = self._head
while (v):
print(v._element, "->", end=" ")
v = v._next
print("None")
def add_first(self, element):
newest = self._Node(element, self._head) # 새 노드 생성
self._head = newest
self._size += 1
def add_last(self, element):
newest = self._Node(element) # 새 노드 생성
if self._head == None: # empty list
self._head = newest
else:
tail = self._head
while tail._next != None:
tail = tail._next
tail._next = newest
self._size += 1
def remove_first(self):
# head 노드의 값 리턴. empty list이면 None 리턴
if self._head == None: # empty list
return None
element = self._head._element
self._head = self._head._next
self._size -= 1
return element
def remove_last(self):
# tail 노드의 값 리턴
# empty list이면 None 리턴
if self._head == None:
return None
prev = None
tail = self._head
while tail._next != None:
prev = tail
tail = tail._next
if prev == None:
self._head = None
else:
prev._next = None
self._size -= 1
return tail._element
def search(self, element):
# element 값을 저장된 노드 리턴. 없으면 None 리턴
v = self._head
while v:
if v._element == element: return v
v = v._next
return v
def __iter__(self): # generator 정의
v = self._head
while v != None:
yield v
assert isinstance(v._next, object)
v = v._next
def search(self, element):
for v in self:
if v._element == element:
return v
return None
def remove(self, element):
# 노드 x를 제거한 후 True리턴. 제거 실패면 False 리턴
x = self.search(element)
if x == None or self._size == 0:
return False
if x == self._head:
self.remove_first()
else:
prev = self._head
while prev._next != x :
prev = prev._next
prev._next = x._next
self._size -= 1
return True
### 연결 스택 ###
# 클래스 선언
class Empty(Exception):
"""Error attempting to access an element from an empty container."""
pass
class LinkedStack:
"""LIFO Stack implementation using a singly linked list for storage."""
class _Node:
"""Lightweight, nonpublic class for storing a singly linked node."""
__slots__ = '_element', '_next' # streamline memory usage
def __init__(self, element, next): # initialize node's fields
self._element = element # reference to user's element
self._next = next # reference to next node
def __init__(self):
"""Create an empty stack."""
self._head = None # reference to the head node
self._size = 0 # number of stack elements
def __len__(self):
"""Return the number of elements in the stack."""
return self._size
def is_empty(self):
"""Return True if the stack is_empty."""
return self._size == 0
def push(self, e):
"""Add element e to the top of the stack."""
self._head = self._Node(e, self._head) # create and link a new node
self._size += 1
def top(self):
"""Return (but do not remove) the element at the top of the stack.
Raise Empty exception if the stack is_empty.
"""
if self.is_empty():
raise Empty('Stack is_empty')
return self._head._element # top of stack is at head of list
def pop(self):
"""Remove and return the element from the top of the stack (i.e., LIFO).
Raise Empty exception if the stack is_empty.
"""
if self.is_empty():
raise Empty('Stack is_empty')
answer = self._head._element
self._head = self._head._next # bypass the former top node
self._size -= 1
return answer
### 연결 큐 ###
class Empty(Exception):
"""Error attempting to access an element from an empty container."""
pass
class LinkedQueue:
"""FIFO queue implementation using a singly linked list for storage."""
class _Node:
"""Lightweight, nonpublic class for storing a singly linked node."""
__slots__ = '_element', '_next' # streamline memory usage
def __init__(self, element, next):
self._element = element
self._next = next
def __init__(self):
"""Create an empty queue."""
self._head = None
self._tail = None
self._size = 0 # number of queue elements
def __len__(self):
"""Return the number of elements in the queue."""
return self._size
def is_empty(self):
"""Return True if the queue is_empty."""
return self._size == 0
def first(self):
"""Return (but do not remove) the element at the front of the queue.
Raise Empty exception if the queue is_empty.
"""
if self.is_empty():
raise Empty('Queue is_empty')
return self._head._element # front aligned with head of list
def dequeue(self):
"""Remove and return the first element of the queue (i.e., FIFO).
Raise Empty exception if the queue is_empty.
"""
if self.is_empty():
raise Empty('Queue is_empty')
if self._size == 1: # special case as queue is_empty
self._tail = None # removed head had been the tail
answer = self._head._element
self._head = self._head._next
self._size -= 1
return answer
def enqueue(self, e):
"""Add an element to the back of queue."""
newest = self._Node(e, None) # node will be new tail node
if self.is_empty():
self._head = newest # special case: previously empty
else:
self._tail._next = newest
self._tail = newest # update reference to tail node
self._size += 1
### 원형 연결리스트 ###
class Empty(Exception):
"""Error attempting to access an element from an empty container."""
pass
class CircularQueue:
"""Queue implementation using circularly linked list for storage."""
class _Node:
"""Lightweight, nonpublic class for storing a singly linked node."""
__slots__ = '_element', '_next' # streamline memory usage
def __init__(self, element, next):
self._element = element
self._next = next
def __init__(self):
"""Create an empty queue."""
self._tail = None # will represent tail of queue
self._size = 0 # number of queue elements
def __len__(self):
"""Return the number of elements in the queue."""
return self._size
def is_empty(self):
"""Return True if the queue is_empty."""
return self._size == 0
def first(self):
"""Return (but do not remove) the element at the front of the queue.
Raise Empty exception if the queue is_empty.
"""
if self.is_empty():
raise Empty('Queue is_empty')
head = self._tail._next
return head._element
def dequeue(self):
"""Remove and return the first element of the queue (i.e., FIFO).
Raise Empty exception if the queue is_empty.
"""
if self.is_empty():
raise Empty('Queue is_empty')
oldhead = self._tail._next
if self._size == 1: # removing only element
self._tail = None # queue becomes empty
else:
self._tail._next = oldhead._next # bypass the old head
self._size -= 1
return oldhead._element
def enqueue(self, e):
"""Add an element to the back of queue."""
newest = self._Node(e, None) # node will be new tail node
if self.is_empty():
newest._next = newest # initialize circularly
else:
newest._next = self._tail._next # new node points to head
self._tail._next = newest # old tail points to new node
self._tail = newest # new node becomes the tail
self._size += 1
def rotate(self):
"""Rotate front element to the back of the queue."""
if self._size > 0:
self._tail = self._tail._next # old head becomes new tail
### 양방향 연결리스트 ###
class _Node:
"""Lightweight, nonpublic class for storing a doubly linked node."""
__slots__ = '_element', '_prev', '_next' # streamline memory
def __init__(self, element, prev, next): # initialize node's fields
self._element = element # user's element
self._prev = prev # previous node reference
self._next = next # next node reference
class _DoublyLinkedBase:
"""A base class providing a doubly linked list representation."""
def __init__(self):
"""Create an empty list."""
self._header = self._Node(None, None, None)
self._trailer = self._Node(None, None, None)
self._header._next = self._trailer # trailer is after header
self._trailer._prev = self._header # header is before trailer
self._size = 0 # number of elements
def __len__(self):
"""Return the number of elements in the list."""
return self._size
def is_empty(self):
"""Return True if list is_empty."""
return self._size == 0
def _insert_between(self, e, predecessor, successor):
"""Add element e between two existing nodes and return new node."""
newest = self._Node(e, predecessor, successor) # linked to neighbors
predecessor._next = newest
successor._prev = newest
self._size += 1
return newest
def _delete_node(self, node):
"""Delete nonsentinel node from the list and return its element."""
predecessor = node._prev
successor = node._next
predecessor._next = successor
successor._prev = predecessor
self._size -= 1
element = node._element # record deleted element
node._prev = node._next = node._element = None # deprecate node
return element # return deleted element
### 연결 덱 ###
from .doubly_linked_base import _DoublyLinkedBase
class Empty(Exception):
"""Error attempting to access an element from an empty container."""
pass
class LinkedDeque(_DoublyLinkedBase): # note the use of inheritance
"""Double-ended queue implementation based on a doubly linked list."""
def first(self):
"""Return (but do not remove) the element at the front of the deque.
Raise Empty exception if the deque is_empty.
"""
if self.is_empty():
raise Empty("Deque is_empty")
return self._header._next._element # real item just after header
def last(self):
"""Return (but do not remove) the element at the back of the deque.
Raise Empty exception if the deque is_empty.
"""
if self.is_empty():
raise Empty("Deque is_empty")
return self._trailer._prev._element # real item just before trailer
def insert_first(self, e):
"""Add an element to the front of the deque."""
self._insert_between(e, self._header, self._header._next) # after header
def insert_last(self, e):
"""Add an element to the back of the deque."""
self._insert_between(e, self._trailer._prev, self._trailer) # before trailer
def delete_first(self):
"""Remove and return the element from the front of the deque.
Raise Empty exception if the deque is_empty.
"""
if self.is_empty():
raise Empty("Deque is_empty")
return self._delete_node(self._header._next) # use inherited method
def delete_last(self):
"""Remove and return the element from the back of the deque.
Raise Empty exception if the deque is_empty.
"""
if self.is_empty():
raise Empty("Deque is_empty")
return self._delete_node(self._trailer._prev) # use inherited method
### 원형 양방향 연결 덱 ###
class _CircularDoublyLinkedBase:
"""A base class providing a doubly linked list representation."""
#-------------------------- nested _Node class --------------------------
# nested _Node class
class _Node:
"""Lightweight, nonpublic class for storing a doubly linked node."""
__slots__ = '_element', '_prev', '_next' # streamline memory
def __init__(self, element, prev, next): # initialize node's fields
self._element = element # user's element
self._prev = prev # previous node reference
self._next = next # next node reference
def __str__(self): # modified
return str(self._element) # modified
#-------------------------- list constructor --------------------------
def __init__(self):
"""Create an empty list."""
self._header = self._Node(None, None, None)
self._header._next = self._header # modified
self._header._prev = self._header # modified
self._size = 0 # number of elements
#-------------------------- public accessors --------------------------
def __len__(self):
"""Return the number of elements in the list."""
# your code
return self._size
def is_empty(self):
"""Return True if list is empty."""
# your code
return self._size == 0
#-------------------------- nonpublic utilities --------------------------
def _insert_between(self, e, predecessor, successor):
"""Add element e between two existing nodes and return new node."""
newest = self._Node(e, predecessor, successor)
predecessor._next = newest
successor._prev = newest
self._size += 1
return newest
def _delete_node(self, node):
"""Delete nonsentinel node from the list and return its element."""
predecessor = node._prev
successor = node._next
predecessor._next = successor
successor._prev = predecessor
self._size -= 1
element = node._element # record deleted element
node._prev = node._next = node._element = None # deprecate node
return element # return deleted element
def __iter__(self): # generator 정의
v = self._header._next
while v != self._header:
yield v
assert isinstance(v._next, object)
v = v._next
def __str__(self): # 연결 리스트의 값을 print 출력
return " -> ".join(str(v) for v in self)
class Empty(Exception):
"""Error attempting to access an element from an empty container."""
pass
class CircularLinkedDeque(_CircularDoublyLinkedBase): # note the use of inheritance
"""Double-ended queue implementation based on a doubly linked list."""
def first(self):
"""Return (but do not remove) the element at the front of the deque.
Raise Empty exception if the deque is empty.
"""
if self.is_empty():
raise Empty('Deque is empty')
#head = self._header._next
return self._header._next._element
def last(self):
"""Return (but do not remove) the element at the back of the deque.
Raise Empty exception if the deque is empty.
"""
if self.is_empty():
raise Empty("Deque is empty")
return self._header._prev._element
def insert_first(self, e):
"""Add an element to the front of the deque."""
self._insert_between(e, self._header, self._header._next)
def insert_last(self, e):
"""Add an element to the back of the deque."""
self._insert_between(e, self._header._prev, self._header) # before trailer
def delete_first(self):
"""Remove and return the element from the front of the deque.
Raise Empty exception if the deque is empty.
"""
if self.is_empty():
raise Empty("Deque is empty")
return self._delete_node(self._header._next)
def delete_last(self):
"""Remove and return the element from the back of the deque.
Raise Empty exception if the deque is empty.
"""
if self.is_empty():
raise Empty("Deque is empty")
return self._delete_node(self._header._prev)
D = CircularLinkedDeque()
command_list = [(D.insert_first, 3, 'D.insert_first(3)'),
(D.insert_first, 7, 'D.insert_first(7)'),
(D.first, None, 'D.first()'),
(D.delete_last, None, 'D.delete_last()'),
(len, D, 'len(D)'),
(D.delete_last, None, 'D.delete_last()'),
(D.delete_last, None, 'D.delete_last()'),
(D.insert_first, 6, 'D.insert_first(6)'),
(D.last, None, 'D.last()'),
(D.insert_first, 8, 'D.insert_first(8)'),
(D.is_empty, None, 'D.is_empty()'),
(D.last, None, 'D.last()')]
idx = 0
for command, args, cmd_str in command_list:
print(idx, ':', cmd_str, end="\t") # 실행할 명령어를 출력
try:
return_v = None
if args == None :
return_v = command() # 메소드 호출
else:
return_v = command(args) # 메소드를 호출할 때 인자(args)가 존재하면 전달
except Empty as e: # Empty Exception이 발생하면 종료되지 않도록 오류를 출력
print(e, end="\t")
if return_v != None: print(return_v, end="\t") # 메소드 호출 결과가 None이 아니면 출력
print('[', D, ']') # 덱 내용을 출력
idx += 1
|
from copy import copy, deepcopy
class Graph:
def __init__( self ):
# This is 'y' in Eq. 2
self.orderedVertexList = []
# This is M in Eq. 2
self.numberOfVertices = 0;
# end constructor
def getLossFunction( self, secondGraph, norm = 1.5 ):
M = self.getNumberOfVertices()
D = self.getSimilarityScore( secondGraph, norm )
delta = ( 1 / M ) * ( M - D )
#print( delta )
return delta
# end function getLossFunction
# Compute the similarity score between this graph
# and the input graph based Eq. 2
def getSimilarityScore( self, secondGraph, norm = 1.5 ):
X =\
len( self.getNodesWithDifferentNeighbors( secondGraph ) )
VSizes =\
self.getForwardStreakCardinality( secondGraph )
WSizes =\
self.getBackwardStreakCardinality( secondGraph )
VSum = 0
for v in VSizes:
VSum = VSum + v**norm
# end for v
WSum = 0
for w in WSizes:
WSum = WSum + w**norm
# end for w
similarityScore = ( X + VSum + 0.5 * WSum )**( 1/norm )
return similarityScore
# end function getSimilarityScore
# Get the cardinality of each backward streak
# This returns a list, where ith value is the
# size of the ith backward streak. Basically,
# |W_i| in Eq. 2
def getBackwardStreakCardinality( self, secondGraph ):
cardinality = []
backwardStreaks =\
self.getBackwardStreak( secondGraph )
for streak in backwardStreaks:
cardinality.append( len( streak ) )
# end for
return cardinality
# end function getBackwardStreakCardinality
# Get backward streaks
# This returns W in Eq. 2
def getBackwardStreak( self, secondGraph ):
secondGraphBackward =\
secondGraph.createBackwardGraph()
backwardStreaks =\
self.getForwardStreak( secondGraphBackward )
return backwardStreaks
# end function getBackwardStreak
# Create a new graph from the current one
# Everything is the same but the vector
# list is in the reversed order
def createBackwardGraph( self ):
backwardVectorList =\
deepcopy( list( reversed( self.orderedVertexList ) ) )
backwardGraph = Graph()
backwardGraph.initializeADummyGraph( backwardVectorList )
return backwardGraph
# end function createBackwardGraph
# Get the cardinality of the ith forward
# streak in this graph and the input graph
# This is similar to V_i in Eq. 2
# It returns a list that where ith location
# is the cardinality of ith streak
def getForwardStreakCardinality( self, secondGraph ):
cardinality = []
forwardStreaks = self.getForwardStreak( secondGraph )
for streak in forwardStreaks:
cardinality.append( len( streak ) )
# end for
return cardinality
# end function getForwardStreakCardinality
# Compute and return all forward streaks
# This is equivalent to V in Eq. 2
def getForwardStreak( self, secondGraph ):
forwardStreaks = []
flatForwardStreaks = [];
intersection = self.getIntersection( secondGraph )
for node in intersection:
if node in flatForwardStreaks:
continue
currentStreak = [node]
index1 = self.orderedVertexList.index( node )
index2 = secondGraph.orderedVertexList.index( node )
while index1 < self.getNumberOfVertices()-1 and\
index2 < secondGraph.getNumberOfVertices()-1:
index1 = index1 + 1
index2 = index2 + 1
if self.orderedVertexList[index1] !=\
secondGraph.orderedVertexList[index2]:
break
currentStreak.append( self.orderedVertexList[index1] )
flatForwardStreaks.append( self.orderedVertexList[index1] )
# end while
if len( currentStreak ) == 1:
continue
forwardStreaks.append( currentStreak )
# end for node
return forwardStreaks
# end function getForwardStreak
# This function returns the number of nodes in this
# graph and the input graph that have different neighbors.
# This is similar to |X| in Eq.2
def getNodesWithDifferentNeighborsCardinality(\
self, secondGraph ):
nodesWithDifferentNeighbors =\
self.getNodesWithDifferentNeighbors( secondGraph )
return len( nodesWithDifferentNeighbors )
# end function getNodesWithDifferentNeighborsCardinality
# This function returns nodes in this graph and
# the input graph that have different neighbors.
# Both neighbors must be different.
# This computes X in Eq. 2 in the paper
def getNodesWithDifferentNeighbors( self, secondGraph ):
nodesWithDifferentNeighbors = []
# Find common nodes in both graphs
intersection = self.getIntersection( secondGraph )
for node in intersection:
flag = False
neighborsThisGraph =\
self.getNeighborsOfNode( node )
neighborsSecondGraph =\
secondGraph.getNeighborsOfNode( node )
for neighbor in neighborsThisGraph:
if neighbor in neighborsSecondGraph:
flag = True
# end for neighbor
if flag == True:
continue
nodesWithDifferentNeighbors.append( node )
# end for node
return nodesWithDifferentNeighbors
# end function getNodesWithDifferentNeighbors
# This function computes all the neighbors
# of the node 'node' in the graph
def getNeighborsOfNode( self, node ):
if node not in self.orderedVertexList:
return []
if self.numberOfVertices == 1:
return []
index = self.orderedVertexList.index( node )
if index == 1:
return [self.orderedVertexList[index+1]]
if index == self.numberOfVertices-1:
return [self.orderedVertexList[index-1]]
return [self.orderedVertexList[index-1],\
self.orderedVertexList[index+1] ]
# end function getNeighborsOfNode
# Given this graph and an input graph, this function
# computes the nodes that are common between the two
def getIntersection( self, secondGraph ):
intersection = [];
# Find the common nodes
for node in self.orderedVertexList:
if node in secondGraph.orderedVertexList:
intersection.append( node )
# end for
return intersection
# end function getIntersection
# Load a dummy graph so we have something to
# start with
def initializeADummyGraph( self, nodesOrder = [] ):
if len( nodesOrder ) == 0:
self.orderedVertexList =\
[1, 3, 4, 5, 7, 6, 10, 9, 8]
else:
self.orderedVertexList =\
nodesOrder
# end if
self.updateNumberOfVertices();
# end function initializeADummyGraph
# Determine how many nodes are there in the
# graph
def getNumberOfVertices( self ):
return len( self.orderedVertexList )
# end function getNumberOfVertices
# Make sure the number of nodes is consistend
# with the graph
def updateNumberOfVertices( self ):
self.numberOfVertices = self.getNumberOfVertices();
# end function updateNumberOfVertices
# end class Graph
mygraph = Graph();
labelGraph = Graph();
mygraph.initializeADummyGraph()
labelGraph.initializeADummyGraph( [1,2,3,4,5,6,7,8,9,10] )
my_loss = labelGraph.getLossFunction( mygraph )
|
def countdown(segundos):
if segundos <=0:
print ("Por favor indique un numero correcto")
else:
while segundos >= 0:
print (segundos)
segundos = segundos - 1
print ("La cuenta regresiva termino, ya no te preocupes")
segundos = 6
countdown(segundos) |
# -*- coding: utf-8 -*-
"""Calculates statistics for a given file."""
from typing import Dict, Optional
from .statistics_generator import StatisticsGenerator
# Create a type alias to reduce the length a bit
StatsGenerators = Dict[str, StatisticsGenerator]
class TextStatistics:
"""This class processes text files and generates statistics on the data.
The statistics generated is plugable and you can control which statistics
are provided by passing ``StatisticGenerator`` objects to the constructor.
Attributes:
stats_generators: A dictionary of id -> StatisticGenerator object
mappings.
"""
def __init__(self, stats_generators: StatsGenerators) -> None:
"""Initialise the class
Arguments:
stats_generators: This is a dictionary containing an id to
StatisticsGenerator object mapping.
"""
self.stats_generators: StatsGenerators = stats_generators
def process_file(self, file_name: str) -> None:
"""Calculate statistics for the provided file name.
This method will loop through each of the stats_generators and
calculate statistics for the provided file.
Arguments:
file_name: the location of the file to generate statistics for.
"""
with open(file_name, 'r') as file_handle:
for line in file_handle:
for stats_generator in self.stats_generators.values():
stats_generator.parse_line(line)
def get(self,
key: str,
default: Optional[StatisticsGenerator] = None
) -> Optional[StatisticsGenerator]:
"""Return StatisticsGenerator identified by ``key``, else ``default``.
"""
return self.stats_generators.get(key, default)
|
# -*- coding: utf-8 -*-
""" Provides a Statistics Generator Plygin to calculate the number of words
in text.
"""
from .statistics_generator import StatisticsGenerator
class WordCount(StatisticsGenerator):
"""This class counts the number of words that are parsed.
A word is defined as anything delimited by whitespace.
"""
def __init__(self) -> None:
self._word_count: int = 0
def parse_line(self, line: str) -> None:
"""Count the number of words in the provided line."""
words_in_line: int = len(line.split())
self._word_count += words_in_line
def result(self) -> int:
"""Return the number of words seen."""
return self._word_count
|
# -*- coding: utf-8 -*-
"""An interface for the Statistics Generator Plugins."""
from abc import ABC, abstractmethod
from typing import Any
class StatisticsGenerator(ABC):
"""This class provides an interface for Statistics Generator Plugins.
Each class which calculates a statistic for the TextStatistics module
should inherit the interface from this class so that it's enforced.
The caller will call the ``parse_line`` method for every line seen in the
text file. Once the caller has finished parsing lines, it will call the
``result`` method to obtain the statistics that the plugin is calculating.
"""
@abstractmethod
def parse_line(self, line: str) -> None:
"""Parse a line from a text file.
This method is called for every line in a text file. The subclass
should override this class and generate statistics from the data.
"""
raise NotImplementedError()
@abstractmethod
def result(self) -> Any:
"""Return the result from the parsed data."""
raise NotImplementedError()
def __str__(self) -> str:
"""Return the result as a string."""
return f"{self.result()}"
|
def _m_return(m):
if m >= 0:
return False
else:
return True
def is_not_final_tableau(table):
m = min(table[-1, :-1]) # minimum last row <=> minimum objective fct. coeffs
return m < 0 # <=> not m >= 0
def is_not_final_tableau_r(table):
# print(table, table[:-1, -1])
# print(table.shape, table[:-1, -1].shape)
m = min(table[:-1, -1]) # minimum last column. <=> minimum right side.
return m < 0 # <=> not m >= 0
|
class AbstractVariable:
def __init__(self, name):
self._name = name
@property
def name(self):
return self._name
def __eq__(self, other):
if not isinstance(other, AbstractVariable):
return False
return self.name == other.name and self.__class__ == other.__class__
class ModelVariable(AbstractVariable):
pass
class SlackVariable(AbstractVariable):
pass
class ArtificialVariable(AbstractVariable):
pass
|
def parse_number(number_string):
try:
return int(number_string)
except ValueError:
pass
return float(number_string)
#if number_string.isdigit():
# return int(number_string)
#return float(number_string)
def read(filepath):
with open(filepath, "r") as f:
deserialized = [l.strip() for l in f.readlines()]
objective = deserialized[0]
constraints = deserialized[1:]
assert objective.startswith("obj")
parsed_objective = [parse_number(n) for n in objective.split(" ")[1:]]
for c in constraints:
assert c.startswith("constraint")
var_count = objective.split(" ").__len__() - 1
parsed_constraints = []
for c in constraints:
tmp = c.split(" ")
assert tmp[0] == "constraint"
assert tmp.__len__() - 3 == var_count
left_side = [parse_number(n) for n in tmp[1:var_count + 1]]
ctype = tmp[-2] # == -2 == var_count + 2
assert ctype in {'<=', '>=', '=='}
right_side = parse_number(tmp[-1])
parsed_constraints.append((left_side, ctype, right_side))
return parsed_objective, parsed_constraints
|
list1 = list(map(int, input().strip().split()))
list2 = list(map(int, input().strip().split()))
list1 = set(list1)
list2 = set(list2)
ans=[]
for i in list1:
if(i in list2):
continue;
else:
ans.append(i);
print("Element in List 1 that are not present in List 2:", ans);
|
items = [1,2,4]
i = 0
while items:
if i < 10:
items.append(i)
else:
break
i += 1
print items
|
import copy
def p_item(item, row):
print "r=%3d " % row,
for i in item:
print "%4d" % i,
print
def manually_generate(original_item, n):
item = copy.copy(original_item)
temp = [0 for _ in range(len(item))]
for x in range(n):
for i in range(len(item)-1):
temp[i]= item[i] ^ item[i+1]
temp[len(item)-1] = item[len(item)-1] ^ item[0]
item = copy.copy(temp)
return temp
def get_index(n, index):
return index % n
for i in range(5, 25):
print "------------------------------"
numbers = [x for x in range(1,i+1)]
p_item(numbers,1)
for x in range(1, 25):
p_item(manually_generate(numbers, x),x+1)
|
def max_array(arr):
current_sum = 0
start_index = 0
current_start_index = 0
end_index = 0
max_sum = 0
max_non_contiguous_sum = 0
max_neg_num = arr[0]
for i in range(len(arr)):
if arr[i] > 0:
max_non_contiguous_sum += arr[i]
if arr[i] > max_neg_num:
max_neg_num = arr[i]
current_sum += arr[i]
if current_sum > max_sum:
max_sum = current_sum
end_index = i
start_index = current_start_index
if current_sum < 0:
current_start_index = i + 1
current_sum = 0
# print "max = ", max_sum
# print arr[start_index:end_index+1]
if max_sum == 0:
# print "max = ", max_neg_num
return max_neg_num, max_neg_num
else:
return max_sum, max_non_contiguous_sum
nums = [-1, 3, -5, 4, 6, -1, 2, -7, 13, -3]
print max_array(nums)
nums = [-11, -3, -5, -4, -6, -10, -2, -7, -13, -3]
print max_array(nums)
"""
test_cases = int(raw_input().strip())
for _ in range(test_cases):
raw_input()
numbers = raw_input().strip().split()
numbers = [int(n) for n in numbers]
cont, non_cont = max_array(numbers)
print cont, non_cont
"""
|
from random import randint
M = 20
N = 35
R = 20
print M, N, R
for i in range(M):
for j in range(N):
print "{0}{1}".format(i+1, j+1),
# print(randint(1,9)),
print
|
def max_sub_array(arr):
running_total = 0
max_so_far = 0
end_index = 0
start_index = 0
for ind, i in enumerate(arr):
running_total += i
if running_total <= 0:
running_total = 0
start_index = ind+1
if running_total >= max_so_far:
max_so_far = running_total
end_index = ind
return max_so_far, start_index, end_index
print max_sub_array([904, 40, 523, 12, -335, -385, -124, 481, -31])
nums = [-1, 3, -5, 4, 6, -1, 2, -7, 13, -3]
print max_sub_array(nums)
nums = [-11, -3, -5, -4, -6, -10, -2, -7, -13, -3]
print max_sub_array(nums) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.