text
stringlengths 37
1.41M
|
---|
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.stem.wordnet import WordNetLemmatizer
import string
def clear_text(txt):
# Tokenization
tokens = word_tokenize(txt)
# Lowercase conversion
tokens = [w.lower() for w in tokens]
# Removing punctuation
table = str.maketrans('', '', string.punctuation)
stripped = [w.translate(table) for w in tokens]
# Deleting all non-words
final_wds = [w for w in stripped if w.isalpha()]
# removing stopwords
stop_wd = set(stopwords.words('english'))
final_wds = [w for w in final_wds if w not in stop_wd]
# Lemmatization process
lemtz = WordNetLemmatizer()
final_wds = [lemtz.lemmatize(w) for w in final_wds]
final_text = []
for term in final_wds:
final_text.append(term + " ")
last = ''.join(map(str, final_text))
return last
|
# write a program that uses input to prompt a user for their name and then welcomes them
entered_name = input("Please enter your name :")
print("Hello", entered_name)
|
def calculator():
num_coll = list()
while True:
num = input("Enter a number:")
# check if user entered something and they are all digits
if len(num) > 0 and num.isdigit():
# add number to the list
num_coll.append(int(num))
print("Current numbers:", num_coll)
elif len(num) > 0 and num == "done":
break
# compute the maximum and minimum
print("Maximum:", max(num_coll))
print("Minimum:", min(num_coll))
return
calculator()
|
word = "banana"
count = 0
for letter in word:
if letter == "a":
count += 1
else:
continue
print("The letter [a] appears %s times!" % (str(count)))
|
# Prompt user for the first point
x_1 = input("Enter x1:")
# Prompt user for the first point
y_1 = input("Enter y1:")
# Prompt user for the first point
x_2 = input("Enter x2:")
# Prompt user for the first point
y_2 = input("Enter y2:")
# calculate difference between the x coordinates
first_diff = int(x_2) - int(x_1)
# calculate difference between the y coordinates
second_diff = int(y_2) - int(y_1)
# Sum the squares of the differences
square_result = first_diff**2 + second_diff**2
# attain square root by raising to power a half
distance = square_result**(1/2)
print("The difference between the two points is:", distance)
|
from math import sqrt
from math import ceil
import pygame
"""
Just a dot moving left or right
depending on given settings
"""
class Entity:
"""
x, y
direction --> -1 is left and 1 is right
velocity
"""
def __init__(self, x, y, direction, velocity):
self.x = x
self.y = y
self.direction = direction
self.velocity = velocity
def draw(self, screen):
pygame.draw.circle(screen, (0, 255, 0), [self.x, self.y], 10)
def update(self, dTime):
if self.direction == 1:
self.x += self.velocity*dTime
elif self.direction == -1:
self.x -= self.velocity*dTime
def getPosition(self):
return [self.x, self.y]
def isOutsideScreen(self):
if self.x < 0 or self.x > 1000:
return True
return False
"""
This is object representing sound wave
which spreads around 'emitter'
"""
class Wave:
radius = 2
velocity = 3 # Speed of wave
def __init__(self, x, y, ID):
self.x = x
self.y = y
self.id = ID # object identificator
def draw(self, screen):
pygame.draw.circle(screen, (0, 0, 255), [self.x, self.y], self.radius, 1)
def update(self, dTime):
self.radius += self.velocity*dTime
def doesCollideWithCircle(self, position, radius):
"""Return wave id if its colliding, if not return False
--> Checks if circle passed in arguments is colliding with this wave
"""
distBetween = sqrt( (self.x-position[0])**2 + (self.y-position[1])**2 )
if distBetween <= self.radius + radius and distBetween >= abs(self.radius - radius):
return self.id
else:
return False
class FrequencyTimeline:
pointer = [10, 550]
RED = (255, 0, 0)
BLUE = (0, 0, 255)
SPEED = 2
height = 100
width = 1000
lastCollision = False
blocksPositions = [] # List containing x positions of timeline blocks
def __init__(self):
size = (1000, 150)
self.aplha_surface = pygame.Surface(size, pygame.SRCALPHA)
self.aplha_surface.fill((76, 80, 82, 150))
def draw(self, screen):
screen.blit(self.aplha_surface, (0, 550))
pygame.draw.rect(self.aplha_surface, self.BLUE, (0, 500, self.width, self.height), 10)
for blockPos in self.blocksPositions:
pygame.draw.rect(screen, self.RED, (blockPos, 550, 5, self.height), 0)
pygame.draw.circle(screen, self.RED, self.pointer, 7) # a little circle on the top of the pointer - for attention
pygame.draw.line(screen, self.RED, self.pointer, self.bottomPointer(), 2)
def update(self, collision):
self.pointer[0] += self.SPEED # move pointer to the right~!
# If pointer is beyond screen
if self.pointer[0] > self.width:
self.pointer[0] = 5 # go back to the start!
"""If there is block in front of pointer
in range of 250px then d e l e t e i t!
"""
blcksNum = len(self.blocksPositions)
if blcksNum > 2:
isInRange = True
i = 0
while isInRange:
if self.pointer[0] < self.blocksPositions[i] and self.pointer[0] + 250 > self.blocksPositions[i]:
del self.blocksPositions[i]
i = 0
else:
isInRange = False
if i+1 < blcksNum:
i += 1
"""Check if collision with some new
wave occured. If indeed, then add new block
"""
if collision != False:
if self.lastCollision != collision:
self.lastCollision = collision
self.blocksPositions.append( self.pointer[0] )
else:
self.lastCollision = collision
def reset(self):
self.blocksPositions = []
self.pointer[0] = 5 # go back to the start!
def bottomPointer(self):
return [ self.pointer[0], self.pointer[1]+self.height ]
class DopplerEffect:
WHITE = (255, 255, 255)
cycle = 1000 # how often emmit waves (in seconds/10)
waves = []
lastWaveTime = pygame.time.get_ticks()
emitterDirect = -1
observDirect = 1
emitterSpeed = 1
observSpeed = 1
animation = False
def __init__(self):
self.frequencyMeter = FrequencyTimeline()
self.reset()
def render(self, screen):
# Set the screen background
for wave in self.waves:
wave.draw(screen)
self.emitter.draw(screen)
self.observer.draw(screen)
self.frequencyMeter.draw(screen)
def update(self, dTime):
if self.animation:
roundDeltaTime = ceil( dTime )
colission = False
# Create new wave around emitter
now = pygame.time.get_ticks()
if now - self.lastWaveTime >= self.cycle:
newWave = Wave(self.emitter.x, self.emitter.y, len(self.waves)+1)
self.waves.append(newWave)
self.lastWaveTime = now
colission = False
i = 0
foundValidWave = False
toRemove = []
for i in range(0, len(self.waves)):
wave = self.waves[i]
"""Removing waves which went outside of screen
1. we make a circle which contains screen [Center: (500,325), radius: 526]
2. if wave is not colliding with this circle we remove it
"""
if not foundValidWave:
distBetween = sqrt( (wave.x-500)**2 + (wave.y-325)**2 )
if distBetween <= abs(wave.radius - 526) and wave.radius > 526:
toRemove.append(i) # delete wave which went out of screen
else:
foundValidWave = True # If found valid one, there is no need to check no more!!!
if foundValidWave:
wave.update(roundDeltaTime)
if colission == False: # search till collision with wave found
colission = wave.doesCollideWithCircle(self.observer.getPosition(), 5)
toRemove.sort()
i=0
for pos in toRemove:
del self.waves[pos-i]
i+=1
# If emitter or observer went out of border then reset and stop animation
if self.emitter.isOutsideScreen() or self.observer.isOutsideScreen():
self.reset()
self.stop()
#Update entities
self.emitter.update(roundDeltaTime)
self.observer.update(roundDeltaTime)
self.frequencyMeter.update(colission)
# set frequency given in herz
def setFrequency(self, frequency):
self.cycle = 1/frequency * 1000
def setDirection(self, emitt, obsrv):
if emitt != None:
self.emitterDirect = emitt
if obsrv != None:
self.observDirect = obsrv
def setSpeed(self, emitt, obsrv):
self.emitterSpeed = emitt
self.observSpeed = obsrv
def start(self):
self.animation = True
def stop(self):
self.animation = False
def reset(self):
# set starting coords by looking on choosen directions
emittCoords = {'x': 500, 'y':300}
obsvCoords = {'x': 100, 'y':300}
"""Depending on direction settings
we change starting position of emitter and observer"""
if self.emitterDirect == 1 and self.observDirect == 1: # Both going right
emittCoords['x'] = 270
elif self.emitterDirect == -1 and self.observDirect == -1: # Both going left
emittCoords['x'] = 900
obsvCoords['x'] = 650
elif self.emitterDirect == 1 and self.observDirect == -1: # Emitter right, observer left
emittCoords['x'] = 270
obsvCoords['x'] = 400
elif self.emitterDirect == -1 and self.observDirect == 1: # Emitter right, observer left
emittCoords['x'] = 500
obsvCoords['x'] = 100
# Object which is emitting sound
self.emitter = Entity(emittCoords['x'], emittCoords['y'], self.emitterDirect, self.emitterSpeed)
# Observer, which receives sound
self.observer = Entity(obsvCoords['x'], obsvCoords['y'], self.observDirect, self.observSpeed)
# Clear waves array and timeline with sound receiving
self.waves = []
self.frequencyMeter.reset()
|
print("Welcome ")
name = input("Enter your name: ")
age = int(input("Enter your age: "))
energy = int(10)
while age >= 5:
print("You are eligible to play\nLet's begin\nEnergy = 10")
print("In the evening you are walking through a forest and you come across a lake")
choice1 = input('''What will you do
1.Swim across the lake
2.Walk around the lake
3.Go Back
select your choice 1 or 2 or 3:
''')
if choice1 == '1':
print("you swim")
energy -= 5
print('Energy =', energy)
elif choice1 == '2':
print("you walk")
energy -= 2
print('Energy = ', energy)
elif choice1 == '3':
print("game over")
break
else:
print('Select any one of the above')
print('''\nIt's already night and you see a house near the lake, what would you do ?\n
1.Get in the house and take rest
2.stay by the lake and wait till morning
3.Go back''')
choice2 = input("select your choice 1 or 2 or 3: ")
if choice2 == '1':
print("You went into the house and took rest")
energy += 5
print('Energy = ', energy)
elif choice2 == '2':
print("you got cold")
energy -= 5
if energy == '0':
print("Energy = ", energy)
print("out of energy \nGame over")
break
else :
print("Energy = ", energy)
elif choice2 == '3':
print('you got home')
energy -= 5
if energy == '0':
print("Energy = ", energy)
print("out of energy \nGame over")
break
else :
print("Energy left = ", energy)
print("Game Over")
break
else:
print("Select any one of the above")
print('''In the next morning you woke up in the house that you entered last night
1.Would you like to go back
2.Continue your journey''')
choice3 = input("select 1 or 2: ")
if choice3=='1':
energy -= 5
print("You went home\n Energy = ", energy)
print("Game over")
break
elif choice3 == '2':
print("Thank you ", name)
print("The game is still under development ")
break
choice4 = input("would you like to try the converters program\n Type yes/no: " ).lower()
if choice4 == 'yes':
print("here is a simple converter")
import converters
converters.converters()
elif choice4 == 'no':
print("Thank you")
else :
print("invaild entry try again")
|
def solve(bo):
find = find_empty(bo)
if not find:
return True
else:
(row, col) = find
for i in range(1, 10):
if valid(bo, i, (row, col)):
bo[row][col] = i
if solve(bo): # calling solve on new board
return True
bo[row][col] = 0
return False
def valid(bo, num, pos):
"""
:param bo: Board Matrix
:param num: int
:param pos:tuple (row ,col)
:return:
"""
# check row
for j in range(len(bo[0])):
if bo[pos[0]][j] == num and pos[1] != j:
return False
# check column
for i in range(len(bo)):
if bo[i][pos[1]] == num and pos[0] != i:
return False
# check box
box_x = pos[1] // 3
box_y = pos[0] // 3
for i in range(box_y * 3, box_y * 3 + 3):
for j in range(box_x * 3, box_x * 3 + 3):
if bo[i][j] == num and (i, j) != pos:
return False
return True
def find_empty(board):
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == 0:
return (i, j)
|
def main():
example = ['hello', 'good morning', 'bye bye', 'have a good day']
placeOfChange = int(input("Choose the position of the element that you want change : "))
Change = input("What you want place : ")
example[placeOfChange-1] = Change
print(example)
if __name__=="__main__" :
main()
|
list_one = ['six', 'three', 'two', 'one']
list_two = ['four', 'seven', 'five']
final_list = list_two + list_one
print(final_list[-1:-4:-1] + final_list[0:3:2] + final_list[-4:-7:-2])
|
# Programmer - python_scripts (Abhijith Warrier)
# PYTHON GUI TO CONVERT USER-INPUT AMOUNT FROM SELECTED CURRENCY VALUE TO SELECTED CURRENCY BASED ON REAL-TIME CURRENCY RATES
# GET YOUR FREE API KEY FROM : https://www.alphavantage.co
# Importing necessary packages
import requests
import tkinter as tk
from tkinter import *
from tkinter.ttk import Combobox
# Making a list of currencies. You can add more items (currencies) to the list
currencyList = ['INR', 'USD', 'AED', 'AUD', 'BHD', 'BRL', 'CAD', 'CNY', 'EUR', 'HKD',
'IDR', 'BGN', 'ILS', 'GBP', 'DKK', 'JPY', 'HUF', 'RON', 'MYR', 'SEK',
'SGD', 'CHF', 'KRW', 'TRY', 'HRK', 'NZD', 'THB', 'NOK', 'RUB', 'MXN',
'CZK', 'PLN', 'PHP', 'ZAR']
# Defining CreateWidgets() to create necessary widgets for the GUI
def CreateWidgets():
inputAMT_Label = Label(root, text="AMOUNT : ", bg="peachpuff4")
inputAMT_Label.grid(row=1, column=0, padx=5, pady=5)
iAMT = Entry(root, width=14, textvariable=getAMT, bg="snow3", font=('',20), justify="center")
iAMT.grid(row=1, column=2, padx=5, pady=5)
fromLabel = Label(root, text="FROM : ", bg="peachpuff4")
fromLabel.grid(row=2, column=0, padx=5, pady=5)
root.fromList = Combobox(root, width=10, values=currencyList, state="readonly")
root.fromList.grid(row=3, column=0, padx=5, pady=5)
root.fromList.set("INR")
toLabel = Label(root, text="TO : ", bg="peachpuff4")
toLabel.grid(row=2, column=2, padx=5, pady=5)
root.toList = Combobox(root, width=10, values=currencyList, state="readonly")
root.toList.grid(row=3, column=2, padx=5, pady=5)
root.toList.set("INR")
convertButton = Button(root, text="CONVERT", width=15, command=Convert)
convertButton.grid(row=4, column=0, columnspan=3, padx=5, pady=5)
exrateLabel = Label(root, text="EXCHANGE RATE : ",bg="peachpuff4")
exrateLabel.grid(row=5, column=0, padx=5, pady=5, columnspan=2)
root.exrate = Label(root, width=14, font=('',20), bg='snow3', justify="center")
root.exrate.grid(row=5, column=2, padx=5, pady=5)
outputLabel = Label(root, text="CONVERTED AMT : ", bg="peachpuff4")
outputLabel.grid(row=6, column=0,padx=5, pady=5, columnspan=2)
root.outputAMT = Label(root, width=14, font=('',20), bg="snow3", justify="center")
root.outputAMT.grid(row=6, column=2, padx=5, pady=5, columnspan=2)
# Defining Convert() function for converting the curreny
def Convert():
# Fetching & storing user-inputs in resepective variables
# Converting user-input amount which is a string into float type
inputAmt = float(getAMT.get())
from_Currency = root.fromList.get()
to_Currency = root.toList.get()
# Storing the API Key from https://www.alphavantage.co/
apiKey = "Y2ULPCBPVNI7CD31"
# Storing the base URL
baseURL = r"https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE"
# Storing the complete URL
reqURL = baseURL+"&from_currency="+from_Currency+"&to_currency="+to_Currency+"&apikey="+apiKey
# Sending the request to URL & Fetching and Storing the response in response variable
response = requests.get(reqURL)
# Returning the JSON object of the response and storing it in result
result = response.json()
# Getting the exchange rate (Required Information)
exchangeRate = float(result["Realtime Currency Exchange Rate"]['5. Exchange Rate'])
# Displaying exchange rate in respective label after rounding to 2 decimal places
root.exrate.config(text=str(round(exchangeRate, 2)))
# Calculating the converted amount and rounding the decimal to 2 places
calculateAmt = round(inputAmt * exchangeRate, 2)
# Displaying the converted amount in the respective label
root.outputAMT.config(text=str(calculateAmt))
# Creating object of tk class
root = tk.Tk()
# Setting title, background color & size of tkinter window
# & disabling the resizing property
root.geometry("350x250")
root.resizable(False, False)
root.title("PythonCurrenyConverter")
root.config(bg = "peachpuff4")
# Creating tkinter variables
getAMT = StringVar()
fromCurrency = StringVar()
toCurrency = StringVar()
# Calling the CreateWidgets() function
CreateWidgets()
# Defining infinite loop to run application
root.mainloop()
|
"""
题目022:两个乒乓球队进行比赛,各出三人。
甲队为a,b,c三人,乙队为x,y,z三人。
已抽签决定比赛名单。有人向队员打听比赛的名单。
a说他不和x比,c说他不和x,z比,请编程序找出三队赛手的名单。
"""
def t22():
for a in ['x', 'y', 'z']:
for b in ['x', 'y', 'z']:
for c in ['x', 'y', 'z']:
if a != b and b != c and c != a:
if a != 'x' and c != 'x' and c != 'z':
print('a' + a, 'b' + b, 'c' + c)
"""
题目023:
打印出如下图案(菱形):
*
***
*****
*******
*****
***
*
"""
def t23():
num = 7
for i in range(num):
blank = abs(num // 2 - i)
print(' ' * blank + '*' * (num - 2 * blank))
"""
题目026:利用递归方法求5!。
"""
def fac(x):
if x > 1:
return x * fac(x - 1)
else:
return x
def t26():
print(fac(5))
"""
利用递归函数调用方式,将所输入的5个字符,以相反顺序打印出来。
"""
def output(s, length):
if length == 0:
return
print(s[length - 1])
output(s, length - 1)
def t27():
s = input('please input a string:')
length = len(s)
output(s, length)
"""
题目029:给一个不多于5位的正整数,
要求:一、求它是几位数,二、逆序打印出各位数字。
"""
def t29():
s = str(input('please input a number:'))
print(len(s))
print(s[::-1])
"""
题目030:一个5位数,判断它是不是回文数。即12321是回文数,个位与万位相同,十位与千位相同
"""
def t30():
s = str(input('please input a number:'))
l = len(s)
for i in range(l // 2):
if s[i] != s[- i - 1]:
print('false')
break
else:
print('true')
"""
题目031:请输入星期几的第一个字母来判断一下是星期几,如果第一个字母一样,则继续判断第二个字母。
"""
def t31():
week = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']
inp = input('please input a alf:')
arr = []
for day in week:
if inp == day[:len(inp)]:
arr.append(day)
if len(arr) > 0:
print(arr[:len(arr)])
elif len(arr) == 0:
print('none')
"""
32.按相反的顺序输出列表的值
"""
def t32():
# 方法一
a = [1, 2, 3, 4, 5]
print(a[::-1])
# 方法二
a = [1, 2, 3, 4, 5]
a.reverse()
print(a)
# 方法三
a = [1, 2, 3, 4, 5]
a.sort(reverse=True)
print(a)
"""
题目036:求100之内的素数
"""
def t36():
arr = [2]
for i in range(3, 100):
for j in range(2, i):
if i % j == 0:
break
else:
arr.append(i)
print(arr)
"""
题目037:对10个数进行排序
"""
def t37():
a = [1, 4, 7, 3, 9, 0, 5, 2, 1, 6]
a.sort()
print(a)
"""
题目038:求一个3*3矩阵主对角线元素之和。
"""
def t38():
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
s = 0
n = len(a)
for i in range(n):
s += a[i][i]
print(s)
"""
题目039:有一个已经排好序的数组。现输入一个数,要求按原来的规律将它插入数组中。
"""
def t39():
aaa = [1, 5, 8, 14, 28, 39, 60, 89, 134, 324, 612, 900]
b = 555
for a in aaa:
if b > a:
aaa.insert(aaa.index(a), b)
break
else:
aaa.append(b)
print(aaa)
"""
题目044:两个3*3的矩阵,实现其对应位置的数据相加,并返回一个新矩阵:
"""
def t40():
import numpy as np
x = np.array([[12, 7, 3], [4, 5, 6], [7, 8, 9]])
y = np.array([[5, 8, 1], [6, 7, 3], [4, 5, 9]])
z = x + y
print(z)
"""
题目045:统计 1 到 100 之和。
"""
def t45():
s = 0
for i in range(101):
s += i
print(s)
print(sum(range(1, 101)))
# 666
"""
题目046:求输入数字的平方,如果平方运算后小于 50 则退出。
"""
def t46():
while 1:
x = int(input('please input a number:'))
print(x * x)
if x * x < 50:
break
"""
题目047:两个变量值互换
"""
def t47():
a, b = 50, 60
a, b = b, a
print(a, b)
"""
题目062:查找字符串。
"""
def t62():
s = 'abcdefg'
print(s.find('c'))
"""
题目066:输入3个数a,b,c,按大小顺序输出。
"""
def t66():
arr = []
for i in range(3):
a = int(input('please input a num:'))
arr.append(a)
arr.sort(reverse=True)
print(arr)
"""
题目067:输入数组,最大的与第一个元素交换,最小的与最后一个元素交换,输出数组
"""
def t67():
a = [6, 3, 10, 2, 5, 1, 4, 7, 9, 8]
i = a.index(max(a))
a[0], a[i] = a[i], a[0]
i = a.index(min(a))
a[-1], a[i] = a[i], a[-1]
print(a)
"""
题目068:有n个整数,使其前面各数顺序向后移m个位置,最后m个数变成最前面的m个数
"""
def t68():
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
m = 3
b = a[-m:] + a[:-m]
print(b)
# 666
"""
题目070:写一个函数,求一个字符串的长度,在main函数中输入字符串,并输出其长度
"""
def t70():
def geylength(string):
return len(string)
if __name__ == '__main__':
x = 'abcde'
print(geylength(x))
"""
题目076:编写一个函数,输入n为偶数时,调用函数求1/2+1/4+...+1/n,当输入n为奇数时,调用函数1/1+1/3+...+1/n
"""
def t76():
n = int(input('please input a num:'))
s = sum(1 / i for i in range(n, 0, -2))
print(s)
# 666
"""
题目078:找到年龄最大的人,并输出
"""
def t78():
person = {"li": 18, "wang": 50, "zhang": 20, "sun": 22}
name, age = '', 0
for p in person.keys():
if person.get(p) > age:
name, age = p, person.get(p)
print(name, age)
"""
题目080:海滩上有一堆桃子,五只猴子来分。
第一只猴子把这堆桃子平均分为五份,多了一个,
这只猴子把多的一个扔入海中,拿走了一份。
第二只猴子把剩下的桃子又平均分成五份,又多了一个,
它同样把多的一个扔入海中,拿走了一份,
第三、第四、第五只猴子都是这样做的,
问海滩上原来最少有多少个桃子?
"""
def t80():
for total in range(2, 10000):
t = total
remain = lambda t: (t - 1) / 5 * 4
for i in range(5):
t = remain(t)
if t % 1 != 0:
break
else:
print(total, t)
break
"""
题目082:八进制转换为十进制
"""
def t82():
print(bin(10)) # 十转二
print(oct(10)) # 十转八
print(hex(10)) # 十转16
print(int('10', 8)) # 八转十
print(int('10', 2)) # 二转十
print(int('10', 16)) # 16转十
"""
题目083:求0—7所能组成的奇数个数。
"""
def t83():
s = [i for i in '01234567']
import itertools
arr = []
for i in range(1, 9):
a = list(itertools.permutations(s, i))
l = list(map(lambda x: int(''.join(x)), a))
arr += l
print(i, len(l))
arr1 = set(arr)
arr2 = list(filter(lambda x: x % 2 == 1, arr1))
print(len(arr), len(arr1), len(arr2))
"""
题目085:输入一个奇数,然后判断最少几个 9 除于该数的结果为整数。
"""
def t85():
x = int(input('please input a number:'))
for i in range(1, 600):
if int('9' * i) % x == 0:
print(i)
break
else:
print('hehe')
"""
题目096:计算字符串中子串出现的次数
"""
def t96():
x = 'ababaabbaaa'
print(x.count('ab'))
"""
题目100:列表转换为字典。
"""
def t100():
l = ['ak17', 'b51', 'b52', '#64']
d = {}
for i in range(len(l)):
d[i] = l[i]
print(d)
|
def decorator_function(original_function):
def wrapper_function(*args, **kwargs):
print('wrapper executed this before {}'.format(original_function.__name__))
original_function(*args, **kwargs)
return wrapper_function
@decorator_function
def display(name, age):
print('Display Function Ran with {} and {}'.format(name,age))
# decorated_display = decorator_function(display)
# decorated_display()
display('john', 25)
class decorator_class(object):
def __init__(self,original_function):
self.original_function = original_function
def __call__(self, *args, **kwargs):
print('call method executed this before {}'.format(self.original_function.__name__))
return self.original_function(*args, **kwargs)
@decorator_class
def display2(name, age):
print('Display2 Function Ran with {} and {}'.format(name,age))
display2('Kitty', 34)
|
inputstr = input('Enter you statement:').split()
unq = []
for each in inputstr:
if each not in unq:
unq.append(each)
print(' '.join(unq))
|
def isprime(num):
for i in range(2,num-1):
if(num==2):
return True
elif(num%i==0):
break
else:
return True
def findnextprime(num):
prime =num
i=1
while(i==1):
prime=prime+1
if(isprime(prime)==True):
return(prime)
i=0
p=2
i=1
while(i<10001):
p=findnextprime(p)
i=i+1
print(p)
|
# Нэрсийн дарааллаас хамгийн богино нэрийг олж 'Сайн уу?' гэж соль.
names = ["danzanravjaa","bold","bat"]
print(names)
z = 99
for i in names:
urt = len(i)
if z >= urt:
z = urt
a = i
index = names.index(a)
names.insert(index,"Sain uu?")
print(names)
|
# Өгөгдсөн тоон дарааллыг буурахаар эрэмбэл.
nums = [int(x) for x in input().split()]
nums.sort()
nums.reverse()
print(nums)
print(sorted(nums, reverse=True))
|
#!/bin/python
#https://www.hackerrank.com/challenges/common-child/
import sys
def commonChild(s1, s2):
# Complete this function
lcs = []
m = len(s1)
n = len(s2)
for i in range(m):
lcs.append([0]*n)
for i in range(m):
if (s2[0] == s1[i]):
lcs[i][0] = 1
else:
lcs[i][0] = lcs[i-1][0]
for i in range(n):
if (s2[i] == s1[0]):
lcs[0][i] = 1
else:
lcs[0][i] = lcs[0][i-1]
for i in range(1,m):
for j in range(1,n):
if s1[i] == s2[j]:
lcs[i][j] = 1 + lcs[i-1][j-1]
else:
lcs[i][j] = max(lcs[i-1][j], lcs[i][j-1])
return lcs[m-1][n-1]
s1 = raw_input().strip()
s2 = raw_input().strip()
result = commonChild(s1, s2)
print(result)
|
#https://www.hackerrank.com/challenges/flatland-space-stations
#!/bin/python3
import sys
def flatlandSpaceStations(n, stations):
# Complete this function
stations.sort()
size = len(stations)
if size == 1:
return max(n-1-stations[0], stations[0] - 0)
diff = stations[1] - stations[0]
for i in range(1,size-1):
diff = max(diff, stations[i] - stations[i-1])
diff = max(int(diff/2), n-1 - stations[size-1], stations[0])
return int(diff)
if __name__ == "__main__":
n, m = input().strip().split(' ')
n, m = [int(n), int(m)]
c = list(map(int, input().strip().split(' ')))
result = flatlandSpaceStations(n, c)
print(result)
|
'''The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?'''
res = 0
primes = []
number = 600851475143
upper = number ** 0.5 + 1
i = 1
def isPrime(x):
if x % 2 == 0 or x < 3:
return False
else:
for i in range(3, int(x ** 0.5) + 1):
if x % i == 0:
return False
return True
assert isPrime(5)
assert not isPrime(4)
while i < upper:
if number % i == 0 and isPrime(i):
primes.append(i)
i += 1
print(max(primes))
|
running = True
epsilon = .01
guess = 1
counter = 0
while running:
try:
user_number = int(input("Please enter a Number: "))
if user_number < 0:
user_number = user_number * -1
running = False
except ValueError:
print("Enter a valid Number!!")
continue
thinking = True
while thinking:
best_guess = abs(user_number - guess**2)
if best_guess <= epsilon:
thinking = False
print("The Square Root of {} is {}". format(user_number,
round(guess, 2)))
else:
guess = (guess + user_number/guess) / 2
counter += 1
print("Guess number {} is {}". format(counter, round(guess, 2)))
|
from itertools import product
def generate_names():
"""Generate a list of random `adjective + noun` strings."""
adjectives = [
'Exquisite',
'Delicious',
'Elegant',
'Swanky',
'Spicy',
'Food Truck',
'Artisanal',
'Tasty',
]
nouns = [
'Sandwich',
'Pizza',
'Curry',
'Pierogi',
'Sushi',
'Salad',
'Stew',
'Pasta',
'Barbeque',
'Bacon',
'Pancake',
'Waffle',
'Chocolate',
'Gyro',
'Cookie',
'Burrito',
'Pie',
]
return [' '.join(parts) for parts in product(adjectives, nouns)]
|
#Function that prints total amount of coding exercises in a dictionary. Also uses.value function that returns values of a dictionary
num_exercises = {"functions": 10, "syntax": 13, "control flow": 15, "loops": 22, "lists": 19, "classes": 18, "dictionaries": 18}
total_exercises=0
for value in num_exercises.values():
total_exercises+=value
print(total_exercises)
|
# -*-coding:utf8
import hashmap
# create a mapping of states to abbreviation
states = hashmap.new()
hashmap.set(states, 'Oregon', 'OR')
hashmap.set(states, 'Florida', 'FL')
hashmap.set(states, 'California', 'CA')
hashmap.set(states, 'Nwe York', 'NY')
hashmap.set(states, 'Hawaii', 'HI')
cities = hashmap.new()
hashmap.set(cities, 'CA', 'Los Angeles')
hashmap.set(cities, 'HI', 'Honolulu')
hashmap.set(cities, 'FL', 'Orlando')
hashmap.set(cities, 'NY', 'New York')
hashmap.set(cities, 'OR', 'Portland')
print('-' * 10)
print("NY State has: %s" % hashmap.get(cities, 'NY'))
print("HI State has: %s" % hashmap.get(cities, 'HI'))
print('-' * 10)
print("Hawaii's abbreviation is: %s" % hashmap.get(states, 'Hawaii'))
print("Florida's abbreviation is: %s" % hashmap.get(states, 'Florida'))
print('-' * 10)
print('Hawaii has: %s' % hashmap.get(cities, hashmap.get(states, 'Hawaii')))
print('Florida has: %s' % hashmap.get(cities, hashmap.get(states, 'Florida')))
print('-' * 10)
hashmap.list(states)
print('-' * 10)
hashmap.list(cities)
print('-' * 10)
state = hashmap.get(states, 'Texas')
if not state:
print("Sorry, no Texas")
city = hashmap.get(cities, 'TX', 'Not Entered Yet')
print("The city for the state 'TX' is: %s" % city)
|
class Category:
def __init__(self, description):
self.description = description
self.ledger = []
def __str__(self):
ledger_str = (self.description).center(30, '*') + '\n'
for entry in self.ledger:
ledger_str = ledger_str + ((entry["description"]).ljust(23))[:23] + str("{:.2f}".format(entry["amount"])).rjust(7) + "\n"
ledger_str = ledger_str + "Total: " + str(self.get_balance())
return ledger_str
#A deposit method that accepts an amount and description. If no description is given, it should default to an empty string. The method should append an object to the ledger list in the form of {"amount": amount, "description": description}.
def deposit (self, amount, description=""):
self.ledger.append({"amount": amount, "description": description})
#A withdraw method that is similar to the deposit method, but the amount passed in should be stored in the ledger as a negative number. If there are not enough funds, nothing should be added to the ledger. This method should return True if the withdrawal took place, and False otherwise.
def withdraw (self, amount, description=""):
balance = self.get_balance()
if balance >= amount:
amount = amount * -1
self.ledger.append({"amount": amount, "description": description})
return True
else:
return False
#A get_balance method that returns the current balance of the budget category based on the deposits and withdrawals that have occurred.
def get_balance (self):
balance = 0
for entry in self.ledger:
balance = balance + entry["amount"]
return balance
#A transfer method that accepts an amount and another budget category as arguments. The method should add a withdrawal with the amount and the description "Transfer to [Destination Budget Category]". The method should then add a deposit to the other budget category with the amount and the description "Transfer from [Source Budget Category]". If there are not enough funds, nothing should be added to either ledgers. This method should return True if the transfer took place, and False otherwise.
def transfer (self,amount,category):
if self.check_funds(amount):
self.withdraw (amount, ("Transfer to " + category.description))
category.deposit (amount, ("Transfer from " + self.description))
return True
else:
return False
#A check_funds method that accepts an amount as an argument. It returns False if the amount is greater than the balance of the budget category and returns True otherwise. This method should be used by both the withdraw method and transfer method.
def check_funds (self, amount):
balance = self.get_balance()
if balance >= amount:
return True
else:
return False
#Besides the Category class, create a function (outside of the class) called create_spend_chart that takes a list of categories as an argument. It should return a string that is a bar chart
def create_spend_chart(categories = []):
cat_total_spend = {}
cat_perc_spend = {}
grand_total_spend = 0
for category in categories:
total = 0
for entry in category.ledger:
if entry["amount"] < 0:
total = total + (entry["amount"] * -1)
cat_total_spend[category.description] = total
grand_total_spend += cat_total_spend[category.description]
for category in categories:
cat_perc_spend[category.description] = int((100 / grand_total_spend * cat_total_spend[category.description]) // 10) * 10
counter = 100
chart = "Percentage spent by category\n"
while counter >= 0:
chart = chart + (str(counter) + "|").rjust(4) + " "
for category in categories:
if cat_perc_spend[category.description] >= counter:
chart = chart + "o "
else:
chart = chart + " "
chart = chart + '\n'
counter -= 10
chart = chart + " " + ("---" * len(categories)) + "-"
loop = True
counter = 0
while loop == True:
line = "\n "
checknamelength = False
for category in categories:
if len(category.description) >= counter + 1:
line = line + category.description[counter] + " "
checknamelength = True
else:
line = line + " "
if checknamelength == False:
loop = False
else:
chart = chart + line
counter += 1
return chart
|
"""
This module offers a solution to
the "Hamming" exercise on Exercism.io.
"""
import sys
def distance(strand_a: str, strand_b: str) -> int:
if len(strand_a) != len(strand_b):
raise ValueError("sequences not of equal length")
return [n_a == n_b for (n_a, n_b) in zip(strand_a, strand_b)].count(False)
def main():
argn_cmd = len(sys.argv)-1
argv_cmd = sys.argv[1:]
if argn_cmd == 2:
# pylint: disable=unbalanced-tuple-unpacking
dna_strand_a, dna_strand_b = argv_cmd
print(f"Hamming distance = {distance(dna_strand_a, dna_strand_b)}")
else:
raise SystemExit(f"Usage: {sys.argv[0]} dna_strand_a dna_strand_b")
if __name__ == '__main__':
main()
|
"""
This module offers a solution to
the "Isogram" exercise on Exercism.io.
"""
import sys
from typing import List
def is_isogram(string:str) -> bool:
def alpha_pos(c:str) -> int:
return ord(c) - ord("A") + 1
alphagram: List[int] = [None] + [0] * 26
for c in string:
if c.isalpha():
c_l_ap = alpha_pos(c.upper())
alphagram[c_l_ap] += 1
if alphagram[c_l_ap] > 1:
return False
return True
def main():
argn_cmd = len(sys.argv)-1
argv_cmd = sys.argv[1:]
def is_or_isnt_an_isogram(word:str) -> str:
return "is" \
+ ("" if is_isogram(word) else " not") \
+ " an isogram"
if argn_cmd == 1:
print(f"{argv_cmd[0]} {is_or_isnt_an_isogram(argv_cmd[0])}")
else:
raise SystemExit(f"Usage: {sys.argv[0]} word")
if __name__ == '__main__':
main()
|
# Exercise for Udemy course: python-for-data-science-and-machine-learning-bootcamp/
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn import metrics
import numpy as np
customers = pd.read_csv("data/customers.csv")
def linear_Regression():
global X, y_test, lm, y_pred
X = customers[["Avg. Session Length", "Time on App", "Time on Website", "Length of Membership"]]
y = customers["Yearly Amount Spent"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=101)
lm = LinearRegression()
lm.fit(X_train, y_train)
y_pred = pd.Series(lm.predict(X_test))
def analysis_before_prediction():
print(customers.head())
print(customers.info())
print(customers.describe())
print(customers.columns)
sns.jointplot(x="Time on Website", y="Yearly Amount Spent", data=customers)
sns.jointplot(x="Time on App", y="Yearly Amount Spent", data=customers)
sns.jointplot(x="Time on App", y="Length of Membership", data=customers, kind="hex")
sns.pairplot(data=customers)
sns.lmplot(x="Length of Membership", y="Yearly Amount Spent", data=customers)
sns.pairplot(customers)
sns.distplot(customers["Yearly Amount Spent"])
sns.heatmap(customers.corr(), cmap="coolwarm")
def analysis_after_prediction():
coeff_df = pd.DataFrame(lm.coef_, X.columns, columns=['Coefficient'])
plt.scatter(y_test.values, y_pred.values)
plt.xlabel('Y Test')
plt.ylabel('Predicted Y')
# plot the residuals
sns.displot((y_test - y_pred), bins=50)
print(coeff_df)
print('MAE:', metrics.mean_absolute_error(y_test, y_pred))
print('MSE:', metrics.mean_squared_error(y_test, y_pred))
print('RMSE:', np.sqrt(metrics.mean_squared_error(y_test, y_pred)))
# analysis_before_prediction()
linear_Regression()
analysis_after_prediction()
plt.show()
|
# Skill Challenges for Udemy course: The Ultimate Pandas Bootcamp: Advanced Python Data Analysis
# Not cleaned
import pandas as pd
tech_giants = pd.read_csv("data//tech_giants.csv", index_col=["date", "name"])
print(tech_giants.info())
print(tech_giants.head())
tech_df2 = tech_giants.loc[(slice("2015-07-13", "2016-08-17"), slice(None))]
tech_df2_xs = tech_giants.xs(slice("2015-07-13", "2016-08-17"), level=(0))
print(tech_df2)
aapl = tech_df2.loc[(slice(None), "AAPL"), :]
aapl_xs = tech_df2.xs(("AAPL"), level=(1))
print(aapl.sample(10))
ex3 = tech_df2.loc[(slice(None), ["AAPL", "GOOGL"]), ["low", "high"]]
print(ex3)
# year month day
tech_df3 = tech_df2.set_index(["year", "month", "day"])
print(tech_df3.head())
print(tech_df3.loc[(2015, slice(None), slice(None))])
tech_series = tech_df3.stack()
print(tech_series.loc[(slice(None), slice(None), slice(None), "close")].mean())
print(tech_series.loc[(slice(None), slice(None), slice(None), "close")].std())
|
import pandas as pd
import numpy as np
df = pd.read_csv("pandas_tutorial.csv", index_col="S.No", dtype={"Salary": np.float64})
print(df)
df = pd.read_csv("pandas_tutorial.csv", dtype={"Salary": np.float64}, names=["a", "b", "c", "d", "e"])
print(df)
# remove header
df = pd.read_csv("pandas_tutorial.csv", dtype={"Salary": np.float64}, names=["a", "b", "c", "d", "e"], header=0)
print(df)
# skiprows
df = pd.read_csv("pandas_tutorial.csv", dtype={"Salary": np.float64}, names=["a", "b", "c", "d", "e"], skiprows=2)
print(df)
print("---------------------------")
# using If/Truth with pandas:
s = pd.Series([True, False, True])
if s.any():
print("True")
else:
print("False")
if s.all():
print("True")
else:
print("False")
# To evaluate single-element pandas objects in a Boolean context, use the method .bool()
print(pd.Series([True]).bool())
# bitwise boolean
s = pd.Series(range(5))
print(s == 4)
# isin operation
s = pd.Series(list("abc"))
print(s.isin(list("abe")))
df = pd.DataFrame(np.random.randn(6, 4), columns=['one', 'two', 'three',
'four'], index=list('abcdef'))
print(df)
print(df.reindex(['b', 'c', 'e']))
|
import math
def quadratic(a, b, c):
if not isinstance(a, (int, float)) or not isinstance(b, (int, float)) or not isinstance(c, (int, float)):
raise TypeError('bad operand type')
x1 = (-b + math.sqrt(b * b - 4 * a * c)) / 2 * a
x2 = (-b - math.sqrt(b * b - 4 * a * c)) / 2 * a
return x1, x2
|
""" Create a user table in the blog database
"""
# coding: utf-8
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, String, Integer, Text
from sqlalchemy import ForeignKey
from sqlalchemy.orm import relationship
ENGINE = create_engine('mysql://root:931212emily@localhost:3306/blog')
Base = declarative_base()
class User(Base):
""" The mapping for table: user
"""
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
username = Column(String(64), nullable=False, index=True)
password = Column(String(64), nullable=False)
email = Column(String(64), nullable=False, index=True)
articles = relationship('Article')
def __repr__(self):
return '%s(%r)' % (self.__class__.__name__, self.username)
class Article(Base):
""" The mapping for table: article
Relation: one user own multiple article
"""
__tablename__ = 'articles'
id = Column(Integer, primary_key=True)
title = Column(String(255), nullable=False, index=True)
content = Column(Text)
user_id = Column(Integer, ForeignKey('users.id'))
author = relationship('User')
def __repr__(self):
return '%s(%r)' % (self.__class__.__name__, self.title)
Base.metadata.create_all(ENGINE)
|
# -*- coding: utf-8 -*-
class Singleton:
"""
Singleton class decorator can be used to implement any class of singleton case.
But it can't be multiple threading environment.
"""
def __init__(self, cls):
""" The command parameter is a class """
self._cls = cls
def Instance(self):
"""
Return the true instance
"""
try:
return self._instance
except AttributeError:
self._instance = self._cls()
return self._instance
def __call__(self):
raise TypeError('Singletons must be accessed through `Instance()`.')
def __instancecheck__(self, inst):
return isinstance(inst, self._decorated)
# Decorator
@Singleton
class A:
""" A class that need singleton mode """
def __init__(self):
pass
def display(self):
return id(self)
if __name__ == '__main__':
s1 = A.Instance()
s2 = A.Instance()
print(s1, s1.display())
print(s2, s2.display())
print(s1 is s2)
|
#!/usr/bin/env python3
def poly_derivative(poly):
if type(poly) is not list or len(poly) < 1:
return None
for coefficient in poly:
if type(coefficient) is not int and type(coefficient) is not float:
return None
for power, coefficient in enumerate(poly):
if power is 0:
derivative = [0]
continue
if power is 1:
derivative = []
derivative.append(power * coefficient)
while derivative[-1] is 0 and len(derivative) > 1:
derivative = derivative[:-1]
return derivative
|
# Hackerrank 30 Days of code Challenge
# https://www.hackerrank.com/domains/tutorials/30-days-of-code
# Day 8
import sys
N = int(sys.stdin.readline())
phonebook = dict()
for _ in range(N):
name, number = sys.stdin.readline().rstrip().split()
phonebook[name] = number
for _ in range(N):
name = sys.stdin.readline().rstrip()
# there is a testcase that the number of input names doesn't match with N
if not name:
break
try:
phonebook[name]
print("{}={}".format(name, phonebook[name]))
except:
print("Not found")
|
# Hackerrank 30 Days of code Challenge
# https://www.hackerrank.com/domains/tutorials/30-days-of-code
# Day 26
real_day, real_month, real_year = list(map(int, input().split()))
expc_day, expc_month, expc_year = list(map(int, input().split()))
if real_year > expc_year:
print(10000)
elif real_year == expc_year:
if real_month > expc_month:
print((real_month - expc_month) * 500)
else:
if real_day > expc_day:
print((real_day - expc_day) * 15)
else:
print(0)
else:
print(0)
|
a=range(10)
for b in a:
print(b)
d=range(10,20)
for c in d:
print(c)
e=range(20,30,2)
for f in e:
print(f)
g=range(40,30,-1)
for h in g:
print(h)
|
while True:
name=input('Enter User Name:')
if name !='Rahul':
print('Enter the correct User Name')
continue
password=input('Hello , Rahul. What is the Password?')
if password !='Singh':
break
print('Access Granted')
|
import time
from playsound import playsound
#function for getting their alarm input
def get_alarm_time():
hours = float(input("Enter hour(24 hour system): "))
minute = float(input("Enter minute: "))
second = float(input("Enter second: "))
return (hours*60*60) + (minute*60) + second
#function for getting current time
def get_current_time():
return time.time()
#fuction to play audio
def for_ringing_the_bell():
playsound("/home/irondev/Downloads/alarm.mp3")
def stopwatch():
total_time = get_alarm_time() + get_current_time()
while total_time >= time.time():
continue
for_ringing_the_bell()
stopwatch()
|
# global variable
board = [['_', '_', '_'], ['_', '_', '_'], ['_', '_', '_']]
# games board
def print_board():
print(board[0][0] + ' ' + board[0][1] + ' ' + board[0][2])
print(board[1][0] + ' ' + board[1][1] + ' ' + board[1][2])
print(board[2][0] + ' ' + board[2][1] + ' ' + board[2][2])
# function for user input
def user_input_x(turn):
x = 0
print("Its %s turn:" % turn)
x = int(input("input x co-ordinate:"))
return x
def user_input_y(turn):
y = 0
y = int(input("input y co-ordinate:"))
return y
# game algorithm
def game_check():
if board[0][0] == board[0][1] == board[0][2] != '_':
print(board[0][0] + " Won")
return 'won'
elif board[1][0] == board[1][1] == board[1][2] != '_':
print(board[1][0] + " won")
return 'won'
elif board[2][0] == board[2][1] == board[2][2] != '_':
print(board[2][0] + " won")
return 'won'
elif board[0][0] == board[1][0] == board[2][0] != '_':
print(board[0][0] + " won")
return 'won'
elif board[0][1] == board[1][1] == board[2][1] != '_':
print(board[0][1] + " won")
return 'won'
elif board[0][2] == board[1][2] == board[2][2] != '_':
print(board[0][2] + " won")
return 'won'
elif board[0][0] == board[1][1] == board[2][2] != '_':
print(board[0][0] + " won")
return 'won'
elif board[0][2] == board[1][1] == board[2][0] != '_':
print(board[0][2] + " won")
return 'won'
else:
if no_of_blank_space() != 0:
return
else:
print("The math was draw!!!")
def no_of_blank_space():
space = 0
for row in board:
for ele in row:
if ele == '_':
space += 1
return space
# the main console
def play_ttt():
turn = 0
x = 0
y = 0
print("Welcome To TicTacToe")
print("Player 1 in O \nPlayer 2 is X")
print_board()
while no_of_blank_space() != 0:
x = user_input_x(turn)
y = user_input_y(turn)
if turn == 0:
board[x][y] = 'O'
turn = 1
else:
board[x][y] = 'X'
turn = 0
if game_check() == 'won':
print('\n')
print_board()
break
print('\n')
print_board()
print('\n')
option = 'y'
while option == 'y':
play_ttt()
print('\n')
option = input("Want to play again(y/n)")
|
"""
下面的文件将会从csv文件中读取读取短信与电话记录,
你将在以后的课程中了解更多有关读取文件的知识。
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
#返回只拨打电话的set
def getAllZhuJiao(calls):
zhujiao = set()
beijiao = set()
for call in calls:
zhujiao.add(call[0])
beijiao.add(call[1])
for ph in beijiao:
if ph in zhujiao:
zhujiao.remove(ph)
return zhujiao
allZhu = getAllZhuJiao(calls)
for sms in texts:
if sms[0] in allZhu:
allZhu.remove(sms[0])
if sms[1] in allZhu:
allZhu.remove(sms[1])
allZhuList = sorted(list(allZhu))
print("These numbers could be telemarketers: \n" + "\n".join(allZhuList))
"""
任务4:
电话公司希望辨认出可能正在用于进行电话推销的电话号码。
找出所有可能的电话推销员:
这样的电话总是向其他人拨出电话,
但从来不发短信、接收短信或是收到来电
请输出如下内容
"These numbers could be telemarketers: "
<list of numbers>
电话号码不能重复,每行打印一条,按字典顺序排序后输出。
"""
|
A = [1,5,7,10]
def function1(A):
summ = 0
for i in range(len(A)):
summ += A[i]
return summ
summa = function1(A)
print (summa)
def function2(A):
i=0
summ=0
while(i<len(A)):
summ += A[i]
i+=1
return summ
summa2=function2(A)
print(summa2)
def function3(A,i):
if i == 0:
return 0
else:
return A[i-1] + function3(A,i-1)
i=len(A)
summa3 = function3(A,i)
print (summa3)
"""def Sum(A):
if len(A)==1:
return A[0]
else:
return A[0]+Sum(A[1:])
summa4 = Sum(A)
print(summa4)"""
|
"""
DB作成
"""
# coding: utf-8
import sys
import sqlite3
def create_database():
# db作成
db = sqlite3.connect('db.sqlite3')
cur = db.cursor()
try:
sql = """
CREATE TABLE PARAM(
CD TEXT NOT NULL PRIMARY KEY,
VALUE TEXT NOT NULL,
NOTE TEXT,
CREATE_DATETIME TIMESTAMP DEFAULT (datetime(CURRENT_TIMESTAMP, 'localtime'))
)"""
cur.execute(sql)
sql = """
CREATE TABLE SERVER(
ID INTEGER NOT NULL PRIMARY KEY,
SERVER_ID TEXT NOT NULL,
FOLDER_NAME TEXT NOT NULL,
SHOW_MESSAGE INTEGER NOT NULL,
NOTE TEXT,
CREATE_DATETIME TIMESTAMP DEFAULT (datetime(CURRENT_TIMESTAMP, 'localtime')),
UNIQUE(ID, SERVER_ID)
)"""
cur.execute(sql)
sql = """
CREATE TABLE CHANNEL(
ID INTEGER NOT NULL PRIMARY KEY,
SERVER_ID TEXT NOT NULL,
CHANNEL_ID TEXT NOT NULL,
FOLDER_NAME TEXT NOT NULL,
NOTE TEXT
CREATE_DATETIME TIMESTAMP DEFAULT (datetime(CURRENT_TIMESTAMP, 'localtime')),
UNIQUE(ID, SERVER_ID, CHANNEL_ID)
)"""
cur.execute(sql)
db.commit()
db.close()
print('Table created.')
except sqlite3.Error as e:
print('sqlite3.Error occurred:{}'.format(e.args[0]), file=sys.stderr)
if __name__ == '__main__':
create_database()
|
import tensorflow as tf
import numpy as np
import tensorflow.examples.tutorials.mnist.input_data as input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
x_data = tf.placeholder(tf.float32, [None, 784])
y_data = tf.placeholder(tf.float32, [None, 10])
weight1 = tf.Variable(tf.ones([784, 256]))
bias1 = tf.Variable(tf.ones([256]))
y_model1 = tf.matmul(x_data, weight1) + bias1
weight2 = tf.Variable(tf.ones([256, 10]))
bias2 = tf.Variable(tf.ones([10]))
y_model2 = tf.nn.softmax(tf.matmul(y_model1, weight2) + bias2)
loss = -tf.reduce_sum(y_data * tf.log(y_model2))
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(loss)
# tf.argmax 0:按列计算,1:行计算
currect_prediction = tf.equal(tf.argmax(y_model2, 1), tf.argmax(y_data, 1))
# tf.cast张量数据类型转换
accuracy = tf.reduce_mean(tf.cast(currect_prediction, "float"))
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for i in range(1000):
batch_x, batch_y = mnist.train.next_batch(50)
sess.run(train_step, feed_dict={x_data: batch_x, y_data: batch_y})
if i % 50 == 0:
print(sess.run(accuracy, feed_dict={x_data: mnist.test.images, y_data: mnist.test.labels}))
|
#PPC Challange 7
name = input('What is your name?' )
age = int(input("What is your age? "))
birthday = age + 1
print("So your next birthday you are" birthday "?")
#Completed Successfully? Yes
#Did I have Errors? Nope
#How did I solve them? Didn't have any
#What Did I find difficult? figuring out my python math
|
import time
from test6 import player
import keyboard
def main():
print("Bienvenue dans l'Attaque des titans.\nIl n'en tient qu'a vous pour gagner !\n"
"Soyer vif et la victoire sera a vous !")
punch = 0
players = []
pseudo = []
while len(pseudo) < 2:
pseudo.append(str(input("Quel est votre nom combattant ?")))
print("Ce combat opposera donc {} à {}".format(pseudo[0], pseudo[1]))
n = m = 0
while n < 2:
players.append(player(str(pseudo[n]), 250, punch))
print("Le combattant qui entre dans l'arene est {} et il a actuellement {} point de vie \n"
"sortira t'il vainqueurs ?\nSeul l'avenir nous le dira\n".format((players[n].get_pseudo()),
(players[n].get_life())))
n += 1
time.sleep(1)
print("Bon maintenant les presentation faite\nPlace au combat!\n")
while n > 1:
print("{} c'est a toi que revient le droit de frapper".format((players[m].get_pseudo())))
while punch <= 100:
punch += 1
print(punch, sep=' ', end="\r")
if keyboard.is_pressed("ENTER"):
break
else:
if punch == 100:
time.sleep(0.01)
punch = 0
else:
time.sleep(0.01)
players[m] = (player(str(players[m].get_pseudo()), (players[m].get_life()), punch))
if m == 1:
players[m].attack_player(players[m - 1])
print("Vous avez infliger {} degats a {} il lui reste plus que {} point de vie".format(punch,
(players[
m - 1].get_pseudo()),
(players[
m - 1].get_life())))
if int(players[m - 1].get_life()) < 0:
del players[m - 1]
n -= 1
punch = 0
keyboard.release("ENTER")
time.sleep(2)
m = 0
else:
punch = 0
keyboard.release("ENTER")
time.sleep(2)
m = 0
else:
players[m].attack_player(players[m + 1])
print("Vous avez infliger {} degats a {} il lui reste plus que {} point de vie".format(punch,
(players[
m + 1].get_pseudo()),
(players[
m + 1].get_life())))
if int(players[m + 1].get_life()) < 0:
del players[m + 1]
n -= 1
punch = 0
keyboard.release("ENTER")
time.sleep(2)
m = 1
else:
punch = 0
keyboard.release("ENTER")
time.sleep(2)
m = 1
print("bravo {} vous avez gagner".format(players[0].get_pseudo()))
main()
|
def welcome():
print('Hello', end=' ')
print('Bob')
welcome()
def displayAge(age):
print(f'Your age: {age}')
displayAge(20)
#Utwórz funkcję zwracającą iloczyn dwóch liczb. Użytkownik podaje dane z klawiatury.
def iloczyn(a, b):
return a*b
first = float(input('Podaj pierwszą liczbę: '))
second = float(input('Podaj drugą liczbę: '))
print('Wynik mnożenia podanych liczb to:', iloczyn(first,second))
##############
def iloraz(a, b):
return a/b
print('Iloraz wynosi:', iloraz(2, 4))
print('Iloraz wynosi:', iloraz(b=2, a=4))
|
__author__ = 'ishaan'
from jinja2 import Template
from templates import *
import os
class GroupedField(object):
"""
Represents a Section like Work Experience , which can have multiple entries of the same fields
"""
def __init__(self, group, fields, required=False):
"""
Args -
group - Section under which fields will be grouped - ex:Education
fields - Fields which combine to make a single entry in the group
required - If specified , then atleast one entry should be present in the group
"""
self.group = group
self.fields = [Field(**f) for f in fields]
self.required = required
class Field(object):
"""
Represents a Single field in the Resume
"""
def __init__(self, text, required=False, default=None):
"""
Args -
text - Name of the field
required fields cannot be left blank
default - If a field is left blank and default is specified , then default value is used
"""
self.text = text
self.default = default
self.required = required
class Input(object):
def __init__(self, field):
self.field = field
def take_input(self):
"""
Takes Input from the User according to field type and Field constraints
"""
if isinstance(self.field, Field):
return Input.single_field_input(self.field)
elif isinstance(self.field, GroupedField):
print '\n' + self.field.group
data = []
while True:
if not self.field.required or len(data) >= 1:
inp = raw_input("\nDo you want to add " + self.field.group + '? (y or n)')
print '\n'
if inp in ('n', 'N'):
break
field_dict = {}
for f in self.field.fields:
temp = Input.single_field_input(f)
field_dict[f.text.lower().replace('-', '_')] = temp
data.append(field_dict)
return data
@staticmethod
def single_field_input(field):
while True:
temp = raw_input(field.text + '(Required: ' + str(field.required) + ')')
if not temp and field.required:
print "Field is required...Enter again"
continue
elif not temp and field.default:
return field.default
return temp
class Resume(object):
def __init__(self):
self.name = Input(Field("NAME", required=True)).take_input()
self.dob = Input(Field("DOB", required=True)).take_input()
self.email = Input(Field("EMAIL", required=True)).take_input()
self.address = Input(Field("ADDRESS", required=True)).take_input()
self.experience = Input(GroupedField('EXPERIENCE', [{'text': 'COMPANY', 'required': True},
{'text': 'TITLE', 'required': True},
{'text': 'START-DATE', 'required': True},
{'text': 'END-DATE', 'default': 'Present'},
{'text': 'DESCRIPTION'}
])).take_input()
self.education = Input(GroupedField('EDUCATION', [{'text': 'SCHOOL', 'required': True},
{'text': 'DEGREE', 'required': True},
{'text': 'START-DATE', 'required': True},
{'text': 'END-DATE', 'default': 'Present'},
{'text': 'DESCRIPTION'}
], required=True)).take_input()
self.skills = Input(Field('SKILLS')).take_input()
if __name__ == '__main__':
r = Resume()
name = r.name.strip()
while True:
opt = raw_input('EXPORT TO \n1:PLAIN TEXT\n2:CSV\n')
if opt == '1':
template = TXT_TEMPLATE
ext = '.txt'
break
elif opt == '2':
template = CSV_TEMPLATE
ext = '.csv'
break
print "Wrong Option..Try Again"
continue
t = Template(template)
file_name = name + ext
if not os.path.exists('resume'):
os.mkdir('resume')
with open('resume/' + file_name, 'w') as f:
f.write(t.render(resume=r))
print '\nFile saved as {name} in resume folder'.format(name=file_name)
|
"""
Faça um Programa que peça um número e então mostre a mensagem O número informado foi [número]
"""
number = input("digite um numero:")
print("o numero informado foi", number)
|
"""
Faça um programa que pergunte o preço de três produtos e informe qual produto você deve comprar,
sabendo que a decisão é sempre pelo mais barato
"""
produto_one = input("Digite o valor do produto um:")
produto_two = input("Digite o Valor do Produto dois:")
produto_tree = input("Digite o Valor do produto três:")
if not produto_one.isnumeric():
print("Entrada Invalida")
exit()
if not produto_two.isnumeric():
print("Entrada Invalida")
exit()
if not produto_tree.isnumeric():
print("Entrada Invalida")
exit()
produto_one = float(produto_one)
produto_two = float(produto_two)
produto_tree = float(produto_tree)
if produto_one < produto_two and produto_one < produto_tree:
print("Comprar Produto um")
elif produto_two < produto_one and produto_two < produto_tree:
print("Comprar Produto dois")
else:
print("Comprar o Produto três")
if
operadores relacionais
operadores lógicos
bloco de código
|
#https://programmers.co.kr/learn/courses/30/lessons/42627?language=python3
import heapq
def solution(jobs):
answer = 0
heapJob = []
start, now, end = -1, 0, 0
jobsAll = len(jobs)
while end < jobsAll:
for job in jobs:
if start < job[0] <= now:
heapq.heappush(heapJob, [job[1], job[0]])
if heapJob:
minJob = heapq.heappop(heapJob)
start = now
now += minJob[0]
answer += now - minJob[1]
end += 1
else:
now += 1
return answer // jobsAll
# heapJob : jobs의 최소힙
# start 변수 : 시작시간으로 처음에는 -1에서 0 범위의 작업을 찾아야되서 -1로 초기화
# now 변수 : 현재시간
# end 변수 : 완료된 작업의 수
# jobsAll : 작업의 수
# 1) while문으로 모든 작업을 완료할 때까지 실행
# 2) for문으로 주어진 작업을 반복
# 3) heapJob에 push(최소힙), 0번 인덱스를 기존으로 정렬되므로 0번 인덱스에 작업처리 시간 입력
# 4) 최소 힙에 작업이 들어와 있으면 최소힙으로 최소 시간(minJob) 작업 꺼냄
# 5) start 변수에 시작 시간에 현재 시간을 입력
# 6) now 변수에 현재시간에 최소시간 작업을 처리한 시간을 입력
# 7) answer에 현재시간 - 최소시간 작업을 입력받은 시점 입력
# 8) 작업을 처리하면 end +1
# 9) 최소힙에 아무것이 없어도 현재시간은 흘러야 되므로 +1
print(solution([[0, 3], [1, 9], [2, 6]]))
|
#https://programmers.co.kr/learn/courses/30/lessons/42746?language=python3
def solution(numbers):
answer = ''
num1 = [str(i)*3 for i in numbers]
nums = list(enumerate(num1))
nums.sort(key = lambda x:x[1], reverse = True)
for index, value in nums:
answer += str(numbers[index])
return str(int(answer))
solution([3, 30, 34, 5, 9] )
|
import unittest
import gensent
import nltk
class TestSentenceGenerator(unittest.TestCase):
sentence_list = [
'I am Sam, Sam-I-am.',
'That Sam-I-am.',
'That Sam-I-am.',
'I do not like that Sam-I-am.',
'Do you like green eggs and ham?'
]
def test_generator_unprepared(self):
"""Make sure an unprepared sentence generator throws an error."""
sentences = gensent.SentenceGenerator()
self.assertRaises(Exception, sentences._gen_sentences())
def test_two_passes(self):
"""Make sure we can make two passes over the sentence generator iterator."""
sentences = gensent.SentenceGenerator()
sentences.read_sentence_list(self.sentence_list)
#the list() function makes one pass over an iterator, so just do it 2x
self.assertEqual(list(sentences), list(sentences))
def test_process_sentence(self):
sentences = gensent.SentenceGenerator()
result = sentences._process_sentence(self.sentence_list[0])
correct = ['i', 'am', 'sam', 'sam-i-am']
self.assertEqual(result, correct)
def test_process_sentence_russian(self):
sentences = gensent.SentenceGenerator(language='russian', lemma=True)
result = sentences._process_sentence("Три девицы под окном Пряли поздно вечерком.")
correct = ['три', 'девица', 'под', 'окно', 'прясть', 'поздно', 'вечерок']
self.assertEqual(result, correct)
def test_process_US_money(self):
sentences = gensent.SentenceGenerator()
result = sentences._process_sentence("Breakfast cost me $5.60")
correct = ['breakfast', 'cost', 'me', sentences.NUM]
self.assertEqual(result, correct)
def test_process_EU_money(self):
sentences = gensent.SentenceGenerator()
result = sentences._process_sentence("Breakfast cost me €5.60")
correct = ['breakfast', 'cost', 'me', sentences.NUM]
self.assertEqual(result, correct)
def test_process_numbers(self):
sentences = gensent.SentenceGenerator()
result = sentences._process_sentence("Pi is 3.14159")
correct = ['pi', 'is', sentences.NUM]
self.assertEqual(result, correct)
def test_dutch(self):
sentences = gensent.SentenceGenerator(language='dutch', lemma=True)
result = sentences._process_sentence("Ik ga naar buiten toe")
correct = ['ik', 'gaan', 'naar', 'buiten', 'toe']
self.assertEqual(result, correct)
if __name__ == '__main__':
unittest.main()
|
from tkinter import *
from tkinter import messagebox
def call_me():
answer = messagebox.askquestion("Exit","Do you really want to exit ?")
if answer == 'yes':
root.quit()
root = Tk()
b = Button(root, text="Exit ?", command=call_me, fg="green", bg ="black")
b.pack(side = RIGHT,fill = Y)
root.minsize(300,300)
root.mainloop()
|
from tkinter import *
from tkinter import simpledialog
def get_me():
s = simpledialog.askstring("Ask","Enter your name:")
t = str(simpledialog.askfloat("Ask","Enter your weight:"))
u = str(simpledialog.askinteger("Ask","Enter your age:"))
info = ('Name:\t' + s + '\nWeight:\t' + t + '\nAge:\t' + u)
text.insert(INSERT,info)
root = Tk()
button = Button(root,text="PopUp",command=get_me)
button.pack()
text = Text(root, wrap=WORD, height=10,width=30)
text.pack(side=BOTTOM)
root.minsize(300,300)
root.mainloop()
|
def add(a,b):
return a + b
def prin():
print('Your answer is:')
print('start=')
x = int(input("Number 1:"))
y = int(input("Number 2:"))
result = add(x,y)
prin()
print(result)
|
x = 100
if x==10:
print('this is ten')
else:
print('this is not ten')
if x is 10:
print('ten')
if x is not 10:
print('this is not ten')
|
def reverseInParentheses(s):
for i in range(len(s)):
if s[i] == "(":
start = i
if s[i] == ")":
end = i
return reverseInParentheses(s[:start] + s[start + 1:end][::-1] + s[end + 1:])
return s
s = "foo(bar(baz))blim"
print(reverseInParentheses(s))
|
class Student:
def __init__(self,name,age):
self.name = name
self.age = age
def __str__(self):
return 'Name : '+self.name+'\nAge : '+str(self.age)
def __repr__(self):
return {'name':self.name, 'age':self.age}
s1 = Student("Meet",14)
print(s1)
print(s1.__repr__())
|
from tkinter import *
from tkinter.font import Font
root = Tk()
my_font = Font(size=16, family="algerian",weight="bold",slant="italic",underline=1,overstrike=1)
#here weight is the option where you can make text bold
text = Label(root,text="Meet Patel",font = my_font)
text.pack()
root.minsize(300,300)
root.mainloop()
|
import random
import math
import time
import sys
def get_random_robot_choice():
label = ["rock", "paper", "scissors"]
return label[random.randint(0, 2)]
def decide_winner(payer_one, robot_choice):
result = 0
print_result = ""
print("\nYou chose "+payer_one + " and Robot chose "+robot_choice)
if robot_choice == "rock":
if payer_one == "rock":
print_result += "DRAW!! Rock and Rock."
result = 1
elif payer_one == "paper":
print_result += "You win! Paper beats Rock!!"
result = 2
elif payer_one == "scissors":
print_result += "You lose. Rock beats Scissors."
elif robot_choice == "paper":
if payer_one == "rock":
print_result += "You lose. Paper beats Paper."
elif payer_one == "paper":
print_result += "DRAW!! Paper and Paper."
result = 1
elif payer_one == "scissors":
print_result += "You win! Scissors beats Paper!!"
result = 2
elif robot_choice == "scissors":
if payer_one == "rock":
print_result += "You win! Rock beats Scissors!!"
result = 2
elif payer_one == "paper":
print_result += "You lose. Scissors beats paper."
elif payer_one == "scissors":
print_result += "DRAW!! Scissors and scissors."
result = 1
print(print_result)
return result
class game:
def __init__(self, rounds, player_name):
self.rounds = rounds
self.player_name = player_name
self.player_score = 0
self.robot_score = 0
def play_game(self):
# for round in range(self.rounds):
current_round = 1
while True:
print("\n\n**********\n\n")
print("ROUND " + str(current_round) + " start!!")
print("Rock! ", end="", flush=True)
time.sleep(1)
print("Paper! ", end="", flush=True)
time.sleep(1)
print("Scissors! ", end="", flush=True)
time.sleep(1)
print("SHOOT!\n")
user_choice = input("Choose rock, paper or scissors? ")
robot_choice = get_random_robot_choice()
round_result = decide_winner(user_choice, robot_choice)
if round_result == 0: # lose
self.robot_score += 1
elif round_result == 1: # draw
if self.robot_score == self.player_score:
self.rounds += 1
elif round_result == 2: # win
self.player_score += 1
if self.rounds == current_round:
break
print("\n"+self.player_name + " score: " +
str(self.player_score))
print("ROBOT score: " + str(self.robot_score) + "\n")
current_round += 1
def print_results(self):
winner = "ROBOT"
results = "\n\n**********\n\n"
if self.player_score > self.robot_score:
winner = self.player_name
results += "YES! You are the WINNER!\n\n"
else:
results += "SORRY! You are such a loser!\n\n"
results += "The winner is " + winner + "!!\n"
results += self.player_name + " score: " + \
str(self.player_score) + "\n"
results += "ROBOT score: " + str(self.robot_score) + "\n"
results += "\n\n**********\n\n"
print(results)
new_game = game(3, "Gani")
new_game.play_game()
new_game.print_results()
|
"""calculates your updates-per-second"""
from __future__ import division
import time
class Updatefreq:
"""make one of these, call update() on it as much as you want,
and then float() or str() the object to learn the updates per second.
the samples param to __init__ specifies how many past updates will
be stored. """
def __init__(self,samples=20):
self.times=[0]
self.samples=samples
def update(self):
"""call this every time you do an update"""
self.times=self.times[-self.samples:]
self.times.append(time.time())
def __float__(self):
"""a cheap algorithm, for now, which looks at the first and
last times only"""
try:
hz=len(self.times)/(self.times[-1]-self.times[0])
except ZeroDivisionError:
return 0.0
return hz
def __str__(self):
return "%.2fHz"%float(self)
|
from lib.abstract_strategy import SortAlgorithm
class BubbleSort(SortAlgorithm):
def __init__(self, target_list: list):
super().__init__(target_list)
def sort(self) -> None:
n = len(self._target_list)
for i in range(n - 1):
for j in range(n - 1 - i):
if self._target_list[j] > self._target_list[j + 1]:
buff = self._target_list[j]
self._target_list[j] = self._target_list[j + 1]
self._target_list[j + 1] = buff
|
import string
a=list(string.ascii_lowercase+string.ascii_uppercase)
b=input()
c=[]
for i in list(b):
if (i in a) and (i not in c):
c.append(i)
if len(c)>=26:
print("yes")
else:
print("no")
|
'''def f(x):
return 2*x+3
print f(2)
print(3+4*6)
print f(f(6))
v=89
print f(v)
Task 1
def greater(x,y):
if x>y:
return x
else:
return y
x=float(raw_input("Enter your first number: "))
y=float(raw_input("Enter your second number: "))
print greater(x,y)
Task 2
def echo():
x= raw_input("Enter a string: ")
return x + x
print echo()'''
'Task 3'
'''def Display3(x,y,z):
v = x*y*z + 3
print v
Display3(2,3,4)'''
'''l = []
k = list()
j = [1,2,3,4,5,6,7,8,9,10]
print "The lists after clear is called on j"
print "l =", l
print "k =", k
print "j =", j
l.append('a')
k.append('t')
j.append(k)
print "The lists after an append"
print "l =", l
print "k =", k
print "j =", j
l.insert(0,'c')
k.insert(0,'h')
j.insert(5,12)
print "The lists after an insert"
print "l =", l
print "k =", k
print "j =", j
l =[2,3,6,7,8]
k =[4,1,5,12,13]
print "\nThe index of 5 in each list"
#print "l =", l
print "k =", k.index(5)
print "j =", j.index(5)
#Counting to 10 from 1
i = 1
while i <=10:
print i
i += 1
#Counting to 20 from 1
i = 1
while i <=20:
print i
i += 1
#Counting to 20 from 1, only EVEN numbers
i = 1
while i <=10:
if i % 2 == 0:
print i
i += 1
#Counting to 20 from 1, only ODD numbers
i = 1
while i <=10:
if i % 2 == 1:
print i
i += 1
v = ""
while v != "hello":
v = raw_input("Enter a string: ")'''
'''for i in range(1,10):
print i
for i in range(1,21):
print i
for i in range(2,21,2):
print i
for i in range(1,21):
if i % 2 == 0:
print i
for i in range(1,21):
if i % 2 == 1:
print i
for i in "This is a string":
print i
h = []
for i in range(20):
h.append(0)
print h, len(h)
h[1]=1
for i in range(2,20):
h[i] = h[i-1]
print h
d={}
b=dict()
a= {1:2,2:1,3:3,4:5,5:4}
c= {12:"Bob",89:"Jane"}
print a[1]
print c[89]
c[72]="Joe"
print c'''
class Person:
def __init__(self,name):
self.name = name
self.age = 0
def birthday(self):
self.age += 1
t= Person("Jane")
print t.name, t.age
s= Person("Roger")
print s.name,s.age
t.birthday()
print t.name, t.age
|
# Crie um programa que tenha uma tupla única com nomes de produtos e seus respectivos preços, na sequência.
# No final, mostre uma listagem de preços, organizando os dados em forma tabular.
#fazer o len da palavra loja de roupas e dividir o valor por 2, para ficar centralizado
#após isso, somar da metade do total de simbolos utilizados--> 60/2 + len('LOJA DE ROUPAS)/2 --> 37
print('='*60)
print(f'{"LOJA DE ROUPAS":>{37}}')
print('='*60)
produtos_precos=('camiseta',30,'camiseta floral',40,'camiseta social',50,'camisa regata',20,'moletom',90,'calça jeans',
60,'calça social',80,'cinto',40)
#para formatar, foi utilizado como valor total o número 60(referente ao print), menos o valor dos preços+o simbolo RS,totalizando 4 algarismos,resultando em 56 no total
#depois, foi reduzido pelo número de letras que cada produto continha
for c in range(0,len(produtos_precos),2):
print(produtos_precos[c],end='.'*(56-len(produtos_precos[c])))
print(f'R${produtos_precos[c+1]}')
print('='*60)
|
import random
def loto():
print ("Welcome to the Lottery numbers generator.")
vprasanje = raw_input("Please enter how many random numbers would you like to have: ")
try:
stevilo = int(vprasanje)
print loto(stevilo)
except ValueError:
print "Please enter a number."
print "END."
if __name__ == "__main__":
loto()
|
import requests
import json
city=input('input the city name: ')
url='http://api.openweathermap.org/data/2.5/weather?q={}&appid=56eeb1eb05170558d1333d044c94df18&units=metric'.format(city)
res= requests.get(url)
api=json.loads(res.content)
temp=api['main']['temp']
humidity=api['main']['humidity']
wind_speed=api['wind']['speed']
description=api['weather'][0]['description']
print('temp:{} Degree Celsius'.format(temp))
print('humidity: {} %'.format(humidity))
print('wind speed: {} m/s'.format(wind_speed))
print('Description:{} '.format(description))
print()
print('--------------------')
|
class Stack(list):
#stc_ is used to mark original or chaged methods of Stack obj
def stc_is_ismpty(self):
return self == []
def stc_get_size(self):
return len(self)
def _last_idx(self):
return self.stc_get_size() - 1
def stc_push(self, something):
self.append(something)
def stc_pop(self):
return self.pop()
def stc_top(self):
return self[self._last_idx()]
my_stack = Stack([1,2,3,4,5,6])
print(my_stack)
print(my_stack.stc_is_ismpty())
my_stack.stc_push(7)
print(my_stack)
print(my_stack.stc_top())
print(my_stack.stc_pop())
print(my_stack)
print(my_stack.stc_get_size())
|
line = input("Enter some words separated with SPACE, I`ll find the longest: ")
my_list = line.split(" ")
#print(my_list)
my_dict = dict.fromkeys(my_list, 0)
for elem in my_list:
my_dict[elem] = len(elem)
#print(my_dict)
moda = max(my_dict.values())
my_list.clear()
for key in my_dict:
if my_dict[key] == moda:
my_list.append(key)
print("The longest word is " + max(my_list))
|
height = int(input(" Height :"))
x_range = 2*(height - 1)
new_height = x_range // 2
for x in range(x_range,-1,-1):
k_range = abs(x - new_height)
j_range = 2*(height - k_range) - 1
for k in range(k_range):
print(" ",end="")
for j in range(j_range):
print("*",end="")
print()
print('''
................ Without nested loop..................''')
for x in range(x_range,-1,-1):
k = abs(x - new_height)
j = 2*(height - k) - 1
s = " " * k + "*" * j
print(s)
|
def fact(n):
if (n<2):
return 1
return n*fact(n-1)
q = None
while(q!= "q"):
x = int(input("Enter the number :"))
p = fact(x)
print("Factorial of ",x," :",p)
q = input("Press q to exit , any other key to continue :")
|
# Measure the execution time for small bits of python code
import timeit
# s = "-".join(map(str, range(100)))
# print(s)
print(timeit.timeit('"_".join(str(n) for n in range(100))', number=10000))
print(timeit.timeit('"-".join([str(n) for n in range(100)])', number=10000))
print(timeit.timeit('"-".join(map(str, range(100)))', number=10000))
|
from turtle import Turtle, Screen
from random import randint, choice
ballspeed = 10
playerspeed = 30
cursor_size = 20
player_height = 60
player_width = 20
court_width = 800
court_height = 600
FONT = ("Arial", 44, "normal")
def draw_border():
border.pensize(3)
border.penup()
border.setposition(-court_width/2, court_height/2)
border.pendown()
border.forward(court_width)
border.penup()
border.sety(-court_height/2)
border.pendown()
border.backward(court_width)
def filet():
border.penup()
border.pensize(1)
border.setposition(0, -court_height/2)
border.setheading(90)
border.pendown()
for _ in range(court_height // 50):
border.forward(50 / 2 + 1)
border.penup()
border.forward(50 / 2 + 1)
border.pendown()
# Player 1 Movement
def up1():
y = player1.ycor()
y += playerspeed
if y < court_height/2 - player_height/2:
player1.sety(y)
def down1():
y = player1.ycor()
y -= playerspeed
if y > player_height/2 - court_height/2:
player1.sety(y)
# Player 2 movement
def up2():
y = player2.ycor()
y += playerspeed
if y < court_height/2 - player_height/2:
player2.sety(y)
def down2():
y = player2.ycor()
y -= playerspeed
if y > player_height/2 - court_height/2:
player2.sety(y)
def reset_ball():
ball.setposition(0, 0)
ball.setheading(choice([0, 180]) + randint(-60, 60))
def distance(t1, t2):
my_distance = t1.distance(t2)
if my_distance < player_height/2:
t2.setheading(180 - t2.heading())
t2.forward(ballspeed)
# Mainloop
def move():
global score1, score2
ball.forward(ballspeed)
x, y = ball.position()
if x > court_width/2 + cursor_size: # We define scoring
score1 += 1
s1.undo()
s1.write(score1, font=FONT)
reset_ball()
elif x < cursor_size - court_width/2:
score2 += 1
s2.undo()
s2.write(score2, font=FONT)
reset_ball()
elif y > court_height/2 - cursor_size or y < cursor_size - court_height/2:
# We define the border collision
ball.setheading(-ball.heading())
else:
# Check collision between players and ball
distance(player1, ball)
distance(player2, ball)
screen.ontimer(move, 20)
# screen
screen = Screen()
screen.title("Pong")
screen.bgcolor("#fa6800")
screen.setup(width=1.0, height=1.0)
# border
border = Turtle(visible=False)
border.speed('fastest')
border.color("white")
draw_border()
filet()
# Ball
ball = Turtle("circle")
ball.color("white")
ball.penup()
ball.speed("fastest")
reset_ball()
# Player 1
player1 = Turtle("square")
player1.turtlesize(player_height / cursor_size, player_width / cursor_size)
player1.color("white")
player1.penup()
player1.setx(cursor_size - court_width/2)
player1.speed("fastest")
# Player 2
player2 = Turtle("square")
player2.shapesize(player_height / cursor_size, player_width / cursor_size)
player2.color("white")
player2.penup()
player2.setx(court_width/2 + cursor_size)
player2.speed("fastest")
# Player 1 score
score1 = 0
s1 = Turtle(visible=False)
s1.speed("fastest")
s1.color("white")
s1.penup()
s1.setposition(-court_width/4, court_height/3)
s1.write(score1, font=FONT)
# Player 2 score"s
score2 = 0
s2 = Turtle(visible=False)
s2.speed("fastest")
s2.color("white")
s2.penup()
s2.setposition(court_width/4, court_height/3)
s2.write(score2, font=FONT)
# We assign s/z to move the player 1
screen.onkey(up1, "w")
screen.onkey(down1, "s")
# We assign up and down arrow to move the player 2
screen.onkey(up2, "Up")
screen.onkey(down2, "Down")
# Restart
screen.onkey(reset_ball, "p")
screen.listen()
move()
screen.mainloop()
|
bit: int = int(input())
A = [0] * bit
def binary(n):
if n < 1:
print(A)
else:
A[n - 1] = 0
binary(n - 1)
A[n - 1] = 1
binary(n - 1)
binary(bit)
|
# -*- coding:utf-8 -*-
# 导入两个方法
from sys import argv
from os.path import exists
# 定义两个变量
script, from_file, to_file = argv
# 打印from_file,to_file变量
print "Coping from %s to %s" % (from_file, to_file)
# we could do these two on one line too, how?
# 用变量in_file存储文件内容
in_file = open(from_file)
# 读取文件
indata = in_file.read()
# 打印数据长度
print "The input file is %d bytes long" % len(indata)
print "Does the output file exist? %r" % exists(to_file)
print "Ready, hit RETURN to continue, CTRL-C to abort."
# 键盘输入
raw_input()
# 用写的方式打开文件
out_file = open(to_file, 'w')
# 向文件写入内容
out_file.write(indata)
print "Alright, all done."
# 关闭文件
out_file.close()
in_file.close()
|
# 5. 最长回文子串
# 给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。
class Solution:
def longestPalindrome(self, s):
# 中心扩散法
size = len(s)
if size == 0:
return ''
# 最短回文串的长度至少是 1
longest_palindrome = 1
longest_palindrome_str = s[0]
for i in range(size):
palindrome_odd_str, odd_len = self.__center_spread(s, size, i, i)
palindrome_even_str, even_len = self.__center_spread(s, size, i, i + 1)
# 当前找到的最长回文子串
cur_max_sub = palindrome_odd_str if odd_len >= even_len else palindrome_even_str
if len(cur_max_sub) > longest_palindrome:
longest_palindrome = len(cur_max_sub)
longest_palindrome_str = cur_max_sub
return longest_palindrome_str
def __center_spread(self, s, size, index_left, index_right):
# left = right 的时候,表示回文中心是一条线,回文串的长度是奇数
# right = left + 1 的时候,表示回文中心是任意一个字符,回文串的长度是偶数
# 返回当前得到的回文子串和回文子串的长度
left = index_left
right = index_right
while left >= 0 and right < size and s[left] == s[right]:
left -= 1
right += 1
return s[left + 1:right], right - left - 1
if __name__ == '__main__':
solution = Solution()
s = "babad"
longestPalindrome = solution.longestPalindrome(s)
print(longestPalindrome)
|
# 53. 最大子序和
# 给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
# 动态规划
from typing import List
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
size = len(nums)
if size == 0:
return 0
# 起名叫 pre 表示的意思是“上一个状态”的值
pre = nums[0]
res = pre
for i in range(1, size):
pre = max(nums[i], pre + nums[i])
res = max(res, pre)
return res
if __name__ == '__main__':
s = Solution()
nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
result = s.maxSubArray(nums)
print(result)
|
# https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array/description/
# 给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。
# 不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。
# 给你一个已经排好序的数组,删除重复的元素,是原地删除,相同元素只保留一个,返回数组的长度。
# 应该充分利用排好序的数组这个特性来完成。
# 应该注意到一些特殊的测试用例,例如 nums = [] 的时候。注意,题目要求返回新数组的长度。
class Solution:
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 0:
return 0
current_num = nums[0]
j = 1
for i in range(1, len(nums)):
if nums[i] == current_num:
pass
else: # 如果不一样
current_num = nums[i]
nums[j] = nums[i]
j += 1
for i in range(len(nums) - j):
nums.pop()
return j
if __name__ == '__main__':
s = Solution()
nums = [1, 1, 1, 1, 1, 2, 2]
# nums = [1, 1, 2]
# nums = []
res = s.removeDuplicates(nums)
print(nums)
print(res)
|
# 126. 单词接龙 II 困难
# 给定两个单词(beginWord 和 endWord)和一个字典 wordList,找出所有从 beginWord 到 endWord 的最短转换序列。转换需遵循如下规则:
#
# 每次转换只能改变一个字母。
# 转换过程中的中间单词必须是字典中的单词。
# 说明:
#
# 如果不存在这样的转换序列,返回一个空列表。
# 所有单词具有相同的长度。
# 所有单词只由小写字母组成。
# 字典中不存在重复的单词。
# 你可以假设 beginWord 和 endWord 是非空的,且二者不相同。
class Solution:
def findLadders(self, beginWord, endWord, wordList):
"""
:type beginWord: str
:type endWord: str
:type wordList: List[str]
:rtype: List[List[str]]
"""
|
from typing import List
class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
# 判断存在重复元素的索引之差小于某个数
# 先判断 nums [i] = nums [j]
# 然后判断索引值是否相等,所以索引值可以用 map 存起来。
size = len(nums)
if size == 0:
return False
map = dict()
for i in range(size):
if nums[i] in map and i - map[nums[i]] <= k:
# 只要找到 1 个符合题意的就返回
return True
# 更新为最新的索引,这里有贪心选择的思想,索引越靠后,符合题意的数据对的存在性就越大
map[nums[i]] = i
return False
if __name__ == '__main__':
nums = [1, 2, 3, 1]
k = 3
solution = Solution()
result = solution.containsNearbyDuplicate(nums, k)
print(result)
|
# 130. 被围绕的区域
# 给定一个二维的矩阵,包含 'X' 和 'O'(字母 O)。
# 找到所有被 'X' 围绕的区域,并将这些区域里所有的 'O' 用 'X' 填充。
# https://segmentfault.com/a/1190000012898131
class Solution:
def solve(self, board):
"""
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""
global m, n, directions
m = len(board)
if m == 0:
return
n = len(board[0])
directions = [(-1, 0), (0, -1), (1, 0), (0, 1)]
for row_index in range(m):
self.__flood_fill(board, row_index, 0)
self.__flood_fill(board, row_index, n - 1)
for col_index in range(1, n - 1):
self.__flood_fill(board, 0, col_index)
self.__flood_fill(board, m - 1, col_index)
for i in range(m):
for j in range(n):
if board[i][j] == 'O':
board[i][j] = 'X'
if board[i][j] == '-':
board[i][j] = 'O'
def __flood_fill(self, board, x, y):
if 0 <= x < m and 0 <= y < n and board[x][y] == 'O':
board[x][y] = '-'
for direction in directions:
new_x = x + direction[0]
new_y = y + direction[1]
self.__flood_fill(board, new_x, new_y)
if __name__ == '__main__':
# board = [['X', 'X', 'X', 'X'],
# ['X', 'O', 'O', 'X'],
# ['X', 'X', 'O', 'X'],
# ['X', 'O', 'X', 'X']]
board = [['O', 'O', 'O'],
['O', 'O', 'O'],
['O', 'O', 'O']]
# board = [["X", "O", "X", "O", "X", "O"],
# ["O", "X", "O", "X", "O", "X"],
# ["X", "O", "X", "O", "X", "O"],
# ["O", "X", "O", "X", "O", "X"]]
solution = Solution()
solution.solve(board)
for row in board:
print(row)
|
from typing import List
class Solution:
def letterCasePermutation(self, S: str) -> List[str]:
size = len(S)
if size == 0:
return []
res = []
arr = list(S)
self.__dfs(arr, size, 0, res)
return res
def __dfs(self, arr, size, index, res):
if index == size:
return res.append(''.join(arr))
# 先把当前加到 pre 里面
self.__dfs(arr, size, index + 1, res)
# 如果是字母,就变换大小写
if arr[index].isalpha():
if ord(arr[index]) > 90:
arr[index] = chr(ord(arr[index]) - 32)
else:
arr[index] = chr(ord(arr[index]) + 32)
self.__dfs(arr, size, index + 1, res)
if __name__ == '__main__':
solution = Solution()
S = 'a1b2'
res = solution.letterCasePermutation(S)
print(res)
print(ord('z'))
print(ord('Z'))
|
# 219. 存在重复元素 II
# 给定一个整数数组和一个整数 k,
# 判断数组中是否存在两个不同的索引 i 和 j,
# 使得 nums [i] = nums [j],并且 i 和 j 的差的绝对值最大为 k。
class Solution:
def containsNearbyDuplicate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
|
# 154. 寻找旋转排序数组中的最小值 II
# 假设按照升序排序的数组在预先未知的某个点上进行了旋转。
# ( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。
# 请找出其中最小的元素。
# 注意数组中可能存在重复的元素。
from typing import List
class Solution:
def findMin(self, nums: List[int]) -> int:
size = len(nums)
# 根据题意,没有必要单独判断 size = 0 的情况
left = 0
right = size - 1
while left < right:
# mid = left + (right - left) // 2
mid = (left + right) >> 1
if nums[left] > nums[mid]:
# [9,1,2,3, 4, 5,6,7,8]
# mid
# mid 的右边可以被排除了,但它自己有可能是目标数值
right = mid
elif nums[left] < nums[mid]:
# [1,2,3]
# [2,3,1]
# [2,3,4,5, 6, 7,8,9,1]
# mid
left = mid + 1
else:
assert nums[left] == nums[mid]
# [1,1,1,1,1,0,1,1,1]
left = left + 1
# 无需后处理
return nums[left]
if __name__ == '__main__':
solution = Solution()
nums = [1, 3, 5]
res = solution.findMin(nums)
print(res)
|
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def buildTree(self, preorder, inorder):
"""
:type preorder: List[int]
:type inorder: List[int]
:rtype: TreeNode
"""
plen = len(preorder)
ilen = len(inorder)
return self.__helper(preorder, 0, plen - 1, inorder, 0, ilen - 1)
def __helper(self, preorder, prel, prer,
inorder, inl, inr):
# 不能构成区间,所以返回根结点
if prel > prer or inl > inr:
return None
root_val = preorder[prel]
l = inl
step = 0
while l < inr and inorder[l] != root_val:
step += 1
l += 1
root_node = TreeNode(root_val)
root_node.left = self.__helper(preorder, prel + 1, prel + step,
inorder, inl, inl + step - 1)
# 特别注意这个细节,中序遍历开始的时候,是 (inl + step - 1) 这个数值跳过一个结点
root_node.right = self.__helper(preorder, prel + step + 1, prer,
inorder, inl + step + 1, inr)
return root_node
|
# 95. 不同的二叉搜索树 II
# 给定一个整数 n,生成所有由 1 ... n 为节点所组成的二叉搜索树。
#
# 示例:
#
# 输入: 3
# 输出:
# [
# [1,null,3,2],
# [3,2,null,1],
# [3,1,null,null,2],
# [2,1,3],
# [1,null,2,null,3]
# ]
# 解释:
# 以上的输出对应以下 5 种不同结构的二叉搜索树:
#
# 1 3 3 2 1
# \ / / / \ \
# 3 2 1 1 3 2
# / / \ \
# 2 1 2 3
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def generateTrees(self, n):
"""
:type n: int
:rtype: List[TreeNode]
"""
res = []
if n <= 0:
return res
return self.helper(1, n)
def helper(self, left, right):
res = []
if left > right:
# 说明不构成区间,应该返回空结点
res.append(None)
return res
elif left == right:
res.append(TreeNode(left))
return res
else:
for i in range(left, right + 1):
left_sub_tree = self.helper(left, i - 1)
right_sub_tree = self.helper(i + 1, right)
for l in left_sub_tree:
for r in right_sub_tree:
root = TreeNode(i)
root.left = l
root.right = r
res.append(root)
return res
|
class Solution:
def integerBreak(self, n):
if n == 2:
return 1
if n == 3:
return 2
if n == 4:
return 4
res = 1
while n > 4:
res *= 3
n -= 3
res *= n
return res
if __name__ == '__main__':
n = 10
s = Solution()
res = s.integerBreak(n)
print(res)
|
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# 使用 dfs 来解决
# 113. 路径总和 II
# 给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。
# 解法 1 和 解法 2 是一回事。
class Solution(object):
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: List[List[int]]
"""
results = []
self.__dfs([], root, sum, results)
return results
def __dfs(self, path, root, sum, results):
if root is None:
return
if root.left is None and root.right is None and root.val == sum:
result = []
result.extend(path)
result.append(root.val)
results.append(result)
return
path.append(root.val)
if root.left:
self.__dfs(path, root.left, sum - root.val, results)
if root.right:
self.__dfs(path, root.right, sum - root.val, results)
# 这一步很关键
path.pop()
|
# 33. 搜索旋转排序数组
# 假设按照升序排序的数组在预先未知的某个点上进行了旋转。
#
# ( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。
#
# 搜索一个给定的目标值,如果数组中存在这个目标值,则返回它的索引,否则返回 -1 。
#
# 你可以假设数组中不存在重复的元素。
#
# 你的算法时间复杂度必须是 O(log n) 级别。
from typing import List
# 中间元素和右边界比较
class Solution:
def search(self, nums: List[int], target: int) -> int:
size = len(nums)
if size == 0:
return -1
left = 0
right = size - 1
while left < right:
# mid = left + (right - left + 1) // 2
mid = (left + right + 1) >> 1
if nums[mid] < nums[right]:
# [7,8,9,1,2,3,4,5,6] ,后半部分有序
if nums[mid] <= target <= nums[right]:
left = mid
else:
right = mid - 1
else:
# [4,5,6,7,8,9,0,1,2],前半部分有序
if nums[left] <= target <= nums[mid - 1]:
right = mid - 1
else:
left = mid
# 后处理
return left if nums[left] == target else -1
if __name__ == '__main__':
nums = [4, 5, 6, 7, 0, 1, 2]
target = 0
solution = Solution()
result = solution.search(nums, target)
print(result)
|
class Solution:
# 代码有错误,要考虑的边界条件有点复杂,因此不考虑
def searchMatrix(self, matrix, target):
# 特判
rows = len(matrix)
if rows == 0:
return False
cols = len(matrix[0])
if cols == 0:
return False
# 起点:左下角
x = rows - 1
y = 0
# 不越界的条件是:行大于等于 0,列小于等于 cols - 1
while x >= 0 and y < cols:
# 打开下面这行注释,调试代码
print('x:{} y:{}'.format(x, y))
if matrix[x][y] > target:
# 极端情况先判断:
if x == 0 and matrix[0][y] > target:
return False
# 如果大于 target,向上走到第 1 个小于等于 target 的位置,此时列固定
left = 0 # 表示上
right = x # 表示下
while left < right:
mid = (left + right + 1) >> 1
if matrix[mid][y] > target:
right = mid - 1
else:
left = mid
if matrix[left][y] == target:
return True
x = left
elif matrix[x][y] < target:
# 极端情况先判断:
if y == cols - 1 and matrix[x][cols - 1] < target:
return False
# 如果小于 target,向右走到第 1 个大于等于 target 的位置,此时行固定
left = x
right = cols - 1
while left < right:
mid = (left + right) >> 1
if matrix[mid][y] < target:
left = mid + 1
else:
right = mid
if matrix[x][left] == target:
return True
y = left
else:
return True
return False
if __name__ == '__main__':
matrix = [[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]]
target = 12
solution = Solution()
result = solution.searchMatrix(matrix, target)
print(result)
|
# 130. 被围绕的区域
# 给定一个二维的矩阵,包含 'X' 和 'O'(字母 O)。
# 找到所有被 'X' 围绕的区域,并将这些区域里所有的 'O' 用 'X' 填充。
# https://segmentfault.com/a/1190000012898131
class Solution:
def solve(self, board):
"""
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""
# 一开始是常规的代码
m = len(board)
if m == 0:
return
n = len(board[0])
directions = [(-1, 0), (0, -1), (1, 0), (0, 1)]
for row in range(m):
self.__dfs(board, row, 0, m, n, directions)
self.__dfs(board, row, n - 1, m, n, directions)
for col in range(1, n - 1):
self.__dfs(board, 0, col, m, n, directions)
self.__dfs(board, m - 1, col, m, n, directions)
for i in range(m):
for j in range(n):
if board[i][j] == 'O':
board[i][j] = 'X'
if board[i][j] == '-':
board[i][j] = 'O'
def __dfs(self, board, i, j, m, n, directions):
# 把 'O' 变成一个别的符号,然后扩散开来
# 这里相当于 marked
if 0 <= i < m and 0 <= j < n and board[i][j] == 'O':
board[i][j] = '-'
for direction in directions:
new_x = i + direction[0]
new_y = j + direction[1]
self.__dfs(board, new_x, new_y, m, n, directions)
if __name__ == '__main__':
# board = [['X', 'X', 'X', 'X'],
# ['X', 'O', 'O', 'X'],
# ['X', 'X', 'O', 'X'],
# ['X', 'O', 'X', 'X']]
# board = [['O', 'O', 'O'],
# ['O', 'O', 'O'],
# ['O', 'O', 'O']]
board = [["X", "O", "X", "O", "X", "O"],
["O", "X", "O", "X", "O", "X"],
["X", "O", "X", "O", "X", "O"],
["O", "X", "O", "X", "O", "X"]]
solution = Solution()
solution.solve(board)
for row in board:
print(row)
|
import gzip
import cPickle
import numpy as np
def load_data():
"""Opens the file containing the MNIST data set and returns it in a
format to be modified by the load_data_wrapper function.
"""
f = gzip.open('../data/mnist.pkl.gz', 'rb')
training_data, validation_data, test_data = cPickle.load(f)
f.close()
return (training_data, validation_data, test_data)
def load_data_wrapper():
"""The load_data_wrapper functions returns a tuple containing the
training data, validation data, and test data. The format of the
data returned from load_data is not the most convenient, so here it
is changed to play nicely with the network and its functions produced
in the network class.
"""
tr_d, va_d, te_d = load_data()
training_inputs = [np.reshape(x, (784, 1)) for x in tr_d[0]]
training_results = [vectorized_result(y) for y in tr_d[1]]
training_data = zip(training_inputs, training_results)
validation_inputs = [np.reshape(x, (784, 1)) for x in va_d[0]]
validation_data = zip(validation_inputs, va_d[1])
test_inputs = [np.reshape(x, (784, 1)) for x in te_d[0]]
test_data = zip(test_inputs, te_d[1])
return (training_data, validation_data, test_data)
def vectorized_result(j):
"""Function to take a single digit j (the expected value of a
handwritten digit) and return a 10-d vector with a zero in every
place except the j-unit. This is how the digit is represented in
vector form in the network class.
"""
e = np.zeros((10, 1))
e[j] = 1.0
return e
|
def LipYear(y):
if ((y % 400 == 0) or
(y % 100 != 0) and
(y % 4 == 0)):
return "its a leap year";
else:
return "its not a leap year";
# Driver code
if __name__ == '__main__':
year = int(input("Enter a year: "));
print(LipYear(year));
'''
[10: 49AM] TejasChokshi
year = int(input("Enter a year: "))
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
else:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
'''
|
#!env python
'''
Each new term in the Fibonacci sequence is generated by adding the previous two terms.
By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the
even-valued terms
--
Solution -
1. Create a generator that yields fibonacci numbers
2. Wrap it in a filter that only lets even numbers through
3. Sum up the values coming out of the filter
'''
def createFibonacciGenerator(limit):
a, b = 0, 1
while a < limit:
yield a
a, b = b, a + b
if __name__ == "__main__":
evenFibs = filter(lambda x: x % 2 == 0, createFibonacciGenerator(4e6))
print("Sum of even-values fibonacci terms that do not exceed 4 million: ", sum(evenFibs))
'''Output
Sum of even-values fibonacci terms that do not exceed 4 million: 4613732
'''
|
from copy import copy, deepcopy
def main():
file1 = open('input.txt', 'r')
lst = []
while True:
line = file1.readline()
if not line:
break
lst.append(int(line))
max_elem = max(lst)
lst.append(0)
lst.append(max_elem + 3)
lst = sorted(lst)
count_one_diff = 0
count_three_diff = 0
for i in range(len(lst) - 1):
if lst[i + 1] - lst[i] == 1:
count_one_diff += 1
if lst[i + 1] - lst[i] == 3:
count_three_diff += 1
result = count_one_diff * count_three_diff
print(result)
if __name__ == '__main__':
main()
|
def count_trees(right, down):
lst = []
file1 = open('input.txt', 'r')
while True:
line = file1.readline()
if not line:
break
lst.append(line)
col = right
row = down
count = 0
while row < len(lst):
if lst[row][col] == '#':
count = count + 1
col = (col + right) % (len(lst[0]) - 1)
row = row + down
return count
def main():
res = count_trees(3, 1) * count_trees(1, 1) * count_trees(5, 1) * count_trees(7, 1) * count_trees(1, 2)
print(res)
if __name__ == "__main__":
main()
|
from copy import copy, deepcopy
from enum import Enum
class Direction(Enum):
EAST = 'east'
WEST = 'west'
NORTH = 'north'
SOUTH = 'south'
north = 'N'
south = 'S'
east = 'E'
west = 'W'
forward = 'F'
right = 'R'
left = 'L'
def turn_right(degrees, waypoint_x, waypoint_y):
if degrees == 0 or degrees == 360:
return waypoint_x, waypoint_y
elif degrees == 270:
return waypoint_y, -waypoint_x
elif degrees == 180:
return -waypoint_x, -waypoint_y
elif degrees == 90:
return -waypoint_y, waypoint_x
return waypoint_x, waypoint_y
def turn_left(degrees, waypoint_x, waypoint_y):
return turn_right(360 - degrees, waypoint_x, waypoint_y)
def main():
file = open('input.txt', 'r')
x = 0
y = 0
waypoint_x = 1
waypoint_y = 10
while True:
line = file.readline()
if not line:
break
instruction = line[0]
value = int(line[1:])
if instruction == north:
waypoint_x += value
elif instruction == south:
waypoint_x -= value
elif instruction == east:
waypoint_y += value
elif instruction == west:
waypoint_y -= value
elif instruction == right:
waypoint_x, waypoint_y = turn_right(value, waypoint_x, waypoint_y)
elif instruction == left:
waypoint_x, waypoint_y = turn_left(value, waypoint_x, waypoint_y)
elif instruction == forward:
x += value * waypoint_x
y += value * waypoint_y
distance = abs(0 - x) + abs(0 - y)
print(distance)
if __name__ == '__main__':
main()
|
"""
A year is a leap year if it is divisible by 4, except that years divisible
by 100 are not leap years unless they are also divisible by 400.
Ask the user to enter a year, and, using the // operator, determine
how many leap years there have been between 1600 and that year.
"""
thatYear = eval(input("enter that year:"))
count = (thatYear - 1600 ) // 4
cen =(thatYear - 1600) // 100
cen400 = 0
for i in range(1600,thatYear,100):
cen400 += 1
print("leap year count:", count - cen + cen400)
|
import sys
from itertools import cycle, izip
KEY = 's3cr3t'
# method from: https://dustri.org/b/elegant-xor-encryption-in-python.html
def encrypt(message):
return(''.join(chr(ord(c)^ord(k)) for c,k in izip(message, cycle(KEY))))
def main(argv):
if len(argv) == 0:
print("Error! No argument(s) specified.")
return
inputfile = argv[0]
if len(argv) == 1:
outputfile = inputfile
else:
outputfile = argv[1]
f1 = open(inputfile, "r")
f2 = open(outputfile, "a+")
f2.write(encrypt(f1.read()))
f1.close()
f2.close()
if __name__ == "__main__":
main(sys.argv[1:])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.