text stringlengths 37 1.41M |
|---|
#!/usr/bin/env python
import glob
import re
import os
import sys
import argparse
# Function to load in a variable all terms to be searched
#
# input: file name
# return: array
def loadSearches(fileName):
toSearch = None
with open(fileName) as origin_file:
toSearch = origin_file.readlines()
return toSearch
# Function search and count
#
# input: fileName to search in
# string
# output: occurrences
def howMany(fileName,stringSearch, case=False):
with open(fileName) as search_file:
counter = 0
for line in search_file:
if case:
line = re.findall(r'^'+stringSearch+'$', line)
else:
line = re.findall(r'^'+stringSearch+'$', line,re.IGNORECASE)
if len(line) > 0:
counter += 1
return counter
########################################################################
########################################################################
# MAIN
########################################################################
########################################################################
args = argparse.Namespace()
__version__ = "0.10"
__description__ = 'Search strings in files'
# Create argument parser
usage = '\r{}\nusage: %(prog)s -f <file_lista> -d <dir_logs> [-c <num>] [-s] | [-h] | [-v]' \
.format('Version {version}'.format(version=__version__).ljust(len('usage: ')))
mypar = argparse.ArgumentParser(description=__description__, usage=usage,
formatter_class=argparse.RawTextHelpFormatter)
mypar.add_argument('-v', '--version', action='version',
version='%(prog)s v. {version}'
.format(version=__version__),
help='show program version')
mypar.add_argument('-c', type=int,action='store', dest='counter',default=1, help='numero minimo di occorrenze (0 = solo valori unici')
mypar.add_argument('-s', action='store_true', dest='Case', default=False, help='case sensitive')
required = mypar.add_argument_group('required arguments')
required.add_argument(
'-f', '--file', help='<file_lista> file contenente le stringhe da cercare',
required=True, default='', metavar='<file_lista>')
required.add_argument(
'-d', '--dir', help='<directory> directory che contiene i file in cui cercare',
required=True, default='', metavar='<directory>')
# check if arguments is passed, otherwise print help
if len(sys.argv) == 1:
mypar.parse_args(['-h'])
else:
args = mypar.parse_args()
if not os.path.exists(args.file):
print("ERRORE: il file {} non esiste".format(args.file))
sys.exit(1)
else:
searchFileName = args.file
if not os.path.exists(args.dir):
print("ERRORE: la directory {} non esiste".format(args.dir))
sys.exit(1)
else:
path = args.dir
limitOccurrences = args.counter
checkCase = args.Case
files = [f for f in glob.glob(path + "**/*", recursive=True)]
myList = loadSearches(searchFileName)
for k in files:
for number, i in enumerate(myList):
numOccurrences = howMany(k,i, checkCase)
if numOccurrences == None:
numOccurrences = 0
if numOccurrences >= limitOccurrences and limitOccurrences > 0:
print("{},{},{}".format(i.rstrip(),k,numOccurrences))
if numOccurrences == limitOccurrences and limitOccurrences == 0:
print("{},{},{}".format(i.rstrip(), k, numOccurrences))
|
import re
def op(to_calc):
if "+" or "-" or "x" or "/" in to_calc:
to_calc = re.split("(\D)",to_calc)
while len(to_calc) > 2:
a = to_calc[0]
b = to_calc[2]
if to_calc[1] == "+":
c = int(a) + int(b)
elif to_calc[1] == "-":
c = int(a) - int(b)
elif to_calc[1] == "x":
c = int(a) * int(b)
elif to_calc[1] == "/":
c = int(a) / int(b)
elif to_calc[1] == "%":
c = int(a) / 100
return c
del to_calc[0:3]
to_calc.insert(0, c)
print(to_calc)
return to_calc[0]
def f_op(to_calc):
if "+" or "-" or "x" or "/" in to_calc:
to_calc = re.split('([^\d\.])', to_calc)
print(to_calc)
while len(to_calc) > 2:
a = to_calc[0]
b = to_calc[2]
if to_calc[1] == "+":
c = float(a) + float(b)
elif to_calc[1] == "-":
c = float(a) - float(b)
elif to_calc[1] == "x":
c = float(a) * float(b)
elif to_calc[1] == "/":
c = float(a) / float(b)
elif to_calc[1] == "%":
c = float(a) / 100
return c
del to_calc[0:3]
to_calc.insert(0, c)
print(to_calc)
return to_calc[0] |
#!/usr/bin/python
#Filename:simplestclass.py
class Person:
def __init__(self, name):
self.name = name
def sayHi(self):
print 'how are you?', self.name
p = Person('LiLei')
p.sayHi() |
import math
import random
import turtle
import os
# set up screen
wn = turtle.Screen()
wn.bgcolor("dark blue")
wn.title("Turtle Defender")
wn.bgpic("turtle_fighter_background.gif")
# register the shapes
# draw border
border_pen = turtle.Turtle()
border_pen.speed(0)
border_pen.color("light blue")
border_pen.penup()
border_pen.setposition(-300, -300)
border_pen.pendown()
border_pen.pensize(3)
for side in range(4): # creates a box for the border
border_pen.fd(600) # moves line x amount of pixels in one direction
border_pen.lt(90) # turns the pen to go in a different direction as it is drawing the square
border_pen.hideturtle()
# set the score to 0
score = 0
# draw the score
score_pen = turtle.Turtle()
score_pen.speed(0)
score_pen.color("white")
score_pen.penup()
score_pen.setposition(-290, 280)
score_string = "Score %s" % score
score_pen.write(score_string, False, align="left", font=("Arial", 14, "normal"))
score_pen.hideturtle()
# create player turtle
player = turtle.Turtle()
player.color("green")
player.shape("circle")
player.penup()
player.speed(0)
player.setposition(0, -250)
player.setheading(90)
player_speed = 15
# create enemy
# initializing enemy object within the GUI
enemy = turtle.Turtle()
enemy.color("red")
enemy.shape("circle")
enemy.penup()
enemy.speed(0)
enemy.setposition(-200, 250)
enemy_speed = 2
# choose the number of enemies
number_of_enemies = 5
# create an empty list of enemies
enemies = []
# add enemies to the list
for i in range(number_of_enemies):
enemies.append(turtle.Turtle())
for enemy in enemies:
enemy.color("red")
enemy.shape("circle")
enemy.penup()
enemy.speed(0)
x = random.randint(-200, 200)
y = random.randint(100, 250)
enemy.setposition(x, y)
enemy_speed = 2
# create the player's weapons
weapon = turtle.Turtle()
weapon.color("light blue")
weapon.shape("triangle")
weapon.penup() # prevents weapons from drawing a line as it moves through the GUI
weapon.speed(0)
weapon.setheading(90)
weapon.shapesize(0.5, 0.5)
weapon.hideturtle()
weapon_speed = 20
# initializing state of the weapon
# ready to fire
# firing
weapon_state = "ready"
# move the player to the left and right
def move_left():
"""
Checking boundaries for the player so they
do not move off of the board when moving to the left.
Keeps the player inside the world of the game.
"""
x = player.xcor()
x -= player_speed
if x < -280:
x = - 280
player.setx(x)
def move_right():
"""
Checking boundaries for the player so they
do not move off of the board when going to the right.
Keeps the player inside the world of the game.
"""
x = player.xcor()
x += player_speed
if x > 280:
x = 280
player.setx(x)
def fire_weapon():
# set weapon state as a global if it needs to be changed
global weapon_state # any change within this function will be reflected in the global scope
if weapon_state == "ready":
weapon_state = "fire"
# move the weapon to be just above the player
x = player.xcor()
y = player.ycor() + 10
weapon.setposition(x, y)
weapon.showturtle()
def isCollision(t1, t2):
distance = math.sqrt(math.pow(t1.xcor() - t2.xcor(), 2) + math.pow(t1.ycor() - t2.ycor(), 2))
if distance < 18:
return True
else:
return False
# create keyboard bindings
# initializing connection between keyboard commands to player movement in the GUI
turtle.listen()
turtle.onkey(move_left, "Left")
turtle.onkey(move_right, "Right")
turtle.onkey(fire_weapon, "space")
# primary game loop
while True: # while the game is running, or while the player is actually playing the game
for enemy in enemies:
# move the enemy
x = enemy.xcor() # initializing the x coordinates of the enemy AI
x += enemy_speed # setting the enemy speed
enemy.setx(x) # setting the x coordinates to the x values on the GUI
# need the enemy to reverse once it touches either edge of the board
if enemy.xcor() > 280:
for e in enemies:
y = e.ycor() # initializing the y coordinates
y -= 40 # every time the enemy hits the boarder, the enemy will drop down 40 pixels, and hence will get
# closer to the player
e.sety(y)
# change the enemy's direction
enemy_speed *= -1
if enemy.xcor() < -280:
for e in enemies:
y = e.ycor() # initializing the y coordinates
y -= 40 # every time the enemy hits the boarder, the enemy will drop down 40 pixels, and hence will get
# closer to the player
e.sety(y)
# change the enemy's direction
enemy_speed *= -1
# checking for collision between the weapon and the enemy
if isCollision(weapon, enemy):
# reset weapon
weapon.hideturtle()
weapon_state = "ready"
weapon.setposition(0, -400) # moves weapon off the screen
# reset the enemy
x = random.randint(-200, 200)
y = random.randint(100, 250)
enemy.setposition(x, y)
# update score
score += 10
score_string = "Score: %s" % score
# on type of string when using python's string formatting capabilities. More specifically, %s converts a
# specified value to a string using the str() function.
score_pen.clear()
score_pen.write(score_string, False, align="left", font=("Arial", 14, "normal"))
# checking for collision between the player and the enemy
if isCollision(player, enemy):
# reset weapon
player.hideturtle()
enemy.hideturtle()
print("Game Over")
break
# move the weapon
if weapon_state == "fire":
y = weapon.ycor()
y += weapon_speed
weapon.sety(y)
# checking to see if the weapon has reached the top
if weapon.ycor() > 275:
weapon.hideturtle()
weapon_state = "ready"
delay = raw_input("Press enter to finish")
|
print("Welcome to Treasure Island.")
print("Your mission is to find the treasure.")
#https://www.draw.io/?lightbox=1&highlight=0000ff&edit=_blank&layers=1&nav=1&title=Treasure%20Island%20Conditional.drawio#Uhttps%3A%2F%2Fdrive.google.com%2Fuc%3Fid%3D1oDe4ehjWZipYRsVfeAx2HyB7LCQ8_Fvi%26export%3Ddownload
first_choice = input("... Type 'left' or 'right' ")
if first_choice=="right":
print("Fail into a hole. Game Over.")
elif first_choice=="left":
second_choice = input("... Type 'swim' or 'wait' ")
if second_choice=="swim":
print("Attacked by Trout. Game Over.")
elif second_choice=="wait":
third_choice = input("...Which door? Type 'red', 'blue' or 'yellow' ")
if third_choice=='red':
print("Burned by Fire. Game Over.")
elif third_choice=='blue':
print("Eaten by Beasts. Game Over.")
elif third_choice=='yellow':
print("You win!!!")
print('''
*******************************************************************************
| | | |
_________|________________.=""_;=.______________|_____________________|_______
| | ,-"_,="" `"=.| |
|___________________|__"=._o`"-._ `"=.______________|___________________
| `"=._o`"=._ _`"=._ |
_________|_____________________:=._o "=._."_.-="'"=.__________________|_______
| | __.--" , ; `"=._o." ,-"""-._ ". |
|___________________|_._" ,. .` ` `` , `"-._"-._ ". '__|___________________
| |o`"=._` , "` `; .". , "-._"-._; ; |
_________|___________| ;`-.o`"=._; ." ` '`."\` . "-._ /_______________|_______
| | |o; `"-.o`"=._`` '` " ,__.--o; |
|___________________|_| ; (#) `-.o `"=.`_.--"_o.-; ;___|___________________
____/______/______/___|o;._ " `".o|o_.--" ;o;____/______/______/____
/______/______/______/_"=._o--._ ; | ; ; ;/______/______/______/_
____/______/______/______/__"=._o--._ ;o|o; _._;o;____/______/______/____
/______/______/______/______/____"=._o._; | ;_.--"o.--"_/______/______/______/_
____/______/______/______/______/_____"=.o|o_.--""___/______/______/______/____
/______/______/______/______/______/______/______/______/______/______/_____ /
*******************************************************************************
''')
else:
print("Game Over.")
else:
print("Game Over.")
else:
print("Game Over.") |
#https://repl.it/@MashaPodosinova/coffee-machine-start#main.py
MENU = {
"espresso": {
"ingredients": {
"water": 50,
"coffee": 18,
},
"cost": 1.5,
},
"latte": {
"ingredients": {
"water": 200,
"milk": 150,
"coffee": 24,
},
"cost": 2.5,
},
"cappuccino": {
"ingredients": {
"water": 250,
"milk": 100,
"coffee": 24,
},
"cost": 3.0,
}
}
resources = {
"water": 300,
"milk": 200,
"coffee": 100,
}
profit = 0
turn_off = False
def check_up(order_ingredients):
"""Rerurns true when order can be made"""
for item in order_ingredients:
if order_ingredients[item] >= resources[item]:
print(f"Sorry there in not {item}")
return False
return True
def calc_coins():
"""Returns the total amount of money from the customer"""
quarters = int(input("how many quarters?: "))
dimes = int(input("how many dimes?: "))
nickels = int(input("how many nickles?: "))
pennies = int(input("how many pennies?: "))
total = quarters * 0.25 + dimes * 0.1 + nickels * 0.05 + pennies * 0.01
return total
def is_sufficient(money_received, price):
"""Returns true if it is enough money"""
if price <= money_received:
change = round(money_received - price, 2)
print(f"Here is your {option}.Enjoy!\nHere us £{change} in change")
global profit
profit += price
return True
else:
print(f"Sorry not enough money")
return False
def make_cup(drink_name, order_ingredients):
"""Deduct the required ingredients from the resources"""
for item in order_ingredients:
resources[item] -= order_ingredients[item]
print(f"Here is your {drink_name} ☕️Enjoy!")
while not turn_off:
option = input("\nWhat would you like? (espresso/latte/cappuccino): ")
if option == "off":
turn_off = True
elif option == "report":
print(f'Water : {resources["water"]}ml\n'
f'Milk : {resources["milk"]}ml\n'
f'Coffee : {resources["coffee"]}ml\nMoney : {profit}')
else:
drink = MENU[option]
if check_up(drink["ingredients"]):
user_money = calc_coins()
if is_sufficient(user_money, drink["cost"]):
make_cup(option, drink["ingredients"]) |
#link to Repl
#https://repl.it/@MashaPodosinova/blind-auction-start#main.py
from replit import clear
#HINT: You can call clear() to clear the output in the console.
from art import logo
print(logo)
data={}
auction_in_progress = True
while auction_in_progress:
name = input("What is your name?: ")
bid = int(input ("What is your bid?: £"))
answer = input("Are there any other bidders? Type 'yes' or 'no'. ").lower()
data[name] = bid
clear()
if answer == "no":
auction_in_progress = False
for player in data:
highest = 0
print(data[player])
if data[player] > highest:
highest = data[player]
name = player
print(f"The winner is {name} with a bid of £{highest}") |
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 4 17:06:58 2021
@author: Kovid
"""
from datetime import timedelta
def seconds_to_text(secs):
days = secs//86400
hours = (secs - days*86400)//3600
minutes = (secs - days*86400 - hours*3600)//60
seconds = secs - days*86400 - hours*3600 - minutes*60
result = ("{0} day{1} ".format(days, "s" if days != 1 else "") if days else "") + \
("{0} hr{1} ".format(hours, "s" if hours != 1 else "") if hours else "") + \
("{0} min{1} ".format(minutes, "s" if minutes != 1 else "") if minutes else "") + \
("{0} sec{1} ".format(seconds, "s" if seconds != 1 else "") if seconds else "")
return result
def seconds_to_text_(secs):
sec = timedelta(seconds=int(secs))
result = str(sec)
return result
if __name__ == "__main__":
secs = 1000
res = seconds_to_text(secs)
print(res)
secs = 1000
res = seconds_to_text_(secs)
print(res)
|
class Node(object):
def __init__(self,data):
self.data=data
self.link=None
class LinkedList(object):
def __init__(self):
self.head=None
self.size=0
def insertend(self,data):
if not self.head:
self.head=data
else:
actucal=self.head
while actucal.link!=None:
actucal=actucal.link
actucal.link=data
self.size+=1
def transveral(self):
actucal=self.head
r=[]
while actucal!=None:
r.append(actucal.data)
actucal=actucal.link
print("->".join(r))
def swap(self):
actucal=self.head
if(self.size%2==0):
while(actucal!=None):
temp=actucal.data
actucal.data=actucal.link.data
actucal.link.data=temp
actucal=actucal.link.link
else:
while(actucal.link!=None):
temp=actucal.data
actucal.data=actucal.link.data
actucal.link.data=temp
actucal=actucal.link.link
node1=Node("A")
node2=Node("B")
node3=Node("C")
node4=Node("D")
node5=Node("E")
node6=Node("F")
ll1=LinkedList()
ll1.insertend(node1)
ll1.insertend(node2)
ll1.insertend(node3)
ll1.insertend(node4)
ll1.insertend(node5)
#ll1.insertend(node6)
ll1.transveral()
ll1.swap()
ll1.transveral()
|
##########
#Question#
##########
'''
URL: https://leetcode.com/problems/minimum-depth-of-binary-tree/
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
Note: A leaf is a node with no children.
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: 2
Example 2:
Input: root = [2,null,3,null,4,null,5,null,6]
Output: 5
Constraints:
The number of nodes in the tree is in the range [0, 105].
-1000 <= Node.val <= 1000
'''
##########
#Solution#
##########
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def minDepth(self, root: TreeNode) -> int:
return self.height(root)
def height(self, node: TreeNode) -> int:
if node == None:
return 0
if node.left == None and node.right == None:
return 1
if node.left == None:
return self.height(node.right)+1
if node.right == None:
return self.height(node.left)+1
return min(self.height(node.right), self.height(node.left) )+1
|
##########
#Question#
##########
'''
URL: https://leetcode.com/problems/longest-common-prefix/
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Example 1:
Input: strs = ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Constraints:
0 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i] consists of only lower-case English letters.
'''
##########
#Solution#
##########
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
result_prefix = ""
if len(strs) == 0:
return result_prefix
if len(strs) == 1:
return strs[0]
first_str=strs[0]
for i in range(1,len(strs)):
result_prefix= self.compare(first_str, strs[i])
if result_prefix == "":
break
first_str=result_prefix
return result_prefix
def compare(self, str1:str, str2: str) -> str:
return_str = ""
min_len = min(len(str1), len(str2))
if min_len < 1:
return return_str
for i in range(0, min_len):
if str1[i] != str2[i]:
break
return_str = return_str+str1[i]
print(return_str)
return return_str
|
##########
#Question#
##########
'''
URL: https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/submissions/
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example:
Given the sorted array: [-10,-3,0,5,9],
One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
0
/ \
-3 9
/ /
-10 5
'''
##########
#Solution#
##########
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
tree = self.createBST(nums, 0, len(nums)-1)
return tree
def createBST(self, nums: List[int], start:int, end:int) -> TreeNode:
if start > end:
return
mid = start + (end - start) // 2
node = TreeNode(nums[mid])
node.left = self.createBST(nums, start, mid-1)
node.right = self.createBST(nums, mid+1, end)
return node
|
##########
#Question#
##########
'''
URL: https://leetcode.com/problems/pascals-triangle-ii/
Given an integer rowIndex, return the rowIndexth row of the Pascal's triangle.
Notice that the row index starts from 0.
In Pascal's triangle, each number is the sum of the two numbers directly above it.
Follow up:
Could you optimize your algorithm to use only O(k) extra space?
'''
##########
#Solution#
##########
class Solution:
def getRow(self, rowIndex: int) -> List[int]:
if rowIndex < 0:
return []
result = []
for i in range(rowIndex+1):
tempResult=[]
for j in range(0,i+1):
if j in (0,i):
tempResult.append(1)
else:
tempResult.append(result[j-1]+result[j])
result=tempResult
return result
|
x = input('please enter your name x :')
if( len(x) <5) :
print('your name is short')
if (len(x)>5):
print('your name is correct')
|
__author__ = 'willflowers'
import random
class Game:
def __init__(self, player):
self.player = player
def start(self):
player = Player()
if self.player.turns <= 8:
player.start()
else:
return self.player.score
class Player:
def __init__(self):
self.score = 0
self.rolls = 0
self.turns = 0
self.rounds = 0
self.turn_score = 0
self.turn_over = False
def turn(self):
if self.turn_over == True:
self.score += self.turn_score
self.turns += 1
def round(self):
self.roll = random.randint(1, 6)
if self.roll == 1:
self.turn_score = 0
self.turn_over = True
self.turn()
else:
self.turn_score += self.roll
self.rounds += 1
def start(self):
while not self.turn_over:
self.round()
def turn(self):
if self.turn_over == True:
self.score += self.turn_score
self.turnscore = 0
self.turns += 1
#Will roll once every turn
class Player1(Player):
def is_player_done(self):
if self.rounds == 1:
self.turn_over = True
self.turn()
#Will roll three times if possible every turn
class Player3(Player):
def is_player_done(self):
if self.rounds == 3:
self.turn_over = True
self.turn()
#Will roll four times if possible every turn
class Player4(Player):
def is_player_done(self):
if self.rounds == 4:
self.turn_over = True
self.turn()
if __name__ == '__main__':
will = Player3()
game = Game(will)
print(game.start()) |
import copy
class Element(object):
def __init__(self, value):
self.value = value
self.next = None
class LinkedList(object):
def __init__(self, head=None):
self.head = head
def append(self, new_element):
current = self.head
if self.head:
while current.next:
current = current.next
current.next = new_element
else:
self.head = new_element
def print(self):
current = self.head
if self.head:
while current.next:
print("[" + str(current.value) + "]", end=' ---> ')
current = current.next
print("[" + str(current.value) + "]", end='')
else:
print("list is empty")
def prepend(self, new_element):
new_element.next = self.head
self.head = new_element
def get_length(self):
length = 0
current = self.head
if self.head:
while current.next:
length = length + 1
current = current.next
length = length + 1
return length
def delete_from_end(self):
last = self.head
second_last = self.head
while last.next:
second_last = last
last = last.next
second_last.next = None
print('deleted node: ' + str(last.value))
del last
def delete_from_start(self):
first_node = self.head
self.head = self.head.next
print('deleted node: ' + str(first_node.value))
del first_node
# position should be 2 or greater as well as less than the length of the list
def add_at(self, new_element, position):
if self.get_length() > position and self.get_length() >= 2:
current = self.head
for currentPosition in range(1, position-1):
current = current.next
new_element.next = current.next
current.next = new_element
else:
print('Wrong position')
def delete_from(self, position):
if self.get_length() > position and self.get_length() >= 2:
current = self.head
for currentPosition in range(1, position-1):
current = current.next
deleted_node = current.next
current.next = current.next.next
print('deleted node: ' + str(deleted_node.value))
del deleted_node
else:
print('Wrong position')
def merge(self, other_list):
list1 = copy.deepcopy(self)
list2 = copy.deepcopy(other_list)
current = list1.head
if list1.head:
while current.next:
current = current.next
current.next = list2.head
return list1
def slice(self, lower_index, uper_index):
list_to_be_sliced = copy.deepcopy(self)
first = list_to_be_sliced.head
if list_to_be_sliced.head:
for current in range(1, lower_index):
first = first.next
last = list_to_be_sliced.head
if list_to_be_sliced.head:
for current in range(1, uper_index):
last = last.next
list_to_be_sliced.head = first
last.next = None
return list_to_be_sliced
def splice(self, start, end):
list_to_be_sliced = copy.deepcopy(self)
first = list_to_be_sliced.head
if list_to_be_sliced.head:
for current in range(1, start):
first = first.next
last = list_to_be_sliced.head
if list_to_be_sliced.head:
for current in range(1, end):
last = last.next
first.next = last.next
return list_to_be_sliced
def deep_splice(self, start, delete_count):
list_to_be_sliced = copy.deepcopy(self)
first = list_to_be_sliced.head
if list_to_be_sliced.head:
for current in range(1, start):
first = first.next
last = list_to_be_sliced.head
if list_to_be_sliced.head:
for current in range(1, delete_count+start):
last = last.next
first.next = last.next
return list_to_be_sliced
def is_exists(self, element):
number = self.head
while number:
if element.value == number.value:
return True
number = number.next
return False
def find(self, index):
if self.get_length() >= index or self.get_length() >= 1:
current = self.head
count = 0
while current:
if count == index:
return current.value
count += 1
current = current.next
else:
print("wrong index")
|
import csv
# ? Reading a csv file and printing.
# with open('data.csv', 'r') as csv_file:
# csv_reader = csv.reader(csv_file)
# # To allow us to skip the first line.
# next(csv_reader)
# for line in csv_reader:
# ? Write the contents into a new file, with - delimiter
# with open('data.csv', 'r') as csv_file:
# csv_reader = csv.reader(csv_file)
# with open('new_data.csv', 'w') as new_csv_file:
# csv_writer = csv.writer(new_csv_file, delimiter='-')
# for line in csv_reader:
# csv_writer.writerow(line)
# ? You can also use Dict methods, to Read or Write as a Dictionary.
# ? Here I'm going to read as a Dictionary, and then use the values
# ? to store into a list of Dictionary Tuples.
# list_values = []
# with open('data.csv', 'r') as csv_file:
# csv_reader = csv.DictReader(csv_file)
# for line in csv_reader:
# dict_values = {}
# dict_values['PassengerId'] = line['PassengerId']
# dict_values['Survived'] = line['Survived']
# list_values.append(dict_values)
# print(list_values)
# ? Writing using WriteDict
# with open('data.csv', 'r') as csv_file:
# csv_reader = csv.DictReader(csv_file)
# with open('new_data.csv', 'w') as new_csv_file:
# field_names = csv_reader.fieldnames
# csv_writer = csv.DictWriter(new_csv_file, fieldnames=field_names)
# csv_writer.writeheader()
# for line in csv_reader:
# csv_writer.writerow(line)
|
import random
class dado:
def __init__(self, lados):
self.lados = lados
def jogar_dados(self):
while True:
print(random.randrange(1, (self.lados)+1))
while True:
continuar = input("Continuar jogando ? (S/N)")
if continuar == "N" or continuar == "n":
break
elif continuar == "S" or continuar == "s":
break
else:
print("***Entrada incorreta***\n ")
if continuar == "N" or continuar == "n":
break
print("os dados foram deixados de lado")
dado_20 = dado(20)
dado_20.jogar_dados()
|
class Solution:
def compareString(self, str1, str2):
v1Int = int(str1) if str1 != "" else 0
v2Int = int(str2) if str2 != "" else 0
if v1Int > v2Int:
return 1
elif v1Int < v2Int:
return -1
else:
return 0
def compareVersion(self, version1, version2):
"""
:type version1: str
:type version2: str
:rtype: int
"""
v1 = ""
v2 = ""
r1 = 0
r2 = 0
stop1 = False
stop2 = False
while 1:
if r1 < len(version1) and version1[r1] != ".":
v1 += version1[r1]
else:
stop1 = True
if r2 < len(version2) and version2[r2] != ".":
v2 += version2[r2]
else:
stop2 = True
if stop1 and stop2:
compare = self.compareString(v1, v2)
if compare != 0 or (r1 >= len(version1) and r2 >= len(version2)):
return compare
v1 = ""
v2 = ""
stop1 = False
stop2 = False
if not stop1: r1 += 1
if not stop2: r2 += 1
if len(version1) != len(version2):
return self.compareString(v1, v2)
return 0
print(Solution().compareVersion("1", "1.0")) |
class Solution:
def toLowerCase(self, str):
"""
:type str: str
:rtype: str
"""
LOWER_UPPER_DIFF = 32
newStr = ""
for c in str:
asciiValue = ord(c)
if asciiValue >= 65 and asciiValue <= 90: # is Uppercase
c = chr(asciiValue + LOWER_UPPER_DIFF)
newStr += c
return newStr
print(Solution().toLowerCase("Hello")) |
import pandas as pd
# import numpy as np
# import csv
df = pd.read_csv("C:/Users/iamay/Desktop/PY/data/nyc_weather.csv")
print(df)
print(df.head())
print(df.tail())
print(df.columns)
print(df['EST'])
print(type(df['EST']))
print(df['Temperature']['EST'])
print(df['WindSpeedMPH'].min())
print(df['EST'][df['Temperature']==df['Temperature'].max()])
print(df['Temperature'].mean())
print(df['Temperature'].std())
print(df.describe()) |
#key modification
import sys
def alphabet():
#alpha= "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
#Entering the alphabets in string.
alpha= ""
#Generate the alphabet
for i in range(0,26):
alpha = alpha + chr(i+65)
return alpha
def Remove_dup_specialchar(key):
#Removing numbers or special characters from key
key1=''
key=key.upper()
b=0
while (b<len(key)):
if(ord(key[b])>=65 and ord(key[b])<=90):
key1=key1+key[b]
b=b+1
jreplace=key1
key1=''
v=0
while(v<len(jreplace)):
if(jreplace[v]=='J'):
key1=key1+'I'
else:
key1=key1+jreplace[v]
v=v+1
#now key is in key1
#removing duplicates from the key:
le=len(key1)
uniq=''
j=0
c=0
m=0
while(j<le):
c=0
#print("the j value")
if(j==0):
uniq=uniq+key1[0]
k=0
leng=len(uniq)
while(k<leng):
if(ord(key1[j])==ord(uniq[k])):
c=1
k=k+1
if(c==1):
m=1
else:
uniq=uniq+key1[j]
j=j+1
return uniq
def Generate_Matrix(uniq,alpha):
#the unique key is in uniq variable
#Inserting the unique key into matrix
Matrix = [[0 for x in range(5)] for x in range(5)]
lenn=len(uniq)
x=0
i=0
j=0
while(x<lenn):
Matrix[i][j]=uniq[x]
#print("the matrix have")
x=x+1
j=j+1
if(j==5):
i=i+1
j=0
ik=i
ij=j
y=0
uniq=uniq.upper()
while(y<26):
c=0
z=0
while(z<lenn):
#print("the uniq[z]=",uniq[z],z,alpha[y])
if(ord(alpha[y])==ord(uniq[z])):
c=1
z=z+1
if(c==1):
m=1
else:
if(ord(alpha[y])!=74):
Matrix[i][j]=alpha[y]
#print(i,j,"matrix :",Matrix[i][j])
#print(Matrix[i][j])
j=j+1
if(j==5):
i=i+1
j=0
y=y+1
#printing the matrix
###
#print("The matrix is :\n")
for line in Matrix:
#print(line)
m=0
return Matrix
#####
def Clean_message(encryptmsg):
#removing numbers or special character from the message
msg=encryptmsg
msg=msg.upper()
message=''
b=0
while (b<len(msg)):
if(ord(msg[b])>=65 and ord(msg[b])<=90):
message=message+msg[b]
b=b+1
print("The message is :",message)
return message
def Encrypt():
key=input("please enter the secret key : ")
encryptmsg=input("please enter the message to encrypt :")
#generating alphabets
alpha=alphabet()
#cleaning the key
uniq= Remove_dup_specialchar(key)
#print("The unique key is :",uniq)
#generating matix
Matrix=Generate_Matrix(uniq,alpha)
#cleanning the message
message=Clean_message(encryptmsg)
#inserting x if their is a double characters in message
#print("the message is :",message)
msg=message
le=len(message)
xmsg=''
j=0
i=0
c=0
m=0
while(i<le):
c=0
if(i==0):
xmsg=xmsg+msg[0]
i=i+1
if(i<len(msg)):
if(ord(xmsg[j])==ord(msg[i])):
xmsg=xmsg+'X'
xmsg=xmsg+msg[i]
j=j+2
else:
xmsg=xmsg+msg[i]
j=j+1
else:
m=0
i=i+1
#print("\nThe x inserted message is : ",xmsg)
#the x inserted message is in variable xmsg
l=len(xmsg)
if(l%2==1):
xmsg=xmsg+'X'
#print("the x inserted at end msg :",xmsg)
encryptmsg=xmsg
#print("The encryptedmsg",encryptmsg)
#encrypting the message
e=0
dmsg=''
while(e<len(encryptmsg)):
p1,q1=position(encryptmsg[e],Matrix)
e=e+1
if(e<len(encryptmsg)):
p2,q2=position(encryptmsg[e],Matrix)
if(q1==q2):
if(p1==4):
dmsg=dmsg+Matrix[0][q1]
else:
dmsg=dmsg+Matrix[p1+1][q1]
if(p2==4):
dmsg=dmsg+Matrix[0][q2]
else:
dmsg=dmsg+Matrix[p2+1][q2]
elif(p1==p2):
if(q1==4):
dmsg=dmsg+Matrix[p1][0]
else:
dmsg=dmsg+Matrix[p1][q1+1]
if(q2==4):
dmsg=dmsg+Matrix[q2][0]
else:
dmsg=dmsg+Matrix[p2][q2+1]
else:
dmsg=dmsg+Matrix[p1][q2]
dmsg=dmsg+Matrix[p2][q1]
#print("the e")
#print(e)
e=e+1
print("\nThe encrypted message is :",dmsg)
#function to find the position of letters in matrix
def position(letter,Matrix):
x=y=0
if(letter=='J'):
letter='I'
for i in range(5):
for j in range(5):
if (Matrix[i][j]==letter):
x=i
y=j
return x,y
def Decrypt():
#Re
key=input("please enter the secret key : ")
decryptmsg=input("please enter the Encrypted message :")
#generating alphabets
alpha=alphabet()
#cleaning the key
uniq= Remove_dup_specialchar(key)
#print("The unique key is :",uniq)
#generating matix
Matrix=Generate_Matrix(uniq,alpha)
#cleanning the message
dmsg=Clean_message(decryptmsg)
#decrypting the encrypted message
g=0
emsg=''
while(g<len(dmsg)):
p1,q1=position(dmsg[g],Matrix)
g=g+1
if(g<len(dmsg)):
p2,q2=position(dmsg[g],Matrix)
if(q1==q2):
if(p1==0):
emsg=emsg+Matrix[4][q1]
else:
emsg=emsg+Matrix[p1-1][q1]
if(p2==0):
emsg=emsg+Matrix[4][q2]
else:
emsg=emsg+Matrix[p2-1][q2]
elif(p1==p2):
if(q1==0):
emsg=emsg+Matrix[p1][4]
else:
emsg=emsg+Matrix[p1][q1-1]
if(q2==0):
emsg=emsg+Matrix[q2][4]
else:
emsg=emsg+Matrix[p2][q2-1]
else:
emsg=emsg+Matrix[p1][q2]
emsg=emsg+Matrix[p2][q1]
g=g+1
print("The decoded message is :",emsg)
#requesting user for input
print( "Welcome to Playfair Cipher ->")
print("Enter: \n1.Encrypt\n2.Decrypt \n3.Quit")
x = input()
while(x=='1' or x=='2' or x=='3'):
if(x=='1'):
Encrypt()
elif(x=='2'):
Decrypt()
else:
sys.exit()
x=input("\nEnter: \n1.Encrypt\n2.Decrypt \n3.Quit :\n")
|
import numpy as np
# 原函数
def F(x):
return x**3 + x**2 + x - 3
# 导数
def f(x):
return 3*x**2 + 2*x + 1
# 牛顿迭代法
def Newton(x):
return x -F(x) / f(x)
#初值
x = -0.7
e0 = 1.7
for i in range(7):
print(i)
x = Newton(x)
print("x=", x)
print("e=", np.fabs(x - 1))
print("e_{i}/e_{i-1}=", np.fabs(x - 1)/ np.power(e0, 2))
e0 = np.fabs(x - 1) |
import sqlite3
connection = sqlite3.connect('data.db')
cursor = connection.cursor()
create_table = "CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, username text,password text)"
# Execute table creation
cursor.execute(create_table)
create_table = "CREATE TABLE IF NOT EXISTS items (name text, price real)"
# Execute table creation
cursor.execute(create_table)
cursor.execute("INSERT INTO items VALUES ('test', 12.99)")
# Commit changes to database
connection.commit()
# Close connection
connection.close()
|
a = input("nhap du lieu ")
import string
for i in a:
if 97<= ord(i) <= 122:
u = ord(i)-32
for t in string.ascii_uppercase:
if ord(t) == u:
a = a.replace(i,t)
print(a)
|
class Rectangle:
def __init__(self,l,w):
self.a = l
self.b = w
def area(self):
c = self.a*self.b
return c
i = Rectangle(5,10)
print(i.area()) |
class MySingleton:
are_we_instantiated_value = None
'''
__new__ happens even before __init__ that would be a constructor for the object created so that's the "first step".
We override the __new__ method with the tracked class variable that is called "are_we_instantiated_value".
We first set the "are_we_instantiated_value" to None, then the __new__ gets overridden in a way that if the class
variable's value is None, we instantiate the object, otherwise we just return the same object all the time.
This ensures that it's only been created once.
'''
def __new__(cls):
if cls.are_we_instantiated_value is None:
cls.are_we_instantiated_value = object.__new__(cls)
cls.internal_value = 10
return cls.are_we_instantiated_value
# Let's create the first object.
first_object = MySingleton()
# Let's print out the object's internal value.
print(first_object.internal_value)
# Let's set the internal value to 20 to ensure we changed it.
first_object.internal_value = 20
# Let's print out the memory address and the changed value - of the first object.
print(first_object)
print(first_object.internal_value)
# So let's create a second object.
second_object = MySingleton()
# Let's create the second object's internal value to another value
second_object.internal_value = 30
# And see the memory address of the second object!
print(second_object)
# See the second object's internal value and first being the same now?
print(first_object.internal_value)
print(second_object.internal_value)
# You get the idea now I guess
third_object = MySingleton()
third_object.internal_value = 40
print(third_object)
print(third_object.internal_value)
|
intervals = [[1,3],[2,4],[5,7],[6,8]]
def custom(a,b):
return a[0]-b[0]
intervals.sort(cmp =custom)
stack = []
for interval in intervals:
if stack==[]:
stack.append(interval)
else:
old = stack.pop()
if interval[0]<=old[1]:
if interval[1]>old[1]:
stack.append([old[0], interval[1]])
else:
stack.append(old)
else:
stack.append(old)
stack.append(interval)
print stack
|
a = [1,3,0,5,8,5]
b = [2,4,6,7,9,9]
c =[]
for i in range(len(a)):
c.append((a[i],b[i]))
def cusort(a,b):
return a[1]-b[1]
c.sort(cmp = cusort)
print 0,
prev = c[0][1]
for i in range(1,len(c)):
start = c[i][0]
if start>prev:
print i,
prev = c[i][1]
|
string = "abbabb"
matrix = [[False for i in range(len(string))] for i in range(len(string)) ]
for i in range(len(matrix)):
matrix[i][i] = True
max_val = 0
start = 0
for L in range(2, len(string)+1):
for i in range(0, len(string)-L+1):
if L==2:
if string[i] == string[i+1]:
matrix[i][i+1] = True
max_val = L
start = i
else:
j = i+L-1
if (string[i]==string[j]):
if L>max_val:
max_val = L
start = i
matrix[i][j] = (string[i]==string[j]) and matrix[i+1][j-1]
print max_val
print string[start:start+L]
|
def sudoku_display_unit(sudoku):
'''
Reshapes a given array inorer to get a predefined display format of SUDOKU.
No matter what the input size output will be in the predefined format.
'''
count = 0
for i in sudoku:
if count % 3 == 0:
print(*'-'*(len(i) + int((len(i) / 3)-1)))
for j in range(len(i)):
if j == (len(i)-3):
print(*i[-3:])
elif j % 3 == 0:
print(*i[j:j + 3], '|', end=' ')
count += 1
print(*'-'*(len(i) + int((len(i) / 3)-1)))
|
try:
number_given = int(input("Number: "))
for i in range(1,number_given):
remainder = number_given % i
if i != 1 and remainder == 0:
print(f"{number_given} is NOT a prime number")
break
elif i == (number_given - 1) and remainder != 0 or number_given == 2:
print(f"{number_given} is a prime number")
except:
print("Please enter a valid integer number")
|
#!/usr/bin/python
import scramble
demoScrambler = scramble.Scrambler()
scrambledTexts = []
glitchAmt = 10
text = "This is a demonstration text string that shall be randomly glitched and destroyed."
text = text.split()
for x in range(22):
scrambledTexts.append( demoScrambler.scramble_text(text, glitchAmt) )
glitchAmt += 10
print ""
for scrambledText in scrambledTexts:
toPrint = scrambledText[0]
for word in scrambledText[1:]:
toPrint += " " + word
print toPrint |
import random, math
"""This file contains the vector class. A vector can be defined as
a number with a direction, but in this case it is easier to define
vectors just by their x and y components. Values like position, velocity,
and acceleration should all be stored as vectors for simplicity's sake.
Vectors can be created like so:
myvar = Vector(10,-5)
This would create a vector called myvar, which would have an x value of 10
and a y value of -5.
Each vector function has a short comment describing its use."""
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
self.uBoundX = None
self.uBoundY = None
self.lBoundX = None
self.lBoundY = None
def __str__(self):
#by defining this, printing a vector will print this instead
#of something like "<vector>0x29384000"
return "X:" + str(self.x)+ ", Y:" + str(self.y) +\
"\nUpper X Bound: " + str(self.uBoundX) +\
", Upper Y Bound: " + str(self.uBoundY) +\
"\nLower X Bound: " + str(self.lBoundX) +\
", Lower Y Bound: " + str(self.lBoundY)
def clear(self):
#sets ALL attributes to 0 or None
self.x = 0
self.y = 0
self.clearBounds()
def bound(self, x=None, y=None):
#Caps maximum/minimum values vector is allowed to have
#uses single number, makes it maximum, then negates it
#and makes that the minimum
if x < 0 or y < 0:
raise ValueError("Number below zero.")
if x != None:
self.uBoundX = x
self.lBoundX = -x
if y != None:
self.uBoundY = y
self.lBoundY = -y
#both bounded functions return -1 if the value is less than the lower bound,
#return 1 if it is greater than the upper bound, and 0 if it is within
#both bounds
def boundedX(self,x):
if self.lBoundX != None and x <= self.lBoundX:
return -1
elif self.uBoundX != None and x >= self.uBoundX:
return 1
else:
return 0
def boundedY(self,y):
if self.lBoundY != None and y <= self.lBoundY:
return -1
elif self.uBoundY != None and y >= self.uBoundY:
return 1
else:
return 0
#specifically sets lower bounds only
def lBound(self, x=None, y=None):
#sets lower bounds for vector
if x != None:
if self.uBoundX != None and x > self.uBoundX:
raise ValueError("Lower bound is greater than upper bound.")
self.lBoundX = x
if y != None:
if self.uBoundY != None and y > self.uBoundY:
raise ValueError("Lower bound is greater than upper bound.")
self.lBoundY = y
#sets only upper bounds
def uBound(self, x=None, y=None):
#sets upper bounds for vector
if x != None:
if self.lBoundX != None and x < self.lBoundX:
raise ValueError("Upper bound is smaller than lower bound.")
self.uBoundX = x
if y != None:
if self.lBoundY != None and y < self.lBoundY:
raise ValueError("Upper bound is smaller than lower bound.")
self.uBoundY = y
def clearBounds(self):
#sets all caps to None
self.uBoundX = self.lBoundX = self.uBoundY = self.lBoundY = None
def add(self, x, y):
#this function adds x and y to the vector's current x and y values
#runs test x and y values through the user-set caps
#if any value is < negCap or > posCap then the value
#is just set to its respective cap
xBound = self.boundedX(self.x+x)
if xBound > 0:
self.x = self.uBoundX
elif xBound < 0:
self.x = self.lBoundX
else:
self.x += x
yBound = self.boundedY(self.y+y)
if yBound > 0:
self.y = self.uBoundY
elif yBound < 0:
self.y = self.lBoundY
else:
self.y += y
def addV(self, vect):
#adds another vectors x and y values to this one's
x, y = vect.get()
#runs test x and y values through the user-set caps
#if any value is < negCap or > posCap then the value
#is just set to its respective cap
xBound = self.boundedX(self.x+x)
if xBound > 0:
self.x = self.uBoundX
elif xBound < 0:
self.x = self.lBoundX
else:
self.x += x
yBound = self.boundedY(self.y+y)
if yBound > 0:
self.y = self.uBoundY
elif yBound < 0:
self.y = self.lBoundY
else:
self.y += y
def set(self, x, y):
#sets vector's x and y values to x and y
#this function is limited by the caps
xBound = self.boundedX(x)
if xBound > 0:
self.x = self.uBoundX
elif xBound < 0:
self.x = self.lBoundX
else:
self.x = x
yBound = self.boundedY(y)
if yBound > 0:
self.y = self.uBoundY
elif yBound < 0:
self.y = self.lBoundY
else:
self.y = y
def setV(self, v):
#sets this vector's values to another vector's values
#affected by current caps
x, y = v.get()
xBound = self.boundedX(x)
if xBound > 0:
self.x = self.uBoundX
elif xBound < 0:
self.x = self.lBoundX
else:
self.x = x
yBound = self.boundedY(y)
if yBound > 0:
self.y = self.uBoundY
elif yBound < 0:
self.y = self.lBoundY
else:
self.y = y
def get(self):
return (self.x, self.y)
def getV(self):
return Vector(self.x, self.y)
def integize(self):
#turns vector's float values to integers
self.x = int(self.x)
self.y = int(self.y)
def round(self, ndigits):
#rounds vector values to ndigits amount of digits
self.x = round(self.x,ndigits)
self.y = round(self.y,ndigits)
def normalize(self):
#turns vector into unit vectors, for example a vector pointing
#straight up would have values x=0,y=1
length = math.sqrt(self.x*self.x + self.y*self.y)
if length != 0:
self.x /= length
self.y /= length
def dot(self, c):
#dot products the vector, essentially multiplies each value by c
self.x *= c
self.y *= c
def theta(self, radians=True):
#gets the angle of the vector in terms of the unit circle
#returns in radians unless theta() is called with radians=False
if self.x != 0 and self.y != 0:
theta = math.atan(self.y/self.x)
else:
theta = 0
if self.x < 0 and self.y > 0:
theta += math.pi
elif self.x < 0 and self.y < 0:
theta += math.pi
elif self.x > 0 and self.y < 0:
theta += 2*math.pi
elif self.x > 0 and self.y > 0:
pass
elif self.x == 0:
if self.y > 0:
theta = math.pi/2
else:
theta = (3*math.pi)/2
elif self.y == 0:
if self.x > 0:
theta = 0
else:
theta = math.pi
else:
theta = 0
if radians:
return theta
else:
return math.degrees(theta)
def rotate(self,theta):
#theta should be in radians
cs = round(math.cos(theta),3)
sn = round(math.sin(theta),3)
px = self.x * cs - self.y * sn
py = self.x * sn + self.y * cs
self.x = round(px,3)
self.y = round(py,3)
def length(self):
return math.sqrt((self.x*self.x)+(self.y*self.y))
|
#importing commandline arguments libraries
from sys import argv
#splitting the command line arguments and storing each for further
script, filename = argv
#opening the filename and stroing as a string variable
text = open(filename)
print(f"Here's your file {filename}")
#printing the string variable
print(text.read())
#For inputting the new file again we take input from the user
print("Type the file name again")
newfile = input('> ')
#Storing the newfile as string in the new string variable
newtext = open(newfile)
print("Printing the new file")
#Again printing the newtext contents i.e newfile
print(newtext.read())
|
# Inheritance
# Override methods Explicitly
class parent(object):
def explicit(self):
print("Parent explicit function")
class child(parent):
def explicit(self):
print("Child explicit function")
father = parent()
son = child()
father.explicit()
son.explicit() |
animals = ['bear', 'python3.6', 'peacock', 'kangaroo', 'whale', 'platypus']
print("\nAll the list members:")
print(animals)
print("\nLast item of the list:")
print(animals[-1])
print("\nFirst two items of the list:")
print(animals[0:3])
print("\nItems from 2 to last but one:")
print(animals[1:-1])
print("\nLast two items")
print(animals[4:])
|
fname = input("Enter file name: ")
fhand = open(fname)
count=0
total=0
for line in fhand:
line = line.rstrip()
if line.startswith("X-DSPAM-Confidence:"):
count = count + 1
s = line.find("0")
x = line[s:]
total = total + float(x)
avg=total/count
print("Average spam confidence:",avg)
|
"""
This file is the place to write solutions for the
skills assignment called skills-sqlalchemy. Remember to
consult the exercise instructions for more complete
explanations of the assignment.
All classes from model.py are being imported for you
here, so feel free to refer to classes without the
[model.]User prefix.
"""
from model import *
init_app()
# -------------------------------------------------------------------
# Part 2: Discussion Questions
# 1. What is the datatype of the returned value of
# ``Brand.query.filter_by(name='Ford')``?
#
# flask_sqlalchemy.BaseQuery object
# 2. In your own words, what is an association table, and what type of
# relationship (many to one, many to many, one to one, etc.) does an
# association table manage?
#
# Association table manages two, many to many, tables. It
# links those tables through foriegn keys. Association table
# has a one to many relationship
# to the tables.
# -------------------------------------------------------------------
# Part 3: SQLAlchemy Queries
# Get the brand with the ``id`` of "ram."
q1 = "Brand.query.filter_by(brand_id='ram').all()"
# Get all models with the name "Corvette" and the brand_id "che."
q2 = "Model.query.filter(Model.name=='Corvette', Model.brand_id=='che').all()"
# Get all models that are older than 1960.
q3 = "Model.query.filter(Model.year < 1960).all()"
# Get all brands that were founded after 1920.
q4 = "Brand.query.filter(Brand.founded > 1920).all()"
# Get all models with names that begin with "Cor."
q5 = "Model.query.filter(Model.name.like('Cor%')).all()"
# Get all brands that were founded in 1903 and that are not yet discontinued.
q6 = "Brand.query.filter(Brand.founded=='1903', Brand.discontinued==None).all()"
# Get all brands that are either 1) discontinued (at any time) or 2) founded
# before 1950.
q7 = "Brand.query.filter((Brand.founded < '1950') | (Brand.discontinued!=None)).all()"
# Get any model whose brand_id is not "for."
q8 = "Model.query.filter(Model.brand_id!='for').all()"
# -------------------------------------------------------------------
# Part 4: Write Functions
def get_model_info(year):
"""Takes in a year and prints out each model name, brand name, and brand
headquarters for that year using only ONE database query."""
car_list = db.session.query(Model.name, Brand.brand_id, Brand.name, Brand.headquarters).filter(Model.year==year).\
join(Brand).all()
for car in car_list:
print "%s \t %s \t %s \t %s \n" % (car[0], car[1], car[2], car[3])
def get_brands_summary():
"""Prints out each brand name and each model name with year for that brand
using only ONE database query."""
car_list = db.session.query(Brand.name, Model.name).filter(Model.year).join(Brand).all()
def search_brands_by_name(mystr):
"""Returns all Brand objects corresponding to brands whose names include
the given string."""
brand_objs = Brand.query.filter(Brand.name.like('%mystr%')).all()
return brand_objs
def get_models_between(start_year, end_year):
"""Returns all Model objects corresponding to models made between
start_year (inclusive) and end_year (exclusive)."""
cars_in_range = Model.query.filter(Model.year > start_year, Model.year < end_year).all()
return cars_in_range
|
import smtplib
import getpass
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import datetime
import re
def mail():
"""
Docstring for mail function
mail(receiver), receiver should be email address
this function will ask sender email and password
for GMAIL, please make sure to allow less secure apps
https://myaccount.google.com/u/1/lesssecureapps?pli=1&pageId=none
"""
split_term = '@'
sender = str(input("Please enter sender email: "))
receiver = str(input("Please enter receiver email: "))
sen = re.split(split_term, sender)
if sen[1] == 'gmail.com':
allow = str(input("Did you enable allow secure apps on gmail settings y or n? "))
if allow.lower() == 'y':
password = getpass.getpass(prompt='Enter {} Password password: '.format(sender))
smtpObj = smtplib.SMTP('smtp.gmail.com', 587)
smtpObj.starttls()
smtpObj.login(sender, password)
message = MIMEMultipart()
message["Subject"] = "Email generated by Python"
message["From"] = sender
message["To"] = receiver
user = re.split(split_term, receiver)
# Write the mail body text part
text = """Hi, {} \nThis email generated by Python programm! \nEmail generated on """.format(user[0]) +str(datetime.datetime.now().strftime("%Y %m %d %H:%M:%S'"))
part1 = MIMEText(text, "plain")
message.attach(part1)
try:
smtpObj.sendmail(sender, receiver, message.as_string())
print("{} Sent an email to {}".format(message.as_string(), receiver))
except:
print('error sending mail to {}'.format(receiver))
smtpObj.quit()
else:
print("Please enable allow secure apps on https://myaccount.google.com/u/0/lesssecureapps?pli=1&pageId=non")
else:
print("sender email {} is different than gmail.com".format(sen[1]))
mail(receiver)
|
# -*- coding: utf-8 -*-
import sqlite3
class DataBase:
def __init__(self, db_path, db_file):
self.db_file = db_path + db_file
self.db = None
def create_db(self):
"""
Создание необходимых таблиц для работы с ботом
"""
self.db = sqlite3.connect(self.db_file)
cursor = self.db.cursor()
# Создаём таблицу users, если она не существует
cursor.execute("""CREATE TABLE IF NOT EXISTS users
(
user_id INT PRIMARY KEY,
state INT,
email TEXT
)""")
self.db.commit()
def check_user(self, user_id):
"""
Проверяем на существование пользователя в системе
"""
self.create_db()
self.db = sqlite3.connect(self.db_file)
cursor = self.db.cursor()
cursor.execute('SELECT * FROM users WHERE user_id = ?', [user_id])
if cursor.fetchone() == None:
self.add_user(user_id)
def add_user(self, user_id):
"""
Добавляем нового пользователя в БД
"""
self.db = sqlite3.connect(self.db_file)
cursor = self.db.cursor()
data = [user_id, '1']
cursor.execute('INSERT INTO users (user_id, state) VALUES (?, ?)', data)
self.db.commit()
def update_email(self, user_id, email):
"""
Добавляем или обновляем email пользователя
"""
self.check_user(user_id)
self.db = sqlite3.connect(self.db_file)
cursor = self.db.cursor()
data = [email, user_id]
cursor.execute('UPDATE users SET email = ? WHERE user_id = ?', data)
self.db.commit()
def get_user(self, user_id):
"""
Возвращаем данные определённого пользователя
"""
self.db = sqlite3.connect(self.db_file)
cursor = self.db.cursor()
cursor.execute('SELECT state, email FROM users WHERE user_id = ?', [user_id])
return cursor.fetchone()
def get_state(self, user_id):
"""
Возвращаем текущее состояние пользователя
"""
self.check_user(user_id)
return self.get_user(user_id)[0]
def set_state(self, user_id, state):
"""
Устанавливаем определённое состояние пользователя
"""
self.db = sqlite3.connect(self.db_file)
cursor = self.db.cursor()
state = state
data = [state, user_id]
cursor.execute('UPDATE users SET state = ? WHERE user_id = ?', data)
self.db.commit()
def get_email(self, user_id):
"""
Возвращаем email пользователя
"""
return self.get_user(user_id)[1] |
print "I will now count my chickens:"
print "Hens", 25 + 30 / 6
print "Roosters", 100 - 25 * 3 % 4
print "Now I will count the eggs:"
# this equals 7 ...
print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
# this is what the above equation is w/ some brackets around what's
# happening
print "Is this 7?", (3 + 2 + 1 - 5) + (4 % 2) - (1 / 4) + 6
print "Is it true that 3 + 2 < 5 - 7?"
# hmm... apparently no brackets necessary,
# operator precedence ...
print 3 + 2 < 5 - 7
print "What is 3 + 2?", 3 + 2
print "What is 5 - 7?", 5 - 7
print "Oh, what's why it's False."
print "How about some more."
print "Is it greater?", 5 > -2
print "Is it greater or equal?", 5 >= -2
print "Is it less or equal?", 5 <= 2
import math
x = 5242424244
pent10 = math.floor(math.log(x, 10)) - 1
divisor = math.pow(10, pent10)
rounded = int(math.floor(x/divisor)*divisor)
print "What is %s rounded to the penultimate magnitude of 10?, well it is %s" % (x, rounded)
|
from commands import Command
class Enter(Command):
def do(self, text: str):
player = self.get_player()
house = self.get_house()
current_room = player.get_location()
location = text
# Step 1:
# check to see if there is a room with the same name
# as location
room = house.find_room_by_name(location)
if room is None:
print(f'Hey silly. The room \'{location}\' does not exist.')
print('Try typing in a REAL room!')
return
# Step 2:
# check if there is a door linked to location FROM the
# player's current location
if current_room.can_player_travel_to(room):
player.set_location(room)
else:
print(f'Hey silly. You can\'t go to {location} from here.')
def get_description(self):
return 'Travel to the room specified.'
def get_aliases(self):
return [
'go to',
'travel to',
'walk to',
'mosey on over to',
'crawl to',
'skip to',
'run to',
'head to',
'head over to'
]
|
data1 = (2014, 7, 2)
data2 = (2014, 7, 11)
if data1[1] == data2[1] and data1[0] ==data2[0]:
if data1[2] > data2[2]:
print('Różnica wynosi ',(data1[2]) - (data2[2]), 'dni.')
elif data2[2] > data1[2]:
print('Różnica wynosi ',(data2[2]) - (data1[2]), 'dni.')
else: print('Podane daty są takie same!')
|
a = 120
b = 150
for n in range(1, 121):
if a / n is int and b / n is int:
print(n)
else:
print('co jest?')
|
var = 2
var2 = var ** (1/2)
print('Vidente \n')
print('Número {} \nO antecessor é {} o sucessor é {}'.format(var,(var-1),(var+1)), end="") #\n quebra de linha #end linga os dois prints
print("")
print('Rais quadrada de {} é {}\n'.format(var,var2)) |
for index, character in enumerate("abcdefgh"):
print(index, character)
even = [2,4,6,8]
odd = [1,3,5,7,9]
even.extend(odd)
print(even)
even.sort()
print(even)
another_even = even
print(another_even)
even.sort(reverse=True)
print(even)
print(another_even) |
def min(*args, **kwargs):
key = kwargs.get("key",None)
print(key)
order_as = ""
print("str",isinstance(key, str), "int", isinstance(key,int))
if isinstance(key,str):
order_as = "str"
elif isinstance(key,int):
order_as = "int"
vals_list = []
arg_list = []
print(order_as)
if order_as == "str":
print("list(args)", list(*args))
arg_list = arg_list + list(*args)
else:
arg_list = args
for val in arg_list:
if isinstance(val, list):
vals_list = vals_list + val
else:
vals_list.append(val)
print("print(vals_list)",vals_list)
for key in kwargs:
vals_list.append(kwargs[key])
min_val = None
if len(vals_list) > 0:
min_val = vals_list.pop(0)
else:
return None
for val in vals_list:
if val < min_val:
min_val = val
return min_val
def max(*args, **kwargs):
vals_list = []
keys = kwargs.keys()
for val in args:
if isinstance(val, list):
vals_list = vals_list+val
else:
vals_list.append(val)
for key in kwargs:
vals_list.append(kwargs[key])
max_val = 0
if len(vals_list) > 0:
max_val = vals_list.pop(0)
else:
return None
for val in vals_list:
if val > max_val:
max_val = val
return max_val
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
#print(min(3,2,my=8,your=9))
#print(max(3, 2, my=8, your=9))
#print(max([1, 2, 0, 3, 4]))
print(min("hello", key=str))
#print(max(1,29292,[1, 2, 0, 3, 4],key={a:10,b:999999}))
"""
assert max(3, 2) == 3, "Simple case max"
assert min(3, 2) == 2, "Simple case min"
assert max([1, 2, 0, 3, 4]) == 4, "From a list"
assert min("hello") == "e", "From string"
assert max(2.2, 5.6, 5.9, key=int) == 5.6, "Two maximal items"
assert min([[1, 2], [3, 4], [9, 0]], key=lambda x: x[1]) == [9, 0], "lambda key"
""" |
# Name: Jennifer Daniels
# Assignment: HW3
# Description: Program performs tests on function contrived_func
# using random testing method
# Function being tested
from credit_card_validator import credit_card_validator
import random
import unittest
class TestCase(unittest.TestCase):
"""
Class contains methods that generate random numbers for Visa,
Master, and American Express credit cards. Credit card numbers
are generated with lengths of 14 - 17, set prefixs, and random.
Visa credit card:
prefix: 4
Master credit card:
prefix: 51-55
prefix: 2221 - 2720
American Express:
prefix: 34
prefix: 37
"""
def test_generate_testcases(self):
"""
Method iterates through each type of credit card with correct
length and performs 100000 iterations. A random test is
performed on different lengths and 100000 iterations
"""
c_length = [14, 15, 16, 17]
for i in range(0, 4):
for j in range(100000):
if i == 0:
credit_card_num = self.v_card(15)
elif i == 1:
credit_card_num = self.m_card(14)
elif i == 2:
credit_card_num = self.e_card(13)
elif i == 3:
c_choice = random.choice(c_length) # chooses length
credit_card_num = self.rnd_card(c_choice)
# passed credit card number into test function
credit_card_validator(credit_card_num)
print('Failure: {} should be {}'.format(credit_card_num, True))
def v_card(self, v_len):
"""
Generates and returns Visa credit card, length 16, and prefix 4
"""
v_num = ''
for j in range(v_len):
# generates and combines credit card number
v_num = v_num + ''.join(str(random.randint(0, 9)))
# combines prefix and generated numbers
v_card_num = "4" + ''.join(v_num)
return v_card_num
def m_card(self, m_len):
"""
Generates and returns Master credit card, length 16,
and random prefixes from 51-55 and 2221-2720.
"""
# 50% choice for choosing initial prefix
m_prefix = random.randint(0, 1)
if m_prefix == 0:
s_prefix = random.randint(2221, 2720)
m_num = ''
for j in range(m_len-2):
# generates and combines credit card number
m_num = m_num + ''.join(str(random.randint(0, 9)))
# combines prefix and generated numbers
m_card_num = str(s_prefix) + ''.join(m_num)
else:
s_prefix = random.randint(51, 55)
m_num = ''
for j in range(m_len):
# generates and combines credit card number
m_num = m_num + ''.join(str(random.randint(0, 9)))
# combines prefix and generated numbers
m_card_num = str(s_prefix) + ''.join(m_num)
return m_card_num
def e_card(self, e_len):
"""
Generates and returns American Express credit card,
length 16, and random prefixes 34 and 37.
"""
# 50% choice for choosing initial prefix
e_prefix = random.randint(0, 1)
if e_prefix == 0:
e_num = ''
for j in range(e_len):
# generates and combines credit card number
e_num = e_num + ''.join(str(random.randint(0, 9)))
# combines prefix and generated numbers
e_card_num = "34" + ''.join(e_num)
else:
e_num = ''
for j in range(e_len):
# generates and combines credit card number
e_num = e_num + ''.join(str(random.randint(0, 9)))
# combines prefix and generated numbers
e_card_num = "37" + ''.join(e_num)
return e_card_num
def rnd_card(self, rnd_len):
"""
Generates and returns random credit of various lengths and
prefixes.
"""
rnd_num = ''
for j in range(rnd_len):
# generates and combines credit card number
rnd_num = rnd_num + ''.join(str(random.randint(0, 9)))
# combines prefix and generated numbers
rnd_card_num = rnd_num
return rnd_card_num
if __name__ == '__main__':
unittest.main()
|
# mutating a list created with repetition
# initializing a variable with values
myList = [1,2,3,4]
# repetition
A = [myList]*3
myList[2] = 45
# output required
print(A)
print(myList[2])
print(myList[1:3]) |
number = int(input("Type a number: "))
count = 0
while str(number) != str(number) [::-1]:
number = int(number) + int(str(number)[::-1])
count = count + 1
print(f"checking {number}")
print("Palindrome found in " + str(count) + "steps. Final number was: " + str(number))
backWards = input('TYPE!').lower()
countStr = len(backWards) - 1
sdrawKacb = ''
while countStr > -1:
sdrawKacb = sdrawKacb + backWards[countStr]
countStr = countStr - 1
|
#DECORATORS INTRO
def hello():
return 'Hi Ale!'
def other(some_def_func):
print('Other code runs here')
print(some_def_func())
other(hello)
#ORIGINAL FUNCTION
def new_decorator(original_func):
def wrap_func():
print('Some extra code before original func')
original_func()
print('Some extra code after original func')
return wrap_func
def func_needs_decorator():
print('I want to be decorated')
#This returns the original function wrapped by other code
decorated_func = new_decorator(func_needs_decorator)
#We execute the decorated function
decorated_func()
#Easier syntax
@new_decorator
def func_needs_decorator():
print('I want to be decorated')
#Run the decorated function, if we comment the @ we run the normal func
func_needs_decorator()
|
import functools
def require_ints(func):
@functools.wraps(func)
def wrapper(*args,**kwargs):
kwargs_value=[i for i in kwargs.values()]
for arg in list(args)+kwargs_value:
if not isinstance(arg,int):
raise TypeError("{} only accepts integers as arguments.".format(func.__name__))
return func(*args,**kwargs)
return wrapper
@require_ints
def foo(x,y):
"""Return the sum of x and y"""
return x+y
#抛出异常,只接受整数作为参数
#print (foo(3,4.2))
#输出8
print (foo(3,5))
# Help on function foo in module __main__:
#
# foo(x, y)
# Return the sum of x and y
print (help(foo)) |
from pandas import *
data1 = {"java": 2000, "python": 1000, "c++": 2000}
index1 = {"java", "python", "c", "c#"}
se = Series(data=data1, index=index1)
print se
column = ["id", "name", "age", "sex", "score", "final"]
data = {"id": ["1", "2", "3"],
"name": ["han", "min", "yang"],
"age": [18, 19, 22],
"sex": ["man", "woman", "man"],
"score": [99, 100, 99]}
fr = DataFrame(data=data, columns=column)
print fr |
file = open('./input')
# PART 1
sum = 0
for line in file:
sum += int(line) // 3 - 2
print(sum)
|
class Role:
"""
"""
role = None
def __init__(self, role):
self.role = role
def set_role(self, role):
self.role = role
def get_role(self):
return self.role
def compare(self, roleB):
return roleB == self.role
def is_attacker(self):
return self.role == "Attacker"
def is_defender(self):
return self.role == "Defender"
def is_reserve(self):
return self.role == "Reserve"
def is_portal(self):
return self.role == "Portal"
def is_cannibal(self):
return self.role == "Cannibal"
def is_destroyer(self):
return self.role == "Destroyer" |
class Suplicio:
def __init__(self, listeilor):
self.listeilor=listeilor
def Ordenacion (self):
x = self.listeilor.upper()
return(x)
lista= "Hello world Practice makes perfect"
p1=Suplicio(lista)
print(p1.Ordenacion())
"""
input: Hello world Practice makes perfect
Output: Same shit, but UPPERCASE
""" |
#Complete the function to return the first digit to the right of the decimal point.
def first_digit(num):
num2=str(num)
posicion= 0
for x,y in enumerate(num2):
if y == ".":
posicion=x
return num2[posicion+1]
#Invoke the function with a positive real number. ex. 34.33
print(first_digit(6.24))
"""
Example input 1.79
Example output 7
""" |
#Complete the function to return the number of day of the week for k'th day of year.
def day_of_week(k):
return k%7
#Invoke function day_of_week with an interger between 0 and 6 (number for days of week)
print(day_of_week(12))
"""(jueves, viernes, sabado, domingo, lunes, martes, miercoles)"""
""" domingo, lunes, martes, miercoles, jueves, viernes""" |
#Complete the function "digits_sum" so that it prints the sum of a three digit number.
def digits_sum(num):
return int((str(num))[0])+int((str(num))[1])+int((str(num))[2])
#Invoke the function with any three-digit-number
#You can try other three-digit numbers if you want
print(digits_sum(123))
"""
Example input 123
Example output 6
""" |
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 11 13:19:11 2016
@author: tzupan
"""
class callRoom(object):
'''
representation of the call block (called a room)
'''
def __init__(self, bankersInRoom, startTime, dayTime):
'''
initializes a call block; saves all parameters as attributes of the instance
bankersInRoom: a list of bankers in the room for current hour
startTime: the starting hour of the call block (must be an float between 0 and 13)
dayTime: am or pm
inCall: an empty list of the bankers that are currently in a call
'''
self.bankersInRoom = bankersInRoom
assert type(startTime) == int and startTime in range(0,13)
self.startTime = startTime
self.dayTime = dayTime
#self.InCall = []
def getBankersName(self, incomingCall):
'''
'''
ableBankers = [x for x in self.bankersInRoom if x.canReceiveCall(incomingCall)]
return [x.getBankerName() for x in ableBankers]
def getAvailableBankers(self, incomingCall):
'''
returns a list of bankers who are currently ABLE to take calls
'''
return [x for x in self.bankersInRoom if x.canReceiveCall(incomingCall)]
def getBusyBankers(self, incomingCall):
'''
returns a list of bankers who are currently UNABLE to take calls
'''
return [x for x in self.bankersInRoom if x.canReceiveCall(incomingCall) == False] |
#Extracts email addresses from a text file
#pt-1 prints number of email addresses with softwire.com domain
#open the file
#read the contents line by line
#check for the substring '@softwire.com'
import re
with open('sample.txt') as f:
count = 0
contents = f.read()
for i in range(len(contents)):
if (contents[i: i + 13] == '@softwire.com'):
count = count + 1
print(count)
#pt-2 using regex to find all email addresses:
addrs = re.findall('@\S+', contents)
print(len(addrs))
#pt3-using a dictionary
popular_domains = {}
#add emails to the dictionary
for addr in addrs:
popular_domains[addr] = popular_domains.get(addr, 0) + 1
list_popular_domains = (popular_domains.items())
#lambda denotes the start of an Inline function.
decending_popular_domains = sorted(list_popular_domains, reverse=True, key=lambda email_pair: email_pair[1])
print(decending_popular_domains)
|
# CENG 487 Assignment4 by
# Ahmet Semsettin Ozdemirden
# StudentNo: 230201043
# Date: 05-2019
from shapes import Shape
class Scene:
def __init__(self):
self.originalNodes = []
self.nodes = []
def add(self, node):
self.originalNodes.append(node)
self.nodes.append(node)
# helper method for subdivision (subdivision could be implemented more efficiently)
def subdivide(self, subdivisionLevel):
nodes = []
for originalNode in self.originalNodes:
node = Shape(originalNode.name)
# start from level 2 since level 1 subdivision is equal to object itself.
for i in range(subdivisionLevel - 1):
node.subdivide()
nodes.append(node)
self.nodes = nodes
|
class Worker:
name: str
surname: str
position: str
_income: dict
def __init__(self, name, surname, position, income):
self.name = name
self.surname = surname
self.position = position
self._income = income
class Position(Worker):
def get_full_name(self):
print(f"{self.name} {self.surname}")
def get_total_income(self):
print(f"Wage+bonus = {self._income['wage'] + self._income['bonus']}")
Brown = Position("Bobby", "Brown", "Manager", {"wage": 12000, "bonus": 2000})
Brown.get_full_name()
Brown.get_total_income()
Smith = Position("John", "Smith", "Agent", {"wage": 8000, "bonus": 1000.50})
Smith.get_full_name()
Smith.get_total_income() |
digit_list = [1, 1, 1, 45, 5, 5, 67, 123, 123, 9, 15, 1589, 1, 45, 767, 5]
def digit_filter(list_in):
for i in list_in:
if list_in.count(i) == 1:
yield i
final_list = []
for digit in digit_filter(digit_list):
final_list.append(digit)
print(final_list)
|
class Cells:
def __init__(self, cores: int):
self.cores = cores
def __add__(self, other):
return Cells(self.cores + other.cores)
def __sub__(self, other):
if (self.cores - other.cores) > 0:
return Cells(self.cores - other.cores)
else:
return "разница ячеек меньше либо равна нулю"
def __mul__(self, other):
return Cells(self.cores * other.cores)
def __truediv__(self, other):
return Cells(int(self.cores / other.cores))
def __str__(self):
return f'клетка содержит {self.cores} ячеек'
def make_order(self, cores_in_row: int):
num_full_rows, num_in_last_row = divmod(self.cores, cores_in_row)
row = '*' * cores_in_row
result_string = (row + '\n') * num_full_rows + '*' * num_in_last_row
return result_string
cell1 = Cells(25)
cell2 = Cells(5)
print(f'Результат сложения: {cell1 + cell2}')
print(f'Результат вычитания {cell1 - cell2}')
print(f'Результат вычитания: {cell2 - cell1}')
print(f'Результат произведения клеток: {cell1 * cell2}')
print(f'Результат деления клеток: {cell1 / cell2}')
cell3 = Cells(27)
print(cell3.make_order(5)) |
# Part I
param1 = 34
param2 = 48430
param3 = 56.89
param4 = "Hello!"
print(param1)
print(param2)
print(param4)
sum13 = param1 + param2 + param3
print(sum13)
# Part II
address_city = input("Введите город: ")
address_street = input("Введите улицу: ")
address_house_number = input("Введите номер дома: ")
address_house_floors = int(input("Введите количество этажей в доме: "))
print(f"Ваш адрес: город {address_city}, улица {address_street}, дом {address_house_number}")
print(f"Количество этажей в вашем доме: {address_house_floors}")
|
number = input("Введите целое положительное число: ")
i = 0
a = 0
while i != len(number):
b = int(number[i])
if a <= b:
a = b
i += 1
print(f"Самая большая цифра в данном числе: {a} ")
|
import numpy as np
a = np.array( ([1,2,3],
[4,5,6]) )
print('matrix a dengan ukuran', a.shape)
print(a)
#transpose
matriksT = a.transpose()
print("Transpose\n", matriksT)
#menjadikan matriks menjadi vektor
print("jadi vektor\n", a.ravel())
#reshape matrix
print("reshape\n", a.reshape(3,2))
#resize matrix, sama dgn reshape tp nilai a diubah
print("resize\n", a.resize(3,2))
print("matriks a\n", a) |
#Find if string a palindrome
# return True if it's a palindrome and False otherwise
def isPalindrome(string, begin_id, end_id):
if begin_id>=end_id:#
return True
elif string[begin_id]==string[end_id]:
return isPalindrome(string, begin_id+1, end_id-1)
else:
return False
#print isPalindrome('abba', 0, 3)
#having fun with recursion factorial
def Factorial(number):
if number == 0 or number ==1: #base cases
return 1
else:
return Factorial(number-1)*number #recursion call
#next I will write a binary search
def BinarySearch(array, numb, min_index, max_index):
k = (min_index+max_index)/2
if min_index>max_index:
return -1
else:
if numb == array[k]:
return k
elif numb< array[k]:
return BinarySearch(array, numb, min_index, k-1)
else:
return BinarySearch(array, numb, k+1, max_index)
# A=[1,2,3,4,5,6,7,21,33,45,99,100,120,1000]
# print BinarySearch(A, 101, 0, len(A)-1)
def FindPeakOneD(array, min_index, max_index):
k=(min_index+max_index)/2
if k==min_index and array[k]>array[k+1]:
return array[k]
if k==max_index and array[k]>array[k-1]:
return array[k]
elif array[k]>array[k-1] and array[k]>array[k+1]:
return array[k]
elif array[k]<array[k+1]:
return FindPeak(array, k+1, max_index)
elif array[k]<array[k-1]:
return FindPeak(array, min_index, k-1)
# B = [1,4,5,6,20,17,16]
# print FindPeak(B,0, len(B)-1)
def countSplitMerge(array,p,q,r):
left_array = array[p:q+1]
right_array = array[q+1:r+1]
i=0; j=0; k=p
inv_count=0
while i<=q-p and j<=r-q-1:
if left_array[i]<=right_array[j]:
array[k] = left_array[i]
i += 1
else:
array[k] = right_array[j]
j += 1
inv_count += q-p-i+1
k += 1
while i<=q-p:
array[k] = left_array[i]
i += 1
k += 1
while j<=r-q-1:
array[k] = right_array[j]
j += 1
k += 1
return inv_count
def FindInversionSort(array,p,r):
#First establish a base case when an array has one member
if r<=p:
return 0
else:
k = (r+p)/2
left_inv = FindInversionSort(array,p,k)
right_inv = FindInversionSort(array,k+1,r)
split_inv = countSplitMerge(array,p,k,r)
return left_inv+right_inv+split_inv
def pow(a, b):
#base case
if b==0:
return 1
elif b%2==0:
return pow(a, b/2)*pow(a, b/2)
else:
return pow(a, b/2)*pow(a, b/2)*a
#print pow(3,2)
# Infinitely long stream of integers [1,2,3,4,5,6,7,...]
# Read one integer at a time, and compute the running average of the previous n elements(inclusive).
# n is given.
# Write a function to implement this.
# public int readCurrent();
element_queue = []
current_ave = 0#(current_ave*n-element_pop+curr_element)/float(n)
def running_ave(stream, n):
curr = stream.readCurrent()
current_ave = curr/float(n)
if len(element_queue)<n:
element_queue.append(curr)
else:
element_pop=element_queue.pop()
element_queue.append(curr)
current_ave = (current_ave*n-element_pop+curr)/float(n)
return current_ave
# f(w,x) = wTx
# y = sign(wTx)
# Pr_like(feed_data)
# designing the features:
# 1. freq of clicks
# 2. number of word mathch of feed with user's profile or interest
|
# 继承
class Car():
"""模拟汽车"""
def __init__(self, name, model, year):
"""初始化描述汽车属性"""
self.name = name
self.model = model
self.year = year
self.odometer_reading = 0 # 给属性设置默认值 [设置里程数初始值为0]
def get_descriptive_name(self):
"""返回整洁的描述信息"""
long_name = str(self.year) + " " + self.name + " " + self.model
return long_name
def read_odmeter(self):
"""打印公里数"""
print("这辆车已经行驶了: " + str(self.odometer_reading) + "公里了")
def update_odometer(self, mileage):
"""将里程表设置为指定的值"""
if mileage > self.odometer_reading:
self.odometer_reading = mileage
else:
print("请不要造假里程数谢谢~")
def increment_odmeter(self, mileage):
"""将里程数增加指定的量"""
self.odometer_reading += mileage
def fill_gas_tank(self):
"""添加汽油"""
print("添加汽油")
class Battery():
"""模拟电池"""
def __init__(self, battery_size=70): # battery_size 默认值为70
"""初始化电池属性"""
self.battery_size = battery_size
def describe_battery(self):
"""打印描述电瓶容量的信息"""
print("电池容量为: " + str(self.battery_size) + "-kWh")
def get_range(self):
"""打印可行驶公里数"""
if self.battery_size == 70:
range = 240
elif self.battery_size == 85:
range = 290
message = "这个电动车可以跑" + str(range) + "公里"
print(message)
class ElectricCar(Car):
"""电动车的独特之处"""
def __init__(self, name, model, year):
"""初始化父类的属性"""
super().__init__(name, model, year)
# super(ElectricCar, self).__init__(name, model, year) # 也可用
"""初始化弗雷的属性, 再初始化电动车特有的属性"""
# 设置实例用作类的属性
self.battery = Battery()
def describe_battery_by_car(self):
"""打印一条描述电瓶容量的消息"""
self.battery.describe_battery()
# 重写该父类的方法
def fill_gas_tank(self):
"""电动车不需要加油"""
print("电动车...不用加油...")
my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())
my_tesla.describe_battery_by_car()
my_tesla.battery.describe_battery()
my_tesla.fill_gas_tank()
my_tesla.battery.get_range() |
# 文件读取
# 读取整个文件
# 函数 open 接收一个参数: 要打开的文件的名称
# Python 在当前执行的文件所在目录中查找指定的文件
# 关键字 with 在不再需要访问文件后将其关闭.
# 通过 with, Python 可以自己控制关闭文件的时机, 防止自行通过 open() close() 导致程序出错
# 使用 read() 读取文件的全部内容.
# read() 在到达文件末尾时, 返回一个空字符串, 这个字符串显示出来就是一个空行
# 可以使用 .rstrip() 删除多余空行
with open('file_text/pi_digits.txt') as file_object_1:
contents = file_object_1.read()
print(contents.rstrip())
# 注: 在 PyCharm 中, 无论是否使用 .rstrip() 都会出现空行
# 在终端中, 无论是否使用 .rstrig() 都不会出现空行
# 文件路径
# 可以使用相对路径/绝对路径
# OS X / Linux
# [/]
# with open('text_files_path/filename.txt') as file_object:
# Windows
# [\]
# with open('text_files_path\filename.txt') as file_object:
# 逐行读取
with open('file_text/pi_digits.txt') as file_object_2:
for line in file_object_2:
print(line.rstrip()) # 使用.rstrip() 去除每一行后的空行
# 创建一个包含文件各行内容的列表
# [.readlines()] 从文件中读取每一行, 将其存储在一个列表中
with open('file_text/pi_digits.txt') as file_object_3:
lines = file_object_3.readlines()
# 此时可以在 with 代码块外访问 lines
for line in lines:
print(line.rstrip()) # 使用.rstrip() 去除每一行后的空行
|
def make_pizza(size, *toppings):
'''概述要制作的披萨'''
print("做一个尺寸为: " + str(size) + ", 包含: ")
for topping in toppings:
print("- " + topping)
print("的披萨")
def get_price():
print("The price is 20") |
# 存储用户输入的数据
import json
username = input("你叫什么名字?\n")
filename = 'username.json'
with open("json/" + filename, 'w') as f_obj:
json.dump(username, f_obj)
print("我已经将你深深刻在我的心里~")
|
#!/usr/bin/python
import mysql.connector as mariadb
"""mariadb_connection = mariadb.connect(host='localhost', user='root', password='godman')
cursor = mariadb_connection.cursor()
cursor.execute("CREATE DATABASE mylibrary")
mariadb_connection.commit()"""
"""comment out the above code after creating the database"""
mariadb_connection = mariadb.connect(host='localhost', user='root', password='godman', database='mylibrary')
cursor = mariadb_connection.cursor()
cursor.execute("CREATE TABLE books (BookID INT NOT NULL PRIMARY KEY AUTO_INCREMENT, Title VARCHAR(100) NOT NULL,SeriesID INT, AuthorID INT)")
cursor.execute("CREATE TABLE authors (id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, Name VARCHAR(255))")
cursor.execute("CREATE TABLE series (id INT NOT NULL PRIMARY KEY AUTO_INCREMENT)")
sql = "INSERT INTO books (Title,SeriesID,AuthorID) VALUES (%s, %s, %s)"
val = [
('Lord of The Rings', '1', '1'),
('Fellowship of The Rings', '2', '1'),
('The Hobbit', '4', '1'),
('Things Fall Apart', '1', '2')
]
cursor.executemany(sql, val)
mariadb_connection.commit()
|
print("Input a number:")
try:
number = int(input())
except ValueError:
print("This is not a number")
exit(0)
if number < 0:
print("This is not a positive number")
exit(0)
def generate_prime_numbers(num):
prime_numbers = []
for x in range(2, num + 1):
for y in range(2, x):
if x % y == 0:
break
else:
prime_numbers.append(x)
return prime_numbers
if number == 1:
number_count = {1: 1}
else:
number_count = {}
while number != 1:
for x in generate_prime_numbers(number):
if number % x == 0:
if x in number_count.keys():
number_count[x] = number_count[x] + 1
else:
number_count[x] = 1
number = int(number / x)
res = ""
for key in number_count:
if number_count[key] == 1:
res = res + str(key) + " * "
else:
res = res + str(key) + "^" + str(number_count[key]) + " * "
print(res[0:-3])
|
class Device(object):
def __init__(self, unit_name, mac_address, ip_address, login, password):
self._unit_name = unit_name
self._mac_address = mac_address
self._ip_address = ip_address
self._login = login
self._password = password
@property
def unit_name(self):
print('get unit_name')
return self._unit_name
@unit_name.setter
def unit_name(self, value):
print(f'set unit_name - {self._unit_name} -> {value}')
self._unit_name = value
@property
def mac_address(self):
print('get mac_address')
return self._mac_address
@mac_address.setter
def mac_address(self, value):
print(f'set mac_address - {self._mac_address} -> {value}')
self._mac_address = value
@property
def ip_address(self):
print('get ip_address')
return self._ip_address
@ip_address.setter
def ip_address(self, value):
print(f'set ip_address - {self._ip_address} -> {value}')
self._ip_address = value
@property
def login(self):
print('get login')
return self._login
@login.setter
def login(self, value):
print(f'set login - {self._login} -> {value}')
self._login = value
@property
def password(self):
print('get password')
return self._password
@password.setter
def password(self, value):
print(f'set password - {self._password} -> {value}')
self._password = value
d = Device('1234', '000', '111', 'abcd', 'qwerty')
d.ip_address = '192.192.192.192'
print(d.ip_address)
|
#-*- coding:utf-8 -*-
'''
Created on 2019. 4. 8.
@author: there
'''
first = 1
while first <= 9:
second = 1
while second <= 9:
print("%d * %d = %d" % (first, second, first * second))
second += 1
first += 1
|
import csv
import os
#set the path where the file I am reading is located in my directory
file_to_load = os.path.join('../Resources','election_data.csv')
#set the file path where the results file will go
#file_to_output = os.path.join('Analysis','election_analysis.txt')
total_votes = 0
candidate = ""
candidate_votes = {}
candidate_percentages ={}
winner_votes = 0
winner = ""
# open csv file
with open(file_to_load) as voter_data:
reader = csv.reader(voter_data)
next(reader)
# tally votes
for row in reader:
total_votes = total_votes + 1
candidate = row[2]
if candidate in candidate_votes:
candidate_votes[candidate] = candidate_votes[candidate] + 1
else:
candidate_votes[candidate] = 1
# calculate vote percentage and identify winner
for person, vote_count in candidate_votes.items():
candidate_percentages[person] = '{0:.0%}'.format(vote_count / total_votes)
if vote_count > winner_votes:
winner_votes = vote_count
winner = person
dashbreak = "-------------------------"
# print out results
print("Election Results")
print(dashbreak)
print(f"Total Votes: {total_votes}")
print(dashbreak)
for person, vote_count in candidate_votes.items():
print(f"{person}: {candidate_percentages[person]} ({vote_count})")
print(dashbreak)
print(f"Winner: {winner}")
print(dashbreak)
filepath = os.path.join('..''/Resources','election_analysis.txt')
with open(filepath,'w') as text:
text.write(dashbreak + "\n")
text.write(f"Total Votes: {total_votes}" + "\n")
text.write(dashbreak + "\n")
for person, vote_count in candidate_votes.items():
text.write(f"{person}: {candidate_percentages[person]} ({vote_count})" + "\n")
text.write(dashbreak + "\n")
text.write(f"Winner: {winner}" + "\n")
text.write(dashbreak + "\n") |
# -*- coding: utf-8 -*-
# 第二次作业 - 试值法求利率(非线性方程求解)
import math
# 年金计算函数
def f(x):
p = 300
n = 240
A = 12*p*((1+x/12)**n-1)/x-500000
return A
# a为左端点值,b为右端点值,accuracy为给定误差
def FalsePosition(a, b, accuracy):
# 如果f(a)*f(b) > 0,此方法不适用
if f(a)*f(b) > 0 :
print("This method is not suitable ")
return
err = 100000
n = 0
# while循环
while (err > accuracy):
c = b - f(b)*(b-a) / ( f(b)-f(a) )
if f(c) == 0:
break
elif f(a)*f(c) < 0:
b = c
c = b - f(b)*(b-a) / ( f(b)-f(a) )
else:
a = c
c = b - f(b)*(b-a) / ( f(b)-f(a) )
err = abs(f(c))
n = n + 1
return (n, round(c, 11))
# main函数
def main():
left, right, accuracy = map(float, input().split())
result = FalsePosition(left, right, accuracy)
print(result[0])
print(result[1])
if __name__ == '__main__':
main()
|
# -*- coding: utf-8 -*-
# 第一次作业 - 二分法求利率(非线性方程求解)
import math
def f(x):
p=300
n=240
A=12*p*((1+x/12)**n-1)/x-500000
return A
def regula(a, b, accuracy):
delta = 0.5 * 10**(-accuracy)
n = math.floor( (math.log(b-a) - math.log(delta))*1.0 / math.log(2) )
if f(a) * f(b) > 0 :
print("ya,yb are not suitable ")
return
for k in range(1000000):
c = (a + b) / 2
if f(c) == 0:
break
elif f(a)*f(c) < 0:
b = c
c = (a + b) / 2
else:
a = c
c = (a + b) / 2
err = abs(b - a) / 2
if err < delta:
break
# print(k+1)
return (n, round(c, accuracy+1))
def main():
left, right, accuracy = input().split()
left = float(left)
right = float(right)
accuracy = int(accuracy)
result = regula(left, right, accuracy)
print(result[0])
print(result[1])
if __name__ == '__main__':
main()
|
def sumDigit():
global num
global summ
while num > 0:
summ += num % 10
num = int(num / 10)
number=int(input("Enter the number:"))
num=number
summ = 0
sumDigit()
print("The sum of the digits in",number," is",summ)
|
word=input("Enter the word:")
def printRTri():
for i in range(len(word),-1,-1):
print(word[i:len(word)])
printRTri()
|
number=int(input("Please enter the number:"))
factorial=1
for i in range (0, number):
factorial *= (number - i)
print(factorial)
|
myList = ["animal", "dog", "fish", "food", "game"]
print("The full words...")
output = ""
for i in myList:
output += i + " "
print(output)
print("")
print("Just the first letters...")
def First():
for i in myList:
print(i[0])
First()
|
def calcPayment(r, P, n, t):
return P*((1+r/n)**(n*t))/(t*12)
r=float(input("Enter the interest rate:"))
P=float(input("Enter the principal:"))
n=float(input("Enter the number of times the loan is compunded per year:"))
t=float(input("Enter the life of the loan in years:"))
print("The interest of your loan is {:0.2f}".format(calcPayment(r, P, n, t)))
|
#pirate game
from random import randint
pirate_secret = randint(1, 99)
tries = 0
guess = 0
print ("Эй на палубе! Я Ужасный пират Робертс, и у меня есть секрет!")
print ("Это число от 1 до 99. Я дам тебе 6 попыток.")
print ("Твой вариант?")
print (pirate_secret) ############ otladka
while guess != pirate_secret and tries < 6:
key = input()
guess = int(key)
tries = tries+1
if guess < pirate_secret:
print ("Это слишком мало, презренный пес!")
elif guess > pirate_secret:
print ("Это слишком много, сухопутная крыса!")
elif guess == pirate_secret:
print ("Хватит! Ты угадал мой секрет!")
else:
print ("Попытки кончились!")
print ("Это число ", pirate_secret)
print ("Попыток было", tries)
|
# Определить по координатам вершин треугольника является ли он прямоугольным
# Татаринова ИУ7-14Б
from math import sqrt
eps = 1e-7
# Ввод координат вершин
x1, y1 = map (int, input("Введите координаты A: ").split()) # точка А
x2, y2 = map (int, input("Введите координаты B: ").split()) # точка B
x3, y3 = map (int, input("Введите координаты C: ").split()) # точка С
# Рассчет длин сторон
AB = sqrt((x2 - x1)**2 + (y2 - y1)**2)
BC = sqrt((x3 - x2)**2 + (y3 - y2)**2)
CA = sqrt((x3 - x1)**2 + (y3 - y1)**2)
if (abs(AB**2 + BC**2) - CA**2) < eps or abs(BC**2 + CA**2 - AB**2) < eps or abs(CA**2 + AB**2 - BC**2) < eps:
print("Треугольник прямоугольный")
else:
print ("Треугольник непрямоугольный")
|
# Дан список, нужно найти самую длинную последовательность вида:
# Первый элемент равен последнему, второй равен предпоследнему и тд и записать это в новый список
# И еще сформировать список Z, который состоит из элементов изначального списка, которые повторяются более 1 раза
def search(value, array, start=0):
for i in range(start, len(array)):
if array[i] == value:
return i
return -1
def sequenceSearch(array):
startMax = endMax = 0
start = 0
end = len(array) - 1
max = 0
for i in range(len(array)):
start = i
end = search(array[i], array, start+1)
while end != -1:
currentStart = start + 1
currentEnd = end - 1
while array[currentStart] == array[currentEnd]:
if currentEnd <= currentStart:
if (end - start + 1) > max:
startMax = start
endMax = end
max = end - start + 1
break
elif array[currentStart] != array[currentEnd]:
pass
currentStart += 1
currentEnd -= 1
end = search(array[i], array, end + 1)
res =[]
for i in range(startMax, endMax + 1):
res.append(array[i])
return res
def main():
list = [4, 1, 2, 3, 3, 2, 1, 5, 1]
res = sequenceSearch(list)
print(res)
Z = []
for i in range(len(list)):
if search(list[i], list, i+1) != -1 and search(list[i], Z) == -1:
Z.append(list[i])
print(Z)
main() |
eps = float(input("Введите eps: "))
sum = 0
a = 1
n = 1
res = a / n
while abs(res) > eps:
sum += res
n += 2
a *= -1
res = a / n
print ("Сумма ряда =", sum * 4) |
def selectionSort(array):
for i in range(len(array)):
minind = i
for j in range(i, len(array)):
if array[j] < array[minind]:
minind = j
array[i], array[minind] = array[minind], array[i]
return array
def insertionSort(array):
for i in range(1, len(array)):
current = array[i]
j = i - 1
while j >= 0 and current < array[j]:
array[j+1] = array[j]
j -= 1
array[j + 1] = current
return array
def insertionSortWithBarier(array):
array = [0] + array
for i in range(1, len(array)):
array[0] = array[i]
j = i - 1
while array[j] > array[0]:
array[j + 1] = array[j]
j -= 1
array[j + 1] = array[0]
return array[1:]
def insertionSortWithBinSearch(array):
for i in range(1, len(array)):
current = array[i]
start = 0
end = i
while start < end:
mid = (end + start) // 2
if current < array[mid]:
end = mid
else:
start = mid + 1
j = i - 1
while j >= start:
array[j+1] = array[j]
j -= 1
array[start] = current
return array
def shellSort(array):
inc = len(array) // 2
while inc > 0:
for i in range(len(array)):
current = array[i]
while i >= inc and current < array[i - inc]:
array[i] = array[i - inc]
i -= inc
array[i] = current
inc = 1 if inc == 2 else int(inc * 5.0 // 11)
return array
def bubbleSort(array):
for i in range(len(array) - 1):
for j in range(len(array) - 1 - i):
if array[j] > array[j + 1]:
array[j], array[j + 1] = array[j + 1], array[j]
return array
def bubbleSortWithFlag(array):
for i in range(len(array) - 1):
flag = True
for j in range(len(array) - 1 - i):
if array[j] > array[j + 1]:
array[j], array[j + 1] = array[j + 1], array[j]
flag = False
if flag:
break
return array
def shakerSort(array):
n = len(array)
left = 0
right = n - 1
while left < right:
new_right = left
for j in range(left, right):
if array[j] > array[j + 1]:
array[j], array[j + 1] = array[j + 1], array[j]
new_right = j
right = new_right
new_left = right
for j in range(right, left, -1):
if array[j] < array[j - 1]:
array[j], array[j - 1] = array[j - 1], array[j]
new_left = j
left = new_left
return array
from random import randint
def quickSort(array):
if len(array) == 0:
return array
randInd = randint(0, len(array) - 1)
randElement = array[randInd]
left = [x for x in array if x < randElement]
rigth = [x for x in array if x > randElement]
return quickSort(left) + [randElement] + quickSort(rigth)
print(quickSort([4, 1, 6, 3, 5, 2, 0])) |
# Вводится строка состоящая из скобок(),[],{},нужно найти отрезок максимальной длины , где скобки расставлены правильно
# (([}[) - такого отрезка нет
# ([}{}]([])[((] - ([]), длина 4,начало-7,конец-10
str = '([{(}}]'
array = []
lengthMax = 0
startMax = 0
for j in range(len(str)):
start = j
length = 0
for i in range(j, len(str)):
if str[i] == '(' or str[i] == '[' or str[i] == '{':
array.insert(0, str[i])
length += 1
elif str[i] == ')':
if len(array)>0 and array[0] == '(':
array.remove('(')
length += 1
else:
array.clear()
length = 0
break
elif str[i] == ']':
if len(array)>0 and array[0] == '[':
array.remove('[')
length += 1
else:
array.clear()
length = 0
break
elif str[i] == '}':
if len(array)>0 and array[0] == '{':
array.remove('{')
length += 1
else:
array.clear()
length = 0
break
if len(array) == 0:
if length > lengthMax:
lengthMax = length
startMax = start
if lengthMax == 0:
print("Такого отрезка нет")
else:
print(str[startMax:(startMax+lengthMax)])
|
__author__ = 'peter'
###################################################
print("basics")
a = 10
b = 202
c = a + b
d, e, f = 2, 3, 4
name = 'Peter'
print(c)
print(name, len(name))
print(d,e,f)
g = None
print(g)
###################################################
print("collections")
dict = {'name': 'peter', 'id': 10, 'dept': 'it'}
print(dict.keys())
print(dict.values())
tuple = ('rahul', 100, 60.4, 'deepak')
print(tuple)
list1 = ['aman', 678, 20.4, 'saurav',202]
print(list1)
print(list1[1:4])
print(list1 * 3)
###################################################
print("operators")
if(a in list1):
print("a is in list")
else:
print("a is NOT in list")
if(b in list1):
print("b is in list")
else:
print("b is NOT in list")
if(a is b):
print("they are the same")
else:
print("they are different")
###################################################
print("loops, ranges")
#t3 = (1,2,3,4,5,6)
list2 = []
for i in range(2,10):
j = a * i
#print(j)
list2.append(j)
print("list2:\n", list2)
for j in range (1,6):
for k in range (5,j-1,-1):
print("*"),
print
a=10
while a>0:
print ("Value of a is",a)
#a=a-2
a -= 2
###################################################
print("typecasting")
a=10
b="10"
c="20"
print(int(b) + a)
print(b+c)
###################################################
print("basic ops:")
print (3 + 4)
print (3 - 4)
print (3 * 4)
print (3 / 4)
print (3 % 2)
print (3 ** 4) # 3 to the fourth power
print (3 // 4) #floor division
|
def is_bouncy(n):
'''In the changes list, "False" indicates a decrease and "True" indicates
an increase thus in order the number to be either increasing or decreasing
the "changes" should consist of same values at the end of the operations'''
changes = []; num_str = str(n)
for i in range(1, len(num_str)):
current_num, preceding_num = int(num_str[i]), int(num_str[i - 1])
if preceding_num == current_num:
pass
else:
changes.append(preceding_num > current_num)
if False in changes and True in changes:
return True
return False
if __name__ == '__main__':
number, bouncy_count = 0, 0
while True:
number += 1
if is_bouncy(number):
bouncy_count += 1
if bouncy_count / number == 99 / 100:
print(number)
break
|
from math import pow
def square_of_sum(n): return pow((n * n + n) / 2, 2)
def sum_of_squares(n): return (n * (n + 1) * (2 * n + 1)) / 6
print(square_of_sum(100) - sum_of_squares(100))
|
import sqlite3
# Query the DB and return all records:
# ------------------------------------
def show_all():
conn = sqlite3.connect("customer.db")
c = conn.cursor()
c.execute("SELECT rowid, * FROM customers")
items = c.fetchall()
for item in items:
print(item)
conn.commit()
conn.close()
# Lookup with WHERE:
# ------------------------------------
def lookup_single_field(field, value):
conn = sqlite3.connect("customer.db")
c = conn.cursor()
#cmd = "SELECT rowid, * FROM customers WHERE " + field + " = " + value
#print(cmd)
c.execute("SELECT rowid, * FROM customers WHERE " + field + " = " + value)
items = c.fetchall()
for item in items:
print(item)
conn.commit()
conn.close()
# Add a new record to the table:
# ------------------------------
def add_one(first_name, last_name, email):
conn = sqlite3.connect("customer.db")
c = conn.cursor()
c.execute("INSERT INTO customers VALUES (?, ?, ?)", (first_name, last_name, email))
conn.commit()
conn.close()
# Add many records to the table:
# ------------------------------
def add_many(list):
conn = sqlite3.connect("customer.db")
c = conn.cursor()
c.executemany("INSERT INTO customers VALUES (?, ?, ?)", (list))
conn.commit()
conn.close()
# Delete a record from the table
# by using rowid as a string:
# ------------------------------
def delete_one(id):
conn = sqlite3.connect("customer.db")
c = conn.cursor()
c.execute("DELETE FROM customers WHERE rowid = (?)", (id))
conn.commit()
conn.close()
|
import sqlite3
# Connect to database:
conn = sqlite3.connect("customer.db")
# Create a cursor
c = conn.cursor()
# Insert data
c.execute("""INSERT INTO customers VALUES (
'John',
'Elder',
'john@codemy.com'
)""")
# Or write the command in 1 line:
# c.execute("INSERT INTO customers VALUES ('John', 'Elder', 'john@codemy.com')")
print("Command executed succesfully!")
# Commit our command
conn.commit()
# Close our connection
conn.close() |
#!/usr/bin/env python
# Octagonal Hull module
import unittest
import copy
from dot import Dot
# Hull class
#
# Defines a hull that is an intersection of half-planes with specified set of normal vectors
#
# The center of the cross is (0,0)
# The grid is on integral points with odd coordinates
class Hull:
# initialize with the Morpion cross
def __init__(self):
self.put(Dot(3,9))
self.put(Dot(9,3))
self.put(Dot(9,-3))
self.put(Dot(3,-9))
self.put(Dot(-3,-9))
self.put(Dot(-9,-3))
self.put(Dot(-9,3))
self.put(Dot(-3,9))
self.fill_directions =\
[ Dot(0, 2), # N
Dot(2, 2), # NE
Dot(2, 0), # E
Dot(2, -2), # SE
Dot(0, -2), # S
Dot(-2, -2), # SW
Dot(-2, 0), # W
Dot(-2, 2) ] # NW
def initFromId(self, id):
self.sides = map(int,id.split('_')[1:])
self.dirty=True
# todo: find a reference point inside
# return unique id of the polygon
def id(self):
return "hull_" + "_".join(map(str, self.sides))
# add point and possibly enlarge the hull
def put(self, dot):
self.dirty = True
self.ref = dot
for i, s in enumerate(self.sides):
self.sides[i] = max(s, dot * self.directions[i])
# determine whether dot is inside of the hull
def inside(self, dot):
for i, s in enumerate(self.sides):
if self.sides[i] < dot * self.directions[i]:
return False
return True
# flood fill the hull and find points on the boundary
def fill(self, dot):
if dot in self.interior_set:
return
if self.inside(dot):
self.interior_set.add(dot)
if dot.x < self._lx:
self._lx = dot.x
if dot.x > self._hx:
self._hx = dot.x
if dot.y < self._ly:
self._ly = dot.y
if dot.y > self._hy:
self._hy = dot.y
for d in self.fill_directions:
self.fill(dot + d)
else:
self.boundary_set.add(dot)
def compute(self):
if not self.dirty:
return
self.boundary_set = set()
self.interior_set = set()
# todo: check properly if self.ref is set
if not self.ref is None:
self._lx = self.ref.x
self._hx = self.ref.x
self._ly = self.ref.y
self._hy = self.ref.y
self.fill(self.ref)
self.dirty = False
def boundary(self):
self.compute()
return self.boundary_set
def interior(self):
self.compute()
return self.interior_set
def lx(self):
self.compute()
return self._lx
def ly(self):
self.compute()
return self._ly
def hx(self):
self.compute()
return self._hx
def hy(self):
self.compute()
return self._hy
def pr(self):
self.compute()
cross = [ Dot(3,9), Dot(9,3), Dot(9, -3), Dot(3, -9),
Dot(-3,-9), Dot(-9,-3), Dot(-9,3), Dot(-3,9) ]
bd = '';
for y in range(self.ly(), self.hy()+1,2):
for x in range(self.lx(), self.hx()+1,2):
if Dot(x,y) in cross:
bd = bd + '#'
elif Dot(x,y) in self.interior():
bd = bd + '*'
else:
bd = bd + '-'
bd = bd + '\n'
return bd
def edge(self, dir):
self.compute()
norm = -1000000
for d in self.interior_set:
n = d.x * dir.x + d.y * dir.y
if n > norm:
norm = n
len = 0
for d in self.interior_set:
if d.x * dir.x + d.y * dir.y == norm:
len = len + 1
return len - 1
def width(self):
self.compute()
return 1 + (self.hx() - self.lx()) / 2
def height(self):
self.compute()
return 1 + (self.hy() - self.ly()) / 2
def symmetryClass(self):
return self.id()
# return distances of half-plane boundaries
def halfplanes(self):
return " ".join(map(str, self.sides))
@staticmethod
def createFromId(id):
if id.startswith("rect"):
h = Rectangle()
else:
h = Octagon()
h.initFromId(id)
return h
class Rectangle(Hull):
def __init__(self):
self.sides = [ 0, 0, 0, 0 ]
self.directions =\
[ Dot(0, 2), # N
Dot(2, 0), # E
Dot(0, -2), # S
Dot(-2, 0) ] # W
self.dirty = True
Hull.__init__(self)
def symmetryClass(self):
cl = copy.copy(self.sides)
if self.width() < self.height():
x = cl.pop(0)
cl.append(x)
if cl[0] < cl[2]:
cl[0], cl[2] = cl[2], cl[0]
if cl[1] < cl[3]:
cl[1], cl[3] = cl[3], cl[1]
return "rect_" + "_".join(map(str, cl))
# return distances of half-plane boundaries, with corners
def halfplanes(self):
return " 0 ".join(map(str, self.sides)) + " 0"
class Octagon(Hull):
def __init__(self):
self.sides = [ 0, 0, 0, 0, 0, 0, 0, 0 ]
self.directions =\
[ Dot(0, 2), # N
Dot(2, 2), # NE
Dot(2, 0), # E
Dot(2, -2), # SE
Dot(0, -2), # S
Dot(-2, -2), # SW
Dot(-2, 0), # W
Dot(-2, 2) ] # NW
self.dirty = True
Hull.__init__(self)
def symmetryClass(self):
cl = copy.copy(self.sides)
if self.width() < self.height():
x = cl.pop(0)
cl.append(x)
x = cl.pop(0)
cl.append(x)
if cl[0] < cl[4] or (cl[0] == cl[4] and cl[1] < cl[3]):
cl[0], cl[4] = cl[4], cl[0]
cl[1], cl[3] = cl[3], cl[1]
cl[7], cl[5] = cl[5], cl[7]
if cl[2] < cl[6] or (cl[2] == cl[6] and cl[6] < cl[1]):
cl[2], cl[6] = cl[6], cl[2]
cl[1], cl[7] = cl[7], cl[1]
cl[3], cl[5] = cl[5], cl[3]
return "oct_" + "_".join(map(str, cl))
#
# Unit tests for the Hull class
#
class HullTests(unittest.TestCase):
def testBlank(self):
self.failUnless(True)
def main():
unittest.main()
if __name__ == '__main__':
main()
|
"""
Solving the Laplace equation using a perceptron of 1 hidden layer.
\frac{d^2y}{dx_1^2} + \frac{d^2y}{dx_2^2} = 0
Subject to y(0,x_2) = y(1,x_2) = y(x_1,0) = 0, y(x_1,1) = \sin(\pi x_1)
The analytical solution is y_a = \frac{1}{e^\pi - e^{-\pi}}\sin(\pi x_1)(e^{\pi x_2} - e^{-\pi x_2})
The trial solution is y_t = x_2 \sin(\pi x_1) + x_1(1 - x_1)x_2(1 - x_2)N, where N = N(x, params) is a MLP, and x = [x_1, x_2]^T.
"""
import autograd.numpy as np
import autograd
from autograd.misc.optimizers import adam
import random
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
def sigmoid( z ):
"""
Sigmoid function.
:param z: Input vector of values.
:return: Element-wise sigmoid function of input vector z.
"""
return 1.0 / ( 1.0 + np.exp( -z ) )
def sigmoidPrime( z ):
"""
Derivative of sigmoid function.
:param z: Input vector of values.
:return: Element-wise sigmoid'(z).
"""
return sigmoid( z ) * ( 1.0 - sigmoid( z ) )
def sigmoidPrimePrime( z ):
"""
Second derivative of sigmoid function.
:param z: Input vector of values.
:return: Element-wise sigmoid''(z).
"""
return sigmoid( z ) * ( 1.0 - sigmoid( z ) ) * ( 1.0 - 2.0 * sigmoid( z ) )
def nnet( x, params ):
"""
Compute output from neural network.
:param x: Input vector with two coordinates: (x_1, x_2).
:param params: List [(W,b),(V,)], where W is an Hx2 matrix (w_ij = weight from x_j input to neuron i), b is an H-element bias vector, and V is an H-element weight vector.
:return: Scalar evaluation of neural network.
"""
W = params[0][0] # Weights towards hidden layer.
b = params[0][1] # Biases for hidden layer units.
V = params[1][0] # Weights towards output layer.
z = np.dot( W, x ) + b
sigma = sigmoid( z ) # Become inputs for output layer neuron.
return np.dot( V, sigma ) # Output neuron is linear.
def dkNnet_dxjk( x, params, j, k ):
"""
Compute the kth partial derivate of the nnet with respect to the jth input value.
:param x: Input vector with two coordinates: (x_1, x_2).
:param params: Network parameters (cfr. nnet(.)).
:param j: Input coordinate with respect to which we need the partial derivative (0: x_1, 1: x_2).
:param k: Partial derivative order (1 or 2 supported).
:return: \frac{d^kN}{dx_j^k} evaluated at x = (x_1, x_2).
"""
W = params[0][0]
b = params[0][1]
V = params[1][0]
z = np.dot( W, x ) + b
if k == 1:
sigmaPrime = sigmoidPrime( z )
else:
sigmaPrime = sigmoidPrimePrime( z )
return np.dot( V * (W[:,j] ** k), sigmaPrime )
def phi_a( x ):
"""
Analytical solution.
:param x: Input value vector (x_1, x_2).
:return: \frac{1}{e^\pi - e^{-\pi}}\sin(\pi x_1)(e^{\pi x_2} - e^{-\pi x_2})
"""
return 1.0 / ( np.exp( np.pi ) - np.exp( -np.pi ) ) \
* np.sin( np.pi * x[0] ) \
* ( np.exp( np.pi * x[1] ) - np.exp( -np.pi * x[1] ) )
def d2Phi_a_dx12( x ):
"""
Second partial derivative of the analytical function with respect to x_1 evaluated at x = (x_1, x_2).
:param x: Input value vector (x_1, x_2).
:return: \frac{d^2\phi_a}{dx_1^2} evaluated at x = (x_1, x_2).
"""
return -( np.pi ** 2 ) / ( np.exp( np.pi ) - np.exp( -np.pi ) ) * np.sin( np.pi * x[0] ) * ( np.exp( np.pi * x[1] ) - np.exp( -np.pi * x[1] ) )
def d2Phi_a_dx22( x ):
"""
Second partial derivative of the analytica function with respect to x_2 evaluated at x = (x_1, x_2).
:param x: Input value vector (x_1, x_2).
:return: \frac{d^2\phi_a}{dx_2^2} evaluated at x = (x_1, x_2).
"""
return ( np.pi ** 2 ) / ( np.exp( np.pi ) - np.exp( -np.pi ) ) * np.sin( np.pi * x[0] ) * ( np.exp( np.pi * x[1] ) - np.exp( -np.pi * x[1] ) )
def phi_t( x, params ):
"""
Trial function.
:param x: Input value vector (x_1, x_2).
:param params: Neural network params (cfr. nnet(.)).
:return: Approximation to ODE solution.
"""
return x[1] * np.sin( np.pi * x[0] ) + x[0] * ( 1.0 - x[0] ) * x[1] * ( 1.0 - x[1] ) * nnet( x, params )
def d2Phi_t_dx12( x, params ):
"""
Second partial derivative of the trial function with respect to x_1 evaluated at x = (x_1, x_2).
:param x: Input value vector (x_1, x_2).
:param params: Neural network params (cfr. nnet(.)).
:return: \frac{d^2\phi_t}{dx_1^2} evaluated at x = (x_1, x_2).
"""
return -( np.pi ** 2 ) * x[1] * np.sin( np.pi * x[0] ) + x[1] * ( 1.0 - x[1] ) \
* ( x[0] * ( 1.0 - x[0] ) * dkNnet_dxjk( x, params, 0, 2 ) + 2.0 * ( 1.0 - 2.0 * x[0] ) * dkNnet_dxjk( x, params, 0, 1 ) - 2.0 * nnet( x, params ) )
def d2Phi_t_dx22( x, params ):
"""
Second partial derivative of the trial function with respect to x_2 evaluated at x = (x_1, x_2).
:param x: Input value vector (x_1, x_2).
:param params: Neural network params (cfr. nnet(.)).
:return: \frac{d^2\phi_t}{dx_2^2} evaluated at x = (x_1, x_2).
"""
return x[0] * ( 1.0 - x[0] ) \
* ( x[1] * ( 1.0 - x[1] ) * dkNnet_dxjk( x, params, 1, 2 ) + 2.0 * ( 1.0 - 2.0 * x[1] ) * dkNnet_dxjk( x, params, 1, 1 ) - 2.0 * nnet( x, params ) )
def error( inputs, params ):
"""
Compute the average of the squared error.
:param inputs: List of input vector values.
:param params: Neural network parameters.
:return: Avg squared error.
"""
totalError = 0
for x in inputs:
totalError += ( d2Phi_t_dx12( x, params ) + d2Phi_t_dx22( x, params ) ) ** 2
return totalError / float( len( points ) )
def plotSurface( XX, YY, ZZ, title, zLabel=r"$\phi$" ):
"""
Plot a 3D surface.
:param XX: Grid of x coordinates.
:param YY: Grid of y coordinates.
:param ZZ: Grid of z values.
:param title: Figure title.
:param zLabel: Label for z-axis.
"""
fig1 = plt.figure()
ax = fig1.gca( projection='3d' )
surf = ax.plot_surface( XX, YY, ZZ, cmap=cm.jet, linewidth=0, antialiased=False, rstride=1, cstride=1 )
fig1.colorbar( surf, shrink=0.5, aspect=5 )
ax.set_xlabel( r"$x_1$" )
ax.set_ylabel( r"$x_2$" )
ax.set_zlabel( zLabel )
plt.title( title )
plt.show()
def plotHeatmap( Z, title ):
"""
Plot a heatmap of a rectangular matrix.
:param Z: An m-by-n matrix to plot.
:param title: Figure title.
:return:
"""
fig1 = plt.figure()
im = plt.imshow( Z, cmap=cm.jet, extent=(0, 1, 0, 1), interpolation='bilinear' )
fig1.colorbar( im )
plt.title( title )
plt.xlabel( r"$x_1$" )
plt.ylabel( r"$x_2$" )
plt.show()
if __name__ == '__main__':
np.random.seed( 31 )
random.seed( 11 )
N = 7 # Number of training samples per dimension.
MinVal = 0
MaxVal = 1
points = []
for ii in range( N + 1 ):
for jj in range( N + 1 ):
points.append( np.array( [ii/N, jj/N] ) ) # Training dataset.
random.shuffle( points )
# Training parameters.
H = 7 # Number of neurons in hidden layer.
batch_size = 4
num_epochs = 50
num_batches = int( np.ceil( len( points ) / batch_size ) )
step_size = 0.055
def initParams():
return [(np.random.uniform( -1, +1, (H, 2) ), np.random.uniform( -1, +1, H )), (np.random.uniform( -1, +1, H ),)]
def batchIndices( i ):
idx = i % num_batches
return slice( idx * batch_size, (idx + 1) * batch_size )
# Define training objective
def objective( params, i ):
idx = batchIndices( i )
return error( points[idx], params )
# Get gradient of objective using autograd.
objective_grad = autograd.grad( objective )
print( " Epoch | Train accuracy " )
def printPerf( params, i, _ ):
if i % num_batches == 0:
train_acc = error( points, params )
print( "{:15}|{:20}".format( i // num_batches, train_acc ) )
# The optimizers provided can optimize lists, tuples, or dicts of parameters.
optimizedParams = adam( objective_grad, initParams(), step_size=step_size,
num_iters=num_epochs * num_batches, callback=printPerf )
printPerf( optimizedParams, 0, None )
# Get maximum error.
maxError = 0
for xp in points:
y_a = phi_a( xp )
y_t = phi_t( xp, optimizedParams )
error = np.abs( y_a - y_t )
if error > maxError:
maxError = error
print( "Max error:", maxError )
# Plot solutions.
# Make data.
X = np.linspace( MinVal, MaxVal, 100 )
Y = np.linspace( MinVal, MaxVal, 100 )
X, Y = np.meshgrid( X, Y )
Z_a = np.zeros( X.shape ) # Analytic solution.
Z_t = np.zeros( X.shape ) # Trial solution with neural network.
Z_e = np.zeros( X.shape ) # Error surface.
d2Z_a_x12 = np.zeros( X.shape ) # Second derivatives of analytic solution.
d2Z_a_x22 = np.zeros( X.shape )
d2Z_t_x12 = np.zeros( X.shape ) # Second derivatives of trial solution.
d2Z_t_x22 = np.zeros( X.shape )
d2Z_e_x12 = np.zeros( X.shape ) # Error surface for second derivatives with respect to x_1.
d2Z_e_x22 = np.zeros( X.shape ) # Error surface for second derivatives with respect to x_2.
for ii in range( X.shape[0] ):
for jj in range( X.shape[1] ):
v = np.array( [X[ii][jj], Y[ii][jj]] ) # Input values.
Z_a[ii][jj] = phi_a( v ) # Evalutating solutions.
Z_t[ii][jj] = phi_t( v, optimizedParams )
Z_e[ii][jj] = np.abs( Z_a[ii][jj] - Z_t[ii][jj] )
d2Z_a_x12[ii][jj] = d2Phi_a_dx12( v ) # Evaluating derivatives.
d2Z_a_x22[ii][jj] = d2Phi_a_dx22( v )
d2Z_t_x12[ii][jj] = d2Phi_t_dx12( v, optimizedParams )
d2Z_t_x22[ii][jj] = d2Phi_t_dx22( v, optimizedParams )
d2Z_e_x12[ii][jj] = np.abs( d2Z_a_x12[ii][jj] - d2Z_t_x12[ii][jj] )
d2Z_e_x22[ii][jj] = np.abs( d2Z_a_x22[ii][jj] - d2Z_t_x22[ii][jj] )
# Plotting solutions.
plotSurface( X, Y, Z_a, r"Analytic solution $\phi_a(\mathbf{x})$" )
plotSurface( X, Y, Z_t, r"Trial solution $\phi_t(\mathbf{x}, \mathbf{p})$" )
# Plotting the error heatmap.
plotHeatmap( Z_e, r"Error heatmap for $|\phi_a(\mathbf{x}) - \phi_t(\mathbf{x})|$" )
# Plotting second derivatives.
plotSurface( X, Y, d2Z_a_x12, r"Second derivative of analytical solution with respect to $x_1$", r"$\phi''_a$" )
plotSurface( X, Y, d2Z_a_x22, r"Second derivative of analytical solution with respect to $x_2$", r"$\phi''_a$" )
plotSurface( X, Y, d2Z_t_x12, r"Second derivative of trial solution with respect to $x_1$", r"$\phi''_t$" )
plotSurface( X, Y, d2Z_t_x22, r"Second derivative of trial solution with respect to $x_2$", r"$\phi''_t$" )
# Plotting the error heatmap for second derivatives.
plotHeatmap( d2Z_e_x12, r"Error heatmap for second derivatives with respect to $x_1$" )
plotHeatmap( d2Z_e_x22, r"Error heatmap for second derivatives with respect to $x_2$" ) |
EntNumA = int(input("Enter a Number: "))
EntNumB = int(input("Enter another Number: "))
Sum = EntNumA + EntNumB
Subtract = EntNumA - EntNumB
Multiple = EntNumA * EntNumB
Division = EntNumA / EntNumB
print("The Sum of A and B is: ", Sum)
print("The Subtraction of A and B is: ", Subtract)
print("The Multiple of A and B is: ", Multiple)
print("The Division of A and B is: ", Division) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.