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)
pr... |
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.co... |
"""
定义函数
函数function,通常接受输入参数,并有返回值。
它负责完成某项特定任务,而且相较于其他代码,具备相对的独立性。
In [1]:
def add(x, y):
""Add two numbers""
a = x + y
return a
函数通常有一下几个特征:
使用 def 关键词来定义一个函数。
def 后面是函数的名称,括号中是函数的参数,不同的参数用 , 隔开, def foo(): 的形式是必须要有的,参数可以为空;
使用缩进来划分函数的内容;
docstring 用 "" 包含的字符串,用来解释函数的用途,可省略;
return 返回特定的值,如果省略,返回 None ... |
"""
Python 自1.5以后增加了re的模块,提供了正则表达式模式
re模块使Python语言拥有了全部的正则表达式功能
正则表达式,又称规则表达式。(英语:Regular Expression,在代码中常简写为regex、regexp或RE),计算机科学的一个概念。正则表达式通常被用来检索、替换那些符合某个模式(规则)的文本。
许多程序设计语言都支持利用正则表达式进行字符串操作。例如,在Perl中就内建了一个功能强大的正则表达式引擎。正则表达式这个概念最初是由Unix中的工具软件(例如sed和grep)普及开的。正则表达式通常缩写成“regex”,单数有regexp、regex,复数有regexps、regexes、r... |
"""
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):任何传入函数的参数和变量必须
放在圆括号之间,用逗号分隔,函数从函数... |
"""
简单的数学运算
整数相加,得到整数:
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 [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]
还可以在列表推导式中加入条件进行筛选。
例如在上面的例子中,假如只想保留列表中不大... |
"""
对应于元组(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 Yor... |
"""
列表是可变的(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... |
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")
#prin... |
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)... |
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.... |
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:
br... |
"""
基本用法
判断,基于一定的条件,决定是否要执行特定的一段代码,例如判断一个数是不是正数:
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 "... |
#排序:冒泡排序,选择排序, 快速排序,插入法,计数器排序
#普通排序
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)
#按长... |
"""
概述:
目前代码比较少,写在一个文件中还体现不出什么缺点,但是随着代码量越来越多,代码就越来越难以维护
为了解决难以维护问题,我们把很多相似功能的函数分组,分别放到不同文件中去,这样每个文件所包含的内容相对较少
而且对于每一个文件的大致功能可用文件名来体现,很多编程语言都是这么来组织代码结构,一个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(righth... |
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()
... |
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 ... |
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 = com... |
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... |
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 - Mid... |
#!/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 ... |
#!/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()
... |
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:
... |
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 enume... |
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, star... |
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 celc... |
"""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.
... |
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:
s2... |
"""
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 = ... |
"""
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 mi... |
#!/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:
... |
# -*- 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
... |
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: # ищем строки, в которы... |
# -*- 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 ... |
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'):
... |
#!/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 ... |
#! /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_... |
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 :
... |
'''
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]
... |
#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 re... |
'''
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 h... |
#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 ... |
'''
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... |
'''
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... |
'''
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(obj... |
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()
... |
#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 th... |
'''
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):
# sel... |
'''
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[la... |
#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 c... |
''' 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 addTwoLis... |
'''
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... |
'''
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... |
#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, ... |
'''
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 a... |
#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 +=... |
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... |
#! /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... |
# -*- 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):
... |
'''
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为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 ... |
'''
给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{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:
d... |
# -*- 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... |
'''
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{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根节点
... |
'''
汇编语言中有一种移位指令叫做循环左移(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 = "g... |
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")
... |
"""
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__ == "__... |
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 far... |
# 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_... |
# 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 indic... |
### 단방향 연결리스트 ###
# 노드 클래스
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__(... |
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... |
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 fil... |
# -*- 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 ... |
# -*- 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 mo... |
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... |
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.__c... |
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:
deseriali... |
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]= ite... |
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:
... |
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_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.