text
stringlengths 37
1.41M
|
---|
outstanding_balance_ = float(raw_input('Balance: '))
interest_rate = float(raw_input('Rate: '))
count = 0
while 1:
payment = 10 * count
outstanding_balance = outstanding_balance_
for month in range(1, 13):
monthly_interest_rate = (interest_rate / 12.0)
monthly_unpaid_balance = outstanding_balance - payment
outstanding_balance = monthly_unpaid_balance + (monthly_interest_rate * monthly_unpaid_balance)
if outstanding_balance <= 0:
break
if outstanding_balance <= 0:
break
count += 1
print 'Lowest Payment:', payment
|
#This game is written by Siang and Nikko
import pygame
from pygame.locals import * #maybe get rid of later
class BrickBreaker:
def __init__(self, winWidth, winHeight):
"""Constructor of game
Inputs
1)Window width and height"""
#Set window width and height
self.winWidth = winWidth
self.winHeight = winHeight
#Create game window
self.win = pygame.display.set_mode((self.winWidth, self.winHeight))
pygame.display.set_caption("Brick Breaker")
#Set background color to white
self.bgcolor = (255,255,255)
self.win.fill(self.bgcolor)
#Create paddle and ball objects in game, create paddleGroup
self.paddle = Paddle(self.winWidth, self.winHeight)
self.paddleGroup = pygame.sprite.Group()
self.paddleGroup.add(self.paddle)
self.ball = Ball(self.winWidth, self.winHeight)
#Set number of rows of bricks to 3
self.row = 3
#Create a list of all bricks and allSprites
self.bricks = pygame.sprite.Group()
self.allSprites = pygame.sprite.Group()
#Add paddle and ball to list of allSprites
self.allSprites.add(self.paddle)
self.allSprites.add(self.ball)
for y in range(self.row):
for x in range(5):
#Position bricks in correct locations to form self.row X 5 grid
xpos = self.winWidth // 10 + x * self.winWidth // 5
ypos = self.winHeight // 24 + y * self.winHeight // 12
newBrick = Brick(xpos, ypos)
#Append brick to list of bricks and allSprites
self.bricks.add(newBrick)
self.allSprites.add(newBrick)
#Sets state: None if still playing, "Win" if won, and "Loss" if lost
self.state = None
#Sets quit to False, if quit is True, exit window
self.quit = False
def draw(self):
"""Draws all objects in window"""
#Erase all objects in window
self.win.fill((255,255,255))
#Draws all objects
for sprt in self.allSprites:
self.win.blit(sprt.image, sprt.rect)
#Update the window
pygame.display.flip()
def play(self):
""" Loops through game in three stages
1) Start screen
2) Gameplay
3) End screen"""
#Sets up clock for timing
clock = pygame.time.Clock()
#Start screen loop
start = False
while not self.quit and not start:
for event in pygame.event.get():
#Start game on left-click
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
self.paddle.moving = True
start = True
#Allows user to exit window
if event.type == pygame.QUIT:
if self.quit == False:
self.quit = True
#Draws all objects in window
self.draw()
#Gameplay loop
while not self.state and not self.quit:
for event in pygame.event.get():
#If the user clicks the left button, the paddle will begin moving
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
self.paddle.moving = True
#If the user clicks the right button, the paddle will stop moving
if event.type == pygame.MOUSEBUTTONUP and event.button == 1:
self.paddle.moving = False
#If the user moves the mouse left and right, the paddle follows
if event.type == pygame.MOUSEMOTION and self.paddle.moving:
self.paddle.updatePos(event.pos)
#Allows the user to exit window
if event.type == pygame.QUIT:
if self.quit == False:
self.quit = True
#Moves ball
self.ball.moveStep()
#Checks if game is won or lost
self.checkState()
#Checks the collisions
self.collision()
#Draws all objects in window
self.draw()
#Sets frame/second
clock.tick(80)
#End screen loop
while not self.quit:
#Allows user to exit the window
for event in pygame.event.get():
if event.type == pygame.QUIT:
if self.quit == False:
self.quit = True
def collision(self):
"""Checks if ball collides with bricks or paddle"""
#Creates list of bricks that were collided with
bricksHit = pygame.sprite.spritecollide(self.ball, self.bricks, False)
#If any bricks were collided with, change direction of ball and remove brick from
#window
if bricksHit:
for brick in bricksHit:
#6 is needed to account for the ball moving slightly inside the brick
#Change y-direction
if (brick.rect.left < (self.ball.rect.right -6)< brick.rect.right) or (brick.rect.left < (self.ball.rect.left + 6) < brick.rect.right):
self.ball.speed[1] *= -1
brick.kill()
#3 is needed to account for the ball moving slightly inside the brick
#Change x-direction
elif (brick.rect.top < (self.ball.rect.top - 3)< brick.rect.bottom) or (brick.rect.top < (self.ball.rect.bottom + 3) < brick.rect.bottom):
self.ball.speed[0] *= -1
brick.kill()
#Creates list containing paddle if paddle is collided with
paddleHit = pygame.sprite.spritecollide(self.ball, self.paddleGroup, False)
#If the paddle is collided with, change the direction of the ball
if paddleHit:
#6 is needed to account for the ball moving slightly inside the brick
#Change y-direction
if (paddleHit[0].rect.left < (self.ball.rect.right-6)< paddleHit[0].rect.right) or (paddleHit[0].rect.left < (self.ball.rect.left+6) < paddleHit[0].rect.right):
self.ball.speed[1] *= -1
#3 is needed to account for the ball moving slightly inside the brick
#Change x-direction
elif (paddleHit[0].rect.top < (self.ball.rect.top - 3)< paddleHit[0].rect.bottom) or (paddleHit[0].rect.top < (self.ball.rect.bottom + 3) < paddleHit[0].rect.bottom):
self.ball.speed[0] *= -1
def checkState(self):
"""Checks whether game is won or lost"""
#Checks if player lost because the ball went off screen
if self.ball.rect.top >= self.winHeight:
self.state = "Loss"
#Checks if player won because all bricks were gone
if not self.bricks:
self.state = "Win"
class Brick(pygame.sprite.Sprite):
def __init__(self, xpos, ypos):
"""Constructor for Brick
Inputs:
1)x position of brick center
2)y position of brick center"""
#Calls the Sprite init function
super().__init__()
#Import brick image
#self.image = pygame.image.load("test.png").convert()
self.image = pygame.Surface((50,30))
#Set all white pixels in self.image to transparent
self.image.set_colorkey((255,255,255))
#Set brick initial position
self.rect = self.image.get_rect(center = (xpos, ypos))
class Paddle(pygame.sprite.Sprite):
def __init__(self, winWidth, winHeight):
"""Constructor for Paddle class
Inputs:
1) Window's width
2) Window's height"""
#Calls the Sprite init function
super().__init__()
#Set window width and height
self.winWidth = winWidth
self.winHeight = winHeight
#Import paddle image
#self.image = pygame.image.load("test.png").convert()
self.image = pygame.Surface((300,30))
#Set all white pixels in self.image to transparent
self.image.set_colorkey((255,255,255))
#Set paddle initial position
self.rect = self.image.get_rect()
self.rect.centerx = self.winWidth // 2
self.rect.centery = self.winHeight - self.rect.height // 2
#Set paddle movement to False
self.moving = False
def updatePos(self, mouse):
"""Change the position of paddle based on mouse position"""
#Move paddle if the mouse moves in the window, but do not move the paddle off screen
if mouse[0] > self.rect.width // 2 and mouse[0] < (self.winWidth - self.rect.width // 2):
self.rect.centerx = mouse[0]
class Ball(pygame.sprite.Sprite):
def __init__(self, winWidth, winHeight):
"""Constructor of Ball class
Inputs:
1) Window's width
2) Window's height"""
#Calls the Sprite init function
super().__init__()
#Set window width and height
self.winWidth = winWidth
self.winHeight = winHeight
#Set ball's speed and direction
self.speed = [3, 3]
#Import ball image
#self.image = pygame.image.load("test.png").convert()
self.image = pygame.Surface((30,30))
#Set all white pixels in self.image to transparent
self.image.set_colorkey((255,255,255))
#Set ball initial position
self.rect = self.image.get_rect()
self.rect.centerx = self.rect.width // 2
self.rect.centery = self.winHeight // 2
def moveStep(self):
"""Moves ball and change direction if it collides with top or sides of window"""
#Check for collision with sides of window
if (self.rect.left <= 0 and self.speed[0] <= 0) or (self.rect.right >= self.winWidth and self.speed[0] >= 0):
#Switch x-component of direction
self.speed[0] *= -1
#Check for collision with top of window
if self.rect.top <= 0 and self.speed[1] <= 0:
#Switch y-component of direction
self.speed[1] *= -1
#Change position
self.rect.centerx += self.speed[0]
self.rect.centery += self.speed[1]
def main():
#Sets up pygame module
pygame.init()
#Create BrickBreaker object
game = BrickBreaker(600, 400)
#Play the game
game.play()
if __name__=="__main__":
main()
|
import random
num = []
def stuff(list):
i = 0
while i <=6:
list.append(random.randint(1,6)+random.randint(1,6)+random.randint(1,6))
i = i +1
print(list)
def avg(list):
t = 0
for i in range(len(list)):
t = t + list[i]
print(t//len(list))
def main():
stuff(num)
avg(num)
li = [7,10,9,15,12,12]
random.shuffle(li)
print(li)
if __name__ == "__main__":
main()
|
age = 31
if age < 18:
rate = 450
else:
if age > 100:
rate = 500
else:
if age < 25:
rate = 400
else:
rate = 300
print(rate)
|
import turtle
import tictactoeai
# Configure these variables as you like (within reason).
radius = 100
padding = 10
user = "O"
# These variables are then automatically configured.
if user == "O":
ai = "X"
else:
ai = "O"
numMoves = 0
stillPlaying = True
board = [[" ", " ", " "], [" ", " ", " "], [" ", " ", " "]]
def drawBoard():
'''Draws an empty board. Each cell is a square of side length 2 * (radius + padding).'''
global radius
global padding
size = radius + padding
turtle.penup()
turtle.setposition(-size, -3 * size)
turtle.pendown()
turtle.setposition(-size, 3 * size)
turtle.penup()
turtle.setposition(size, -3 * size)
turtle.pendown()
turtle.setposition(size, 3 * size)
turtle.penup()
turtle.setposition(-3 * size, -size)
turtle.pendown()
turtle.setposition(3 * size, -size)
turtle.penup()
turtle.setposition(-3 * size, size)
turtle.pendown()
turtle.setposition(3 * size, size)
def drawO(row, col):
'''Draws an O in the given row and column.'''
global radius
global padding
size = radius + padding
x = -2 * size + col * 2 * size
y = -2 * size + (2 - row) * 2 * size
turtle.penup()
turtle.setposition(x + radius, y)
turtle.setheading(90)
turtle.pendown()
turtle.circle(radius)
def drawX(row, col):
'''Draws an X in the given row and column.'''
global radius
global padding
size = radius + padding
x = -2 * size + col * 2 * size
y = -2 * size + (2 - row) * 2 * size
turtle.penup()
turtle.setposition(x - radius, y - radius)
turtle.pendown()
turtle.setposition(x + radius, y + radius)
turtle.penup()
turtle.setposition(x - radius, y + radius)
turtle.pendown()
turtle.setposition(x + radius, y - radius)
def handleClick(x, y):
'''This function is called whenever the user clicks in the turtle window with the mouse. It is passed the (x, y) coordinates of the mouse click. The origin is in the middle of the window, x increases to the right, and y increases up. This function interprets the mouse click as a user move, and then lets the AI move, if appropriate.'''
global radius
global padding
global board
global stillPlaying
global numMoves
size = radius + padding
# Convert (x, y) into (row, col).
if y < -size:
row = 2
elif y > size:
row = 0
else:
row = 1
if x < -size:
col = 0
elif x > size:
col = 2
else:
col = 1
if stillPlaying and board[row][col] == " ":
# Interpret this click as a user move.
numMoves += 1
board[row][col] = user
if user == "O":
drawO(row, col)
else:
drawX(row, col)
if tictactoeai.hasWon(board, user) or numMoves == 9:
stillPlaying = False
else:
# Let the AI take its move.
move = tictactoeai.aiMove(board, ai)
numMoves += 1
board[move[0]][move[1]] = ai
if ai == "O":
drawO(move[0], move[1])
else:
drawX(move[0], move[1])
if tictactoeai.hasWon(board, ai) or numMoves == 9:
stillPlaying = False
def main():
# Initialize the turtle and the drawing canvas.
turtle.hideturtle()
turtle.speed(0)
drawBoard()
# Register functions to respond to user events --- in this case, just one.
screen = turtle.getscreen()
screen.onclick(handleClick)
# Every interactive turtle program ends by entering the main loop.
# All subsequent action occurs in event handlers such as handleClick.
screen.mainloop()
if __name__ == "__main__":
main()
|
# In this file, all plaintext strings are assumed to contain only spaces and upper-case Roman characters A, B, C, ..., Z. Each encryption system has an encryptor and a decryptor.
# Convert letters A, ..., Z to indices 0, ..., 25.
# Also handle a, ..., z, just because we can.
def indexFromLetter(char):
if "A" <= char <= "Z":
return ord(char) - ord("A")
elif "a" <= char <= "z":
return ord(char) - ord("a")
else:
return None
# Convert indices back to upper-case letters.
def letterFromIndex(index):
if index < 0 or index > 25:
return None
else:
return chr(index + ord("A"))
### RAIL FENCE ###
def railFenceEncryption(s):
evens = ""
odds = ""
for i in range(len(s)):
if i % 2 == 0:
evens += s[i]
else:
odds += s[i]
return evens + odds
def railFenceDecryption(s):
evens = s[0:((len(s) + 1) // 2)]
odds = s[((len(s) + 1) // 2):len(s)]
answer = ""
for i in range(len(odds)):
answer += evens[i] + odds[i]
if len(evens) > len(odds):
answer += evens[-1]
return answer
### ROT13 ###
def rot13Encryption(s):
answer = ""
for char in s:
if char == " ":
answer += char
else:
answer += letterFromIndex((indexFromLetter(char) + 13) % 26)
return answer
rot13Decryption = rot13Encryption
### CAESAR ###
def caesarEncryption(s, n):
answer = ""
for char in s:
if char == " ":
answer += char
else:
answer += letterFromIndex((indexFromLetter(char) + n) % 26)
return answer
def caesarDecryption(s, n):
return caesarEncryption(s, -n)
### SUBSTITUTION ###
sub = "THEQUICKSLVRFOXJMPDAZYBWNG"
def substitutionEncryption(s, sub):
answer = ""
for char in s:
if char == " ":
answer += char
else:
answer += sub[indexFromLetter(char)]
return answer
def substitutionInverse(sub):
alp = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
inv = ""
for i in range(0,26):
for j in range(0,26):
if sub[j] == chr(i + 65):
inv += alp[j]
return inv
# This function is correct as it is written. Do not alter it.
# It will work once you have a working version of substitutionInverse.
def substitutionDecryption(s, sub):
return substitutionEncryption(s, substitutionInverse(sub))
### RE-IMPLEMENTING CAESAR IN TERMS OF SUBSTITUTION ###
def caesarEncryptionSub(s, n):
# !! This is where you re-write the Caesar encryption using substitutionEncryption.
alp = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
sub = ""
for char in alp:
if char == " ":
sub += char
else:
sub += letterFromIndex((indexFromLetter(char) + n) % 26)
#return sub
answer = ""
for char in s:
if char == " ":
answer += char
else:
answer += sub[indexFromLetter(char)]
return answer
### REPEATED PAD ###
def repeatedPadIndex(plaintext, key):
keyIndex = indexFromLetter(key)
ptIndex = indexFromLetter(plaintext)
newIndex = (ptIndex + keyIndex) % 26
return letterFromIndex(newIndex)
def repeatedPadIndexD(plaintext, key):
keyIndex = indexFromLetter(key)
ptIndex = indexFromLetter(plaintext)
newIndex = (keyIndex - ptIndex) % 26
return letterFromIndex(newIndex)
plaintext = "SECRET DOLPHIN ATTACK AT NOON"
key = "GNIJIEB"
def repeatedPadEncryption(plaintext, key):
answer = ""
keyLen = len(key)
for i in range(len(plaintext)):
ch = plaintext[i]
if ch == " ":
answer += ch
else:
answer += repeatedPadIndex(key[i%keyLen], ch)
return answer
encryptedtext = "YRKAMX JBTYPMO NBCIGL NB VSPT"
def repeatedPadDecryption(encryptedtext, key):
# !! Replace the next line with code to compute and return the plaintext.
answer = ""
keyLen = len(key)
for i in range(len(encryptedtext)):
ch = encryptedtext[i]
if ch == " ":
answer += ch
else:
answer += repeatedPadIndexD(key[i%keyLen], ch)
return answer
### BREAKING CAESAR ###
t = "KITZTMBWV KWTTMOM KA GMIP"
def caesarBreak(t):
# !! Place code here to decrypt a Caesar cipher without knowing its key
for i in range(0,26):
answer = ""
for char in t:
if char == " ":
answer += char
else:
answer += letterFromIndex((indexFromLetter(char) + i) % 26)
print(i+1)
print(answer)
return None
### FREQUENCY ANALYSIS TO BREAK SUBSTITUTION ###
def stringFromFileName(fileName):
with open(fileName) as file:
return file.read()
def frequencies(string):
#counts = []
#for i in range(26):
# counts += [0]
# Here's a Python trick to accomplish the preceding lines simply:
# Multiplying a list by an integer concatenates that many copies of the list.
counts = [0] * 26
for char in string:
index = indexFromLetter(char)
if index != None:
counts[index] += 1
total = sum(counts)
freqs = [0] * 26
for i in range(len(counts)):
freqs[i] = counts[i] / total
return freqs
def main():
s = "CARLETON COLLEGE CS YEAH"
print("plaintext:")
print(s)
print("rail fence:")
print(railFenceEncryption(s))
print(railFenceDecryption(railFenceEncryption(s)))
print("rot13:")
print(rot13Encryption(s))
print(rot13Decryption(rot13Encryption(s)))
print("Caesar with key 8:")
print(caesarEncryption(s, 8))
print(caesarDecryption(caesarEncryption(s, 8), 8))
print("Substitution:")
print(substitutionEncryption(s, sub))
print("Substitution(substitutionEncryption(s,sub),sub)")
print(substitutionDecryption(substitutionEncryption(s,sub),sub))
print("Repeated Pad Cipher")
print(repeatedPadEncryption(plaintext,key))
print("Repeated Pad Cipher repeatedPadDecryption(encryptedtext,key)")
print(repeatedPadDecryption(encryptedtext, key))
print("Caesar Encryption with Substitution (caesarEncryptionSub(s, n))")
print(caesarEncryptionSub(s, 10))
print("Caesar Break")
print(caesarBreak(t))
# !! Add code here to demonstrate the other ciphers, breaking Caesar, etc.
# If the user ran this file directly (rather than imported it), then do main.
if __name__ == "__main__":
main()
|
def insert_sort(lists):
count = len(lists)
# 因为第一个元素自成有序序列,所以遍历从第二个元素开始
for i in range(1, count):
# 获取当前需要向前插入的元素
key = lists[i]
# 从i前面一个位置开始插入
j = i - 1
while j >= 0:
# 如果待插位置的原有元素比待插元素大(如果是降序也可以是小)
# 那么移动j元素到j+1位,j元素用待插元素替代
# 这个过程简直是逆向的冒泡,但是被插入序列本身的有序性决定这次冒泡最多只需一次遍历
if lists[j] > key:
lists[j+1] = lists[j]
lists[j] = key
j -= 1
return lists
if __name__ == "__main__":
lists = [3,4,2,8,9,5,1]
for i in lists:
print(i, end=' ')
print('')
for i in insert_sort(lists):
print(i, end=' ')
print('')
|
'''
This script can convert a picture to character picture.
Usage:
python3 ascii.py filename [-o|--output] [--width] [--height]
'''
from PIL import Image
import argparse
class ImgToChar():
'''
Usage:
1.New a object
2.Call draw() method
'''
def __init__(self):
self.parser = argparse.ArgumentParser()
self.parser.add_argument('file')
self.parser.add_argument('-o', '--output')
self.parser.add_argument('--width', type=int, default=50)
self.parser.add_argument('--height', type=int, default=50)
self.args = self.parser.parse_args()
self.IMG = self.args.file
self.WIDTH = self.args.width
self.HEIGHT = self.args.height
self.OUTPUT = self.args.output
def __get_char(self, r, g, b, alpha=256):
ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjf"+\
"t/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ")
if alpha == 0:
return ' '
length = len(ascii_char)
gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b)
unit = (256.0 + 1) / length
return ascii_char[int(gray/unit)]
def draw(self):
im = Image.open(self.IMG)
im = im.resize((self.WIDTH, self.HEIGHT), Image.NEAREST)
txt = ''
for i in range(self.HEIGHT):
for j in range(self.WIDTH):
txt += self.__get_char(*im.getpixel((j, i)))
txt += '\n'
print(txt)
self.__output_to_file(txt)
def __output_to_file(self, txt):
if self.OUTPUT:
with open(self.OUTPUT, 'w') as f:
f.write(txt)
else:
with open('output.txt', 'w') as f:
f.write(txt)
if __name__ == '__main__':
to_char = ImgToChar()
to_char.draw()
|
'''
680. Valid Palindrome II
Easy
Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome.
Example 1:
Input: "aba"
Output: True
Example 2:
Input: "abca"
Output: True
Explanation: You could delete the character 'c'.
Note:
The string will only contain lowercase characters a-z. The maximum length of the string is 50000.
'''
class OfficialSolutionImproved:
def validPalindrome(self, s: str) -> bool:
if s == s[::-1]:
return True
def is_pali_range(i, j):
return s[i:j+1] == s[i:j+1][::-1]
lo = 0
hi = len(s) - 1
while lo <= hi:
if s[lo] != s[hi]:
return is_pali_range(lo+1,hi) or is_pali_range(lo, hi-1)
lo += 1
hi -= 1
|
"""
Создайте класс RandSequence с методами, формирующими вложенную последовательность.
Определить атрибуты:
- sequence - последовательность
Определить методы:
- инициализатор __init__, который принимает длину последовательности n
- метод generate, который принимает длину последовательности n
- метод print_seq, который выводит последовательность на экран
"""
class RandSequence:
sequence = []
def __init__(self, sequence):
self.sequence = sequence
def generate(self):
len(self.sequence)
def __repr__(self):
return f"Последовательность = {self.sequence}"
def print_seq(self):
return self.sequence
numbers = RandSequence([1, 4, 656, 343, 9, 6, 645])
print(numbers)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by iFantastic on 2019/7/4
"""
1.6. 面试题目:1块钱1瓶水,2个瓶盖换一瓶水,
用程序实现输入钱数,得到水的个数
1 1
2 2+1
3 3+1+1 5
4 4+1+1+1 7
。。。。。。
"""
while True:
money = int(input("请输入钱数:\n"))
connt = 2 * money - 1
print("水的个数是 %d" % connt)
if __name__ == '__main__':
pass
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by iFantastic on 2019/7/4
'''
6.1. find
find 检测str是否包含在mystr中,如果是返回开始索引值,否则返回-1
6.2. rfind
rfind 类似于find,不过是从右边开始找。
'''
starts = "郭富城、刘德华、黎明、fzd、刘德华"
# 从左往右找第一个字符串的索引 下标 从0 开始
index = starts.find("郭富城") # 将返回值传给index
print(index)
index = starts.find("刘德华")
print(index)
index = starts.find("大东东")
print(index) #不包含在字符串列表中就返回 -1
# rfind 从右侧往左侧开始找
# 查找到的索引也是从左数的索引
indexindex = starts.rfind("郭富城")
print(indexindex)
indexindex = starts.rfind("刘德华")
print(indexindex)
if __name__ == '__main__':
pass
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by iFantastic on 2019/7/9
"""
定义一个网络用户类 要处理的信息有用户ID、用户密码、email地址。
在建立类的实例时 把以上三个信息都作为参数输入
其中用户ID和用户密码是必须的 缺省的email地址,是用户ID加上字符串"@gameschool.com"
判断邮箱是否合法,判断id不能为空的方法
要求定义函数,能获取出用户的个人信息。
"""
class NetUser:
def __init__(self, id, pwd):
self.id = id
self.pwd = pwd
# 自动初始化
self.email = id + "@gameschool.com"
def checkId(self, id):
if id == None or id == "" or id.strip() == "":
return False
return True
def checkEmail(self, email):
if email.endswith("@gameschool.com"):
return True # 为真
return False
if __name__ == '__main__':
netUser = NetUser("18", "123")
# 可以重新定义属性参数,以下定义的就是不合法的
netUser.id = ""
netUser.email = "xx"
# 检查id是否合法
checkId = netUser.checkId(netUser.id)
if checkId:
print("id合法")
else:
print("id不合法")
# 检查email是否合法
checkEmail = netUser.checkEmail(netUser.email)
if checkEmail:
print("邮箱合法")
else:
print("邮箱不合法")
|
try:
age=int(input("enter age :"))
if(age<18):
raise ValueError;
else:
print("Valid age")
except ValueError:
print("you are not eligible for voting")
|
import random
print(random.randrange(5))
def elementexist(lis,search):
for e in lis:
if e==search:
return True
return False
l=[1,2,3,4,5,6]
if elementexist(l,4):
print("Element Exist")
else:
print("Element doesn't exist")
L=[]
L.append(random.randrange(5))
print(L)
'''
import random
import math
def checkelement():
for i in range(0,5):
a=[]
a.append(random.randrange(5))
if a in a:
break
else:
print("Random numbers", a)
checkelement()
'''
|
def InsertInList(x, p, q):
l.insert(p,q)
if __name__ == '__main__':
N = int(input())
l = []
for i in range(N):
x = input()
if(x.find("insert")>=0):
temp = x[7:]
a, b = temp.split()
p = int(a)
q = int(b)
InsertInList(l, p, q)
elif(x.find("print")>=0):
print(l)
elif(x.find("remove")>=0):
temp = x[7:]
temp = int(temp)
l.remove(temp)
elif(x.find("append")>=0):
temp = x[7:]
temp = int(temp)
l.append(temp)
elif(x.find("sort")>=0):
l.sort()
elif(x.find("pop")>=0):
l.pop(-1)
elif(x.find("reverse")>=0):
l.reverse()
|
# -*- coding: utf-8 -*-
# from collections.abc import Iterable
def a(b, *a, **data):
# print(11, b, a, type(a), data, type(data))
print(11, b, a, type(a), data, type(data))
c(data)
def c(cc=22, aa=44, bb=56, a=1, b=543, c=45):
print(22, cc, aa, bb, a, b, c)
b = {"a": 'b', 'b': 2, 'c': 3}
bb = [111, 5644]
c(*bb, 4445, **b)
# a = [1, 1, 1]
# b = [2, 2, 2]
# c = [3, 3, 3]
# arr = []
# for i in range(len(a)):
# print(i)
# arr.append({a[i], b[i], c[i]})
# print(arr)
# print(next(abc), 11)
# print(next(abc), 22)
# print(abc, isinstance(abc, Iterable), type(abc))
|
# sets - множества
# не можем получить элемент по индексу
# не можем удалить элемент
# множество контейнер уникальных и повторяющихся элементов
# st = set()
# st2 = {54, True, "get"}
# lst = [54, 54, True, True, 5, 3, 8, 3]
# umit = set(lst)
# #print(st2[0]) будет ошибка
# print(type(st2))
# st2.add(54)
# print(st2)
# print(umit)
# print(len(st2)) #получить число элемента в множестве
# # val = {} - dict
# # s = () - tuple
# # lst2 = [] - list
# st - set()
# st.add(True)
# st.add(58)
# st.add("good")
# copylst = st.copy()
# st.remove(58)
# print(st)
# print(copylst)
# st.pop()
# print(st)
# st.discard(777777777777777)
# st.clear() #очистка множества
# print(st)
# fset = {54, 96, 78, 22, 36, 4}
# sset = {"set", "dict", "tuple", "list", "str", "int", "float", 4, 96}
# fset.update(sset)
# print(fset)
# # fset.intersection_update(sset)
# # print(fset)
# print(fset.intersection(sset))
# # print(sset.intersection(fset))
# print(fset.difference(sset))
# print(fset - sset)
# print(fset & sset)
# print(fset | sset)
# print(fset ^ sset)
#Problem1
# st = set()
# st2 = {3, 8, 10, 14, 2}
# st3 = {4, 3, 9, 12, 7}
# st4 = {1, 11, 5, 6, 13}
# st.update(st2)
# st.update(st3)
# st.update(st4)
# print(st)
# print(len(st2))
# print(len(st3))
# print(len(st4))
# print(type(st2))
# st2.pop
# st3.pop
# st4.pop
# print(st2)
# print(st3)
# print(st4)
# menu = {"lagman":80, "borsh":50}
# menu["beshparmak"] = 130
# menu["samsa"] = 20
# menu["lagman"] = 135
# del menu["borsh"]
# print(menu)
# Problem 020
# seet = {".update()","intersection_update()",".intersection()","difference()", "sdisjoint()", ".issubset()", ".issuperset()", ".union()", ".symmetric_difference()", ".copy()", ".update()", ".difference_update()", ".symmetric_difference_update()", ".add()", ".remove()", ".discard()", ".pop()", ".clear()"}
# dictii = {".clear()", ".copy()", ".fromkeys()", ".get()", ".items()", ".keys()", ".pop()", "popitem()", "setdefault()", "update()", "values()"}
# print(seet & dictii)
# cars = []
# car = input("Введите вашу машину: ")
# cars.append(car)
# print("Ваша машина: ", cars)
# students = ("Erbol", "Dior", "Nurbek")
# student = input("Input students name: ")
# if student in students:
# print("{name} is our student".format(name=student))
# else:
# print("{name} is our student".format(name=student))
mydict = {"play":"играть", "run":"бегать"}
mydict["swim"] = "плавать"
mydict["jump"] = "прыгать"
mydict["brake"] = "ломать..???"
word = input("Введите слово для перевода: ")
print(mydict[word])
|
#list = маасив
# lst = list()
# lst.append("nurbek")
# lst.append(True)
# lst.append(34)
# lst.append(55.4)
# print(lst)
# 0 1 2 3 4
# lst2 = ["cat", False, 58, "kg", [544, "dog", False]]
# a = lst2[4]
# lst2.remove(lst2[4])
# a.remove(544)
# lst2.append(a)
# print(lst2)
# mylst = [25, 8, 9, 8, 10, 5*8]
# mystr = ["cat", "car", *mylst, "mentor", "mentee"]
# # mylst.append(mystr)
# # mylst.extend(mystr)
# mystr.insert(0, "First")
# mystr.insert(4, "Good")
# mystr.insert(5, "ITC")
# # mystr.pop(11)
# del mylst[0]
# mylst.reverse()
# print(mylst[::-1])
#tuple
# from typing import Text
# tpl = tuple()
# tpl2 = (5, 6, 8, True, ["Boy", "Girl", 54, 5])
# first = []
# last = []
# first.extend(tpl2[:4])
# last.extend(tpl2[-1])
# print(len(first)+len(last))
# tpl3 = 54, 5, 34
# tpl4 = 54,
# print(type(tpl3))
# print(tpl3)
# print(tpl4)
# print(tpl2[2])
# hello = "Hello world!"
# a = list(hello)
# last = a[-1]
# a[-1] = "."
# print(a)
#Dictionary - slovar
# mydick = dict()
# print(type(mydick))
# mydick2 = {"name":"Anna", "age":15, "is_student":True, 5:[5, 6, True, (5, "dad",)], "hair":"yellow"}
# print(len(mydick2))
# print(mydick2["hair"])
# mydick2["animal"] = ["dog", "cat"]
# mydick3 = dict()
# mydick3["food"] = ["shaverma", "cacke", "tako"]
# mydick4 = dict()
# mydick4["planets"] = "mars"
# del mydick2["animal"]
# del mydick3["food"]
# del mydick4["planets"]
# print(mydick2, mydick3, mydick4)
# mydick = dict()
# mydick[15] = "число"
# mydick[True] = "истина"
# print(type(mydick))
# print(mydick)
# mydick.clear()
# print(mydick)
# print(mydick2.keys())
#problem12
# spicok = dict()
# spicok = {"car":"tesla", "game":"MINECRAAAAAAAAFT", "братик":"Emir_baike", "Nword":"New"}
# print(len(spicok))
# print(spicok["братик"])
#problem32
|
#__str__
#ООП - наследование
# class Cat:
# def __init__(self, name2, age, tail, color, paws):
# self.name = name2
# self.age = age
# self.tale = tail
# self.color = color
# self.paws = paws
# def __str__(self):
# return self.name
# class Tiger(Cat):
# def say(self, a):
# print(f"{self.name} says '{a}'")
# class Tiger(Cat):
# pass
# def say(self,a):
# print(f"{self.name} says '{a}'")
# mur = Cat("Baranduga", 1.5, 1, "yellow", 4)
# print(mur.name)
# print(mur)
# tiger = Tiger("Тигруля", 9, 1, "orange", 4)
# print(tiger.name)
# print(tiger.paws)
# print(tiger)
# tiger.say("Askar")
from numbers import operators
class Cheknum :
def chekphonenum(self, number):
if len(number) == 10 and number[0] == "0":
print("Ваш намбер валит на гелике")
code = number[1:4]
if code in operators["megacom"]:
print("Ваш апарат Мигаком")
elif code in operators["beeline"]:
print("Пчел ты...")
elif code in operators["O"]:
print("у тебя О")
else:
print("Ваш намбер инвалид, он не можит спустится, купитэ ему пашаговою инструкцию")
numberInput = input("Водите ваш намбер: ")
myNumber = Cheknum()
myNumber.chekphonenum(numberInput)
# class Human:
# def __init__(self, name, sourname, gender = "male"):
# self.name = name
# self.sourname = sourname
# self.gender = gender
# def __str__(self):
# if self.gender == "male":
# return f"гражданин {self.sourname} {self.name}"
# elif self.gender == "female":
# return f"гражданка {self.sourname} {self.name}"
# else:
# return f"{self.sourname} {self.name}"
# man = Human("Alex", "Tronhon")
# print(man.name)
# print(man.sourname)
# print(man.gender)
# print(man)
# woman = Human("Anna", "Woltsonn", "female")
# print(woman.name)
# print(woman.sourname)
# print(woman.gender)
# print(woman)
# class Publication:
# def __init__(self, name, date, pages, library, type):
# self.name = name
# self.date = date
# self.pages = pages
# self.library = library
# self.type = type
# class Book(Publication):
# def __init__(self):
# self.type = "book"
# book = Book()
# print(book.type)
|
def go_vert(lines, idx, start_line):
# find direction up or down
if start_line != 0:
if lines[start_line - 1][idx] != ' ':
direction = 'u'
cur_line = start_line - 1
else:
direction = 'd'
cur_line = start_line + 1
else:
direction = 'd'
cur_line = start_line + 1
letters_crossed = ""
while lines[cur_line][idx] != '+':
if lines[cur_line][idx] == ' ':
break
if lines[cur_line][idx].isalpha():
letters_crossed += lines[cur_line][idx]
if direction == 'u':
if cur_line - 1 < 0:
break
else:
cur_line -= 1
else:
if cur_line + 1 == len(lines):
break
else:
cur_line += 1
return (cur_line, letters_crossed)
def go_horiz(lines, line, start_idx):
# find direction left or right
if start_idx != 0:
if lines[line][start_idx - 1] != ' ':
direction = 'l'
cur_idx = start_idx - 1
else:
direction = 'r'
cur_idx = start_idx + 1
else:
direction = 'r'
cur_idx = start_idx + 1
letters_crossed = ""
last_path = False
while lines[line][cur_idx] != '+':
if lines[line][cur_idx] == ' ':
break
if lines[line][cur_idx].isalpha():
letters_crossed += lines[line][cur_idx]
if direction == 'l':
if cur_idx - 1 < 0:
break
else:
cur_idx -= 1
else:
if cur_idx + 1 == len(lines[line]):
break
else:
cur_idx += 1
return (cur_idx, letters_crossed)
def go_through(lines, idx, line_idx, vertical):
if vertical == True:
cur_line, letters_crossed = go_vert(lines, idx, line_idx)
return (idx, cur_line, letters_crossed)
else:
cur_idx, letters_crossed = go_horiz(lines, line_idx, idx)
return (cur_idx, line_idx, letters_crossed)
if __name__ == "__main__":
lines = list()
with open("input19", "r") as f:
for line in f:
lines.append(line[:-1])
list_test = list()
list_test.append(" | ")
list_test.append(" | +--+ ")
list_test.append(" A | C ")
list_test.append(" F---|----E|--+ ")
list_test.append(" | | | D ")
list_test.append(" +B-+ +--+ ")
#lines = list_test
#for line in lines:
# print(line)
start_idx = lines[0].index('|')
cur_idx = start_idx
cur_line = 0
letters = ""
vertical = True
distance_traveled = 1
while True:
new_idx, new_line, letters_crossed = go_through(lines, cur_idx, cur_line, vertical)
vertical = ~vertical
distance_traveled += abs(new_idx - cur_idx) + abs(new_line - cur_line)
cur_idx, cur_line = new_idx, new_line
if lines[cur_line][cur_idx] == ' ':
distance_traveled -= 1
letters += letters_crossed
break
else:
letters += letters_crossed
print(letters, distance_traveled)
|
import functools
def comment_lines_with_escaping(
text,
prefix="#",
escape_prefix="# EPY",
escape_format_string="# EPY: ESCAPE {}"):
"""
Build a Python comment line from input text.
Parameters
----------
text : str
Text to comment out.
prefix : str
Character to append to the start of each line.
"""
def escape_if_necessary(line):
if line.startswith(escape_prefix):
return escape_format_string.format(line)
else:
return "{}{}".format(prefix, line)
splitlines = [
escape_if_necessary(line)
for line in text.splitlines()]
return "\n".join(splitlines)
def ipython2encodedpython(code):
def tweak_transform(orig_transform):
"""
Takes the transform and modifies it such that we compare each line to its transformation. If they are
different, that means the line is a special ipython command. We strip that from the output, but record the
special command in a comment so we can restore it.
"""
def new_push_builder(push_func):
def new_push(line):
result = push_func(line)
if line != result:
return "# EPY: ESCAPE {}".format(line)
return result
return new_push
orig_transform.push = functools.update_wrapper(new_push_builder(orig_transform.push), orig_transform.push)
return orig_transform
from IPython.core.inputtransformer import StatelessInputTransformer
@StatelessInputTransformer.wrap
def escaped_epy_lines(line):
"""Transform lines that happen to look like EPY comments."""
if line.startswith("# EPY"):
return "# EPY: ESCAPE {}".format(line)
return line
"""Transform IPython syntax to an encoded Python syntax
Parameters
----------
code : str
IPython code, to be transformed to Python encoded in a way to facilitate transformation back into IPython.
"""
from IPython.core.inputsplitter import IPythonInputSplitter
# get a list of default line transforms. then capture
fake_isp = IPythonInputSplitter(line_input_checker=False)
logical_line_transforms = [escaped_epy_lines()]
logical_line_transforms.extend([tweak_transform(transform) for transform in fake_isp.logical_line_transforms])
isp = IPythonInputSplitter(line_input_checker=False, logical_line_transforms=logical_line_transforms)
result = isp.transform_cell(code)
if result.endswith("\n") and not code.endswith("\n"):
# transform_cell always slaps a trailing NL. If the input did _not_
# have a trailing NL, then we remove it.
result = result[:-1]
return result
|
import sys
l = [n*2 for n in range(10000)] # List comprehension
g = (n for n in range(10000)) # Generator expression
print(type(l)) # <type 'list'>
print(type(g)) # <type 'generator'>
print(sys.getsizeof(l)) # 9032
print(sys.getsizeof(g)) # 80
print("new")
# firstn with list
def firstn(n):
num, nums = 0, []
while num < n:
nums.append(num)
num += 1
return nums
# firstn with generator pattern
class firstn1(object):
def __init__(self, n):
self.n = n
self.num = 0
def __iter__(self):
return self
def __next__(self):
if self.num < self.n:
cur, self.num = self.num, self.num + 1
else:
raise StopIteration()
return cur
# firstn generator
def firstn2(n):
num = 0
while num < n:
yield num
num += 1
l = firstn(10000)
i = firstn1(10000)
g = firstn2(10000)
print(type(l))
print(type(i))
print(type(g))
print(sys.getsizeof(l))
print(sys.getsizeof(i))
print(sys.getsizeof(g))
|
people_1 = {
'first_name': 'Xinhan',
'last_name': 'Niu',
'age': 21,
'city': 'Hefei',
}
people_2 = {
'first_name': 'Zhuang',
'last_name': 'Li',
'age': '21',
'city': 'Hefei',
}
people_3 = {
'first_name': 'Gangjun',
'last_name': 'Zhang',
'age': '21',
'city': 'Hefei',
}
people = [people_1, people_2, people_3]
for person in people:
print(person)
|
while True:
print('\nPlease enter two numbers\n(Enter "q" to exit.)')
numbers_1 = input('first number: ')
if numbers_1 == 'q':
break
numbers_2 = input('second number: ')
if numbers_2 == 'q':
break
try:
sum = int(numbers_1) + int(numbers_2)
except ValueError:
print('Please enter numbers')
else:
print(sum)
|
lists = ['mountain', 'river', 'country', 'city', 'language']
print(sorted(lists))
print(len(lists))
|
favorite_numbers = {
'alice': [1, 3, 4],
'bob': [5, 67, 2],
'david': [3, 78, 5],
'eric': [3, 5, 7],
'frank': [23],
}
for name, numbers in favorite_numbers.items():
print(name)
print(numbers)
|
class Restaurant:
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
def describe_restaurant(self):
print(
f'restaurant name:{self.restaurant_name}\ncuisine type:{self.cuisine_type}'
)
def open_restaurant(self):
print('This restaurant is open.')
|
def make_album(singer_name, album_name, number_of_songs=None):
if number_of_songs == None:
album = {'singer': singer_name, 'album_name': album_name}
else:
album = {
'singer': singer_name,
'album_name': album_name,
'number': number_of_songs
}
return album
while True:
print('\nPlease input some information about the album')
print('(Enter "q" to quit)')
singer = input('Please input the singer name: ')
if singer == 'q':
break
album_name = input('Please input the album name: ')
if album_name == 'q':
break
print(make_album(singer, album_name))
|
# Задание 1 из домашней работы №8
class Date:
current_date: str = "00-00-0000"
def __init__(self, current_date):
self.current_date = current_date
def __str__(self):
return self.current_date
@classmethod
def get_date(cls, current_date):
c_day, c_month, c_year = (current_date.split("-"))
return int(c_day), int(c_month), int(c_year)
@staticmethod
def validate(day, month, year):
if year > 0:
if 1 <= month <= 12:
if 1 <= day <= 31:
return "Validation successful!"
else:
return "Enter valid date please!"
else:
return "Enter valid date please!"
else:
return "Enter valid date please!"
curr_date = Date("01-02-1993")
print(curr_date)
print(curr_date.get_date("01-02-1993"))
date_to_validate = curr_date.get_date("01-01-1996")
print(Date.validate(date_to_validate[0], date_to_validate[1], date_to_validate[2]))
|
#Задание 1 из домашней работы №2
saved_list = [1, 2, 3, 4]
created_list = [11, "Number", 11.086, saved_list, None]
length_of_list = int(len(created_list))
i = 0
while i < length_of_list:
print(type(created_list[i]))
i += 1
|
# Задание 3 вторая часть
translate = {'One': 'Odin', 'Two': 'Dva', 'Three': 'Tri', 'Four': 'Chetire'}
result = []
with open("translate.txt") as file_obj:
for line in file_obj:
strings = line.split(" - ")
print(strings)
print(translate[strings[0]], "-", strings[1])
result.append(translate[strings[0]] + " - " + strings[1])
print(result)
with open("translate_1.txt", "w") as file_obj:
file_obj.writelines(result)
|
ranges = [[53,57],[42,43],[58,63]]
result =['','']
outcomes = ["This diamond is bad","This is a good diamond"]
feedback = ["Inputs are all valid", "The number of properties must equal 3","At least one input is incorrect"]
properties = ['58','43','56']
def DiamondQuality (properties):
for i in range (len (properties)):
i = str(properties [i])
print (i)
if i.isalpha():
result [0] = feedback [2]
elif len (properties) != 3:
result [0] = feedback [1]
else:
for i in range (len(properties)):
print (i)
if ranges [i][0] <= int(properties[i]) <= ranges [i][1] :
result [0] = feedback [0]
result [1] = outcomes [1]
else:
result [0] = feedback [0]
result [1] = outcomes [0]
print (result)
return result
DiamondQuality(properties)
|
def duplicatereverse(text):
if len(text) == 0:
return text
else:
return text[-1] + duplicatereverse(text[0:-1]) + text[-1]
def main():
word = input ('Introduce text to duplicate and reverse: ', )
print("Input is: ", word)
print("Duplicated and Reversed text is: ", duplicatereverse(word))
main()
|
characters = [a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,zip]
digits = [0,1,2,3,4,5,,6,7,8,9]
symbols = [¬,!,£,$,%,^,&,*,(,),_,+]
from random import randint:
def randomCharacter (characters):
n
def makePassword (lenght):
password = ''
for i in range (lenght - 2):
password = password + randomCharacter ('abcdefghijklmnopqrstuvwxyz')
randomDigit = randomCharacter ('0123456789')
password = insertAtRandom (password, randomDigit)
randomSymbol = randomCharacter ('+!"£$%')
return password
def main():
value = int (input ('Introuduce lenght:',))
print (makePassword (value))
print ('Hello')
main ()
|
#printing function
a=int(input("enter the value of a "))
b=int(input("enter the value of b"))
def add():
return a+b
def sub():
return a-b
def mulitiplication():
return a*b
def divion():
return a%b
print("addition of ",a,"and",b,"=",add())
print("subtraction of ",a,"and",b,"=",sub())
print("mulitiplication of ",a,"and",b,"=",mulitiplication())
print("modules of",a,"and",b,"=",divion())
|
#printing values
print("the value of a=")
a=18
print(a)
print("the value of b=")
b=12
print(b)
c=a+b
print("the value of c=")
print(c)
|
import math
# Parameters - num is a positive integer
def prime_factorization(num):
curr = num
factors = {}
while curr % 2 == 0:
if not 2 in factors:
factors[2] = 1
else:
factors[2] = factors[2] + 1
curr = curr/2
divisor = 3
while curr > 1:
if curr % divisor == 0:
curr = curr/divisor
if not divisor in factors:
factors[divisor] = 1
else:
factors[divisor] = factors[divisor] + 1
else:
divisor = divisor + 2
return factors
# Will find the lcm of num and all numbers below > 0.
def lcm(num):
lcm_factors = {}
for x in xrange(2, num+1):
factors = prime_factorization(x)
for f in factors:
if f in lcm_factors:
lcm_factors[f] = max(factors[f], lcm_factors[f])
else:
lcm_factors[f] = factors[f]
product = 1
for n in lcm_factors:
for x in xrange(lcm_factors[n]):
product = product*n
return product
print lcm(10)
print lcm(20)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 18 23:51:59 2020
@author: ms
"""
n = 10**10-1
def isPrime(n):
# Corner cases
if (n <= 1):
return False
if (n <= 3):
return True
# This is checked so that we can skip
# middle five numbers in below loop
if (n % 2 == 0 or n % 3 == 0):
return False
i = 5
while(i * i <= n):
if (n % i == 0 or n % (i + 2) == 0):
return False
i = i + 6
return True
from itertools import permutations
base = '123456789'
done = False
l = len(str(n))
for l in range(len(str(n)), 0, -1):
for i in permutations(base[:l][::-1]):
i = int(''.join(i))
if i > n or not isPrime(i):
continue
done = True
break
if done:
break
if done:
print(i)
else:
print(-1)
|
import pandas as pd
def prescribe(disease):
remedy = []
medicine = []
df = pd.read_csv('deseaseremedies.csv', engine='python')
for row in df.values:
if row[0].lower() == disease:
remedy.append(row[1])
medicine.append(row[2])
while '-' in medicine:
medicine.remove('-')
print (remedy)
print (medicine[0])
return medicine[0]
# todo pass automatically
prescribe('migraine') # input must be lower case
|
# This class initially will create a bank object with a name you choose and
# then will print the following menu (it should print this menu, until user says exit)
from bank import Bank
from client import Client
import time
while True:
print('''
Welcome to International Bank!
Choose an option:
1. Open new bank account
2. Open existing bank account
3. Exit
''')
kies_1 = int(input('your choise : '))
if kies_1 == 1:
print('''
To create an account, please fill in the information below.
''')
a = str(input('Name: '))
b = int(input('Deposit amount: '))
Client(a,b)
elif kies_1 == 2:
print('''
To access your account, please enter your credentials below.
''')
while True:
name = input('Name: ')
account_number =int(input('Account Number: '))
authen = Bank.authentication(Bank,name,account_number)
if authen == True:
print('Authentication successful!')
break
else:
print('Authentication failed!\nReason: account not found.')
continue
while True:
print(f'''
Welcome {name}!
Choose an option:
1. Withdraw
2. Deposit
3. Balance
4. Exit
''')
kies_2 = int(input('your choise : '))
if kies_2 == 1:
amount = int(input('Withdraw amount: '))
Client.withdraw(Client,account_number,amount)
time.sleep(2)
elif kies_2 ==2:
deposit = int(input('Deposit amount: '))
Client.deposit(Client,account_number,deposit)
time.sleep(2)
elif kies_2 == 3:
Client.balance(Client,account_number)
time.sleep(2)
elif kies_2 == 4:
break
elif kies_1 == 3:
break
|
list = []
print("printing list",list)
if list==[] :
print("list is empty")
else :
print("list is not empty")
|
# The reduce(fun,seq) function is used to apply a particular function
# passed in its argument to all of the list elements mentioned
# in the sequence passed along.This function is defined
# in “functools” module.
#
# Working :
# At first step, first two elements of sequence are picked and
# the result is obtained.
# Next step is to apply the same function to the previously
# attained result and the number just succeeding the second
# element and the result is again stored.
# This process continues till no more elements are left in the container.
# The final returned result is returned and printed on console.
#
# python code to demonstrate working of reduce()
# importing functools for reduce()
import functools
# initializing list
lis = [ 1 , 3, 5, 6, 2, ]
# using reduce to compute sum of list
print ("The sum of the list elements is : ",end="")
print (functools.reduce(lambda a,b : a+b,lis))
# using reduce to compute maximum element from list
print ("The maximum element of the list is : ",end="")
print (functools.reduce(lambda a,b : a if a > b else b,lis))
|
try:
f=open('hi.txt')
print("from try")
print(f.read())
if f.name=='hi.txt':
print ("hi again")
raise FileNotFoundError #atemshi l exception lewla
# specific exception
except IOError as e:
print('First!')
except FileNotFoundError :
print("stooooop")
# general exception at the bottom of the code
except Exception as e:
print(e)
else :
print("hi babay")
finally:
# this finnaly will always be executed , we can do many tings like closing db file ....
print("see y soon ")
print("end of programme")
|
def title_case(title, minor_words):
ignore_minor = True
r = ''
for t in title.lower().split(' '):
r += ' {}'.format(
t.capitalize()
if ignore_minor or t not in minor_words.lower().split(' ')
else t
)
ignore_minor = False
return r[1:]
def title_case_best_solution(title, minor_words=''):
title = title.capitalize().split()
minor_words = minor_words.lower().split()
return ' '.join([word if word in minor_words else word.capitalize() for word in title])
|
class TheBlackJackDivTwo():
def score(self,cards):
count=0
for i in range(len(cards)):
print cards[i][0]
if cards[i][0]=='2' or cards[i][0]=='3' or cards[i][0]=='4' or cards[i][0]=='5' or cards[i][0]=='6' or cards[i][0]=='7' or cards[i][0]=='8' or cards[i][0]=='9':
print "x"
count+=int(cards[i][0])
elif cards[i][0]=="T":
count+=10
elif cards[i][0]=="A":
count+=11
else:
count+=10
return count
x=TheBlackJackDivTwo()
print x.score(("3S", "KC", "AS", "7C", "TC", "9C", "4H", "4S", "2S"))
|
class InsideOut(object):
def unscramble(self,line):
#self.line=line
#line= list(line)
#x=len(line)/2
#print x,len(line)
r=s=""
#r+=line[:]
#r+=line[0,x]
#r+=line[len(line)/2:]
#r+=line[0:len(line)/2]
for i in range(len(line)/2,len(line)):
r+=line[i]
for i in range(0,len(line)/2):
r+=line[i]
for i in range(len(r)-1,-1,-1):
s+=r[i]
return s
x=InsideOut()
print x.unscramble(("I ENIL SIHTHSIREBBIG S"))
|
class SoccerLeagues(object):
def points(self,matches):
r=[]
for i in range(len(matches)):
p=0
for j in range(len(matches[i])):
while(i!=j):
if matches[i][j]=='W':
p+=3
break
elif matches[i][j]=='D':
p+=1
break
r.append(p)
return r
x=SoccerLeagues()
print x.points(("-WW","W-W","WW-"))
|
class WhiteCells(object):
def countOccupied(self,board):
self.board=""
count=0
#board=list(board)
for i in range(len(board)):
c_1=board[i]
#c_1=list(c_1)
if i%2==0:
for j in range(0,len(c_1),2):
if c_1[j]=='F':
count+=1
else:
for j in range(1,len(c_1),2):
if c_1[j]=='F':
count+=1
return count
#print "count is %d"%count
#print c_1
#print c_1[j]
#print board[i]
print ""
for i in range(len(board)):
if i%2!=0:
print board[i]
x=WhiteCells()
print x.countOccupied(("FFFFFFFF","........","........","........","........","........","........","........"))
|
import WordSupply
# add classes for Player for multiplayer version
def main():
print("Starting a game of Hangman...\n")
welcome()
def startgame(attempts_int, wordLength_int):
attemptedChars_list = []
word_str = WordSupply.pickWord(wordLength_int)
gameWord_str = "*" * len(word_str)
print(f"GAME WORD: {gameWord_str}")
#loop, chagne to true
while '*' in gameWord_str:
userGuess_char = input("Enter a character: ")
if userGuess_char in attemptedChars_list:
print(f"You has already tried {userGuess_char}.")
print('-'*75)
elif userGuess_char in word_str:
tempWord_str = ""
for i in range(len(word_str)-1):
if userGuess_char != word_str[i]:
if gameWord_str[i] == "*":
tempWord_str += (word_str[i]).replace(word_str[i], "*")
else:
tempWord_str += word_str[i]
else:
tempWord_str += userGuess_char
gameWord_str = tempWord_str
print(f"Correct {userGuess_char} was in word: {gameWord_str}")
print('-'*75)
attemptedChars_list.append(userGuess_char)
else:
attempts_int -= 1
print(f"Wrong {userGuess_char} was not in word: {gameWord_str}. {attempts_int} more attempts remaining")
print('-'*75)
if attempts_int == 0:
#one last attempt, say the word (use google voice)
print(f"YOU LOST the word was: {word_str}")
finished()
break
print("YOU WON")
finished()
def finished():
playAgin_char = input("Want to play again? (y/n)")
if playAgin_char == 'y':
welcome()
else:
print("Finished")
def welcome():
attempts_int = wordLength_int = 0
while True:
attempts_int = int(input("Select the number of attempts [1-15]: "))
if(attempts_int > 15 and attempts_int < 0):
print("You entered a wrong number for the number of attempts, try again.")
continue
wordLength_int = int(input("Select the minimum word length [4-12]: "))
if(wordLength_int > 12 and attempts_int < 4):
print("You entered a wrong number for the number of attempts, try again")
continue
break
startgame(attempts_int, wordLength_int)
if __name__ == "__main__":
main()
|
class LinkedList:
"""
Linked list implementation
TODO: have a linked list class and use it to create single, double, and
circular linked list classes...
"""
def __init__(self):
"""
Initializes a Doubly Linked list
Example:
```python
list = LinkedList()
```
"""
self.head = None
self.count = 0
"""
The head of the linked list, or first element.
"""
def append(self, data):
"""
Given an input, creates a node, and adds to the end of linked list.
Example:
```python
list = LinkedList()
list.append("foo")
# `list` contains a node with a data property set to "foo"
```
"""
new_node = Node(data)
if self.head is None:
self.head = new_node
else:
current_node = self.head
past_node = None
while current_node is not None:
past_node = current_node
current_node = current_node.next
past_node.next = new_node
new_node.past = past_node
self.count += 1
def size(self):
"""
Return the number of nodes in the linked list.
Example:
```python
list = LinkedList()
# 3 nodes inserted into list
print(list.size()) # prints 3 to stdout
```
"""
return self.count
def delete(self, data):
"""
Traverse list looking for `data`; if a node's data matches the input
it's deleted.
All matching nodes are deleted.
Example:
```python
list = LinkedList()
# nodes are inserted and the list, an array, is [1, 2, 3, 3, 4, 5]
list.delete(3)
# list as an array will now be [1, 2, 4, 5]
```
"""
current_node = self.head
last_node = None
while current_node is not None:
if current_node.data == data:
if current_node == self.head:
self.head = current_node.next
else:
last_node.next = current_node.next
if current_node.next is not None:
current_node.next.past = last_node
self.count -= 1
else:
last_node = current_node
current_node = current_node.next
def insert(self, data):
"""
Given an input, create a node, and insert into the head of the list.
Example:
```python
list = LinkedList()
list.insert("foo")
# `list` contains a node with a data property set to "foo"
```
"""
new_node = Node(data)
self.count += 1
if self.head is None:
self.head = new_node
else:
next_node = self.head
self.head = new_node
self.head.next = next_node
next_node.past = new_node
def reverse(self):
"""
Reverse the order of the list.
Example:
```python
# given a list, as an array, looks like [1, 2, 3, 4, 5]
list.reverse()
# list will now, as an array, look like [5, 4, 3, 2, 1]
```
"""
previous = None
current_node = self.head
while current_node is not None:
# save a reference to next node
next_node = current_node.next
# reverse current pointers
current_node.past = current_node.next
current_node.next = previous
# save previous and point to next node
previous = current_node
current_node = next_node
self.head = previous
def to_array(self):
"""
Returns a linked list as an array of the data properties of each node.
Example:
```python
# given a list with 3 nodes with data 1, 2, 3
print(list.to_array())
# will print '[1, 2, 3]'
```
"""
array = []
node = self.head
if node is None:
return array
while node.next is not None:
array.append(node.data)
node = node.next
array.append(node.data)
return array
class Node:
def __init__(self, data):
"""
Given an input, creates a new node, to be used in a linked list.
"""
self.data = data
"""
The data the node is storing.
"""
self.next = None
"""
Pointer to the next node in the list.
"""
self.past = None
"""
Pointer to the previous node in the list.
"""
def to_string(self):
"""
Return a node as a string with each property on a newline.
"""
strs = ["Node ID: {}".format(self)]
strs.append("Node data: {}".format(self.data))
strs.append("Node next: {}".format(self.next))
strs.append("Node past: {}".format(self.past))
return "\n".join(strs)
|
import xml.etree.ElementTree as ET
import sys
def read_xml(xml_file):
tree = ET.parse(xml_file)
root = tree.getroot()
return root
def search(term, root):
words = term.lower().split()
output = []
i = 0
for word in words:
for child in root:
if word == root[i][0].text:
for item in child.findall('accounts/number'):
output.append(item.text)
i = i+1
i=0
result = []
for item in output:
if item not in result:
result.append(item)
print('The Account Numbers associated with <',term,'> is ', result)
if __name__=="__main__":
root = read_xml(sys.argv[1])
search(sys.argv[2],root)
|
#!/usr/bin/python3
import geopandas as gp
import pandas as pd
import argparse
'''Code takes latitude and longitude coordinates along with path to shapefile
and returns a neighborhood council identifier in response. Can be run as
executable from command line or imported into another codebase as the
classify_point function and run.
SHAPEFILE: http://geohub.lacity.org/datasets/674f80b8edee4bf48551512896a1821d_0/data
USE: python3 geocode_nc.py -lat 34.040871 -long -118.235202 -shp shp/ '''
parser = argparse.ArgumentParser(description='Assign a point within Los Angeles to a neighborhood council using a shapefile boundary')
parser.add_argument('-lat', '--latitude', type=float,
help='latitude coordinate value')
parser.add_argument('-long', '--longitude', type=float,
help='longitude coordinate value')
parser.add_argument('-shp', '--shapefile',
help='path to shapefile directory')
args = parser.parse_args()
def load_coords(latitude, longitude):
# load coordinates as geopandas dataframe
df = pd.DataFrame([{'name': 'POINT', 'lat': latitude, 'long': longitude}])
gp_coord = gp.GeoDataFrame(df, geometry=gp.points_from_xy(df.long, df.lat))
gp_coord.crs = "epsg:4326"
return gp_coord
def load_shapefile(file_path):
# load shapefile
gp_shape = gp.read_file(file_path)
gp_shape.crs = "epsg:4326" # This is true for NC shapefile
return gp_shape
def classify_point(latitude, longitude, shapefile_path):
# perform join between coords and shapefile
pt = load_coords(latitude, longitude)
shp = load_shapefile(shapefile_path)
joined_shp = gp.sjoin(pt, shp, how='left', op='intersects')
nc = joined_shp.Name[0]
# Return point classification
if nc != nc: # Check if returned value is nan
return 'Point outside Los Angeles County'
else:
return nc
if __name__ == '__main__':
nc = classify_point(latitude=args.latitude,
longitude=args.longitude,
shapefile_path=args.shapefile)
print(nc)
|
"""
Space Station Simulation
Using SimPy and Tkinter
"""
import numpy as np
import simpy
from tkinter import *
import tkinter.scrolledtext as tkscrolled
HOUR = 60 # 60 minutes in a hour
SIM_YEAR = 1 # How many years will continue to simulate
HUMAN_NUMBER = 5 # How many humans are in the simulation
YEAR = 5 # 365 days in a year
DAY = 24 * HOUR # 24 hours in a day
MY_SIM_TIME = DAY*YEAR*SIM_YEAR # Simulation works for a year
WORK_VARIANCE = 2 # Variance of work time
MEAL_VARIANCE = 3 # Variance of meal preparation
BREATH_VARIANCE = 1 # Variance inhaling in a minute
WORK_TIME = 0.75 * HOUR # Average work time in minutes
BREAK_TIME = 0.25 * HOUR # Average break time between work times in minutes
WORK_NUMBER = 8 # How many times they would work in a day
TOTAL_MEAL_TIME = 1.5 * HOUR # Meal time in minutes
MEAL_READY_TIME = 0.5 * HOUR # Meal preparations in minutes
RELAXATION_TIME = 3.5 * HOUR # Relaxation time in minutes (Watch a movie or workout)
SLEEP_TIME = 8 * HOUR # Sleep time of every human
BREATH_NUMBER = 15 # Average breath number of a human in a minute
OXYGEN_CONSUMPTION_SECOND = 2 # Average oxygen consumption of a human in a second
TOTAL_OXYGEN_CONSUMPTION = 0 # General oxygen consumption of the system
AVERAGE_WATER_WASTE = 350 # Average water waste in liter
AVERAGE_CALORIE_REQUIREMENT = 2000 # Average calorie requirement for a human
CALORIE_VARIANCE = 100 # Variance of required calories
TOTAL_CALORIE_CONSUMPTION = 0 # Total calorie consumption during the simulation
WATER_RECYCLE = 0.15 # Rate of wasted water in recycling
WATER_VARIANCE = 50 # Variance of consumption of water for a human in a day
class Human(object):
def __init__(self, env, name):
self.env = env
self.name = name
def food(self, number):
calorie_requirement = int(np.random.normal(AVERAGE_CALORIE_REQUIREMENT, CALORIE_VARIANCE))
temp = TOTAL_CALORIE_CONSUMPTION + calorie_requirement
print("\tToday Subject consumed %d calorie"
% calorie_requirement)
temp2 = "\tToday Subject consumed %d calorie" % calorie_requirement
changeText(text=str(temp2), number=number)
globals().update(TOTAL_CALORIE_CONSUMPTION=int(temp))
def oxygen(self, rate, time, number):
oxygen_consumption = int(np.random.normal(BREATH_NUMBER, BREATH_VARIANCE))
output = oxygen_consumption / OXYGEN_CONSUMPTION_SECOND * time * rate
print("Subject consumed %d grams oxygen"
% output)
temp = TOTAL_OXYGEN_CONSUMPTION + output
globals().update(TOTAL_OXYGEN_CONSUMPTION=int(temp))
temp2 = "Subject consumed %d grams oxygen" % output
changeText(text=str(temp2), number=number)
def water():
water_consumption = int(np.random.normal(AVERAGE_WATER_WASTE, WATER_VARIANCE))
output = water_consumption * WATER_RECYCLE
water_waste = HUMAN_NUMBER * output * YEAR *SIM_YEAR
print("Total water wasted by human %d" % water_waste)
return "Total water wasted by human %d" % water_waste
def waking_up(self, number):
preparation_time = int(np.random.normal(MEAL_READY_TIME, MEAL_VARIANCE))
meal_time = TOTAL_MEAL_TIME - preparation_time
print("Subject spend %d minute for the meal preparation. So Subject have %d minutes to eat "
% (preparation_time, meal_time))
temp = "Subject spend %d minute for the meal preparation. So Subject have %d minutes to eat " % (preparation_time, meal_time)
changeText(text=str(temp), number=number)
Human.oxygen(self, 1, TOTAL_MEAL_TIME ,number)
return TOTAL_MEAL_TIME
def morning_work_hour_time(self, number):
total_worktime = 0
total_breaktime = 0
for i in range(int(WORK_NUMBER/2)):
work_time = int(np.random.normal(WORK_TIME, WORK_VARIANCE))
break_time = HOUR - work_time
print("This Subject should work %d minutes and break for %d minutes" % (work_time, break_time))
total_worktime += work_time
total_breaktime += break_time
print("This Subject worked for %d minutes and breaks for %d minute in total before meal"
% (total_worktime, total_breaktime))
temp = "This Subject worked for %d minutes and breaks for %d minute in total before meal" % (total_worktime, total_breaktime)
changeText(text=str(temp), number=number)
time = (total_worktime + total_breaktime)
Human.oxygen(self, 1.25, time, number)
return time
def lunch_time(self, number):
preparation_time = int(np.random.normal(MEAL_READY_TIME, MEAL_VARIANCE))
meal_time = TOTAL_MEAL_TIME - preparation_time
print("Subject spend %d minute for the meal preparation. So they have %d minutes to eat "
% (preparation_time, meal_time))
temp = "Subject spend %d minute for the meal preparation. So they have %d minutes to eat " % (preparation_time, meal_time)
changeText(text=str(temp), number=number)
Human.oxygen(self, 1, TOTAL_MEAL_TIME, number)
return TOTAL_MEAL_TIME
def evening_work_hour_time(self, number):
total_worktime = 0
total_breaktime = 0
for i in range(int(WORK_NUMBER/2)):
work_time = int(np.random.normal(WORK_TIME, WORK_VARIANCE))
break_time = HOUR - work_time
print("This Subject should work %d minutes and break for %d minutes" % (work_time, break_time))
total_worktime += work_time
total_breaktime += break_time
print("This Subject worked for %d minutes and breaks for %d minute in total before meal"
% (total_worktime, total_breaktime))
temp = "This Subject worked for %d minutes and breaks for %d minute in total before meal" % (total_worktime, total_breaktime)
changeText(text=str(temp), number=number)
time = (total_worktime + total_breaktime)
Human.oxygen(self, 1.25, time,number)
return time
def dinner_time(self, number):
preparation_time = int(np.random.normal(MEAL_READY_TIME, MEAL_VARIANCE))
meal_time = TOTAL_MEAL_TIME - preparation_time
print("Subject spend %d minute for the meal preparation. So Subject have %d minutes to eat "
% (preparation_time, meal_time))
temp = "Subject spend %d minute for the meal preparation. So Subject have %d minutes to eat " % (preparation_time, meal_time)
changeText(text=str(temp), number=number)
Human.oxygen(self, 1, TOTAL_MEAL_TIME, number)
return TOTAL_MEAL_TIME
def relax_time(self, number):
Human.oxygen(self, 1, RELAXATION_TIME, number)
return RELAXATION_TIME
def sleep_time(self, number):
Human.oxygen(self, 0.75, SLEEP_TIME, number)
Human.food(self,number)
return SLEEP_TIME
def setup():
resources = []
for number in range(HUMAN_NUMBER):
multienv = simpy.Environment()
simpy.Environment()
human = Human(multienv, number)
resources.append([multienv, human])
return resources
def pro(env, human):
old_time = env.now
yield env.timeout(human.waking_up(human.name))
new_time = env.now - old_time
print("\n\tBreakfast end after %d minutes for human %d\n" % (new_time, human.name))
temp = "\n\tBreakfast end after %d minutes for human %d\n" % (new_time, human.name)
changeText(text=str(temp), number=human.name)
def pro2(env, human):
old_time = env.now
yield env.timeout(human.morning_work_hour_time(human.name))
new_time = env.now - old_time
print("\n\tWork time end after %d minutes for human %d\n" % (new_time, human.name))
temp = ("\n\tWork time end after %d minutes for human %d\n" % (new_time, human.name))
changeText(text=str(temp), number=human.name)
def pro3(env, human):
old_time = env.now
yield env.timeout(human.lunch_time(human.name))
new_time = env.now - old_time
print("\n\tLunch end after %d minutes for human %d\n" % (new_time, human.name))
temp = "\n\tLunch end after %d minutes for human %d\n" % (new_time, human.name)
changeText(text=str(temp), number=human.name)
def pro4(env, human):
old_time = env.now
yield env.timeout(human.evening_work_hour_time(human.name))
new_time = env.now - old_time
print("\n\tWork time end after %d minutes for human %d\n" % (new_time, human.name))
temp = "\n\tWork time end after %d minutes for human %d\n" % (new_time, human.name)
changeText(text=str(temp), number=human.name)
def pro5(env, human):
old_time = env.now
yield env.timeout(human.dinner_time(human.name))
new_time = env.now - old_time
print("\n\tDinner time end after %d minutes for human %d\n" % (new_time, human.name))
temp = "\n\tDinner time end after %d minutes for human %d\n" % (new_time, human.name)
changeText(text=str(temp), number=human.name)
def pro6(env, human):
old_time = env.now
yield env.timeout(human.relax_time(human.name))
new_time = env.now - old_time
print("\n\tRelaxatation time end after %d minutes for human %d\n" % (new_time, human.name))
temp = "\n\tRelaxatation time end after %d minutes for human %d\n" % (new_time, human.name)
changeText(text=str(temp), number=human.name)
def pro7(env, human):
old_time = env.now
yield env.timeout(human.sleep_time(human.name))
new_time = env.now - old_time
print("\n\tSleep time end after %d minutes for human %d\n" % (new_time, human.name))
temp = "\n\tSleep time end after %d minutes for human %d\n" % (new_time, human.name)
changeText(text=str(temp), number=human.name)
def start():
results = []
res = setup()
print(SIM_YEAR)
globals().update(MY_SIM_TIME = DAY * YEAR * SIM_YEAR)
while res[0][0].now < MY_SIM_TIME:
for i in res:
i[0].process(pro(i[0], i[1]))
i[0].run()
for i in res:
i[0].process(pro2(i[0], i[1]))
i[0].run()
for i in res:
i[0].process(pro3(i[0], i[1]))
i[0].run()
for i in res:
i[0].process(pro4(i[0], i[1]))
i[0].run()
for i in res:
i[0].process(pro5(i[0], i[1]))
i[0].run()
for i in res:
i[0].process(pro6(i[0], i[1]))
i[0].run()
for i in res:
i[0].process(pro7(i[0], i[1]))
i[0].run()
results.append(Human.water())
print("Total of oxygen consuption of system %d grams of oxygen" %TOTAL_OXYGEN_CONSUMPTION)
print("To produce %d gram oxygen %d gram water should be electrolysed" % (TOTAL_OXYGEN_CONSUMPTION , ((TOTAL_OXYGEN_CONSUMPTION/1000) * 36) / 22.4))
print("Total calorie requirement all space staion is %d calorie" %TOTAL_CALORIE_CONSUMPTION)
results.append("Total of oxygen consuption of system %d grams of oxygen" %TOTAL_OXYGEN_CONSUMPTION)
results.append("To produce %d gram oxygen %d gram water should be electrolysed" % (TOTAL_OXYGEN_CONSUMPTION , ((TOTAL_OXYGEN_CONSUMPTION/1000) * 36) / 22.4))
results.append("Total calorie requirement all space staion is %d calorie" %TOTAL_CALORIE_CONSUMPTION)
return results
# start()
TEXTBOX = []
def changeText(text, number):
text = text + "\n"
TEXTBOX[number].insert(INSERT, text)
TEXTBOX[number].see(END)
def run():
globals().update(HUMAN_NUMBER=int(human_number.get()))
globals().update(SIM_YEAR=int(year_number.get()))
mainBox = tkscrolled.ScrolledText(root, width=64, height=10)
mainBox.config(font=("consolas", 10), undo=True, wrap='word')
mainBox.grid(row=3, column=1)
for i in range(HUMAN_NUMBER):
temp = "Human %d" % i
Textbox = tkscrolled.ScrolledText(mainBox, width=60, height=10)
Textbox.config(font=("consolas", 10), undo=True, wrap='word')
Textbox.see(END)
Label(mainBox, text=temp).grid(row=(((int(i/4))+2)*2)-1, column=(i % 4))
Textbox.grid(row=((int(i/4))+2)*2, column=(i % 4))
TEXTBOX.append(Textbox)
results = start()
top = Toplevel()
top.title("Results of Simulation")
resultText = ""
for i in range(len(results)) :
resultText +=results[i]
resultText += "\n"
msg = Message(top, text=resultText)
msg.config(width=500)
msg.pack()
button = Button(top, text="Dismiss", command=top.destroy)
button.pack()
root = Tk()
w, h = root.winfo_screenwidth(), root.winfo_screenheight()
root.geometry("%dx%d+0+0" % (w, h))
Label(root, text="Human Number").grid(row=0, column=0)
human_number = Scale(root, from_=1, to=20, orient=HORIZONTAL)
human_number.grid(row=0, column=1)
Label(root, text="Year").grid(row=1, column=0)
year_number = Scale(root, from_=1, to=10, orient=HORIZONTAL)
year_number.grid(row=1, column=1)
b = Button(root, text="Run Simulation", command=run)
b.grid(row=1, column=2)
root.mainloop()
|
#### Simple decorators
def my_decorator(func):
def wrapper():
print('something is happening before the function is called')
func()
print('something is happeing after the function is called')
return wrapper
def say_whee():
print('Whee!')
say_whee = my_decorator(say_whee)
say_whee()
#Another example
from datetime import datetime
#wrap around another function
def not_during_the_night(func):
def wrapper():
if 7<= datetime.now().hour < 22:
func()
else:
pass #Hush, the neighbors are asleep
return wrapper
say_whee()
say_whee = not_during_the_night(say_whee)
###snytax sugar
def my_decorator(func):
def wrapper():
print('before the function is called')
func()
print('after the function is called')
return wrapper
@my_decorator
def say_whee():
print('Whee!')
print('styling decorator----')
say_whee()
|
#Inheritance: What common attributes and behaviors exist between real-world objects?
#Inheritance models an is a relationship (Cat is an animal; Apple is a fruit; Fish is a food and an animal)
#Composition: How are objects in the real world composed (made up) of one another?
#Composition models a has a relationship (A car is composed of an engine)
#In Python, one class can be a component of another composite class
class MyError(Exception):
def __init__(self, message):
super().__init__(message)
#raise MyError("Something went wrong")
#Interface: a description of the features and behaviors
class PayrollSystem:
def calculate_payroll(self, employees):
print("Calculating Payroll")
print('===================')
for employee in employees:
print(f'Payroll for: {employee.id} - {employee.name}')
print(f'- Check Amount: {employee.calculate_payroll()}')
print('')
#this is an abstract class. We can only inherit from it but not instantiate it
from abc import ABC, abstractmethod
class Employee(ABC):
def __init__(self, id, name):
self.id = id
self.name = name
@abstractmethod
def calculate_payroll(self):
pass
class SalaryEmployee(Employee):
def __init__(self, id, name, weekly_salary):
super().__init__(id, name)
self.weekly_salary = weekly_salary
def calculate_payroll(self):
return self.weekly_salary
class HourlyEmployee(Employee):
def __init__(self, id, name, hours_worked, hour_rate):
super().__init__(id, name)
self.hours_worked = hours_worked
self.hour_rate = hour_rate
def calculate_payroll(self):
return self.hour_rate * self.hours_worked
class ComissionEmployee(SalaryEmployee):
def __init__(self, id, name, weekly_salary, commission):
super().__init__(id, name, weekly_salary)
self.commission = commission
def calculate_payroll(self):
fixed = super().calculate_payroll() # same as super().weekly_salary()
return fixed + self.commission
salary_employee = SalaryEmployee(1, "John Smith", 1500)
hourly_employee = HourlyEmployee(2, "Jane Doe", 40, 15)
commission_employee = ComissionEmployee(3, "Kevin Bacon", 1000, 250)
payroll_system = PayrollSystem()
payroll_system.calculate_payroll([
salary_employee,
hourly_employee,
commission_employee
])
class Manager(SalaryEmployee):
def work(self, hours):
print(f'{self.name} screams and yells for {hours}.')
class Secretary(SalaryEmployee):
def work(self, hours):
print(f'{self.name} expends {hours} hours doing office paperwork.')
class SalesPerson(ComissionEmployee):
def work(self, hours):
print(f'{self.name} expends {hours} hours on the phone.')
class FactoryWorker(HourlyEmployee):
def work(self, hours):
print(f'{self.name} manufactures gadgets for {hours} hours.')
class ProductivitySystem:
def track(self, employees, hours):
print("Tracking productivity")
print('=====================')
for employee in employees:
employee.work(hours)
print('')
class TemporarySecretary(Secretary, HourlyEmployee):
def __init__(self, id, name, hours_worked, hour_rate):
HourlyEmployee.__init__(self, id, name, hours_worked, hour_rate)
def calculate_payroll(self):
return HourlyEmployee.calculate_payroll(self)
#TODO: finish the rest materials on composition
|
from PyPDF2 import PdfFileReader, PdfFileWriter
def rotate_pages(pdf_path):
pdf_writer = PdfFileWriter()
pdf_reader = PdfFileReader(pdf_path)
#rotate page 90 degrees to the right
page_1 = pdf_reader.getPage(0).rotateClockwise(90)
pdf_writer.addPage(page_1)
#rotate page 90 degrees to the left
page_2 = pdf_reader.getPage(1).rotateCounterClockwise(90)
pdf_writer.addPage(page_2)
#rotate page upside down
page_3 = pdf_reader.getPage(2).rotateCounterClockwise(180)
pdf_writer.addPage(page_3)
#add a page in normal orientation
pdf_writer.addPage(pdf_reader.getPage(3))
with open('rotated_pages.pdf', 'wb') as fh:
pdf_writer.write(fh)
if __name__=="__main__":
path = "Jupyter_Notebook.pdf"
rotate_pages(path)
|
class Color:
def __init__(self, rgb_value, name):
self.rgb_value = rgb_value
self._name = name
def _set_name(self, name):
if not name:
raise Exception("Invalid Name")
self._name = name
def _get_name(self):
return self._name
name = property(_set_name, _get_name)
## Decorators - another way to create properties
class Foo:
@property
def foo(self):
return 'bar'
from urllib.request import urlopen
class WebPage:
def __init__(self, url):
self.url = url
self._content = None
@property
def content(self):
if not self._content:
print("Retrieving New Page...")
self._content = urlopen(self.url).read()
return self._content
class AverageList(list):
@property
def average(self):
return sum(self)/len(self)
#a = AverageList([1,2,3,4])
# a.average
|
def my_sum(a,b):
return a+b
#my_sum(a, b)
def my_sum2(integers):
res = 0
for x in integers:
res += x
return res
ints = [1,2,3]
print(my_sum2(ints))
def my_sum3(*args):
res = 0
#Iterating over the Python args tuple
for x in args:
res += x
return res
print(my_sum3)
def concatenate(**kwargs):
res = ""
for arg in kwargs.values():
res += arg
return res
print(concatenate(a="real", b='Python', c="Is", d='Great', e='!'))
#order matters
def my_function(a,b, *args, **kwargs):
pass
#unpacking args
list1 = [1,2,3]
list2 = [4,5]
list3 = [6,7,8,9]
print(my_sum3(*list1, *list2, *list3))
my_list = [1,2,3,4,5,6]
a, *b, c = my_list
print(a)
print(b)
print(c)
#a is 1
#b is [2,3,4,5]
#c is 6
list_1 = [1,2,3]
list_2 = [4,5,6]
merged_list = [*list_1, *list_2]
dict1 = {'A': 1, "B": 2}
dict2 = {"C": 3, "D": 4}
merged_dict = {**dict1, **dict2}
a = [*"RealPython"] # a will become a list of characters
#readability count
|
# !/usr/bin/python
# Part 1 Step 1 : Hang Huynh
# pillomavirus_type_63_uid15486 This assume that the "virus genome files" is saved manually file by file
# grabbing files with common ".fas" files in the same directories
# input "common name" by user
import os, glob
from Bio import SeqIO
import fileinput
# Finding the common name of the virus genome in the file to be scan against
# the first letter should be capitalized (based on how i saved the file)
def fileDirectory(name):
file1 = '*.fna'
file2 = name # this part can be change depends on how the data is save
file3 = (file2) + (file1)
file4 = '*' + (file3) # and if the user select "none" then it assume that the user
filelist = glob.glob(file4) # is having all the virus family genome in one file
with open ("virus.fas", "w") as outfile: # or do not have the common name such as new virus type ect.
for f in filelist:
with open(f, "rU") as infile:
seq_records = SeqIO.parse(infile, "fasta")
SeqIO.write(seq_records, outfile, "fasta")
fileDirectory()
"""# This part create the file called "mergeall.fas" which merge all the file...
# with the common name "user input common name"
# This part merge the "Mergeall.fas" file with "userinput.fas" file to...
# create the merging.fas file
def mergeDirectory():
file5 = ["mergeall.fas","test.fas"] # ".fas" is user input file
with open ("virus.fas", "w") as outfile:
for f in file5:
with open(f, "rU") as infile:
seq_records = SeqIO.parse(infile,"fasta")
SeqIO.write(seq_records, outfile,"fasta")
mergeDirectory()
# the final file ouput called "virus.fas" as the input for the ClustalW alignment
"""
# Part 1 Step 2 : Andres Wong
# This will take the user input merged with deposited database genomes
# As a fasta file
# It will perform a multiple sequencfe alignment with ClustalW
# Then look at conserved regions
# From the user input, it will make a list of conserved seqences
# As long as they meet the minimum requirements
def alineacion():
from Bio import SeqIO
from Bio.Align.Applications import ClustalwCommandline
from Bio import AlignIO
# This is the file from previous step, named Ebola.fas
MERGED = "virus.fas"
ALIGNED = "virus.aln"
INPUT = ClustalwCommandline("clustalw", infile = MERGED)
INPUT()
#ALIGNED = AlignIO.read(ALIGNED, "clustal")
# print ALIGNED
# End of Andrew R modified code
# This program will scan through the ClustalW output
# It will tell you the length of the longest continuous sequence
def uninterrupted():
zapato = open('virus.aln', 'r')
longest = 0
das_list = []
blank = 0
nada = 0
howmuch = 0
hone_it = []
max_me = 0
min_me = 0
range_it = ()
map_it = []
location = 0
for line in zapato:
if line[0] == ' ':
blank += 36
for item in line:
howmuch += 1
if item == '*':
longest += 1
if longest >= 17:
location = howmuch - blank
hone_it.append(location)
max_me = max(hone_it)
min_me = min(hone_it)
if item != '*' and longest > 0:
longest = 0
range_it = (min_me,max_me)
hone_it = []
if range_it not in map_it and range_it != (0, 0) and range_it != ():
map_it.append(range_it)
zapato.close()
# print map_it
# print howmuch
# print location
return map_it
# The minimum length criteria can vary, for now, 17 nucleotide minimum shRNA
def place():
map_it = uninterrupted()
primero = 0
segundo = 0
where_is = ()
WALDO = []
criteria = 16
for item in map_it:
primero = item[0] - criteria
segundo = item[1]
where_is = (primero,segundo)
WALDO.append(where_is)
# print WALDO
return WALDO
# For ceviche to work the program has to assign a name to user input variable
# It can be called EBO for now
# It cannot have any aronym of nucleotide bases
# Just change the Tai in code below to name given to user sequence
def ceviche():
zapato = open('virus.aln', 'r')
picante = ''
valid = ['C','T','G','A','-']
for line in zapato:
if line[0] == 'g' and line[1] == 'i' and line[2] == '|' and line[3] == '1':
for item in line:
if item in valid:
picante += str(item)
zapato.close()
return picante
def candidates():
picante = ceviche()
WALDO = place()
ready = 0
go = 0
CONSERVED = ''
OUTPUT = []
for item in WALDO:
ready = item[0]
go = item[1] + 1
CONSERVED = picante[ready:go]
OUTPUT.append(CONSERVED)
return OUTPUT
# Below is in FASTA format
# Gives te sequences to BLAST against human genome
def split_em():
OUTPUT = candidates()
TERMINATOR = []
original = ''
for item in OUTPUT:
# print 'This is the original long sequence %s and is %s long' % (item,len(item))
while len(item) > 16:
TERMINATOR.append(item)
original = item
item = item[1:]
# Code below compensates for item being appended earlier
# This way, the length is one more than the original item
while len(original) > 17:
original = original[0:-1]
# print original
TERMINATOR.append(original)
return TERMINATOR
def to_blast():
alineacion()
TERMINATOR = split_em()
blast_me = open('andres.fas','a')
fasta_id = 0
for item in TERMINATOR:
fasta_id += 1
blast_me.write('>pre_candidate_%s\n' % (fasta_id))
blast_me.write('%s\n' % (item))
blast_me.close()
# Read the file andres.fas for the next step for BLAST
# User interface below
to_blast()
"""
#IIIIIIII
# parser of alignment from blastn output
# based on the currently deprecated biopython/NCBIStandalone.py
# Biopython's old parser of blastall output
# Small parts of the original codes are modified to fit our needs
# blastn_scanner: input a blastn_output file, looking for info we want to parse.
class blastn_scanner (object):
def __init__ (me,
version, #what version of blastn used?
database_name, #what db used for blastn?
database_sequences, #number of sequences in the target db
database_letters, #total size (in basepairs) of the db
counts_hits, #number of targets hit
results): #holder for all the info we want parsed for next step
#results contains info produced from class blastn_result
me.version = version
me.database_name = database_name
me.database_sequences = database_sequences
me.database_letters = database_letters
me.counts_hits = counts_hits
me.results = results
# blastn_results: holder of all info from HSP
class blastn_results (object):
def __init__ (me,
identities, #% identities; 100% for siRNA
strand, #Plus or Minus
query_sequence, #sequences matched to target, saved for next step
query_start,
query_end): #coordinates of the query HSP - not much meaningful for us
me.identities = identities
me.strand = strand
me.query_sequence = query_sequence
me.query_start = query_start
me.query_end = query_end
def scan_blastn (blastn_output_file, identity_cutoff = 90):
line = blastn_output_file.readline()
if not line.startswith("BLASTN"):
raise TypeError ('Not a BLASTN output file')
version = line.rstrip() #store "BLATN 2.2.30+"
while True:
line = blastn_output_file.readline()
if line.startswith("Database:"):
database_name = line.rstrip().split()[1] #store the name of HG
break
while True:
line = blastn_output_file.readline()
if "sequences" in line or "total letters" in line:
words = line.rstrip().split()
database_sequences = int (words[0].replace (",","") ) #how many sequences in db?
database_letters = int (words[2].replace (",","") ) #how big is the db?
break
while True: #locate the benchmark of hits or no hits
line = blastn_output_file.readline()
if "No hits found" in line:
break #exit()? to terminate
elif line.startswith ("Sequences producing significant alignments:"):
break
elif not line:
raise TypeError ("No description section in blastn output")
# Move to each entry of HSP
results = []
counts_hits =0
parse_flag = False
while True:
hsp_line = blastn_output_file.readline()
if not hsp_line:
break
if "Identities" in hsp_line: #extract %identities
parse_flag = False
counts_hits += 1
temp = hsp_line.rstrip().split()[3].replace("(","")
identities = int (temp.replace("%),", ""))
if "Strand" in hsp_line: #extract strand polarity
temp = hsp_line.rstrip().replace("/", " ")
strand = temp.split()[-1]
if hsp_line.startswith ("Query"): #reach Query line
temp = hsp_line.rstrip().split()
query_start = int(temp[1])
query_sequence = temp[2]
query_end = int(temp[3])
while True:
hsp_line = blastn_output_file.readline()
if not hsp_line:
break
if hsp_line.startswith("Query"):
temp = hsp_line.rstrip().split()
start = int (temp[1])
#if abs (start - query_end) !=1:
#raise TypeError ("something wrong with the Query sequence positions")
if start < query_start:
query_start = start
raise TypeError ("start: minus Query or something wrong")
query_sequence = query_sequence + temp[2]
end = int (temp[3])
if end > query_end:
query_end = end
else:
raise TypeError ("end: minus Query or something wrong")
#print ("test while T ", counts_hits, " start: ", query_start, " end: ", query_end)
elif "Score" in hsp_line:
parse_flag = True
break
elif "Lambda" in hsp_line:
parse_flag = True
break
print ("test while T ", counts_hits, " start: ", query_start, " end: ", query_end)
#print ("\n")
# record the info extracted from each hsp entry to results
if parse_flag:
result = blastn_results (identities, strand, query_sequence, query_start, query_end)
results.append (result)
print ("end of program")
return blastn_scanner (version, database_name, database_sequences, database_letters, counts_hits, results)
def fasta_output (records, fasta_output_file):
target = open (fasta_output_file, 'w')
for i in range (records):
target.write (">hits%d \n" % i)
target.write (test.results[i].query_sequence.replace("-",""))
target.write ("\n")
handle = open ("Ebola_blast_output.txt")
#handle = open ("blastp.txt")
test= scan_blastn(handle, identity_cutoff = 90)
fasta_output (test.counts_hits, 'Ebola_hits')
# IIIIIIII
#emulate on Ruffus
import os
def ebola_conservative_regions (infile, outfile):
current_region =0
for line in open (infile):
if line[0] == '>':
current_region += 1
current_file = open ("%d.%s" % (current_region, outfile), "w")
current_file.write(line)
def runBlast (infile, outfile):
os.system ("blastn -query %s -db NT_033778.fna -out %s.output -outfmt 0" % (infile,outfile))
ebola_conservative_regions ('teflon_segs.txt', 'teflon_segment')
no_segments =11
for segment in range(no_segments):
runBlast ('%d.teflon_segment' % segment, '%d.teflon_segment' % segment)
# IIIIIIII
# This program was written to handle step 5
# It searches the ebola genome input from user
# Looking for the hits from the BLAST search
# And eliminates the human hits from the user viral genome
# So this kind of precedes my original stepG
# The output is an ebola genome without regions of human alignments
# In FASTA format
# Written by Andres W
def separalo():
pre_file = open('Ebola_Human_Hits.fas','r')
DNA = list('GACT')
segment_list = []
temp_seq = ''
temp_seq2 = ''
for line in pre_file:
if line[0] != ">":
temp_seq = temp_seq + str(line)
for item in temp_seq:
if item in DNA:
temp_seq2 = temp_seq2 + str(item)
segment_list.append(temp_seq2)
temp_seq = ''
temp_seq2 = ''
pre_file.close()
return segment_list
def virus():
pre_file = open('Ebola_genome.fas','r')
DNA = list('GACT')
pre_viral_genome = ''
viral_genome = ''
for line in pre_file:
if line[0] != ">":
pre_viral_genome += str(line)
for item in pre_viral_genome:
if item in DNA:
viral_genome += str(item)
pre_file.close()
return viral_genome
def comparalo_via_clustal():
from Bio import SeqIO
from Bio.Align.Applications import ClustalwCommandline
from Bio import AlignIO
MERGED = "Ebola_virus_plus_hits.fas"
ALIGNED = "Ebola_virus_plus_hits.aln"
INPUT = ClustalwCommandline("clustalw", infile = MERGED)
INPUT()
ALIGNED = AlignIO.read(ALIGNED, "clustal")
def comparalo_via_re():
import re
segment_list = separalo()
viral_genome = virus()
edited_genome = ''
removed = ''
for segment in segment_list:
if segment in viral_genome:
edited_genome = re.sub(segment, '\n', viral_genome)
viral_genome = edited_genome
return edited_genome
def double_check():
edited_genome = comparalo_via_re()
segment_list = separalo()
count = 0
for segment in segment_list:
if segment not in edited_genome:
count += 1
print count
def to_group2():
edited_genome = comparalo_via_re()
group1_output = open('dre.fas','a')
group1_output.write('>Ebola_genome_minus_human_blastn_hits\n')
cuenta = 0
for base in edited_genome:
cuenta += 1
group1_output.write('%s' % (base))
if cuenta == 70:
cuenta = 0
group1_output.write('\n')
group1_output.close()
to_group2()
"""
|
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 23 12:25:16 2018
@author: Jotun
"""
#Importing necessary stuff
import os
import datetime
import shutil
import tkinter, tkinter.filedialog
root = tkinter.Tk()
root.withdraw()
#Get the back up desitnation directory from user
backupPath= tkinter.filedialog.askdirectory (parent= root, initialdir="/", title= "Please select directory for save backups")
if len(backupPath) > 0:
print ("You chose {0} as your directory for backups".format(backupPath))
else:
print ("Please select a valid directory")
now = datetime.datetime.now() #simplification for dirName
dirName= '{0}_{1}_{2}_{3}{4}'.format(now.day, now.month, now.year, now.hour, now.minute) #the name of the folder will be day_month_year_hourminute
try:
# Create target Directory and all required directories in between
os.makedirs("{0}/SaveGames/MHW/{1}".format(backupPath, dirName))
print("Directory " , dirName , " created ")
except FileExistsError:
print("Directory " , dirName , " already exists")
#Get the original save file from user
defaultSteamPath="E:/Program Files (x86)/Steam/userdata/00000000/582010/remote"
saveFile = tkinter.filedialog.askopenfilename(initialdir = defaultSteamPath, title = "Please select save file to back up",filetypes = ())
if "SAVEDATA1000" in saveFile:
print ("You chose {0} as your save file to back up".format(saveFile))
else:
print ("Please select a valid save file")
shutil.copy2 (saveFile, "{0}/SaveGames/MHW/{1}".format(backupPath, dirName))
|
def isPalindrome(i):
return i == i[::-1]
i = input("Enter word: ")
answer = isPalindrome(i)
if answer:
print("Yes")
else:
print("No")
|
"""Utilities for dealing with latches' actuators in the physical universe."""
import threading
import time
import RPi.GPIO as GPIO
class Latch(object):
"""Class to deal with latches."""
def __init__(self, lock_pin=12):
self.lock_pin = lock_pin
self.lock_lock = threading.RLock()
def __enter__(self):
GPIO.setmode(GPIO.BOARD)
GPIO.setup(self.lock_pin, GPIO.OUT)
GPIO.output(self.lock_pin, GPIO.LOW)
return self
def __exit__(self, type, value, traceback):
GPIO.output(self.lock_pin, GPIO.LOW)
GPIO.cleanup()
def unlock(self, open_period):
"""Open the latch for `open_period` seconds.
Doesn't block: Opens a thread to hold the latch open for the specified
period of time. If this is called while the latch is being held open, this
effectively will do nothing. It will not modify the length of time the latch
is held, nor raise an exception nor fail in any other way."""
def open_sesame():
if self.lock_lock.acquire(blocking=False):
GPIO.output(self.lock_pin, GPIO.HIGH)
time.sleep(open_period)
GPIO.output(self.lock_pin, GPIO.LOW)
self.lock_lock.release()
threading.Thread(target=open_sesame).start()
|
import datetime
def calculate_start_end_date(start_year=2008, start_month=2):
# From the beginning of a month
start_date = datetime.date(start_year, start_month, 1)
end_year, end_month = start_year, start_month + 1
if end_month > 12:
end_year += 1
end_month = 1
end_date = datetime.date(end_year, end_month, 1) - datetime.timedelta(days=1)
return start_date, end_date
|
def year_leap(a):
if (a % 4 == 0,a % 100 != 0) or a % 400 == 0:
print("YES, you birth year is a leap-year")
else:
print("NO, you birth year is not a leap-year")
m = input("print your birth year:")
y = year_leap(int(m))
print(y)
|
import unittest
from OOP1 import ITEmpl
class EmplTest(unittest.TestCase):
def setUp(self):
self.emp = ITEmpl("Nata", "Pin")
def test_name(self):
self.assertEqual (self.emp.name, "Nata")
self.assertEqual (self.emp.surname, "Pin")
|
import pygame
from random import randint
pygame.init()
window = pygame.display.set_mode((500,500))
pygame.display.caption('wordgame')
gamerunning = True
class character():
def __init__(self, name, hp, attack, profession, gold):
self.name = name
self.hp = hp
self.attack = attack
self.profession = profession
self.gold = gold
class monster():
def __init__(self, type, hp):
self.type = type
self.hp = hp
player = character('kuromi', 100, 100, 'knight', 1000)
enemy = monster('goblin', True)
#main loop
while gamerunning == True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gamerunning = False
print ('---' * 8)
print('please select action')
print('1) HUNT')
print('2) OPEN SHOP')
print('3) EXIT GAME')
Player_Choice = input()
if Player_Choice == '1':
print('you have found a goblin')
if player.attack >= 100:
enemy.hp = False
if enemy.hp == False:
print('you have slain an enemy!')
elif Player_Choice == '2':
print('choose an item')
print('cloth armor')
print('potion')
print('short sword')
print('long sword')
elif Player_Choice == '3':
gamerunning = False
else:
print('invalid input')
pygame.quit()
|
def main():
a=int(input("Enter a number"))
for i in range(a):
print("Hello")
if __name__ == '__main__':
main()
|
import os
from Donnee import *
from Fonction import *
print("---------------START--------------")
print("Bonjour,")
nom = input("Bienvenu quel est ton nom: ")
scores = down_save()
score_fin = 0
if nom in scores:
print("Tu as {} points.".format(scores[nom]))
else:
print("Tu est nouveau ici {}". format(nom))
print("donc tu commences avec 0 point.")
scores [nom] = 0
game = True
start = input("On commence {} ? (oui/non) ". format(nom))
if start != 'oui':
game = False
rep = 1
while game:
print("---------Partie {} ---------".format(rep))
points = jeu()
stop = input("Veux-tu faire une nouvelle partie ? (oui/non) ")
if stop == 'non':
game = False
rep += 1
score_fin += points
print ("Reviens quand tu veux.")
print("Tu as gagnié {} point(s), cela fait un total de {} points.".format(score_fin, scores[nom]+ score_fin))
scores[nom] = score_fin + scores[nom]
save(scores)
os.system("pause")
|
#register
#username, password
#generation user id
#login
#username or email and password
#bank operation
#initializing the system
import random
import validation
import database
def init():
print('Welcome to bankPHP')
haveAccount = int(input('do you have an account with us: 1. (yes) 2 (no) \n'))
if (haveAccount == 1):
login()
elif(haveAccount == 2):
register()
else:
print('You have selected an invalid option')
init()
def login():
print('******* Login *******')
account_number_from_user = input('What is your account number? \n')
is_valid_account_number = validation.account_number_validation(account_number_from_user)
if is_valid_account_number:
password = input('What is your password \n')
for account_number,userDetails in database.items():
if (account_number == int(account_number_from_user)):
if (userDetails[3] == password):
bankOperation(userDetails)
print('Invalid account or password')
login()
else:
init()
def register():
print('******Register******')
email = input('What is your email address? \n')
first_name = input('What is your first name? \n')
last_name = input('What is your last name? \n')
password = input('create a password for yourself \n')
account_number = generate_account_number()
#database[account_number] = [ first_name, last_name, email, password, 0]
is_user_created = database.create(account_number,[first_name, last_name, email, password, 0])
if is_user_created:
print('Your account has been created')
print('== ==== ====== ===== ===')
print('Your account number is %d' %account_number)
print('== ==== ====== ===== ===')
login()
else:
print('something went wrong')
register()
def bankOperation(user):
print('welcome %s %s ' % ( user[0], user[1]))
selected_option = int(input('What would you like to do? (1) deposit (2) withdrawal (3) Logout (4) exit \n'))
if ( selected_option == 1):
deposit_operation()
elif ( selected_option == 2):
withdrawal_operation()
elif (selected_option == 3):
logout()
elif ( selected_option == 4):
exit()
else:
print('Invalid option selected')
def withdrawal_operation():
withdraw_option = int(input('How much would you like to withdraw? \n'))
print('Take your #' + withdraw_option + ' cash')
print('Thank you for banking with us')
def deposit_operation():
deposit_option = int(input('How much do you want to deposit? \n'))
print('You have succesfully deposited #' + deposit_option)
print('Thank you for banking with us')
def generate_account_number():
return random.randrange(1111111111,9999999999)
def logout():
login()
### ACTUAL BANKING SYSTEM
#print(generate_account_number())
init()
|
def runningSum(nums):
for i in range(1, len(nums)):
nums[i] += nums[i-1]
print(nums)
runningSum([1,2,3,4])
|
for n in range(int(input())):
ans = 0
for i in input().split():
if int(i)%2 == 1:
ans += int(i)
print("#"+str(n+1)+" "+str(ans))
|
str = input()
tmp = ""
for i in range(0,len(str)):
tmp+=str[i]
if i%10==9:
print(tmp)
tmp=""
print(tmp)
|
def insertion_sort(data):
for index in range(len(data) - 1):
for index2 in range(index+1, 0, -1):
if data[index2] < data[index2 - 1]:
data[index2], data[index2 -1] = data[index2 - 1], data[index2]
else:
break
return data
def insertion_sort2(x):
for size in range(1, len(x)): # size : 비교할 배열의 범위
val = x[size] # val : 비교할 원소
i = size
while i>0 and x[i-1] > val: # 비교할 원소가 바로 앞의 원소보다 작고, 배열 범위내일 동안 실행
x[i] = x[i-1] # 앞의 원소와 위치 교환
i-=1 # 교환했으면 다음 앞에 있는 위치로 지정
x[i] = val # 앞의 원소와 위치 교환2
return x
x = [5,2,4,1,6,3]
print(insertion_sort(x))
|
def kangaroo(x1, v1, x2, v2):
if (x1 <= x2 and v1 <= v2) or (x1 > x2 and v1 > v2):
return 'NO'
if abs(x2 - x1) % abs(v2 - v1) != 0:
return 'NO'
return 'YES'
print(kangaroo(0, 2, 5, 3))
|
graph = {
'A': ['B', 'C'],
'B': ['A','D','E'],
'C': ['A','F'],
'D': ['B'],
'E': ['B'],
'F': ['C']
}
from queue import Queue
# BFS
def bfs(graph, start_node):
visited = {} # 방문했던 노드목록 (dic, set 형태로 구현해야 효율
q = Queue() # bfs는 queue, dfs는 stack : 유일한 차이점!!!
q.put(start_node)
while q.qsize() > 0:
node = q.get() # 큐 특징. FIFO
if node not in visited:
visited[node] = True
for nextNode in graph[node]:
q.put(nextNode)
return visited.keys()
print(bfs(graph, 'A'))
# DFS
def dfs(graph, start_node):
visited = {}
stack = list()
stack.append(start_node)
while stack:
node = stack.pop()
if node not in visited:
visited[node] = True
stack.extend(reversed(graph[node])) # revered 없으면 오른쪽부터 파고듬
return visited.keys()
print(dfs(graph, 'A'))
|
import random
import Field
from Position import Direction, Position
class Particle:
"""Represents a particle in movement with a position
and a direction.
:author: Peter Sander
:author: ZHENG Yannan
"""
def __init__(self, position: Position, direction: Direction,
colour: str, field: Field):
"""Initialize a particle.
:colour: Particle colour.
:field: Field containing the particle.
"""
self.position = position
self.direction = direction
self.colour = colour
self.field = field
self.cure_sign = 0
def move(self) -> None:
"""Particle moves to a new position.
Random move depending on the particle's current position.
"""
nextPosition = self.field.freeAdjacentPosition(self, 2)
self.setPosition(nextPosition)
def setPosition(self, nextPosition: Position) -> None:
"""Place the particle at the given position.
"""
self.field.clear(self.position)
self.position = nextPosition
self.field.place(self)
def __str__(self):
return f'Paricle({self.position})'
def cure(self):
if self.colour == 'red':
self.cure_sign += 1
if self.cure_sign == 21:
k = random.random()
if k >= 0.5:
self.colour = 'black'
self.cure_sign = 100
else:
self.colour = 'spring green'
self.cure_sign = 100
|
from polynomials import *
def test_at_point():
assert Polynomial([1,2,3]).__call__(2)==3*2**2+2*2+1
assert Polynomial([1,2,3]).__call__(4)==3*4**2+2*4+1
assert Polynomial([1,2,3]).__call__(7)==3*7**2+2*7+1
def test_add_2_polynomials():
assert Polynomial([1,2,3])+Polynomial([1,2,3])==Polynomial([2,4,6])
assert Polynomial([-1,2,3])+Polynomial([1,2,3])==Polynomial([0,4,6])
p, q = map(Polynomial,[[1, 0, 1], [0, 2, 0]])
assert p+q+p+p+p-1==Polynomial([3,2,4])
def test_sub_2_polynomials():
assert Polynomial([2,2,2])-Polynomial([1,1,1])==Polynomial([1,1,1])
assert Polynomial([4,2,2,2])-Polynomial([1,1,1])==Polynomial([3,1,1,2])
assert Polynomial([-4,2,2,2])-Polynomial([1,1,1])==Polynomial([-5,1,1,2])
p, q = map(Polynomial,[[1, 0, 1], [0, 2, 0]])
assert p-q-p+(2*p)==Polynomial([2,-2,2])
def test_degree_of_polynomials():
assert Polynomial([1,2,3,4,5]).degree()==4
assert Polynomial([1,2,3,4,0]).degree()==3
assert Polynomial([1,0,3,4,0]).degree()==3
assert Polynomial([0,0,0]).degree()==-1
assert Polynomial([1,0,0,0,0,0,0,0,0,0,0,0,0,0,0]).degree()==0
#LETS GET FUNCY
import random
x = []
for i in range(100000):
x.append(0)
some_number=random.randint(0,100000)
x[some_number]=1
#lets test the funcyness
assert Polynomial(x).degree()==some_number
def test_repr():
assert repr(Polynomial([-4331])) == "-4331"
assert repr(Polynomial([5])) == "5"
assert repr(Polynomial([9999,1])) == "x+9999"
assert repr(Polynomial([0,0,0])) == ""
assert repr(Polynomial([-1,-3,-8])) == "-8x^2-3x-1"
|
import cv2
import numpy as np
import matplotlib.pyplot as plt
from scipy import signal
'''
pad2D(img,padlengths,padtype='constant',cval=0)
Pads the image with given padlengths and given type of padding.
parameters:
* img: image to be padded
* padlengths: a tuple (N,M) to pad the image with N rows and M columns
* padtype: which type of padding
* cval: value to pad image with if padtype is constant
returns:
* img_padded: padded image
'''
def pad2D(img,padlengths,padtype='constant',cval=0):
pad_N = padlengths[0]
pad_M = padlengths[1]
half_pad_N = int((pad_N-1)/2)
half_pad_M = int((pad_M-1)/2)
N,M = img.shape
#Sets values of the padded regions
if( padtype == 'constant'):
img_padded = np.ones((N+pad_N,M+pad_M))
img_padded *= cval
else:
img_padded = np.zeros((N+pad_N,M+pad_M))
#--- Above img ---
img_padded[0:half_pad_N,half_pad_M:(M+half_pad_M)] = img[0:half_pad_N,:][::-1]
#Note: [::-1] flips the image about a horizontal axis.
#Example: A = np.array([[1,2,3],[4,5,6],[7,8,9]])
# A[::-1] gives [[7,8,9],[4,5,6],[1,2,3]]
#--- Under img ---
img_padded[(half_pad_N + N):(pad_N+N),half_pad_M:(M + half_pad_M)] = img[((N-1)-half_pad_N):N,:][::-1]
#--- Left side to img ---
img_padded[half_pad_N:(half_pad_N+N),0:half_pad_M] = img[:,0:half_pad_M][...,::-1]
#Note: [...,::-1] flips the image about a vertical axis.
#Example: A = np.array([[1,2,3],[4,5,6],[7,8,9]])
# A[...,::-1] gives [[3,2,1],[6,5,4],[9,8,7]]
#--- Right side to img ---
img_padded[half_pad_N:(half_pad_N+N),(half_pad_M+M):(M+pad_M)] = img[:,(M-1)-half_pad_M:M][...,::-1]
#--- Corners ---
#NW:
img_padded[0:half_pad_N,0:half_pad_M] = img[0:half_pad_N,0:half_pad_M][::-1][...,::-1]
#NE:
img_padded[0:half_pad_N,(M+half_pad_M):(M+pad_M)] = img[0:half_pad_N,((M-1)-half_pad_M):M][::-1][...,::-1]
#SW:
img_padded[(half_pad_N + N):(N+pad_N),0:half_pad_M] = img[((N-1)-half_pad_N):N,0:half_pad_M][::-1][...,::-1]
#SE:
img_padded[(half_pad_N + N):(N+pad_N),(half_pad_M + M):(pad_M+M)] = img[(N-1)-half_pad_N:N,(M-1)-half_pad_M:M][::-1][...,::-1]
#Place the original image
img_padded[half_pad_N:(N + half_pad_N),half_pad_M:(M + half_pad_M)] = img
return img_padded
'''
convolve2D(img,h)
Convolves a given 2D filter and image.
parameters:
* img: image to be convolved (could be filter aswell, if h is image)
* h: filter to be convolved (could be image aswell, if img is filter)
returns:
* img_convolved: result after convlution
'''
def convolve2D(img,h):
N,M = h.shape
img_padded = pad2D(img,(N,M),padtype='symmetric')
img_N, img_M = img.shape
img_convolved = np.zeros((img_N,img_M))
h_rotated = h[...,::-1][::-1]
for i in range(img_N):
for j in range(img_M):
img_convolved[i,j] = np.sum(img_padded[i:N+i,j:M+j]*h_rotated)
return img_convolved
'''
non_max_suppression(img_direction)
Thins out the given gradient angle image.
parameters:
* img_grad: gradient magnitude image.
* img_direction: the angle image. Assumed to have values 0,45,90 or 135
returns:
* img_thinned: result after thinning
'''
def non_max_suppression(img_grad,img_direction):
N,M = img_direction.shape
img_thinned = np.zeros((N,M))
for y in range(1,N-1):
for x in range(1,M-1):
degree = img_direction[y,x]
a = 0; b = 0
if degree == 0:
a = img_grad[y-1,x]
b = img_grad[y+1,x]
elif degree == 45:
a = img_grad[y+1,x+1]
b = img_grad[y-1,x-1]
elif degree == 135:
a = img_grad[y-1,x+1]
b = img_grad[y+1,x-1]
else:
a = img_grad[y,x-1]
b = img_grad[y,x+1]
if ( img_grad[y,x] > a and img_grad[y,x] > b):
img_thinned[y,x] = img_grad[y,x]
return img_thinned
'''
hysteresis(img_thinned,tw,ts)
Tracks strong edges.
parameters:
* img_thinned: thinned gradient angle image
* tw: threshold for weak edges
* ts: threshold for strong edges
returns:
* img_strong: image where the strong edges are marked
'''
def hysteresis(img_thinned,tw,ts):
N,M = img_thinned.shape
img_strong = np.copy(img_thinned)
img_strong[np.where(img_thinned > ts)] = 255
img_hyst = np.copy(img_strong)
marked = 1
while(marked > 0):
marked = 0
for y in range(1,N):
for x in range(1,M):
if (tw < img_strong[y,x] < ts):
#Using 4-connected neighbourhood. Could also use 8
num_strong = np.sum(img_strong[y-1:y+1,x-1:x+1] == 255)
if (num_strong > 0):
img_hyst[y,x] = 255
marked += 1
img_strong = np.copy(img_hyst)
#Get rid of weak edges
img_strong[np.where(img_strong != 255)] = 0
return img_strong
if __name__ == '__main__':
img = cv2.imread('../houses.png',cv2.IMREAD_GRAYSCALE)
N = 11
sigma = 2
NN = int((N-1)/2)
H = 1/(2*np.pi*sigma**2)*np.array([ [np.exp(-((x*x + y*y)/(2*sigma**2))) for x in range(-NN,NN+1)] \
for y in range(-NN,NN+1)])
H=np.array([[1,1,1],[1,1,1],[1,1,1]])/9.
img_gauss =img# convolve2D(img,H)
test=np.fft.fft2(img)
plt.imshow(np.log(np.abs(np.fft.fftshift(test))**2))
for i in test:
for j in i:
if np.abs(j) > 1e+04:
i=0
test=np.fft.fftn(test)
plt.imshow(np.abs(test))
a=input()
sobel = np.array([[1,2,1],[0,0,0],[-1,-2,-1]])
img_gx = convolve2D(img_gauss,sobel)
img_gy = convolve2D(img_gauss,sobel.T)
img_grad = np.sqrt(img_gx*img_gx + img_gy*img_gy)
img_direction = np.arctan2(img_gy,img_gx)
img_direction = np.mod((np.round(img_direction*180/(np.pi*45))*45),180)
img_thinned = non_max_suppression(img_grad,img_direction)
# Remember to have values between 0 and 255 such that hysteresis gives desired results
img_thinned = ((img_thinned- np.min(img_thinned))*255)/(np.max(img_thinned) - np.min(img_thinned))
img_hyst = hysteresis(img_thinned, 30,60)
plt.imshow(img_hyst,cmap ='gray',interpolation='none')
plt.show()
|
#
# Example file for working with date information
#
def main():
# DATE OBJECTS
from datetime import datetime
# Get today's date from the simple today() method from the date class
today = datetime.today()
print(today)
# print out the date's individual components
print(today.year)
print(today.month)
print(today.day)
# retrieve today's weekday (0=Monday, 6=Sunday)
wd = {0: 'Monday', 1: 'tuesday', 2: 'wednesday',
3: 'thursday', 4: 'friday', 5: 'saturday', 6: 'saturday'}
print(wd[today.weekday()])
# DATETIME OBJECTS
# Get today's date from the datetime class
print(today.date())
# Get the current time
print(today.now())
if __name__ == "__main__":
main()
|
#!/usr/bin/env python3
import os
def get_port():
while True:
try:
port = int(input('Puerto (1024 - 49151): '))
if port >= 1024 and port <= 49151:
break
except Exception:
pass
return port
def get_secure():
type = input('Establecer conexion segura? S/N: ')
return True if type in ['s', 'S'] else False
if __name__ == '__main__':
os.system('clear')
while True:
print('1. Servidor')
print('2. Cliente')
type = input('Opcion: ')
if type in ['1', '2']:
break
else:
os.system('clear')
os.system('clear')
if type == '1':
# Servidor
print('Servidor')
from server import init
init(get_port())
else:
# Cliente
ip = input('Ip del Servidor: ')
from client import init
init(ip, get_port(), get_secure())
|
i = 0
numbers = []
while i < 6:
print ("At the top i is %d" % i)
numbers.append(i)
i = i + 1
print ("Numbers now:", numbers)
print ("At the bottom i is %d" % i)
print "The numbers: "
for num in numbers:
print num
# these are the study drills bellow:
def study_1(n):
i = 0
numbers1 = []
while i < n:
print ("index: %d" % i)
numbers1.append(i)
i = i + 1
print numbers1
def study_2(n):
i = 0
numbers2 = []
while i < n:
print ("index: %d" % i)
numbers2.append(i)
i = i + 1
print numbers2
# Here the inc will give the increment ratio
def study_3(n, inc):
i = 0
numbers3 = []
while i < n:
print ("index: %d" % i)
numbers3.append(i)
i = i + inc
print numbers3
def study_5(n, inc):
numbers5 = range(0, n, inc)
for i in numbers5:
print ("Item : %d" % i)
print numbers5
def study_6(n, inc):
for i in range(0, n, inc):
print ("Item : %d" % i)
study_1(4)
study_2(12)
study_3(8, 2)
study_5(8, 2)
study_6(35, 2)
|
# To see wich version of Python it's used
import sys
print(sys.executable)
print(sys.version)
# Employees names class
class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = (first + '.' + last + '@mail.com').lower()
def fullname(self):
return "%s %s" % (self.first, self.last)
def newemail(self):
return (self.first + '.' + self.last + '@mail.com').lower()
def newpay(self):
return self.pay
# emp1 is set to an instance of Employee and pass some parameters
emp1 = Employee('Claudio', 'Nunez', 35000)
print "\tGet the function from > instance < emp1 Method"
print "\t", "-" * 25, "\n"
# This will get the function named .something from the instance emp1
# and call it with self parameter
print "The employee's fullname is: %s" % emp1.fullname()
print "The employee's email is: %s" % emp1.email
print "The employee's salary is: %s$ per year" % emp1.pay, "\n"
print "\tFrom class > Employee < get the function and call it with emp1 method"
print "\t", "-" * 25, "\n"
# From class Employee get the function named .something
# and call it with parameter beloning to instance emp1
print "The employee's fullname is: %s" % Employee.fullname(emp1)
print "The employee's email is: %s" % Employee.newemail(emp1)
print "The employee's pay is: %s$ per year" % Employee.newpay(emp1), "\n"
|
# this will count the amount of words in a sentence
# this function will split the sentence into words
def break_words(sentence):
"""This function will break up words for us."""
words = sentence.split(' ')
return words
print "Please write something."
sentence = raw_input(">: ")
print "This is your sentence: << %s >>" % sentence
print "Your sentence contains : %d words" % len(break_words(sentence))
print break_words(sentence)
|
# Program to Check Even No in List
def even(x):
if(x%2==0):
return x
a = int(input("Enter no : "))
list1 = []
for i in range(0,a):
v=int(input("Enter No to Add : "))
list1.append(v)
print(list1)
s =list(filter(even,list1))
print("Even No in the List are ",s)
|
a = int(input("Enter a Number : "))
if(a%2==0):
{
print("The No is Even")
}
else:
{
print("The No is odd")
}
|
class delete:
def __init__(self):
self.stacks = []
def push(self, val):
self.stacks.append(val)
def pop(self):
val = self.stacks[-1]
del self.stacks[-1]
return val
stack_object = delete()
stack_object.push(4)
stack_object.push(3)
stack_object.push(2)
stack_object.push(1)
print(stack_object.pop())
print(stack_object.pop())
print(stack_object.pop())
print(stack_object.pop())
|
import json
from src.input.raw import Raw
def read(filename, maximum):
"""
Get data from JSON files.
- filename: str with JSON file with a list of dictionaries.
- maximum: int with maximum length for output list.
- return: [Raw].
"""
raws = []
with open(filename, "r") as f:
for _, line in zip(range(maximum), f):
raw = parse_entry(line)
raws.append(raw)
return raws
def parse_entry(line):
"""
- f: str with JSON line with a dictionary with "title", "text", "summary" and "topic" entries.
- return: Raw.
"""
d = json.loads(line)
head = d["title"]
body = d["text"]
sums = [ d["summary"] ]
category = d["topic"]
return Raw(head, body, sums, category)
|
from math import ceil
def threshold(scores, thresh):
"""
Filter sentences given their associated scores and
the threshold to filter them. Only get those above threshold.
- scores: [float].
- thresh: float.
- return: [int] with selected indices.
"""
return mask([thresh <= s for s in scores])
def mask(booleans):
"""
Filter sentences given a binary mask. Only get true ones.
- booleans: [bool] with binary mask.
- return: [int] with selected indices.
"""
return [i for i in range(len(booleans)) if booleans[i]]
def k_top(scores, k):
"""
Filter sentences given their associated scores and
the maximum desired sentences. Only get the k-most scored ones.
- scores: [str].
- k: int and k > 0.
- return: [int] with selected indices.
"""
if k <= 0: return []
indices = range(len(scores))
return sorted(sorted(indices, key = lambda x: scores[x], reverse = True)[:k])
def p_top(scores, p):
"""
Filter sentences given their associated scores and
the proportion of desired sentences. Only get the p-most scored ones.
- scores: [float]
- p: float and 0 < p <= 1.
- return: [int] with selected indices.
"""
if p <= 0: return []
if p >= 1: return range(len(scores))
return k_top(scores, ceil(p * len(scores)))
|
import os
def arguments(files):
"""
Tidy files so that we get [(original, sum1, sum2)].
All files must be in the same directory.
All files must have the notation of the corpus, i.e.
- <ID>.txt
- SUM_<ID>_<NAME1>.sum
- SUM_<ID>_<NAME2>.sum
where <ID> is the id of the document and <NAME1> <NAME2> are the
names of the authors of the summary.
- files: [str] with files following the notation.
- return: [(str, [str])] where [(original, [summary])].
"""
# Get just .sum
sums = [x for x in files if x.endswith(".sum")]
directory = "" if not files else os.path.dirname(files[0])
return regenerate(directory, associate_id_names(sums))
# Dont' use outside of this module
def associate_id_names(files):
"""
Associate for all IDs, their two NAMEs.
- files: [str] with only *.sum files.
- return: {str: [str]} where {id: [names]}.
"""
association = {}
for filename in files:
ID, name = parts(filename)
if ID in association:
association[ID].append(name)
else:
association[ID] = [name]
return association
def parts(filename):
part = filename.split("_")
ID = part[1] + "_" + part[2]
part = part[3].split(".")
name = part[0]
return ID, name
def regenerate(directory, association):
"""
Regenerate filenames from IDs and NAMEs
- association: {str: [str]} where {id: [names]}.
- return: [(str, [str])] where [(original, [summary])].
"""
files = []
for ID, names in association.items():
original = os.path.join(directory, ID + ".txt")
sums = [os.path.join(directory, "SUM_"+ID+"_"+n+".sum") for n in names]
files.append((original, sums))
return files
|
# бʽ
list1 = [x for x in range(10)]
iter(list1)
print(next(list1))
for l in list1:
print(l)
# Შкʽ
def fun(num):
a, b = 0, 1
count = 0
while count < num:
yield a
a, b = b, a + b
# print(count)
count += 1
print(next(fun(10)))
|
import time
def time_count(fun):
"""统计程序运行时间装饰器"""
def t():
start = time.time()
fun()
end = time.time()
print(fun.__name__, "消耗", end - start, "秒")
return end - start
return t
# 用time_count装饰器装饰函数,统计函数print_count()运行的时间
@time_count
def print_count():
"""
裴波拉契数列生成函数
:return:None
"""
def fun():
a, b = 0, 1
count = 0
while count < 10000:
yield a
a, b = b, a + b
count += 1
for f in fun():
print(f, "\n")
# 用time_count装饰器装饰函数,统计函数print_list()运行的时间
@time_count
def print_list():
# 生成迭代器
ls = (x for x in range(10))
# for循环获取迭代器的内容
for i in ls:
print(i)
# 调用被装饰器装饰的函数
print_count()
# 调用被装饰器装饰的函数
print_list()
class User:
"""定义用户类"""
def __init__(self, account, password, name="新用户", integration=100):
"""
初始化用户对象的属性
:param account: 用户的账号
:param password: 用户的密码
:param name: 用户的昵称
:param integration: 用户的积分
"""
self.account = account
self.name = name
self.password = password
self.integration = integration
# 装饰器,用户验证用户是否合法
def check(fun):
def check_user(user=None):
if isinstance(user, User) and user.account == "admin" and user.password == "admin":
fun()
return True
else:
print("登陆失败")
return False
return check_user
# 用户登录成功后的主页
def show_index():
print("登陆成功")
print("显示主页")
# 用装饰器装饰login函数,用于验证用户的合法性
@check
def login():
return show_index()
# 调用被装饰器装饰的函数,该函数具有了验证密码的功能
res = login(User(account="admin", password="admin"))
print(res)
|
# pop_calculate.py
# CS 1181
# D. Ivan Ochoa
# 16 February, 2021
# Jon Holmes
# Description: script of functions required for population_sim to run.
def as_rate(rate_percentage: str) -> float:
"""accepts desired rate string and returns it as a float"""
amount_in_percent = float(rate_percentage)/100
return amount_in_percent
def years_increase(current_pop: float, growth_rate: float) -> float:
"""calculates increase in population for current year
and returns value as float"""
pop_increase = current_pop * growth_rate
return float(pop_increase)
def expected_population(starting_pop: int, pop_growth_time: int, growth_rate: float) -> int:
"""calculates the expected size of the population
at the end of the time and returns that value as an integer."""
pop_at_end = starting_pop * (1 + growth_rate) ** pop_growth_time
return round(pop_at_end)
def ending_population(starting_pop: float, growth_rate: float) -> float:
"""calculates the population at the end of the year and returns
float"""
pop_at_end = starting_pop + (years_increase(starting_pop, growth_rate))
return pop_at_end
|
import random
class Dog:
def __init__(self, name):
self.name = name
self.age = 0
self.weight = 1
self.sex = random.choice(['m', 'f'])
def __str__(self):
return "{} is {} years old and is {} and weighs {} lbs".format(self.name, self.age, self.sex, self.weight)
def __repr__(self):
return self.__str__()
def bark(self):
return "Woof! My name is {}".format(self.name)
def feed(self, weight):
self.weight += weight
d1 = Dog('fido')
d2 = Dog('lassy')
d3 = Dog('molly')
d1.feed(3)
d1.feed(3)
d1.feed(3)
d1.feed(3)
dogs = [d1, d2, d3]
|
class Cat:
count = 3
def add():
Cat.count += 1
def __init__(self, name):
self.name = name
def meow(self):
return "{} says hello".format(self.name)
def lol(haz):
return haz.name
# ---------------
c = Cat('mews')
# ---------------
def sample(*args, **kwargs):
print('args:', args, 'kwargs:', kwargs)
|
import turtle
import random
import time
# drawing methods
def draw_board():
board_drawer = turtle.Turtle()
board_drawer.speed(20)
board_drawer.pensize(20)
board_drawer.color("white")
for i in range(2):
board_drawer.penup()
board_drawer.goto(turtle.window_width() / 8 - turtle.window_width() / 4 *
i, turtle.window_height() / 3)
board_drawer.pendown()
board_drawer.setheading(270)
board_drawer.forward(turtle.window_height() * 2 / 3)
for i in range(2):
board_drawer.penup()
board_drawer.goto(turtle.window_height() / 3,
turtle.window_width() / 8 - turtle.window_width() / 4 * i)
board_drawer.pendown()
board_drawer.setheading(180)
board_drawer.forward(turtle.window_height() * 2 / 3)
def write_message(message):
writing_turtle.clear()
writing_turtle.penup()
writing_turtle.goto(-300, 300)
writing_turtle.pendown()
writing_turtle.write(message, font=("arial", 20))
def draw_x(x, y):
x_drawer.penup()
x_drawer.goto(x, y)
x_drawer.pendown()
x_drawer.setheading(45)
x_drawer.speed(5)
x_drawer.backward(45)
x_drawer.forward(90)
x_drawer.backward(45)
x_drawer.speed(0)
x_drawer.left(90)
x_drawer.speed(5)
x_drawer.forward(45)
x_drawer.backward(90)
x_drawer.forward(45)
x_drawer.speed(0)
def draw_o(x, y):
o_drawer.setheading(180)
o_drawer.penup()
o_drawer.goto(x, y + 50)
o_drawer.pendown()
o_drawer.circle(50)
def display_board_content(board):
drawer.clear()
current_element = 0
for row in range(3):
for column in range(3):
current_element += 1
xcor = -160 + 160 * column
ycor = 160 - 160 * row
drawer.penup()
drawer.goto(xcor, ycor)
drawer.pendown()
if board[current_element] == "x":
draw_x(xcor, ycor)
continue
elif board[current_element] == "o":
draw_o(xcor, ycor)
continue
drawer.write(
current_board[current_element], font=("Arial", 16))
# game methods
def play_game(board):
display_board_content(board)
game_is_finished = False
turn = 0
while not game_is_finished:
thisTurn(board)
game_is_finished = is_winning_move(board) or turn == 8
if turn == 8:
write_message("Game is tied")
turn += 1
display_board_content(board)
def thisTurn(board):
global turn
while True:
try:
if turn % 2 == 0:
write_message("Player 1".upper())
inputted_num = int(the_screen.numinput("Place your symbol",
"Where would you like to palce your symbol? (one of the numbers shown)", default=None, minval=1, maxval=9))
if board[inputted_num] == "o" or board[inputted_num] == "x":
raise Exception
board[inputted_num] = 'x'
else:
write_message("Player 2".upper())
inputted_num = int(the_screen.numinput("Place your symbol",
"Where would you like to palce your symbol? (one of the numbers shown)", default=None, minval=1, maxval=9))
board[inputted_num] = 'o'
break
except Exception:
time.sleep(3)
turn += 1
def is_winning_move(board):
# check winning possibilities
if (board[1] == board[2] == board[3]
or board[4] == board[5] == board[6]
or board[7] == board[8] == board[9]
or board[1] == board[4] == board[7]
or board[2] == board[5] == board[8]
or board[3] == board[6] == board[9]
or board[1] == board[5] == board[9]
or board[3] == board[5] == board[7]):
if turn % 2 == 1:
write_message("Player 1 wins!".upper())
elif turn % 2 == 0:
write_message("player 2 wins!".upper())
return True
else:
return False
# game time
current_board = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
turn = 0
the_screen = turtle.Screen()
the_screen.title("Tic Tac Toe")
the_screen.bgcolor("black")
drawer = turtle.Turtle()
drawer.speed(0)
drawer.hideturtle()
drawer.color("white")
writing_turtle = turtle.Turtle()
writing_turtle.speed(0)
writing_turtle.hideturtle()
writing_turtle.color("white")
x_drawer = turtle.Turtle()
x_drawer.color("green")
x_drawer.pensize(10)
x_drawer.speed(0)
x_drawer.hideturtle()
o_drawer = turtle.Turtle()
o_drawer.color("blue")
o_drawer.pensize(10)
o_drawer.speed(0)
o_drawer.hideturtle()
draw_board()
play_game(current_board)
write_message("Press anywhere to exit")
turtle.exitonclick()
|
#-------------------------------------------------------------------------------
# Name: ouncesgrams.py
#
# Purpose: A progam that converts ounces to grams from 1 to 15
#
# Author: A. Fazelipour
#
# Created: 03/26/2019
#-------------------------------------------------------------------------------
print("**** Ounces to Grams Converter ****")
print("This program will print out a titled table that can be used to covert ounces to grams, for values from 1 to 15 ounces (1 ounce = 28.35 grams)")
# Table header
print("{0:>15} {01:>20}".format("Ounces", "Grams"))
#Convert Ounces to pounds
total = 1
for ounces in range(16):
grams = round(ounces * 28.35, 2)
print("{0:15} {01:>22}".format(ounces, grams))
|
def caught_speeding(speed, is_birthday):
if speed <= 60 and is_birthday == True or speed >= 61 and speed >= 65 and is_birthday == True:
return (0)
elif speed >= 61 and speed >= 80 and is_birthday == False or speed >= 81 and speed <= 85 and is_birthday == True:
return (1)
else:
return (2)
caught_speeding()
|
class Node(object):
def __init__(self, id):
self.id = id
self.adj_nodes = []
self.visited = False
class Graph(object):
def __init__(self):
self.nodes = {}
def Link(self, node_a, node_b):
for node in [node_a, node_b]:
if node not in self.nodes:
self.nodes[node] = Node(node)
self.nodes[node_a].adj_nodes.append(node_b)
self.nodes[node_b].adj_nodes.append(node_a)
def HamiltonianCycleGraph(graph, root_id):
if root_id not in graph.nodes:
return None
path = DFSGraph(graph, root_id, root_id, len(graph.nodes))
if path is not None:
return [root_id] + path
else:
return None
def DFSGraph(graph, node_id, root_id, length_to_root):
node = graph.nodes[node_id]
node.visited = True
try:
for next_node_id in node.adj_nodes:
if next_node_id == root_id and length_to_root == 1:
return [root_id]
if not graph.nodes[next_node_id].visited:
next_path = DFSGraph(graph, next_node_id, root_id, length_to_root - 1)
if next_path:
return [next_node_id] + next_path
if node_id == root_id and length_to_root == 1:
return []
else:
return None
finally:
node.visited = False
import unittest
class TestHamiltonianCycleGraph(unittest.TestCase):
def GoodGraph(self):
# (0)--(1)--(2)
# | / \ |
# | / \ |
# | / \ |
# (3)-------(4)
graph = Graph()
graph.Link(0, 1)
graph.Link(1, 2)
graph.Link(0, 3)
graph.Link(1, 3)
graph.Link(1, 4)
graph.Link(2, 4)
graph.Link(3, 4)
return graph
def BadGraph(self):
# (0)--(1)--(2)
# | / \ |
# | / \ |
# | / \ |
# (3) (4)
graph = Graph()
graph.Link(0, 1)
graph.Link(1, 2)
graph.Link(0, 3)
graph.Link(1, 3)
graph.Link(1, 4)
graph.Link(2, 4)
return graph
def test_GoodGraph(self):
self.assertEqual([0, 1, 2, 4, 3, 0],
HamiltonianCycleGraph(self.GoodGraph(), 0))
def test_BadGraph(self):
self.assertIsNone(HamiltonianCycleGraph(self.BadGraph(), 0))
def test_SingleNode(self):
graph = Graph()
graph.nodes[0] = Node(0)
self.assertEqual([0], HamiltonianCycleGraph(graph, 0))
def test_EmptyGraph(self):
self.assertIsNone(HamiltonianCycleGraph(Graph(), 0))
def test_NoSuchNode(self):
self.assertIsNone(HamiltonianCycleGraph(self.GoodGraph(), 99))
|
import copy
def BalancedPartition(xs):
_, left_bag = Knapsack(xs, sum(xs) / 2)
right_bag = ArrayMinus(xs, left_bag)
return left_bag, right_bag, abs(sum(left_bag) - sum(right_bag))
def Knapsack(xs, limit):
if limit <= 0:
return 0, []
max_sum = 0
max_bag = []
for i, x in enumerate(xs):
sub_sum, sub_bag = Knapsack(xs[:i] + xs[i+1:], limit - x)
new_sum = sub_sum + x
if new_sum <= limit and new_sum > max_sum:
max_sum = sub_sum + x
max_bag = [x] + sub_bag
return max_sum, max_bag
def ArrayMinus(a, b):
"""Returns a - b as arrays."""
c = copy.deepcopy(a)
for x in b:
c.remove(x)
return c
import unittest
class TestBalancedPartition(unittest.TestCase):
def test_Example(self):
self.assertEqual(1, BalancedPartition([1, 2, 3, 4, 5])[2])
self.assertEqual(1, BalancedPartition([1, 1, 1, 1, 1])[2])
self.assertEqual(0, BalancedPartition([])[2])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.