blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
080f20f81e01b51c18369cf95af339d985d16cb5 | vivekanand-mathapati/coding-for-interviews | /python/binarytree.py | 780 | 3.78125 | 4 | class Node:
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
root = Node()
def insert_node(data):
root = insert(root, data)
def insert(root, data):
if root is None:
root = Node(data)
return root
if data < root.data:
root.left = insert(root.left, data)
else:
root.right = insert(root.right, data)
return root
def display():
in_order(root)
def in_order(root):
if root is None:
in_order(root.left)
print(root.data)
in_order(root.right)
# obj = BinarySearchTree()
# obj.insert_node(10)
# obj.insert_node(5)
# obj.insert_node(20)
# obj.display()
insert_node(10)
insert_node(5)
insert_node(20)
display() |
b76f0012e2010c0d9899879dfff0b013071c36fb | rpereira91/interview-questions | /Mock Interviews/mock_1.py | 2,200 | 3.625 | 4 | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def productExceptSelf(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
length = len(nums)
L, R, answer = [0]*length, [0]*length, [0]*length
L[0] = 1
R[length - 1] = 1
for i in range(1,length):
L[i] = nums[i-1] * L[i-1]
for i in reversed(range(length - 1)):
R[i] = nums[i + 1] * R[i + 1]
for i in range(length):
answer[i] = L[i] * R[i]
return answer
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
sum_1 = 0
sum_2 = 0
carry = 0
temp = l1.val + l2.val
if temp >= 10:
carry = 1
temp -= 10
ans = [temp]
while l1.next or l2.next:
if l1.next:
l1 = l1.next
else:
l1 = ListNode(0)
if l2.next:
l2 = l2.next
else:
l2 = ListNode(0)
temp = l1.val + l2.val + carry
if temp >= 10:
carry = 1
temp -= 10
else:
carry = 0
ans.append(temp)
dummy = node_ans = ListNode(ans[0])
for a in range(1,len(ans)):
node_ans.next = ListNode(ans[a])
node_ans = node_ans.next
if carry:
node_ans.next = ListNode(carry)
node_ans = node_ans.next
return dummy
def isValidBST(self, root):
INT_MAX = 4294967296
INT_MIN = -4294967296
def check_bst(root,mini,maxi):
if not root:
return True
if root.val < mini or root.val > maxi:
return False
return (check_bst(root.left,mini,root.val-1)
and check_bst(root.right,root.val+1,maxi))
return check_bst(root,INT_MIN,INT_MAX)
print(Solution().productExceptSelf([1,2,3,4])) |
84176f794536d7e4e80222954d1ca16ef031683a | Aasthaengg/IBMdataset | /Python_codes/p02255/s169369447.py | 242 | 3.734375 | 4 | def insertionSort(a):
for i,v in enumerate(a):
j=i-1
while j>=0 and a[j]>v:
a[j+1]=a[j]
j-=1
a[j+1]=v
print(*a)
n = int(input())
a = list(map(int,input().split()))
insertionSort(a) |
7eed6f9370819084e9bf0f4893ada67d7c5daf9b | lawrel/unilabs | /lab4.py | 800 | 3.671875 | 4 | import sys
import random
def Rselect(x,k):
if k == 0: return "Invalid K"
def select(array,s,e,k):
if e==s: return array[s]
else:
pivot = random.randint(s,e)
array[s],array[pivot] = array[pivot],array[s]
index = s
for j in range(s+1,e+1):
if array[j] < array[s]:
index += 1
array[index], array[j] = array[j], array[index]
array[s],array[index] = array[index],array[s]
if index == k:
return array[index]
elif index > k:
return select(array,s,index-1,k)
else:
return select(array,index+1,e,k)
return select(x,0,len(x)-1,k-1)
n = int(sys.argv[1])
k = int(sys.argv[2])
x = []
for i in range(0,n):
x.append(random.randint(0,n-1))
print("Selected:",Rselect(x,k))
print("Array:",x)
x.sort()
print("Sorted Array:",x) |
917d904f2729c0650410048416d3180d0d67f03e | elvarlax/python-masterclass | /Section 03/03 - Printing tabs/coding_exercise3.py | 272 | 4.1875 | 4 | """
Coding Exercise 3 - Printing tabs
Write a program that will produce the following output.
All the text should appear in your program's output.
Number 1 The Larch
Number 2 The Horse Chestnut
"""
print("Number 1\tThe Larch")
print("Number 2\tThe Horse Chestnut")
|
0b8384bb89b5cf922391c8b81e0b707fc7c82fa4 | Linkin-1995/test_code1 | /day09/exercise05(sep指定分隔符).py | 376 | 3.953125 | 4 | # 练习:体会print函数参数
# 星号元组形参 , 命名关键字形参
# 实参数量无限 , 关键字实参
# def print(*values, sep = " ", end="\n")
print()
print("你好")
# 还可以打印多个数据
print(1, 2, 3) # 1 2 3
# 还可以指定分隔符
print(1, 2, 3, sep="-") # 1-2-3
print(1, 2, 3, sep="-", end=" ") # 1-2-3
# print(1, 2, 3,"-"," ")# 1-2-3 |
f0ed459cd85b81958c22b169b090713a5ba53164 | henryvu25/630-Final | /630FinalProjectCode.py | 10,491 | 4.40625 | 4 | """
These classes are for a POS at a grocery store. The Food class is the base class
and Produce, Alcohol, and Frozen are subclasses. Each inherit name and unitPrice from
the base class. Depending on the situation, each subclass has its own specific
methods for the POS to deal with.
The 3 design patterns used here are: Factory, Facade, and Prototype.
The FoodFactory class easily instantiates an object from a subclass that inherits from the Food class.
FoodFacade creates a menu interface to easily input an item code to instantiate the object.
Prototype is used in the Receipt class to make copies of receipts and even gift receipts
The driver (main) method will walk you through inputting your groceries into the system.
It will allow you to weigh produce, verify ID for alcohol, and change the quantity of
frozen items. You can then choose to pay and you will have options to pay by cash or card.
After payment, a receipt will be printed out for you.
"""
from abc import ABCMeta, abstractmethod #imports abstract base class and abstract methods for that class
import datetime
import random
import copy
class Food(metaclass=ABCMeta):
def __init__(self, name, unitPrice):
self.name = name
self.unitPrice = unitPrice
@abstractmethod
def getTax(self): #cannot be called/instatiated from the base class
pass
def discount(self, percentOff):
decimal = percentOff / 100
self.unitPrice *= (1 - decimal)
def __str__(self):
return "{}\nUnit Price: ${:.2f}\n".format(self.name, self.unitPrice)
class Produce(Food):
def __init__(self, name, unitPrice, weight, isOrganic = False):
super().__init__(name, unitPrice)
self.weight = weight #in pounds
self.isOrganic = isOrganic #can be used for statistical analysis and business decisions
self.taxAmt = self.getTax()
self.totalPrice = unitPrice * self.weight * (1+ self.taxAmt)
def getTax(self): #each subclass has it's own tax rate
taxAmt = 0.0
return taxAmt
def getWeight(self):
return self.weight
def setWeight(self, w): #produce is usually weighed at the register and can be adjusted if you add more items
self.weight = w
return self.weight
def __str__(self):
return "\n{}\nUnit Price: ${:.2f}\nWeight: {:.2f} lbs.\nTotal Price: ${:.2f}\n".format(self.name, self.unitPrice, self.weight, self.totalPrice)
class Alcohol(Food):
def __init__(self, name, unitPrice, abv, ofAge = False):
super().__init__(name, unitPrice)
self.abv = abv #percent alcohol by volume
self.ofAge = ofAge #Of age to purchase set to False until ID is verified
self.taxAmt = self.getTax()
self.totalPrice = unitPrice * (1 + self.taxAmt)
def getTax(self): #beer, wine, and spirits have different tax amounts
if self.abv <= 10:
taxAmt = 0.05 #these percentages are just examples (amounts vary state to state)
elif self.abv > 10 and self.abv <= 20:
taxAmt = 0.1
else:
taxAmt = 0.2
return taxAmt
def verifyId(self, year, month, date):
birthday = datetime.datetime(year, month, date)
today = datetime.datetime.today()
dateStr = str((today - birthday)/365.25) #divides the days into years and converts the long datetime object to a string
age = int(dateStr[:2]) #converts the first two characters of that string to an int
if age >= 21:
self.ofAge = True
else:
print("Not of age. Purchase prohibited.\n")
self.name = "DO NOT SELL"
self.totalPrice = 0.00
def __str__(self):
return "\n{}\nUnit Price: ${:.2f}\nABV: {:.1f}%\nAlcohol Tax: {}%\nTotal Price: ${:.2f}\n".format(self.name, self.unitPrice, self.abv, self.taxAmt*100, self.totalPrice)
class Frozen(Food):
def __init__(self, name, unitPrice, year, month, date, quantity = 1):
super().__init__(name, unitPrice)
self.expiration = datetime.datetime(year, month, date)
self.quantity = quantity
self.taxAmt = self.getTax()
self.totalPrice = unitPrice * float(self.quantity) * (1 + self.taxAmt)
def getTax(self):
taxAmt = 0.0
return taxAmt
def getQuantity(self):
return self.quantity
def setQuantity(self, q): #can have option to change quantity instead of scanning the same item multiple times
self.quantity = q
def expired(self):
today = datetime.datetime.today()
if today > self.expiration:
print("Item has expired, please replace.")
return True
else:
return False
def __str__(self):
return "\n{}\nUnit Price: ${:.2f}\nQuantity: {}\nTotal Price: ${:.2f}\n".format(self.name, self.unitPrice, self.quantity, self.totalPrice)
class FoodFactory(object): #does not need to be instantiated, used for its class method
@classmethod
def create(cls, name, *args): #takes in class name and and arguments needed for that class
name = name.lower().strip() #since classes are usually capitalized, this simplifies it
#Factory pushes out objects easily depending on the parameters it receives
if name == "produce":
return Produce(*args)
elif name == "alcohol":
return Alcohol(*args)
elif name == "frozen":
return Frozen(*args)
class FoodFacade:
def __init__(self, code = None): #takes an input to find the needed item to instatiate. Can add more items.
self.code = input("[1]Apple \n[2]Potato \n[3]Cilantro \n[4]Beer \n[5]Wine \n[6]Whiskey \n[7]Ice Cream \n[8]TV Dinner \n[9]Pizza Rolls \n[0]Pay \nInput number of your choice: ")
def getItem(self): #takes code and instatiates an object based on it's known price and values
if self.code == "1":
input("Please weigh item. Press ENTER to continue...") #replicates action of weighing produce on the checkout scale
weight = random.randint(1, 5) #this is just a random number as a placeholder for the real weight
return FoodFactory.create("Produce", "Apple", 0.75, weight)
if self.code == "2":
input("Please weigh item. Press ENTER to continue...")
weight = random.randint(1, 5)
return FoodFactory.create("Produce", "Potato", 0.65, weight)
if self.code == "3":
input("Please weigh item. Press ENTER to continue...")
weight = random.randint(1, 5)
return FoodFactory.create("Produce", "Cilantro", 0.50, weight)
if self.code == "4":
alcohol = FoodFactory.create("Alcohol", "Beer", 12.00, 5)
month = int(input("Please verify age with birth month: "))
date = int(input("Please verify age with birth date: "))
year = int(input("Please verify age with birth year: ")) #YYYY format required
alcohol.verifyId(year, month, date)
return alcohol
if self.code == "5":
alcohol = FoodFactory.create("Alcohol", "Wine", 30.00, 13)
month = int(input("Please verify age with birth month: "))
date = int(input("Please verify age with birth date: "))
year = int(input("Please verify age with birth year: "))
alcohol.verifyId(year, month, date)
return alcohol
if self.code == "6":
alcohol = FoodFactory.create("Alcohol", "Whiskey", 39.00, 40)
month = int(input("Please verify age with birth month: "))
date = int(input("Please verify age with birth date: "))
year = int(input("Please verify age with birth year: "))
alcohol.verifyId(year, month, date)
return alcohol
if self.code == "7":
prompt = input("Change quantity? (y/n)")
if prompt == "y":
quantity = input("How many? ")
else:
quantity = 1
return FoodFactory.create("Frozen", "Ice Cream", 8.00, 2020, 8, 31, quantity)
if self.code == "8":
prompt = input("Change quantity? (y/n)")
if prompt == "y":
quantity = input("How many? ")
else:
quantity = 1
return FoodFactory.create("Frozen", "TV Dinner", 5.00, 2020, 8, 2, quantity)
if self.code == "9":
prompt = input("Change quantity? (y/n)")
if prompt == "y":
quantity = input("How many? ")
else:
quantity = 1
return FoodFactory.create("Frozen", "Pizza Rolls", 12.00, 2020, 9, 30, quantity)
class Prototype:
def clone(self):
return copy.deepcopy(self) #imported the copy class to be able to use the clone method
class Receipt(Prototype): #inherite the Prototype class's clone method
def __init__(self, groceryList, paid=False):
self.groceryList = groceryList #an array with all the items
self.total = 0
def totalPrice(self):
for each in self.groceryList:
self.total += each.totalPrice
def getReceipt(self):
print("------------------Receipt--------------------\n")
for each in self.groceryList:
print(each)
print("\nTotal: ${:.2f}\n".format(self.total))
print("--------------Have a nice day!---------------")
def pay(self):
payMethod = input("\nWhat is your payment method?\n[1]Cash\n[2]Card\nInput number of your method: ")
self.paid = True
return "Thank you for your payment! Please take your receipt and have a wonderful day!\n"
def __str__(self):
return "Total: ${:.2f}\n".format(self.total)
def main():
itemList = []
item = 0 #this is a placeholder so that the variable is not None
while item != None:
item = FoodFacade().getItem() #the getItem() method uses the FoodFactory to instantiate an item object. You can type in any number on the menu you like to test it out.
if item != None:
itemList.append(item)
newReceipt = Receipt(itemList)
newReceipt.totalPrice() #this method will total all the items in the list above
print(newReceipt.pay())
newReceipt.getReceipt()
main() |
b84478127c1f73fb4bc344f5ed4ba7eb170a86ac | HenriTammo/Koolitus | /tund1/teegid.py | 185 | 3.546875 | 4 | import math
import random
arv1 = 144
ruutjuur = math.sqrt(arv1)
print (ruutjuur)
arv2 = random.randint(1, 6)
print(arv2)
if arv1 != arv2:
print (arv1, "on alati suurem kui", arv2) |
4601faf68e5abaaea6b59cafb4c2705fc35dacc0 | slamatik/codewars | /5 kyu/Perimeter of squares in a rectangle 5 kyu.py | 231 | 3.828125 | 4 | def perimeter(n):
fib = [1, 1]
while len(fib) < n + 1:
fib.append(fib[-1] + fib[-2])
return sum(fib) * 4
print(perimeter(5))
print(perimeter(7))
print(perimeter(20))
print(perimeter(30))
print(perimeter(100))
|
aaa7a6409f62075705d5b971fe8227770dcec8bf | dvminhtan/python_core | /source/lession_2/baitap7.py | 748 | 3.625 | 4 | """
Tìm và in lên màn hình tất cả các số nguyên trong phạm vi từ 10 đến 99 sao cho tích của 2 chữ số
bằng 2 lần tổng của 2 chữ số đó. Ví dụ: Số 44
"""
a = int(input("Nhap a: "))
b = int(input("Nhap b: "))
while True:
try:
if a < 10 or a > 20:
print("Nhap sai. Nhap lai")
a = int(input("Nhap lai a: "))
break
except ValueError:
print("Integer, please")
for i in range(a, b + 1):
hang_chuc = i // 10
hang_don_vi = i % 10
if hang_chuc * hang_don_vi == 2 * (hang_chuc + hang_don_vi):
print(i, end=" ")
"""
Độ phức tạp của thuật toán được dựa trên 2 nguyên tắc.
1. SỐ phép gán
2. Số phép so sánh
""" |
9aff6a6b092ff3f0eb176e86c019c72a0fc924f3 | gustkust/More-advanced-Python-exercises-for-university | /Physics of perfect elastic ball collisions.py | 9,026 | 3.859375 | 4 | # imports
import pygame
from math import sqrt
from random import randint, uniform
# some variables
SCREEN_WIDTH = 720
SCREEN_HEIGHT = 720
FPS = 60
BACKGROUND_COLOR = (255, 255, 255)
BALLS_COLOR = (31, 132, 155)
BALLS_SIZE = 30
NUMBER_OF_BALLS = 10
BALLS_SPEED = 5
RED_LAUNCH_TIME = 100
STOP_TIME = 3600 + RED_LAUNCH_TIME
RED = (155, 31, 31)
RED_SPEED = BALLS_SPEED / 10
# ball class
class Ball:
def __init__(self, x, y, x_speed, y_speed, radius, color):
self.x = x
self.y = y
self.x_speed = x_speed
self.y_speed = y_speed
self.radius = radius
self.color = color
def draw(self):
pygame.draw.circle(screen, self.color, (int(self.x), int(self.y)), self.radius)
def collision_check(ball1, ball2):
# finds distance between two centres of the balls and sum of their radiates
center_distance = sqrt((ball1.x - ball2.x) ** 2 + (ball1.y - ball2.y) ** 2)
two_radiates_sum = ball1.radius + ball2.radius
# returns True when collision and False otherwise
if center_distance <= two_radiates_sum:
return True
else:
return False
def collision(ball1, ball2):
# collision calculation
# 1
# unit normal vector
n = [ball1.x - ball2.x, ball1.y - ball2.y]
un = [n[0] / (n[0] ** 2 + n[1] ** 2) ** (1 / 2), n[1] / (n[0] ** 2 + n[1] ** 2) ** (1 / 2)]
# unit tangent vector
ut = [-un[1], un[0]]
# 2
# velocity vector for ball1
v1 = [ball1.x_speed, ball1.y_speed]
# velocity vector for ball2
v2 = [ball2.x_speed, ball2.y_speed]
# 3
# vectors to plain numbers
v1n = v1[0] * un[0] + v1[1] * un[1]
v1t = v1[0] * ut[0] + v1[1] * ut[1]
v2n = v2[0] * un[0] + v2[1] * un[1]
v2t = v2[0] * ut[0] + v2[1] * ut[1]
# 4
# new tangent velocities
# there is no friction so this step is not necessary
# 5
# new normal velocities
# there are masses in original formulas, so they are left ones as placeholders
# but because masses are the same it means v1n, v2n = v2n, v1n
v1n, v2n = (v1n * (1 - 1) + 2 * 1 * v2n) / (1 + 1), (v2n * (1 - 1) + 2 * 1 * v1n) / (1 + 1)
# 6
# scalar values to vectors for ball1
v1n = [v1n * un[0], v1n * un[1]]
v1t = [v1t * ut[0], v1t * ut[1]]
# scalar values to vectors for ball2
v2n = [v2n * un[0], v2n * un[1]]
v2t = [v2t * ut[0], v2t * ut[1]]
# 7
# new velocity vectors
v1[0] = v1n[0] + v1t[0]
v1[1] = v1n[1] + v1t[1]
v2[0] = v2n[0] + v2t[0]
v2[1] = v2n[1] + v2t[1]
# assigment to balls
ball1.x_speed = v1[0]
ball1.y_speed = v1[1]
ball2.x_speed = v2[0]
ball2.y_speed = v2[1]
# end of collision calculation
# moving ball1 and ball2 "out of each other"
# point of collision
cx = (ball1.x + ball2.x) / 2
cy = (ball1.y + ball2.y) / 2
# distance from collision point to ball1 centre (a bit smaller than radius)
d = sqrt((ball1.x - cx) ** 2 + (ball1.y - cy) ** 2)
# if balls are exactly into each other, there are wrong setting
if d == 0:
print("Too many, too small or too fast balls.")
exit(0)
# distance between point of the collision and ball1 center point in both axes
dx = ball1.x - cx
dy = ball1.y - cy
# proportions in dx, dy, d triangle
x_ratio = dx / d
y_ratio = dy / d
# x and y in new triangle, where radius is instead of d
new_x = x_ratio * ball1.radius
new_y = y_ratio * ball1.radius
# difference between dx, dy and new_x, new_y
diff_x = new_x - dx
diff_y = new_y - dy
# new positions in relation to center (could be in relation to old position)
# difference times two, so it is like they already bounce back and not get "sticky" first
ball1.x = cx + dx + 2 * diff_x
ball1.y = cy + dy + 2 * diff_y
# same with ball2 in the opposite direction
ball2.x = cx - dx - 2 * diff_x
ball2.y = cy - dy - 2 * diff_y
return ball1, ball2
def move(ball):
# moving ball
ball.x = ball.x + ball.x_speed
ball.y = ball.y + ball.y_speed
# checking for wall collision
if ball.x >= SCREEN_WIDTH - BALLS_SIZE:
ball.x_speed = -ball.x_speed
ball.x = 2 * SCREEN_WIDTH - ball.x - 2 * BALLS_SIZE
if ball.x <= BALLS_SIZE:
ball.x_speed = -ball.x_speed
ball.x = 2 * BALLS_SIZE - ball.x
if ball.y >= SCREEN_HEIGHT - BALLS_SIZE:
ball.y_speed = -ball.y_speed
ball.y = 2 * SCREEN_HEIGHT - ball.y - 2 * BALLS_SIZE
if ball.y <= BALLS_SIZE:
ball.y_speed = -ball.y_speed
ball.y = 2 * BALLS_SIZE - ball.y
return ball
# writes prompt and creates screen and clock
print('\nHello! This program allows to play with perfect elastic ball collisions.')
print('\nAll collision formulas based on article by Chad Berchek '
'"2-Dimensional Elastic Collisions without Trigonometry".')
print('http://www.vobarian.com/collisions/\n')
# On one time unit every ball travels thought as many pixels as their speed says
# It is possible to add masses to this simulation, there is placeholder for it in formulas
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
clock = pygame.time.Clock()
# creating balls
balls = []
for i in range(NUMBER_OF_BALLS):
balls.append(Ball(randint(BALLS_SIZE, SCREEN_WIDTH - BALLS_SIZE),
randint(BALLS_SIZE, SCREEN_HEIGHT - BALLS_SIZE),
uniform(-BALLS_SPEED, BALLS_SPEED), uniform(-BALLS_SPEED, BALLS_SPEED),
BALLS_SIZE, BALLS_COLOR))
# main loop
time = 0
time_since_last_RED_collision = 0
RED_collision_times = []
RED_collision_distances = []
distance_since_last_collision = 0
while True:
time += 1
time_since_last_RED_collision += 1
if time == STOP_TIME:
print('Time since RED ball appeared is', time - RED_LAUNCH_TIME, 'frames, which is',
(time - RED_LAUNCH_TIME) / 60, 'seconds.')
print('Number of collisions with RED ball is {}.'.format(len(RED_collision_times)))
if len(RED_collision_times) == 0:
print('There were no collisions with RED ball.')
else:
print('Average time between collision with RED ball is',
sum(RED_collision_times) / len(RED_collision_times), 'frames, which is',
sum(RED_collision_times) / len(RED_collision_times) / 60, 'seconds.')
print('Average distance between collision with RED ball is',
sum(RED_collision_distances) / len(RED_collision_distances), 'pixels.')
exit(0)
if time == RED_LAUNCH_TIME:
balls.append(Ball(SCREEN_WIDTH - BALLS_SIZE, SCREEN_HEIGHT - BALLS_SIZE, uniform(-RED_SPEED, 0),
uniform(-RED_SPEED, 0), BALLS_SIZE, RED))
time_since_last_RED_collision = 0
# checks if user wants to close the screen
for event in pygame.event.get():
if event.type == pygame.QUIT:
print('Time since RED ball appeared is', time - RED_LAUNCH_TIME, 'frames, which is',
(time - RED_LAUNCH_TIME) / 60, 'seconds.')
print('Number of collisions with RED ball is {}.'.format(len(RED_collision_times)))
if len(RED_collision_times) == 0:
print('There were no collisions with RED ball.')
else:
print('Average time between collision with RED ball is',
sum(RED_collision_times) / len(RED_collision_times), 'frames, which is',
sum(RED_collision_times) / len(RED_collision_times) / 60, 'seconds.')
print('Average distance between collision with RED ball is',
sum(RED_collision_distances) / len(RED_collision_distances), 'pixels.')
exit(0)
# moves balls and checks if any hits the wall
for element in balls:
move(element)
if element.color == RED:
distance_since_last_collision = distance_since_last_collision + sqrt(element.x_speed ** 2
+ element.y_speed ** 2)
# checks for collisions between balls
for ball1_index in range(0, len(balls)):
for ball2_index in range(ball1_index + 1, len(balls)):
if collision_check(balls[ball1_index], balls[ball2_index]):
if balls[ball1_index].color == RED or balls[ball2_index].color == RED:
RED_collision_times.append(time_since_last_RED_collision)
time_since_last_RED_collision = 0
RED_collision_distances.append(distance_since_last_collision)
distance_since_last_collision = 0
balls[ball1_index], balls[ball2_index] = collision(balls[ball1_index], balls[ball2_index])
# breaks the second for loop, so the balls wont stuck into each other
break
# drawing stuff
screen.fill(BACKGROUND_COLOR)
for element in balls:
element.draw()
pygame.display.flip()
clock.tick(FPS)
|
33da3242309a86ac25cb65c52755c2b95b6de0a1 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2535/60606/284125.py | 469 | 3.8125 | 4 | #如果位置和原数组一样,那么就说明可以分割
array = input()[1:-1].split(",")
array = [int(x) for x in array]
origin = array.copy()
origin.sort()
set_origin = set()
set_array = set()
count = 0
for i in range(len(array)):
set_origin.add(origin[i])
set_array.add(array[i])
if len(set_origin.difference(set_array)) == 0:
count+=1
set_origin = set()
set_origin.add(origin[i])
set_array.add(array[i])
print(count) |
fd12201bd93001316255752a17fdb64998497f37 | luismichu/Python | /ej4.py | 772 | 4.125 | 4 | from random import randint
max_num = int(input('Hasta que numero quieres adivinar: '))
intentos = int(input('Numero de intentos: '))
adivinar = randint(0, max_num)
num = input('\nAdivina: ')
if num.isnumeric():
intento = 1
dic = {intento:int(num)}
while intento < intentos and num.isnumeric() and int(num) != adivinar:
print('Casi. Te quedan', (intentos - intento), 'intentos')
print(dic)
num = input('\nAdivina: ')
intento += 1
if num.isnumeric(): dic.update({intento:int(num)})
if num.isnumeric() and int(num) == adivinar:
print('\nEnhorabuena!! Has acertado')
print(dic)
else:
print('\nSe quedo en el casi')
print('Numero no adivinado:', adivinar)
print(dic)
else:
print('\nSe quedo en el casi')
print('Numero no adivinado:', adivinar) |
24818c3f54452988320a34588987345f69e068b9 | yaoyu2001/LeetCode_Practice_Python | /309. Best Time to Buy and Sell Stock with Cooldown.py | 1,248 | 3.875 | 4 | # Say you have an array for which the ith element is the price of a given stock on day i.
#
# Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:
#
# You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
# After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
# Input: [1,2,3,0,2]
# Output: 3
# Explanation: transactions = [buy, sell, cooldown, buy, sell]
class Solution:
def maxProfit(self, prices: [int]) -> int:
# Use 3 dp list to indicate the max profits of every state
# Hold: hold stock, rest and sold(require hold)
# Hold : max(hold[i-1], rest[i-1] - price[i])
# Rest : max(rest[i-1], sold[i-1])
# Sold : hold[i-1] + price[i]
n = len(prices)
# Init 3 dp list
hold = float("-inf")
rest = 0
sold = float("-inf")
for i in range(n):
pre_sold = sold
sold = rest + prices[i]
hold = max(hold, rest - prices[i])
rest = max(rest, pre_sold)
return max(rest, sold)
|
8ef99bcf38165e4588313dad50c151958907739f | qjm100/password | /veiji.py | 2,399 | 3.625 | 4 | #作者:qjm
#鸣谢:Kevil
import getopt
from string import ascii_lowercase as lowercase
import sys
import pyfiglet
def En(p, key):
p = get_trim_text(p)
ptLen = len(p)
keyLen = len(key)
quotient = ptLen // keyLen # 商
remainder = ptLen % keyLen # 余
out = ""
for i in range(0, quotient):
for j in range(0, keyLen):
c = int((ord(p[i * keyLen + j]) - ord('a') + ord(key[j]) - ord('a')) % 26 + ord('a'))
# global output
out += chr(c)
for i in range(0, remainder):
c = int((ord(p[quotient * keyLen + i]) - ord('a') + ord(key[i]) - ord('a')) % 26 + ord('a'))
# global output
out += chr(c)
return out
def De(output, key):
ptLen = len(output)
keyLen = len(key)
quotient = ptLen // keyLen
remainder = ptLen % keyLen
inp = ""
for i in range(0, quotient):
for j in range(0, keyLen):
c = int((ord(output[i * keyLen + j]) - ord('a') - (ord(key[j]) - ord('a'))) % 26 + ord('a'))
# global input
inp += chr(c)
for i in range(0, remainder):
c = int((ord(output[quotient * keyLen + i]) - ord('a') - (ord(key[i]) - ord('a'))) % 26 + ord('a'))
# global input
inp += chr(c)
return inp
def helpyou ():
print ("欢迎来到维吉尼亚\n-h --help 显示帮助\n-k --key 必要参数,秘钥\n-e --jiami输入加密信息\n-d --jiemi 输入要解密信息")
def get_trim_text(text):
text = text.lower()
trim_text = ''
for l in text:
if lowercase.find(l) >= 0:
trim_text += l
return trim_text
if __name__ == '__main__':
a = pyfiglet.Figlet (font='slant')
print (a.renderText ('virginia'))
print ("-h 显示帮助")
try:
longargs = ['help=','jiami=','jiemi=','key=']
opts,args= getopt.getopt( sys.argv[1:], 'he:d:k:', longargs)
for o, a in opts:
if o in ("--key","-k"):
ke = a
if o in ("--help" ,"-h"):
helpyou()
sys.exit()
if o in ("--jiami" ,"-e"):
jiami = a
print (En (jiami,ke))
if o in ("--jiemi" ,"-d"):
jiemi = a
print (De (jiemi,ke))
except getopt.GetoptError:
helpyou()
|
e069bee1fe8f23513246a822a032a12a5a9d85fa | yao76/Coding-Dojo-Python | /Week_3/python/OOP/classes_practice.py | 995 | 4.03125 | 4 | # class User: # declare a class and give it name User
# def __init__(self):
# self.name = "Michael"
# self.email = "michael@codingdojo.com"
# self.account_balance = 0
# guido = User()
# monty = User()
# monty.name = "Monty"
# print(guido.name)
# print(monty.name)
class User:
def __init__(self, username, email_address):# now our method has 2 parameters!
self.name = username # and we use the values passed in to set the name attribute
self.email = email_address # and the email attribute
self.account_balance = 0 # the account balance is set to $0, so no need for a third parameter
# adding the deposit method
def make_deposit(self, amount): # takes an argument that is the amount of the deposit
self.account_balance += amount # the specific user's account increases by the amount of the value received
guido = User("Guido", "guido@python.com")
print(guido.name)
print(guido.email)
guido.make_deposit(100)
print(guido.account_balance) |
cd413b1ca6492c3652972210a91b99c0f5da8db4 | rjcate/Pressure_sensor_use | /single_pressure_plot_and_stats.py | 3,667 | 3.5625 | 4 | '''
Calculate statistics and generate graphs for raw sensor data
using a variety of window sizes. Generates one plot using each
window size per data file input.
Inputs:
sys.argv[1] - directory containing raw data. Generated images also save here
sys.argv[2] - name of the sensor being tested. Gets appended to generated file names
sys.argv[3] - supply voltage for sensor. Gets appended to generated file names
Outputs:
One plot for each data point and window size
Detailed statistics for each pressure point and window size
Usage
python single_pressure_plot_and_stats.py path_to_data_files/ 'name_of_sensor' 'supply_voltage'
'''
import sys
import csv
import glob
import re
import statistics
import pandas as pd
import matplotlib.pyplot as plt
def parse_and_sanitize_input_data(filename):
data = []
with open(filename) as csvfile:
data = list(csv.reader(csvfile))
col0, col1, col2, col3 = [], [], [], []
for row in data:
try:
float(row[0]), float(row[1]), float(row[2]), float(row[3])
except ValueError:
continue # skip rows that have non numerical data
col0.append(float(row[0]))
col1.append(float(row[1]))
col2.append(float(row[2]))
col3.append(float(row[3]))
return col0, col1, col2, col3
def rolling_average(data, window_size):
rolling_sum, result = [0], []
for i, x in enumerate(data, 1):
rolling_sum.append(rolling_sum[i-1] + x)
if i >= window_size:
curr_average = (rolling_sum[i] - rolling_sum[i-window_size])/window_size
result.append(curr_average)
return result
def make_figure(x, y, filename, title='Figure'):
plt.xlabel('Time (ms)')
plt.ylabel('Adc Output (raw, uncalibrated)')
plt.ylim(-25000, 3000)
plt.title(title)
plt.grid(True)
# for i in y:
# plt.plot(x, i, label=pressure)
plt.plot(x, y)
plt.tight_layout()
filename = filename.replace('.csv', '') + '_' + title.replace(' ', '_').lower() + '.png'
print("Saving ", filename)
plt.savefig(filename)
plt.clf()
# plt.show()
def natural_sort(s):
_natural_sort_regex = re.compile(r'([0-9]+)')
return [int(text) if text.isdigit() else text.lower() for text in re.split(_natural_sort_regex, s)]
# build list of files to analyze
file_list = glob.glob(sys.argv[1]+"/*.csv")
file_list.sort(key=natural_sort)
# dataframe to hold results
df = pd.DataFrame(columns=["Data Set Name", "Pressure", "# Samples", "Min", "Max", "Average", "SDev"])
# parse and do calculations for each file
for f in file_list:
try:
gain = int(re.findall(r'(\d+)G', f)[0]) # parse out gain from filename
pressure = float(re.findall(r'_(\d+\.\d+)psi', f)[0]) # parse out gain from filename
except IndexError:
continue # skip analysis for files that don't have gain in the name
idx, ts, adc0, adc1 = parse_and_sanitize_input_data(f) # parse data from file
# calculate stats we care about for this data set
data = [f.split("\\")[-1], pressure, len(adc0), min(adc0), max(adc0), statistics.mean(adc0), statistics.stdev(adc0)]
df = df.append(pd.Series(data, index=df.columns), ignore_index=True)
# # try different averages and make figures
for window_size in [1, 5, 10, 50, 100, 500]:
averaged_data = rolling_average(adc0, window_size)
make_figure(idx[window_size-1:], averaged_data, f, "Pressure={} psi Gain={} Window size={}".format(pressure, gain, window_size))
print(df)
df.to_csv(sys.argv[1] + "/calibration_data.csv")
|
40036b195cb472d18d827d0c3bf1829704db07f0 | Saqlainrocks7/Rock_Paper_Scissors | /ro_pa_sc.py | 1,179 | 3.8125 | 4 | from art import rock, paper, scissors
import random
user_choice = int(input("What do you choose? Type 0 for Rock, 1 for Paper and 2 for Scissors.\n"))
comp_choice = random.randint(0, 2)
game_images = [rock, paper, scissors]
if user_choice == 0 and comp_choice == 2:
print("You chose:\n{}".format(game_images[user_choice]))
print("Computer chose:\n{}".format(game_images[comp_choice]))
print("You Won")
elif user_choice == 2 and comp_choice == 1:
print("You chose:\n{}".format(game_images[user_choice]))
print("Computer chose:\n{}".format(game_images[comp_choice]))
print("You Won")
elif user_choice == 1 and comp_choice == 0:
print("You chose:\n{}".format(game_images[user_choice]))
print("Computer chose:\n{}".format(game_images[comp_choice]))
print("You Won")
elif user_choice == comp_choice:
print("You chose:\n{}".format(game_images[user_choice]))
print("Computer chose:\n{}".format(game_images[comp_choice]))
print("Tie!! Try again")
else:
print("You chose:\n{}".format(game_images[user_choice]))
print("Computer chose:\n{}".format(game_images[comp_choice]))
print("Computer Won")
|
21bf82dca5fcf782509c9dc4bd17d807c6c79d53 | danielhp02/Pong | /code/objects.py | 5,096 | 3.5 | 4 | import random
class Ball():
def __init__(self, startX, startY, pygame, surface, radius):
self.startPos = (startX, startY) # This is where the ball will return to after a point is scored
self.x = startX
self.y = startY
# These are so the bats can interact with the game without pygame being
# imported or this class having to be in the main file.
self.pygame = pygame
self.surface = surface
self.radius = radius
# Getting a random direction for the ball to start in
self.dx = random.randint(-1, 1) * 3
while self.dx == 0:
self.dx = random.randint(-1, 1) * 3
self.dy = random.randint(-3, 3)
while self.dy == 0:
self.dy = random.randint(-3, 3)
self.colour = (255, 255, 255)
self.score = [0,0]
self.pauseTime = 500 # The amount of time (in milliseconds) that the ball stops for after a point is won
self.scoredTime = 0 # The time when the last point was scored; used mainly externally for pausing just the ball
self.scored = False
# Secret!
self.nggyu = self.pygame.mixer.Sound("../assets/nggyu.ogg")
self.cej = self.pygame.mixer.Sound("../assets/cej.ogg")
self.songs = [self.nggyu, self.cej]
def playSong(self): # A suprise for a point is scored (sometimes)
if random.random() < 0.2:
random.choice(self.songs).play()
# Reset the ball after a point is scored
def resetBall(self):
self.scored = True
self.scoredTime = self.pygame.time.get_ticks() # Gets the time when a point was scored
# Reset ball position
self.x = self.startPos[0]
self.y = self.startPos[1]
# Getting a new random direction for the ball to begin in
self.dx = random.randint(-1, 1) * 3
while self.dx == 0:
self.dx = random.randint(-1, 1) * 3
self.dy = random.randint(-3, 3)
while self.dy == 0:
self.dy = random.randint(-3, 3)
# Check for collisions with the bats and the edges of the window
def checkForCollisions(self, windowWidth, windowHeight, leftBat, rightBat):
# Check For collision with top and bottom boundaries
if self.y - self.radius < 0 or self.y + self.radius > windowHeight:
self.dy *= -1
# Left side - awards point to right player
if self.x - self.radius < 0:
self.score[1] += 1
self.resetBall()
self.playSong()
# Right side - awards point to left player
elif self.x + self.radius > windowWidth:
self.score[0] += 1
self.resetBall()
self.playSong()
# Left Bat - Note for both bats: the collisions are only with the innermost side.
if self.x - self.radius < leftBat.x + leftBat.width and leftBat.y < self.y < leftBat.y + leftBat.height:
self.dx *= -1
self.speedUp(leftBat, rightBat)
# Right Bat
if self.x + self.radius > rightBat.x and rightBat.y < self.y < rightBat.y + rightBat.height:
self.dx *= -1
self.speedUp(leftBat, rightBat)
def move(self, windowWidth, windowHeight, leftBat, rightBat):
self.checkForCollisions(windowWidth, windowHeight, leftBat, rightBat)
self.x += self.dx
self.y += self.dy
def draw(self, drawAtStartPos):
if drawAtStartPos:
self.pygame.draw.circle(self.surface, self.colour, (self.startPos[0], self.startPos[1]), self.radius)
else:
self.pygame.draw.circle(self.surface, self.colour, (int(round(self.x)), int(round(self.y))), self.radius)
self.scored = False
# Speeds the ball up if the bat it is colliding with is moving during the collision
def speedUp(self, leftBat, rightBat):
if leftBat.isMoving or rightBat.isMoving:
self.dx *= 1.1
self.dy *= 1.1
class Bat(object):
def __init__(self, x, startY, pygame, surface, width, height):
self.x = x
self.y = startY
# These are so the bats can interact with the game without pygame being
# imported or this class having to be in the main file.
self.pygame = pygame
self.surface = surface
self.width = width
self.height = height
self.speed = 2.5 # The speed the bat will do either way
self.dy = 0 # The speed the bat is currently doing
self.isMoving = False # For the ball to speed up when it collides with a moving bat
self.colour = (255, 255, 255)
def move(self, up, down, bottomLimit):
if up and self.y > 0:
self.dy = -self.speed
self.isMoving = True
elif down and self.y + self.height < bottomLimit:
self.dy = self.speed
self.isMoving = True
else:
self.dy = 0
self.isMoving = False
self.y += self.dy
def draw(self):
self.pygame.draw.rect(self.surface, self.colour, (self.x, self.y, self.width, self.height))
|
53ae25d696254bbb425e80d5106fa94decf85f6c | TheGoldenShark/Advent-Of-Code-2020 | /D6/D6.5.py | 401 | 3.515625 | 4 | import string
with open("input.txt","r") as f: data=f.readlines()
data = [x[:-1] for x in data]
dataProcessed = []
temp=set(string.ascii_lowercase)
for i in data:
if i== '':
dataProcessed.append(temp)
temp=set(string.ascii_lowercase)
else:
temp = temp.intersection(set(i))
dataProcessed.append(temp)
count = 0
for i in dataProcessed:
count += len(i)
print(count) |
07b5de946f56b449de717373ccc4863348fa882a | abhishekdwibedy-2002/Spectrum_Internship_Task | /prgm9.py | 294 | 4.0625 | 4 | n = int(input("Enter number of elements : \n"))
lst=[]
print("Enter",n ,"Elements")
for i in range(0, n):
element = int(input())
lst.append(element)
idx=int(input("Enter the value To Find The Smallest no. :- \n"))
lst.sort()
print("Your " ,idx,"th smallest no. is: ",lst[idx-1]) |
e902c1b74c79d2e277248505c38019dfec282d6c | kgerg2/Imperativ | /2.ora/ropzh.py | 187 | 3.796875 | 4 | def fizzbuzz():
a = int(input("Add meg a számot:"))
eredm = ""
if a % 5 == 0:
eredm += "Fizz"
if a % 3 == 0:
eredm += "Buzz"
return eredm
|
8cfa77fdb730918b71d52f8e4eb078462b5c955e | fatihunal78/Python_Assignments_CodeInPlace | /Assignment2/khansole_academy.py | 867 | 4.1875 | 4 | """
File: khansole_academy.py
-------------------------
Add your comments here.
"""
import random
import math
MIN_NUM = 10
MAX_NUM = 99
def main():
count = 0
while count < 3:
number_1 = random.randint(MIN_NUM, MAX_NUM)
number_2 = random.randint(MIN_NUM, MAX_NUM)
total = number_1 + number_2
print("What is " + str(number_1) + " + " + str(number_2) + "?")
answer = int(input("Your answer: "))
if total != answer:
count = 0
print("Incorrect. The expected answer is " + str(total))
else:
count += 1
print("Correct! You've gotten " + str(count) + " correct in a row.")
print("Congratulations! You mastered addition.")
# This provided line is required at the end of a Python file
# to call the main() function.
if __name__ == '__main__':
main()
|
1045ec6dd515836aa0c1d6ebc72ee665512ccca9 | vins89/Assingment1_math | /Assignment 2/evenodd.py | 447 | 4.1875 | 4 | var1= raw_input("enter a number: ")
if int(var1) % 2 ==0:
print "The number is even"
else:
print ' the number is odd'
if int(var1) % 4 ==0:
print " the number is a multiple of 4"
else:
print " the number is not divisible by 4"
num = int(raw_input("enter number a "))
check = int(raw_input("enter number b "))
c = int(num)/ int(check)
if type(c) == int:
print " a is divisible by b"
else:
print " a is not divisible by b"
|
cc229dbd60bfc347cc468e20e518a81b5678f327 | guyuzhilian/Programs | /Python/project_euler/problem30.py | 547 | 3.90625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# author: lidajun
# date: 2015/7/31
# time: 10:23
def get_nth_digit(num, n):
return (num / pow(10, n-1)) % 10
def sum_of_fifth_power(num):
total = 0
for n in xrange(1, len(str(num))+1):
digit = get_nth_digit(num, n)
total += pow(digit, 5)
return total
def main():
total = 0
for num in xrange(2, 1000000):
if sum_of_fifth_power(num) == num:
print(num)
total += num
print(total)
if __name__ == "__main__":
main() |
5d781a52fb550a565c625739228f90eb61d6db48 | maryferivera14/The-New-Age | /The new age -code.py | 810 | 3.9375 | 4 | def temperatura():
#Aqui recibiria la temperatura de forma automatica al estar conectado el sensor de calor
#Los estados del ventilador seran representados como ON = 1 y OFF = 0
vent=0
cal=float(input("CANTIDAD DE GRADOS: "))
if cal>37:
print("VENTILADOR ENCENDIDO")
vent=vent+1
else:
print("VENTILADOR APANGOSE")
vent=vent+0
#temperatura()
def humedad():
#Se recibira la humedad de la tierra en el valor de "ml / m3" mililitros por metro cubico
#Los tubos de riego se abriran y cerraran de forma automatica segun la situacion
hum=float(input("Nivel de humedad en ml/m3: "))
if hum<10:
print("Sistema de riego activado, dispersando riego...")
else:
print("Sistema de riego desactivado")
humedad()
|
6b58a1e4b9dea5565193c27f8a72a6eeb113fbc4 | sainihimanshu1999/Leetcode---Top-100-Liked-Questions | /intersectionoftwolinkedlist.py | 588 | 3.65625 | 4 | '''
using dictionary
'''
def intersection(self,headA,headB):
dic = {}
curr1 = headA
curr2 = headB
while curr1:
dic[curr1] = curr1.val
curr1 = curr1.next
while curr2:
if curr2 in dic:
return curr2:
dic[curr2] = curr2.val
curr2 = curr2.next
'''
using two pointer approach
'''
def intersection(self,headA,headB):
if not headA or not headB:
return None
pA = headA
pB = headB
while pA!=pB:
pA = pA.next if pA else headB
pB = pB.next if pB else headA
return pA
|
8dbbbb32e1ddabf29571ab1ec3bd89415146537d | LittleFee/python-learning-note | /day06/04-class-inherit.py | 3,461 | 4.46875 | 4 | # 一个类继承(inherit)另一个类时,它将自动获得另一个类的所有属性和方法;原有的类称为父类,
# 而新类称为子类。子类继承了其父类的所有属性和方法,同时还可以定义自己的属性和方法
class Car():
"""描述小汽车,包括年份、制造商和型号"""
def __init__(self,maker,model,year):
"""初始化汽车属性"""
self.maker=maker
self.model=model
self.year = year
self.odometer_reading=0
# 给一个路码表初始读数0
def get_name_des(self):
"""描述汽车"""
long_name=self.maker+' '+self.model+' '+str(self.year)
return long_name
def get_odometer_reading(self):
"""打印路码表读数"""
print('The odometer reading is '+str(self.odometer_reading)+' now')
def update_odometer(self,mile):
"""修改路码表读数+防止往回调路码表"""
# self.odometer_reading=mile
if mile >= self.odometer_reading:
self.odometer_reading=mile
else:
print("You can't roll back an odometer!")
def add_odometer(self,mile):
"""将里程表读数增加指定的量"""
if mile >= 0:
self.odometer_reading+=mile
else:
print("You can't roll back an odometer!")
def fill_gas_tank(self):
"""为演示重写父类方法而添加"""
print("OK Now!")
class E_car(Car):
"""电动车"""
def __init__(self,maker,model,year,size):
"""初始化"""
super().__init__(maker,model,year)
# 父类也称为超类(superclass),名称super因此而得名。
self.battery_size=size
def show_battery_size(self):
"""显示电动车的电池容量"""
print('It\'s has '+str(self.battery_size)+' kwh battery.')
def fill_gas_tank(self):
"""电动汽车没有油箱"""
print("This car doesn't need a gas tank!")
# 对于父类的方法,只要它不符合子类模拟的实物的行为,都可对其进行重写。为此,可在子
# 类中定义一个这样的方法,即它与要重写的父类方法同名。这样,Python将不会考虑这个父类方
# 法,而只关注你在子类中定义的相应方法。
e_car=E_car('Tesla','modelX',2017,80)
print(e_car.get_name_des())
e_car.show_battery_size()
e_car.fill_gas_tank()
# 将实例用作属性
# 使用代码模拟实物时,你可能会发现自己给类添加的细节越来越多:属性和方法清单以及文
# 件都越来越长。在这种情况下,可能需要将类的一部分作为一个独立的类提取出来。你可以将大
# 型类拆分成多个协同工作的小类。
class Battery():
"""把电池提取出来成为一个小类"""
def __init__(self):
self.battery_size=70
self.battery_life=100
def show_battery_size(self):
print('Size of battery is '+str(self.battery_size)+' kwh')
def show_battery_life(self):
print('Life of battery is '+str(self.battery_life)+' hours')
class E_car_2(Car):
"""实例作为属性演示"""
def __init__(self,maker,model,year,size):
"""初始化"""
super().__init__(maker,model,year)
# 父类也称为超类(superclass),名称super因此而得名。
self.batterry=Battery()
ecar=E_car_2('tesla','modelx',2017,80)
ecar.batterry.show_battery_size() |
cc43a518cf27e37dbd7bdfa7b4fc7db4b4973152 | tux-linux/Python-works | /CalculatriceAléatoire.py | 1,228 | 3.9375 | 4 | import random
from math import sqrt
nombres = range(1, 100000)
operations = ["*", "/", "+", "-", "sqrt"]
print("Calculatrice aléatoire Python")
_init_ = 1
while _init_ == 1:
nombre1 = random.choice(nombres)
nombre2 = random.choice(nombres)
operation = random.choice(operations)
if operation == "*":
resultat = nombre1 * nombre2
print("Le produit de {0} et de {1} donne {2}.".format(nombre1, nombre2, resultat))
input("")
elif operation == "/":
resultat = nombre1 / nombre2
print("Le quotient de {0} et de {1} donne {2}.".format(nombre1, nombre2, resultat))
input("")
elif operation == "+":
resultat = nombre1 + nombre2
print("La somme de {0} et de {1} donne {2}.".format(nombre1, nombre2, resultat))
input("")
elif operation == "-":
resultat = nombre1 - nombre2
print("La différence de {0} et de {1} donne {2}.".format(nombre1, nombre2, resultat))
input("")
elif operation == "sqrt":
nombresR = [nombre1, nombre2]
nombre3R = random.choice(nombresR)
resultat = sqrt(nombre3R)
print("La racine carrée de {0} donne {1}.".format(nombre3R, resultat))
input("") |
89357603502974a6d0ecbc82d30660372353f5e6 | eymkarla/gitpy | /dictionary.py | 326 | 4.0625 | 4 | thisdict = {
"apple": "green",
"banana": "yellow",
"cherry": "red"
}
thisdict["apple"] = "red" #change green to red
thisdict = dict(apple="green", banana="yellow", cherry="red")
thisdict["damson"] = "purple" #insert another value in the dict
del(thisdict["banana"]) #delete
print(len(thisdict)) #length of dict
|
351809d6e886b851498b573d3849c5015668db6c | zhaohj2017/nnreach-nsfc | /pipes.py | 477 | 3.53125 | 4 | import numpy as np
import superpara
import activation
import ann
#the neural network weight computed for the ith (i >= 0) step is stored at index i in PIPES
PIPES = []
#after training, add the final value of weights to pipes
def addpipe():
global pipes
w_matrix = ann.weight_matrix.copy()
w_h_o = ann.weight_h_o.copy()
PIPES.append([w_matrix, w_h_o])
#print pipe
def printpipe():
print "The pipes:"
for weight in PIPES:
print weight[0].T #transpose
print weight[1] |
7b0c521ac7a5983b72b3916d5444d81aa8cfdc50 | pedroeml/t1-fcg | /CrowdDataAnalysis/graph/node.py | 1,287 | 3.671875 | 4 | from graph.edge import Edge
class Node:
def __init__(self, item):
"""
:param item:
:param edges:
:type edges: dict
"""
self.item = item
self.edges = {}
def add_edge(self, node, weight):
"""
:param node:
:type node: Node
:param weight:
:return:
"""
try: # try to find the edge between self and node
edge = self.find_edge(node)
except KeyError: # there is no edge between them
self.edges[node.item] = Edge(self, node, weight) # then create one
else:
edge.change_weight(weight) # change its weight
def remove_edge(self, node):
self.edges.pop(node.item)
def find_edge(self, node):
"""
:param node:
:return:
:rtype: Edge
"""
return self.edges[node.item]
def get_edges(self):
"""
:return: [Edge]
:rtype: list
"""
return self.edges.values()
def get_sorted_edges(self):
"""
:return: [Edge]
:rtype: list
"""
return sorted(self.get_edges())
def change_edge_weight(self, node, weight):
self.find_edge(node).change_weight(weight)
|
13047359d89a6d146937d62c4461eb0bc2c89a49 | mHernandes/pad-like-game | /button.py | 1,100 | 3.65625 | 4 | import pygame
from settings import Settings
class Button:
""" A Class to manage the button """
def __init__(self, game):
""" Initializes the Class """
# Settings instances
self.settings = Settings()
# Assign the screen from pinball.py to Button in order to access it and get rect
self.screen = game.screen
self.screen_rect = self.screen.get_rect()
# Button rect
self.font = pygame.font.SysFont(None, 48)
self.rect = pygame.Rect(0, 0, self.settings.button_width, self.settings.button_height)
self.rect.center = self.screen_rect.center
# Text and prepping
text = "Play"
self._prepare_text(text)
def _prepare_text(self, text):
""" Renders text as an image and centers it on the button """
self.text_image = self.font.render(text, True, self.settings.text_color, self.settings.button_color)
self.text_image_rect = self.text_image.get_rect()
self.text_image_rect.center = self.rect.center
def blitme(self):
""" Draw button and blits it """
self.screen.fill(self.settings.button_color, self.rect)
self.screen.blit(self.text_image, self.text_image_rect) |
df95751c57869fb3260b76e2de6e9e8f95f15689 | Andor-Z/My-Learning-Note | /ThinkPython/code/widget_demo.py | 3,660 | 4.5 | 4 | """Solution to an exercise from
Think Python: An Introduction to Software Design
Copyright 2010 Allen B. Downey
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
This program requires Gui.py, which is part of
Swampy; you can download it from thinkpython.com/swampy.
This program demonstrates how to use the Gui module
to create and operate on Tkinter widgets.
The documentation for the widgets is at
http://www.pythonware.com/library/tkinter/introduction/
"""
from swampy.Gui import *
# create the Gui: the debug flag makes the frames visible
g = Gui(debug=False)
# the topmost structure is a row of widgets
g.row()
# FRAME 1
# the first frame is a column of widgets
g.col()
# la is for label
la1 = g.la(text='This is a label.')
# en is for entry
en = g.en()
en.insert(END, 'This is an entry widget.')
la2 = g.la(text='')
def press_me():
"""this callback gets invoked when the user presses the button"""
text = en.get()
la2.configure(text=text)
# bu is for button
bu = g.bu(text='Press me', command=press_me)
# end of the first frame
g.endcol()
# FRAME 2
g.col()
# ca is for canvas
ca = g.ca(width=200, height=200)
item1 = ca.circle([0, 0], 70, 'red')
item2 = ca.rectangle([[0, 0], [60, 60]], 'blue')
item3 = ca.text([0, 0], 'This is a canvas.', 'white')
# mb is for menubutton
mb = g.mb(text='Choose a color')
def set_color(color):
ca.itemconfig(item2, fill=color)
# mi is for menuitem
for color in ['red', 'green', 'blue']:
# Callable is an object that can be used like a function
g.mi(mb, color, command=Callable(set_color, color))
g.endcol()
# FRAME 3
g.col()
def get_selection():
t = lb.curselection()
try:
index = int(t[0])
color = lb.get(index)
return color
except:
return None
def print_selection(event):
print get_selection()
def apply_color():
color = get_selection()
if color:
ca.itemconfig(item1, fill=color)
la = g.la(text='List of colors:')
g.row()
# lb is for listbox
lb = g.lb()
lb.bind('<ButtonRelease-1>', print_selection)
# sb is for scrollbar
sb = g.sb()
g.endrow()
bu = g.bu(text='Apply color', command=apply_color)
g.endcol()
# fill the listbox with color names
fp = open('/etc/X11/rgb.txt')
fp.readline()
for line in fp:
t = line.split('\t')
name = t[2].strip()
lb.insert(END, name)
# tell the listbox and the scrollbar about each other
lb.configure(yscrollcommand=sb.set)
sb.configure(command=lb.yview)
# FRAME 4
g.col()
# te is for text entry
te = g.te(height=5, width=40)
te.insert(END, "This is a Text widget.\n")
te.insert(END, "It's like a little text editor.\n")
te.insert(END, "It has more than one line, unlike an Entry widget.\n")
# st is for scrollable text
st = g.st()
st.text.configure(height=5, width=40)
st.text.insert(END, "This is a Scrollable Text widget.\n")
st.text.insert(END, "It is defined in Gui.py\n")
for i in range(100):
st.text.insert(END, "All work and no play.\n")
g.endcol()
# FRAME 5
# gr is for grid: start a grid with three columns
# the rweights control how extra space is divided among the rows
g.gr(3, rweights=[1,1,1])
for i in range(1, 10):
g.bu(text=str(i))
g.endgr()
# FRAME 6
g.col()
def print_var(obj):
print obj.var.get()
g.la(text='Font:')
fontsize = IntVar()
# rb is for radiobutton
for size in [10, 12, 14, 16, 18]:
rb = g.rb(text=str(size), variable=fontsize, value=size)
rb.configure(command=Callable(print_var, rb))
# cb is for checkbutton
b1 = g.cb(text='Bold')
b1.configure(command=Callable(print_var, b1))
b2 = g.cb(text='Italic')
b2.configure(command=Callable(print_var, b2))
g.endcol()
g.mainloop()
|
71ee82791a257bcf420dd47070b8b7a6463e10b6 | jayhebe/w3resource_exercises | /Basic - Part2/ex5.py | 104 | 3.6875 | 4 | numbers = []
for num in range(1000):
num = str(num).zfill(3)
numbers.append(num)
print(numbers)
|
71c415f2a7105e25dfcae9038151e91925144255 | Song2017/Leetcode_python | /Leetcode/226.invertTree.py | 988 | 3.9375 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def invertTree0(self, root: TreeNode) -> TreeNode:
'''
翻转一棵二叉树
'''
# 当前节点不存在或不存在子节点时返回
if not root or not (root.left or root.right):
return root
root.left, root.right = root.right, root.left
self.invertTree(root.right)
self.invertTree(root.left)
return root
def invertTree(self, root: TreeNode) -> TreeNode:
# bfs
if not root:
return
from collections import deque
q = deque()
q.appendleft(root)
while q:
n = q.pop()
n.left, n.right = n.right, n.left
if n.left:
q.appendleft(n.left)
if n.right:
q.appendleft(n.right)
return root
|
15f47ffa83ab3c0eb6e0cc2c150daa272aadbad3 | Smoow/MIT-UNICAMP-IPL-2021 | /solutions/p2_5.py | 1,586 | 4.34375 | 4 | from string import ascii_lowercase, digits
def handle_letter(char, shift):
"""
Helper function for Caesar Cipher. Handles the case the character is a letter.
Args:
char: length-one string, letter character
shift: shift value of caesar cipher
Returns:
new letter that should be placed in cryptographed message
"""
orig_num_value = ascii_lowercase.find(char)
new_value = (orig_num_value + shift) % 26
return ascii_lowercase[new_value]
def handle_number(char, shift):
"""
Helper function for Caesar Cipher. Handles the case the character is a number.
Args:
char: length-one string, number character
shift: shift value of caesar cipher
Returns:
new number (as str) that should be placed in cryptographed message
"""
orig_num_value = int(char)
new_value = (orig_num_value + shift) % 10
return str(new_value)
def caesar_cipher(msg, shift):
"""
Implements a simple Caesar Cipher on string with shift value shift. Uses
English alphabet, 0-9 digits, punctuation unchanged.
Args:
msg: message to be "cryptographed"
shift: integer shift value
Returns:
cryptographed message through Caesar Cipher with shift value shift
"""
msg = msg.lower() # passar string para minúsculas
out = ""
for char in msg:
if char in ascii_lowercase:
out += handle_letter(char, shift)
elif char in digits:
out += handle_number(char, shift)
else:
out += char
return out
|
ff2660c9e4fe9f9db0cc002381a5bb618377d016 | schatzke/Dailyexercise | /exercise 17 - Decode A Web Page.py | 695 | 3.6875 | 4 | '''
Exercise 17 Decode A Web Page
Use the BeautifulSoup and requests Python packages to print out a list of all the article titles on the New York Times homepage.
Discussion
Concepts for this week:
Libraries
requests
BeautifulSoup: https://www.crummy.com/software/BeautifulSoup/bs4/doc/#output-formatters
'''
# Solution
import requests
from bs4 import BeautifulSoup
source=requests.get('https://www.nytimes.com/').text
soup=BeautifulSoup(source,'lxml')
#print(soup.prettify())
for article in soup.find_all('div',class_='css-1ez5fsm esl82me1'):
print (article.text)
# print ('-----')
# print (article.string) --- be careful the difference between string & text
|
c697b2494bc80202d8c07ac71e3641657955b129 | ben-holland-young/learn | /diff2/calculator.py | 104 | 3.5625 | 4 | calc = input("Input your calculation")
print(eval(calc))
#eval turns a string into runnable python code
|
bd0cbf93feffea1467e470315478b4050c2b3a85 | llpuchaicela/Proyecto-Primer-Bimestre | /NumeroPositivoNegativo.py | 328 | 3.90625 | 4 | print ("Ejercicio7")
print ("Lilibeth Puchaicela")
print("Programa para cálcular si un número es positivo o negativo")
#Declaracion de variables
n = 0
srt = ""
#Datos
n=int(input("Ingrese un número diferente a cero : "))
n = int(n)
#Proceso
if n > 0:
print("El numero" ,n, "es positivo")
else:
print ("El numero" ,n, "es negativo") |
073166a38495c621121ed73c4d7ecc44e69d2e3f | colo1211/Algorithm_Python | /기초 알고리즘 100제/6027. 값변환03.py | 259 | 3.546875 | 4 | a=int(input())
print('%x'%a)
#10진수->16진수로 변환
#print('%x'%변환할10진수)
# 10진수 형태로 입력받고
# %x로 출력하면 16진수(hexadecimal) 소문자로 출력된다.
# (%o로 출력하면 8진수(octal) 문자열로 출력된다.) |
f7ad55c8694b08f61b8ce4767ce5a9da600330f7 | ujjvalchauhan/python-challenge | /PyBank/code/main.py | 1,170 | 3.78125 | 4 | import os
import csv
bank_csv_path = os.path.join( "..", "Resources", "budget_data.csv")
totaltrans =[]
months=[]
average=[]
profchange=[]
with open(bank_csv_path, newline="") as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
next(csvreader,None)
for row in csvreader:
totaltrans.append(float(row[1]))
months.append(row[0])
num=len(months)
total=sum(totaltrans)
for i in range(1):
while i <= len(totaltrans)-2:
profchange.append(totaltrans[i+1]-totaltrans[i])
i=i+1
add=sum(profchange)
average=(add/85)
maxprof=max(profchange)
minprof=min(profchange)
print("financial analysis")
print("__________________________")
print (f"total months: {str(num)}")
print (f"total:$ {str(total)}")
print (f"average change:${str(average)}")
print (f"Greatest Increase in Profits:$ {str(maxprof)}")
print (f"Greatest Decrease in Profits:$ {str(minprof)}") |
08ec943c18b1a38f2c17b50f5a52d224c8baebd5 | jaap3/sourcebuilder | /sourcebuilder/pysourcebuilder.py | 2,537 | 3.75 | 4 | from __future__ import with_statement
import textwrap
from contextlib import contextmanager
from sourcebuilder import SourceBuilder
INDENT = ' ' * 4
TRIPLE_QUOTES = '"' * 3
DOCSTRING_WIDTH = 72
class PySourceBuilder(SourceBuilder):
"""
A special SourceBuilder that provides some convenience context managers
for writing well formatted Python code.
"""
def __init__(self, indent_with=INDENT):
super(PySourceBuilder, self).__init__(indent_with=indent_with)
@contextmanager
def block(self, code, lines_before=0):
"""
A context manager for block structures. It's a generic way to start a
control structure (if, try, while, for etc.) or a class, function or
method definition.
The given ``code`` will be printed preceded by 0 or more blank lines,
controlled by the ``lines_before`` parameter. An indent context is
then started.
Example::
sb = PySourceBuilder()
>>>
>>> with sb.block('class Hello(object):', 2):
... with sb.block('def __init__(self, what=\'World\'):', 1):
... sb.writeln('pass')
...
>>> print sb.end()
class Hello(object):
def __init__(self, what='World'):
pass
"""
for i in range(lines_before):
self.writeln()
self.writeln(code)
with self.indent:
yield
def docstring(self, doc, delimiter=TRIPLE_QUOTES, width=DOCSTRING_WIDTH):
"""
Write a docstring. The given ``doc`` is surrounded by triple double
quotes (\"\"\"). This can be changed by passing a different
``delimiter`` (e.g. triple single quotes).
The docstring is formatted to not run past 72 characters per line
(including indentation). This can be changed by passing a different
``width`` parameter.
"""
doc = textwrap.dedent(doc).strip()
max_width = width - len(str(self.indent))
lines = doc.splitlines()
if len(lines) == 1 and len(doc) < max_width - len(delimiter) * 2:
self.writeln(u'%s%s%s' % (delimiter, doc, delimiter))
else:
self.writeln(delimiter)
for line in lines:
if not line.strip():
self.writeln()
for wrap in textwrap.wrap(line, max_width):
self.writeln(wrap)
self.writeln()
self.writeln(delimiter)
|
965670759666c8237775eda5c657ec2d4f8c075a | shivanshrai13/python-sep-batch | /string_suggestion.py | 425 | 3.734375 | 4 | #This problem was asked by Twitter.
'''Implement an autocomplete system. That is, given a query string s and a set of all
possible query strings, return all strings in the set that have s as a prefix.
For example, given the query string de and the set of strings [dog, deer, deal], return
[deer, deal].'''
a = ['dog', 'deer', 'deal']
p = 'b'
lst = []
for i in a:
if i.startswith(p):
lst.append(i)
print(lst)
|
f216eb3533679ea28b02e21f4a03cb68d4048b03 | s19013/my_program_python | /class/shopping.py | 1,425 | 3.78125 | 4 | import math
class CalcFee:
def __init__(self):
"""初期化"""
self.shipping_fee=1000 #送料
self.tax_rate= 0.08#税率
self.value = 0#合計
self.sppedy =500 #速達
def additem(self,price):
"""商品の値段を加算"""
self.value+=price
def calc(self,ques):
"""最終的 金額"""
self.ques=ques
total=self.value + self.shipping_fee
if ques=="n":
pass
else:
total+=self.sppedy
tax=math.ceil(total*self.tax_rate)
v=math.ceil(total+tax)
return v
def main():
shop=CalcFee()
while True:
itemlist={"a":200,"b":300,"c":400}
print("qで終了")
se_item=input("欲しいものを入力\n{}\n".format(itemlist))
if se_item in itemlist:
count=int(input("個数は?\n"))
for i in range(count):
shop.additem(itemlist[se_item])
elif se_item=="q":
break
else:
print("やり直し")
while True:
ques_sppedy=input("速達をご希望ですか?\n y/n:")
if ques_sppedy=="y":
print("合計{}円です".format(shop.calc("y")))
break
elif ques_sppedy=="n":
print("合計{}円です".format(shop.calc("n")))
break
else:
print("やり直し")
print("注文を承りました\nご利用ありがとう御座いました")
main()
|
ec8ebb8d88ea5047f935282acb20648a1bfd7dde | Vikas6206/PythonBasics | /home/sample/After3Hours/ClassConstructor.py | 435 | 3.75 | 4 | class Point:
#defininng the constuctor via init method
def __init__(self, x, y):
self.x = x
self.y = y
def move(self):
print("move")
def draw(self):
print("draw")
point = Point(10, 20)
print(point.x)
class Person:
def __init__(self,name):
self.name=name
def talk(self):
print(f'{self.name} is talking')
#create object
person=Person("Vikas")
person.talk() |
e4e085bec2fd382183fd9747120af7149669b890 | mocaco/dev236x | /final.py | 1,337 | 4.21875 | 4 | # def main function adding_report()
def adding_report(arg):
print('Input an integer to add to the total or "Q" to quit.')
# init default values
loop = True
total = 0
items = ""
# while loop to provide multiple input
while loop:
# default prompt
check = input('Enter an integer or "Q":')
# check if user input is digit
if check.isdigit():
# get total value with type conversion
total = total + int(check)
# check if full report is required
if arg == "A":
# get items value separated with \n new line
items = items + "\n" + check
# check if input is Q
elif check.startswith("Q"):
# check if full report is required
if arg == "A":
print("Items:", items)
print("\nTotal:\n", total)
# set loop to false to break the loop
loop = False
# check if short report is required
else:
print("Total:\n", total)
# set loop to false to break the loop
loop = False
# incorrect input handling
else:
print(check, "is invalid input.")
adding_report("A")
adding_report("T")
|
ee853617dc0be4b097a6b476156e36de97007eb5 | sanjogj43/Test_Project_1 | /main.py | 836 | 3.9375 | 4 | # print("Hello World")
def print_something(name="Sanjog", age=20):
print("my name is ", name, "and my age is ", age)
# print_something()
def print_inf(*people):
for person in people:
print("Person is ", person)
# print_inf("John", "Smith", "Rog")
def do_math(num1, num2):
return num1 + num2
math1 = do_math(2, 7)
math2 = do_math(3, 19)
# print("Math 1 is ",math1,"Math 2 is ",math2)
check = True
def if_else():
if check == False:
print("False")
else:
print("True")
# if_else()
numbers = [1, 2, 3, 4, 5]
def for_loop():
for num in numbers:
print("number is ", num)
# for_loop()
def while_loop():
curr = 0
run = True
while run:
if curr == 50:
run = False
else:
print(curr)
curr += 1
while_loop() |
3cd6b874a651344fd8125af262d2b36b4f660a93 | FelipeKonig/ExerciciosPython | /107Exercicios.py | 1,208 | 4.03125 | 4 | # 1) Imprima os metodos disponiveis para uma lista e para uma tupla.
# 2) Faca um metodo para retornar apenas as diferencas entre as duas de metodos
# 3) Adicione as coordenadas (latitude, longitude) para os dicts professor1, professor2 e professor3. Copie os dicts do arquivo 106.py
professor1 = {'id': 42, 'name': 'Alexandre Abreu', 'age': 30, 'state_origin': 'Minas Gerais', 'courses': ['Inteligência Artificial', 'Mineração de Dados', 'Programação para Internet I', 'Programação para Internet II']}
professor2 = {'id': 37, 'name': 'Denilson Barbosa', 'age': 40, 'state_origin': 'Paraná', 'courses': ['Inteligência Artificial', 'Banco de Dados I', 'Banco de Dados II', 'Programação para Internet I']}
professor3 = dict(id=28, name='Jorge Armino', idade=37)
lista = (dir(list))
tupla = (dir(tuple))
print(lista)
print(tupla)
print(set(lista).symmetric_difference(tupla))
professor1["latitude"] = 10
professor1["longitude"] = 11
professor2["latitude"] = 12
professor2["longitude"] = 13
professor3["latitude"] = 14
professor3["longitude"] = 15
print(professor1['latitude'], professor1['longitude'])
print(professor2['latitude'], professor2['longitude'])
print(professor3['latitude'], professor3['longitude'])
|
9cdd2c3447e1217d39e8ef682f3fc68972cbfd21 | cs-fullstack-2019-fall/python-coding-concepts1-weekly-5-Kenn-CodeCrew | /question2.py | 372 | 4.15625 | 4 | # ### Problem 2:
# Ask the user for a string. If they enter “Kenn”, “Kevin”, “Erin”, or “Autumn” print “Hello Teacher”. Otherwise print “Hello Student”
userInput = input("Enter a string")
if (userInput == "Kenn" or userInput == "Kevin" or userInput == "Erin" or userInput == "Autumn"):
print("Hello Teacher")
else:
print("Hello Student")
|
249d8e81049ab0ab108b6c76d823c0b70927647f | ChenLaiHong/pythonBase | /test/myself/TestStr.py | 4,482 | 4.0625 | 4 | # 字符串切片操作
# 字符串下标可以为负数但是不能超过长度减1
name = "abcdefgbhk age name"
print(name[0])
# 下标为负数就是从字符串后面开始数
print(name[-1])
# 获取字符串片段:name[起始:结束:步长],获取范围[起始,结束),默认步长为1
# 步长> 0,从左到右;步长< 0,从右到左。注意:不能从头部跳转到尾部,也不能从尾部跳转到头部
print(name[0:3])
print(name[4:1:-1])
# 反转字符串
print(name[::-1])
# len(x):计算字符串的字符个数,转义字符占一个
print(len(name))
# find(sub,start=0,end=len(str)):查找字符索引位置[start,end)
print(name.find("bc"))
print(name.find("b", 3))
print(name.find("b", 4, 7))
# rfind :功能跟find一样,只不过这个是从右往左查找
print(name.rfind("b"))
# index 获取某字符,跟find差不多,find在找不到就返回-1,而index则报错
# print(name.index("xx"))
# rindex 跟index一样,只是从右往左
# print(name.rindex("xx"))
# count(sub,start,end=len(str)),计算某个字符串出现的个数
print(name.count("b"))
# 转换操作
# replace(old,name[,count]):给定新字符串替换原字符串中的旧字符
# old :需要被替换的旧字符;new :替换后的新字符;count :替换的个数,省略则表示替换全部
# 返回替换后的字符串,但是并不会改变原字符串本身
print(name.replace("b", "w"))
print(name.replace("b", "w", 1))
# capitalize()返回首字母大写后的新字符串,并不会改变字符串本身
print(name.capitalize())
# title()返回每个单词首字母大写后的新字符串,不会改变本身
print(name.title())
# lower():将字符串每个字符变小写
name1 = "Wo Xue Python"
print("变小写----"+name1.lower())
# upper():将所有字母变成大写
print(name1.upper())
# 字符串填充压缩操作
# ljust(width,fillchar)表示原字符串靠左。width:指定结果字符串的长度;fillchar:
# 如果原字符串长度 < 指定长度时,填充过去的字符;返回填充完毕的字符
# 填充的字符是一个字符
name2 = " abwwoolcoo"
print(name2.ljust(18, "x"))
# rjust(width,fillchar)原字符串靠右,跟rjust差不多
print(name2.rjust(16, "x"))
# center(width,fillchar)原字符在中间,不能平分时右边比左边多
print(name2.center(18, "x"))
# lstrip(chars):从左侧开始移除指定的存在的字符(单个看),遇到不是指定的字符时就返回
print(name2.lstrip())
# rstrip(chars):从右侧开始移除指定字符
print(name2.rstrip("co"))
# 字符串的分割拼接
# split(sep,maxsplit):将一个大的字符串分割成几个子字符串
# sep:分隔符;maxsplit:最大分割次数,默认为有多少分多少,返回子字符串组成的列表
info = "zs-18-178-0220-6658456"
print(info.split("-"))
print(info.split("-", 3))
# partition(sep),根据指定的分隔符将字符串分成三部分(分隔符左侧内容,分隔符,分隔符右侧内容)
# 返回一个元组类型
print(info.partition("-"))
# rpartition(sep)从右边找,跟partition很像
print(info.rpartition("-"))
# splitlines(keepends)按照换行符(\r,\n)将字符串拆成多个元素,保存在列表中
# keepends:是否保留换行符,bool类型
info2 = "wo \n xue \r python"
print(info2.splitlines())
# join(iterable):iterable可迭代的对象:字符串、元组、列表。将给定的可迭代对象进行拼接
items = ["wo", "xue", "python"]
print("-".join(items))
# 字符串判定操作
# isalpha(),判断字符串中所有字符是否都是字母
print("abc".isalpha())
print(name.isalpha())
# isdigit(),判断字符串中所有字符都是数字
print("15632".isdigit())
print(name.isdigit())
# isalnum()是否是数字或字母
print("123abc".isalnum())
# isspace()字符串中是否所有字符都是空白符包括空格、缩进、换行等不可见转义符
print(" ".isspace())
print(name2.isspace())
# startwith(prefix,start=0,end=len(str)):判定一个字符串是否以某个前缀开头
# prefix:需要判定的前缀字符串;start:判定起始位置(能取到);end:判定结束位置(不包括)
print(name.startswith("a"))
print(name.startswith("a", 3, 7))
# endwith(prefix,start=0,end=len(str)):判定一个字符串以某个后缀结束
print(name.endswith("e"))
# in 判定一个字符串,是否被另一个字符串包含
# not in 判定一个字符串,是否不被另一个字符串包含
|
ffbeca9acc56785f04fe937960409337042309fe | XxSlowMOxX/ProjektUnikot | /gameclass.py | 686 | 3.65625 | 4 | class Game:
def __init__(self, Players):
self.Players = Players
def addPlayer(self,player):
self.Players.append(player)
def getMPos(self):
return [self.Players[0].x, self.Players[0].y, self.Players[0].rep]
def setOPos(self, opos):
# TODO
self.Players[1].x = opos[0]
self.Players[1].y = opos[1]
self.Players[1].rep = opos[2]
class Player:
def __init__(self, sx, sy, sid, col):
self.x = sx
self.y = sy
self._id = sid
self.rep = ">"
def move(self, vx, vy, level):
if(level[self.x+vx][self.y+vy] == " "):
self.x += vx
self.y += vy
|
e8a3b0b2506fb964820d64b6fe2b37350b111465 | Jordan-Rowland/oop-practice | /notebook/notebook.py | 2,197 | 3.546875 | 4 | import datetime
# Store the next available ID for all new notes
last_id = 0
class Note:
"""Represents note in the notebook. Match against a string in searches and store tags for
each note."""
def __init__(self, memo, tags=''):
"""Initialize a note with memo and optional space-separated tags. Automatically set the
note's creation date and a unique ID."""
self.memo = memo
self.tags = tags
self.creation_date = datetime.date.today()
global last_id
last_id += 1
self.id = last_id
def match(self, query):
"""Determine if this note matches the filter query. Return True if it matches, False
otherwise. Search is case insensitive and matches both text and tags."""
return query.lower() in self.memo.lower() or query.lower() in self.tags.lower()
class Notebook:
"""Represent a collection of notes that can be tagged, modified, and searched."""
def __init__(self):
"""Initialize a new notebook with an empty list."""
self.notes = []
def new_note(self, memo, tags=''):
"""Create a new note and add it to the list."""
self.notes.append(Note(memo, tags))
def _find_note(self, note_id):
"""Return the note with the passed ID."""
note = [note for note in self.notes
if str(note_id) == str(note.id)]
if not note:
return None
return note[0]
def modify_memo(self, note_id, memo):
"""Modify the memo of the note with the passed in ID."""
note = self._find_note(note_id)
if not note:
return False
note.memo = memo
return True
def modify_tags(self, note_id, tags):
"""Modify the tags of the note with the passed in ID."""
note = self._find_note(note_id)
if not note:
return False
note.tags = tags
return True
def search(self, query):
"""Find all notes that match the given query string."""
if not self.notes:
print('\nNo matching notes!')
return None
return [note for note in self.notes
if note.match(query)]
|
a4908d1ebe0bbc9d5dc817cfc71c0373b2cbe184 | EltonZhong/leetcode | /middle/PrefixTree.py | 2,747 | 4.09375 | 4 | # coding=utf-8
"""
https://leetcode.com/problems/implement-trie-prefix-tree/description/
"""
from typing import Any
class Trie:
"""
trie
"""
class Node:
"""
node
"""
def __init__(self, ch: Any):
self.children = []
self.char = ch
self.is_leaf = False
self.word = None
if ch is None:
self.is_leaf = True
def insert_children(self, ch: Any, word: str=None):
"""
:param word:
:param ch:
"""
child = Trie.Node(ch)
self.children.append(child)
child.word = word
return child
def __init__(self) -> None:
"""
Initialize your data structure here.
"""
self.root = Trie.Node(None)
def insert(self, word: str):
"""
Inserts a word into the trie.
:type word: str
:rtype: void
"""
node = self.root
for ch in word:
found_child = self.find_child_with_char(node, ch)
if not found_child:
node = node.insert_children(ch)
else:
node = found_child
node.insert_children(None, word=word)
def search(self, word: str):
"""
Returns if the word is in the trie.
:type word: str
:rtype: bool
"""
node = self.find_node_with_prefix(word)
if not node:
return False
for child in node.children:
if child.is_leaf:
return True
return False
def startsWith(self, prefix: str):
"""
Returns if there is any word in the trie that starts with the given prefix.
:type prefix: str
:rtype: bool
"""
return not not self.find_node_with_prefix(prefix)
def find_node_with_prefix(self, prefix: str) -> Any:
"""
Returns if there is any word in the trie that starts with the given prefix.
:type prefix: str
:rtype: bool
"""
node = self.root
for ch in prefix:
found_child = self.find_child_with_char(node, ch)
if not found_child:
return None
node = found_child
return node
def find_child_with_char(self, node: Node, char: str):
"""
:param char:
:param node:
:return:
"""
for child in node.children:
if child.char == char:
return child
return None
# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)
|
8d07c12136d2831cc08935bb89266ddb6f62c947 | gumityolcu/Binari | /Code/syllabliser.py | 3,972 | 3.875 | 4 | """
Türkçede kelime içinde iki ünlü arasındaki ünsüz,
kendinden sonraki ünlüyle hece kurar: a-ra-ba, bi-çi-mi-ne, in-sa-nın, ka-ra-ca vb.
Kelime içinde yan yana gelen iki ünsüzden ilki kendinden önceki ünlüyle,
ikincisi kendinden sonraki ünlüyle hece kurar: al-dı, bir-lik, sev-mek vb.
Kelime içinde yan yana gelen üç ünsüz harften ilk ikisi kendinden önceki ünlüyle,
üçüncüsü kendinden sonraki ünlüyle hece kurar: alt-lık, Türk-çe, kork-mak vb.
"""
vowels = ["a", "ā", "ǎ", "â", "e", "ı", "i", "ī", "î", "o", "ö", "ô", "ō", "u", "ū", "û", "ü"]
longVowels = ["ā", "â", "ī", "î", "ô", "ū", "û"]
def isVowel(c):
return c in vowels
def isLong(c):
return c in longVowels
def get_syllables(word):
if len(word) < 3:
return [word]
if word[0:8]=="<mahlas>":
ret=["<mahlas>"]
if word[8:]!='':
ret+=get_syllables(word[8:])
return ret
if word=="<izafe>" or word=="<beginCouplet>" or word=="<endLine>" or word=="<endCouplet>":
return [word]
# We will assign each character to a syllable in the array inSyllable
inSyllable = [-1] * len(word)
vowelCount = 0
vowelPoss = list()
# Count the number of vowels to find the number of syllables
for c in range(0, len(word)):
if isVowel(word[c]):
vowelCount = vowelCount + 1
inSyllable[c] = vowelCount
vowelPoss.append(c)
# First character belongs to the first syllable
inSyllable[0] = 1
# Last character belongs to the last syllable
inSyllable[-1] = vowelCount
# Assign syllables and edit them according to the logical rule
for c in range(1, len(word) - 1):
if not isVowel(word[c]):
if word[c]=="'":
# ' symbol is always in the second position after the letter n in our data, thus the index c-1 will never go below 0
inSyllable[c] = inSyllable[c-1]
elif isVowel(word[c + 1]):
inSyllable[c] = inSyllable[c + 1]
else:
inSyllable[c] = inSyllable[c - 1]
# Construct syllables from inSyllable array
syllables = [""]*vowelCount
for i in range(0,len(inSyllable)):
syllables[inSyllable[i]-1]=syllables[inSyllable[i]-1]+word[i]
return syllables
def elongateMetre(met):
longMetre = []
for a in met:
if a == "-.":
longMetre.append("-")
longMetre.append(".")
else:
longMetre.append(a)
return longMetre
def get_chars(str):
chrs = list()
c = 0
while c < len(str):
if str[c] == "<":
c2 = c
while str[c2] != ">":
c2 += 1
chrs.append(str[c:c2 + 1])
c = c2
else:
chrs.append(str[c])
c += 1
return chrs
def get_aruz(word):
word = word.replace('·', '')
word = word.replace('-', '')
word = word.replace('\'', '')
word = word.replace(' ', '')
sylls = get_syllables(word)
aruz = list()
for i in sylls:
if i == "<mahlas>":
aruz+=[".","-","-"] # . - - for Binârî
elif i=="<izafe>":
aruz.append(".") # This is a placeholder, the <izafe> tokens is not compared against the actual metre in the FST implementation
elif isVowel(i[-1]):
if not isLong(i[-1]):
aruz.append(".")
else:
aruz.append("-")
else:
if (not isVowel(i[-2])) or (isLong(i[-2]) and i[-1] != "n"):
aruz.append("-.")
else:
aruz.append("-")
return aruz
if __name__=="__main__":
print(get_syllables("bîrışk"))
print(get_syllables("abicim"))
print(get_syllables("nasıl"))
print(get_syllables("âbidelîk"))
print(get_syllables("dünyadüzmü"))
print(get_syllables("altıbuçulmilyon"))
print(get_syllables("yüzdeiki"))
|
03ed5477761ec59a0e7f02c18d80f21e44617ad6 | doctone/myKatas | /piglatin.py | 731 | 4.375 | 4 | '''
Move the first letter of each word to the end of it, then add "ay" to the end of the word. Leave punctuation marks untouched.
Examples
pig_it('Pig latin is cool') # igPay atinlay siay oolcay
pig_it('Hello world !') # elloHay orldway !
'''
def pig_it(text):
#create empty list of new words
new_words = []
final_words = []
#turn text in to list of words
#iterate through each word
for word in text.split():
#move first letter of word to the end of the word
new_words.append(word[1:]+word[0])
#add word + 'ay' to final word list
for word in new_words:
final_words.append(word +'ay')
return ' '.join(final_words)
print(pig_it('this is a test of my new function')) |
d14a8253d21e1cb306b5f3805b5e189bb685322c | opavelkachalo/phoneCallsApp | /main.py | 1,035 | 3.890625 | 4 | from src.classes import Abonnent
import time
def main():
while True:
number = input("Enter your phone number (or press RETURN to exit): ")
if not number:
break
abonnent = Abonnent(int(number))
time.sleep(1)
if abonnent.enter_status:
while True:
print("\nSelect an action:\n1 - Call statistics\n2 - Call history with other contact\n3 - Exit")
choice = int(input("Your choice (enter a number): "))
if choice == 1:
abonnent.statistics()
elif choice == 2:
target_user = int(input("Enter the target phone number: "))
while not target_user:
target_user = int(input("Phone number not found. Try again: "))
abonnent.history(target_user)
else:
break
time.sleep(1)
print("<exiting program>")
time.sleep(1)
if __name__ == '__main__':
main()
|
8e76fe2a8c6d40facc9be2b5a59a2f2ac0f844e9 | melissa1824-cmis/melissa1824-cmis-cs2 | /cs2quiz2.py | 1,713 | 4.15625 | 4 | import math
#PART 1: Terminology
#1) Give 3 examples of boolean expressions.
#a) 3 == 3 #point
#b) 5 != 8 #point
#c) 45 > 23 #point
#
#2) What does 'return' do?
# returns/prints the value/result of the function. #point
#
#3) What are 2 ways indentation is important in python code?
#a) It knows that the next line is part of the function #point
#b) It knows that the next line of the function has to be executed #point
#
#PART 2: Reading
#Type the values for 12 of the 16 of the variables below.
#
#problem1_a) -36 #point
#problem1_b) square root of 3 #point
#problem1_c) 0 #point
#problem1_d) 5 #point
#
#problem2_a) True #point
#problem2_b) False #point
#problem2_c) True
#problem2_d) True #point
#
#problem3_a) 0.3 #point
#problem3_b) 0.5 #point
#problem3_c) 0.5 #point
#problem3_d) 0.5 #point
#
#problem4_a) 5
#problem4_b) 5 #point
#problem4_c)
#problem4_d)
#
#points for 23, 24, 25, 26, 27, 28, 30, 31
# 8 points
print "Type in 3 different numbers (decimals are OK!)"
def number1(number1):
number1 = float(raw_input("A: "))
return number1
def number2(number2):
number2 = float(raw_input("B: "))
return number2
def number3(number3):
number3 = float(raw_input("C: "))
return number3
def compare(number1, number2, number3):
if number1 > number2 and number1 > number3:
return number1
elif number2 > number1 and number2 > number3:
return number2
else:
return number3
def output(number1, number2, number3):
return """
""".format(compare, number1, number2, number3)
def main():
number1 = float(raw_input("A: "))
number2 = float(raw_input("B: "))
number3 = float(raw_input("C: "))
print output(number1, number2, number3)
main()
|
b2481f42ba00f5d6f1ca8d23e92c40aee235ef4b | fpavanetti/python_lista_de_exercicios | /aula23_explicação.py | 2,067 | 3.984375 | 4 | '''
Aula 23 - Tratamento de erros e exceções
----- ERROS ACONTECEM: SEMPRE -----
Existem erros de diferentes tipos
> primt(x), por exemplo, é um erro de sintaxe
O programa estar escrito corretamente não quer dizer que ele está "certo"
print('Oi')
print(x) -> x não foi inicializado. Erro semânetico
Quando o erro não é de ordem sintático, não costumamos chamar de erro,
mas sim de EXCEÇÃO. No caso demonstrado acima, é uma exceção do tipo 'NameError'
n = int(input('Num') > No caso de não ser inserido um número inteiro, retornará
'ValueError' < isso é uma exceção
a = int(input('Numerador: '))
b = int(input('Denominador: '))
r = a / b
print(f'O resultado é {r})
'ZeroDivsionError': erro de divisão por zero
r = 2 / '2'
'TypeError'
lst = [3, 6, 4]
print(lst[3])
'IndexError' / em dicionários: 'KeyError'
import uteis
'ModuleNotFoundError'
'EOFError'
... Existem muitas exceções em Python
Toda exceção é filha de uma classe maior chamada de Exception
> para tratamento de erros e exceções: comandos try/except
try
operação
except
falhou
Verificar a conexão de um site com um Python:
import urllib
import urllibr.request
erros: urllib.error.URLError
site.read() < acessa o código HTML do site
ACESSO A ARQUIVOS
open(nome do arquivo, 'rt') #readtext
open(nome, 'wt+') #writetext +(paracriar)
open('at') append text
readlines
read
'''
try: # tentar
a = int(input('Numerador: '))
b = int(input('Denominador: '))
r = a / b
except (ValueError, TypeError):
print('Infelizmente tivemos um problema com os tipos de dados que você digitou.')
except ZeroDivisionError:
print('Não é possível dividr um número por zero!')
except KeyboardInterrupt:
print('O usuário preferiu não informar os dados!')
except Exception as erro:
print(f'O erro encontrado {erro.__cause__}')
else: #deu certo (opcional)
print(f'O resultado é {r:.1f}')
finally:
print('Volte sempre! Muito obrigado.')
|
23cc9b0343cf4491611295f2a52e9affcfcb7d01 | TheMoira/PythonLearning | /first_file/arithmetics.py | 285 | 3.9375 | 4 | import math
print(10/3)
print(10//3)
print(10**3)
x = 2.9
print(round(x))
print(math.ceil(x))
is_night = True
if (math.floor(x) > 1):
print("x is big")
elif is_night:
print("night")
else:
print("day" + "*" * 20)
if is_night and x:
print("shit") |
9bd2f9e19daa516be1ebe72a793f7057590a9ae5 | alcazar007/python-challenge | /PyBank/main_Second_Attempt.py | 4,109 | 4.375 | 4 | ## PyBank
'''
* In this challenge, you are tasked with creating a Python script for analyzing
the financial records of your company. You will give a set of financial data
called [budget_data.csv](PyBank/Resources/budget_data.csv).
The dataset is composed of two columns: `Date` and `Profit/Losses`.
* Your task is to create a Python script that analyzes the records to calculate each of the following:
* The total number of months included in the dataset
* The net total amount of "Profit/Losses" over the entire period
* The average of the changes in "Profit/Losses" over the entire period
* The greatest increase in profits (date and amount) over the entire period
* The greatest decrease in losses (date and amount) over the entire period
* As an example, your analysis should look similar to the one below:
```text
Financial Analysis
----------------------------
Total Months: 86
Total: $38382578
Average Change: $-2315.12
Greatest Increase in Profits: Feb-2012 ($1926159)
Greatest Decrease in Profits: Sep-2013 ($-2196167)
```
* In addition, your final script should both print the analysis to the terminal and export a text file with the results.
'''
# Imports
import os, csv
# CSV Path
data_file = os.path.join("Resources", "budget_data.csv")
#store objects
profit = []
monthly_changes = []
date = []
# Variables
total_months = 0
total_profit = 0
total_change = 0
initial_profit = 0
# Open csv with reader, header, and F statement
with open (data_file, newline="", encoding="UTF-8") as csv_file:
csv_reader = csv.reader(csv_file, delimiter=",")
csv_header = next(csv_file)
# Loop through the data to variables
for row in csv_reader:
# use count for calculating the number of months in dataset
total_months = total_months + 1
# need to collect data using .append for greatest increase and decrease in profits
date.append(row[0])
# need to collect data using .append profit information and calculate the total profit
profit.append(row[1])
total_profit = total_profit = int(row[1])
# Calculate the average change in profits
final_profit = int(row[1])
# Calculate average change in profit
monthly_change_profits = final_profit - initial_profit
# Store these monthly changes in a list
monthly_changes.append(monthly_change_profits)
# calculate total profits by adding total changes = monthly changes
total_change = total_change + monthly_change_profits
# profits
initial_profit = final_profit
# calculate the average change in profits
average_change_profits = (total_change/total_months)
#Find the max and min change in profit
greatest_increase_profits = max(monthly_changes)
greatest_decrease_profits = min(monthly_changes)
increase_date = date[monthly_changes.index(greatest_increase_profits)]
decrease_date = date[monthly_changes.index(greatest_decrease_profits)]
print("----------------------------")
print("# Finaancial Analysis")
print("total Months: " + str(total_months) + "\n")
print("Total Profits: " + "$" + str(total_profit) + "\n")
print("Average Change:" + "$" + str(int(average_change_profits)))
print("Greatest Increase in Profits: " + str(increase_date) + " ($" + str(greatest_increase_profits) + ")\n")
print("Greatest Decrease in profits: " + str(decrease_date) + " ($" + str(greatest_decrease_profits) + ")\n")
print("------------------------------------------------------------")
with open('financial_analysis.txt', 'w') as text:
text.write("------------\n")
text.write(" Financial Analysis"+ "\n")
text.write("-------------------------\n\n")
text.write(" Total Months: " + str(total_months) + "\n")
text.write(" Total Profits: " + "$" + str(total_profit) + "\n")
text.write(" Average Change: " + "$" + str(int(average_change_profits)) + "\n")
text.write(" Greatest Increase in Profits: " + str(increase_date) + " ($" + str(greatest_increase_profits) + ")\n")
text.write(" Greatest Decrease in Profits: " + str(decrease_date) + " ($" + str(greatest_decrease_profits) + ")\n")
text.write(" -----------------------\n")
|
ddb1a8d6ee748a4efaaf3d9fe160ae24417754ab | kolo-abb/Graph_segmentator_app | /segmentation_app/utils.py | 414 | 3.875 | 4 |
def convertToBinaryData(filename):
#Convert digital data to binary format
with open(filename, 'rb') as file:
blobData = file.read()
return blobData
def writeTofile(data, filename):
# Convert binary data to proper format and write it on Hard Disk
print(filename)
with open(filename, 'wb') as file:
file.write(data)
print("Stored blob data into: ", filename, "\n")
|
80731a463c41a7484990e26e8eafc6f011909b18 | harshath2017/psp-manual_17B37 | /matrix.9.py | 519 | 3.953125 | 4 | def matrixmulti(X, Y):
# X dimension is M x N
# Y dimension is N x P
M = len(X)
N = len(X[0])
P = len(Y[0])
# resultant matrix dimension is M x P
Z = [[0] * P for row in range(M)]
if N != len(Y):
print ("Incorrect dimensions.")
return
for i in range(M):
for j in range(P):
for k in range(N):
Z[i][j] += X[i][k] * Y[k][j]
return Z
X = [1,2],[3,4]
Y = [2,1],[4,6]
print(matrixmulti(X,Y))
|
1044b6463b9d0db8531df31aeb3f50af57b1a8e4 | rmcarthur/acme_labs | /Lab16v1.py | 2,954 | 3.5625 | 4 | import numpy as np
import math
import scipy as sp
from matplotlib import pyplot as plt
## Problem 1 ##
def Newton(func, error, maxiter, guess, prime = None):
h = 1e-6
converge = True
iterations = 0
change = np.inf
x0 = guess
def NoPrime(xold, func):
deriv = (func(xold+h)-func(xold))/h
return xold - func(xold)/deriv
def WithPrime(xold, func, prime):
return xold-(func(xold)/prime(xold))
xnew = -10.
while np.any(change - error > 0 ):
if prime is None:
xnew = NoPrime(x0, func)
iterations += 1
change = abs(x0 - xnew)
x0 = xnew
if iterations >= maxiter:
converge = False
print ('Convergence: False')
return xnew
else:
xnew = WithPrime(x0, func, prime)
iterations += 1
print iterations
change = abs(x0 - xnew)
x0 = xnew
if iterations >= maxiter:
converge = False
print ('Convergence: False')
return xnew
print ('convergence: {} Error: {} Iterations: {}'.format(converge, change, iterations))
return xnew
def f1(x):
return np.cos(x)
def f1prime(x):
return -np.sin(x)
def f2(x):
return x**2*np.sin(1/x)
def f2prime(x):
return 2*x*np.sin(1/x)-np.cos(1/x)
def f3(x):
return (np.sin(x)/x)-x
def f4(x):
return x**2-1
def f5(x):
return x**3-x
def f6(x):
return x**(1/3)
small = 1e-10
print Newton(f1,.0000000001, 10, 1, f1prime )
print Newton(f2, small, 10, 1, f2prime)
print Newton(f3, small, 10, 1, None)
print Newton(f4, small, 10, 2, None)
print Newton(f5, small, 10, 2, None)
print Newton(f4, small, 10, -2, None)
print Newton(f4, small, 10, -2, None)
#print Newton(f6, small, 10, 1)
### Problem 2 ###
def polyJulia(p, realmin, realmax, imin, imax,
maxiter = 200, res = 500, tol = 1e-5):
r = 3
roots = p.roots
roots = np.around(roots, r)
x = np.linspace(realmin, realmax, res)
y = np.linspace(imin, imax, res)
X,Y = np.meshgrid(x,y)
deriv = p.deriv()
c1 = Newton(p, tol, maxiter, X+1j*Y, deriv)
c2 = np.around(c1, r)
for i, root in enumerate(roots):
c2[c2==root]=i+10
s1 = set(c2.flatten())
print s1
plt.pcolormesh(X,Y,c2)
plt.show()
p1 = np.poly1d([1,-2,-2,2])
p2 = np.poly1d([3,-2,-2,2])
p3 = np.poly1d([1,3,-2,-2,2])
p4 = np.poly1d([1,0,0,-1])
polyJulia(p1, -.5, 0, -.25, .25)
polyJulia(p2, -1, 1, -1, 1)
polyJulia(p3, -1, 1, -1, 1)
polyJulia(p4, -1, 1, -1, 1)
### Problem 3 ####
x = np.linspace(-1.5,.5, 500)
y = np.linspace(-1, 1, 500)
X,Y = np.meshgrid(x,y)
C = X + 1j*Y
xold = C.copy()
xnew = np.zeros_like(C, dtype = int)
for i in xrange(30):
try:
xold = xold * xold + C
except:
pass
xnew[np.real(xold) < 1e10] += 1
plt.pcolormesh(X,Y, xnew)
plt.show()
|
0969c35f3081cf507a8000199978d43fc88e2b9e | sahilkumar171193/mycodes | /swap2number.py | 137 | 3.859375 | 4 | a=6
b=5
temp=a
a=b
b=temp
print(a)
print(b)
a=a+b
b=a-b
a=a-b
print(a)
print(b)
a,b=b,a
print(a)
print(b)
|
beb22c5ae57e61e41953fe68ee5cec3c08ea18bd | knut0815/Book | /Part 2/Chapter 11/Multinomial_logistic_regression_using_iris_dataset(Listing_13).py | 1,282 | 3.59375 | 4 | #import the required libraries for model building and data handling.
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score,confusion_matrix
from sklearn.model_selection import train_test_split
#Load the dataset and generate the train and test datasets with features and labels.
data = load_iris()
dataset = list(zip(data.data, data.target))
train , test = train_test_split(dataset, test_size=0.25)
train_features = []
train_labels = []
test_features = []
test_labels = []
for item in train:
train_features.append(item[0])
train_labels.append(item[1])
for item in test:
test_features.append(item[0])
test_labels.append(item[1])
#Build the model with Newton conjugate gradient solver for multinomial classification.
model = LogisticRegression(solver='newton-cg') # since, multiclass
model.fit(train_features,train_labels)
#Get the model parameters.
print(model.coef_,model.intercept_)
#test the model.
results = model.predict(test_features)
acc = accuracy_score(test_labels,results)
cm = confusion_matrix(test_labels,results,labels=[0,1,2])
print(acc)
#print the confusion matrix.
for row in cm:
for item in row:
print(item, end='\t')
print()
|
1f2262d497bd7b4046de491f8a6187f45abc06c9 | wxyBUPT/leetCode.py | /dp/Solution_309.py | 2,681 | 3.765625 | 4 | #coding=utf-8
__author__ = 'xiyuanbupt'
# e-mail : xywbupt@gmail.com
'''
309. Best Time to Buy and Sell Stock with Cooldown Add to List QuestionEditorial Solution My Submissions
Total Accepted: 31636
Total Submissions: 80223
Difficulty: Medium
Contributors: Admin
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)
Example:
prices = [1, 2, 3, 0, 2]
maxProfit = 3
transactions = [buy, sell, cooldown, buy, sell]
'''
class Solution(object):
# 反正都是追求利益最大化,在最大化的状态之间切换
def maxProfitUseDp(self, prices):
if len(prices) < 2:
return 0
prices_len = len(prices)
s0 = [0] * prices_len
s1 = [0] * prices_len
s2 = [0] * prices_len
s0[0] = 0
s1[0] = -prices[0]
s2[0] = float('-inf')
for i in range(1,prices_len):
s0[i] = max(s0[i-1], s2[i-1])
s1[i] = max(s1[i-1], s0[i-1] - prices[i])
s2[i] = s1[i-1] + prices[i]
return max(s0[prices_len-1], s2[prices_len-1])
def maxProfit(self, prices):
if len(prices) < 2:
return 0
sell, buy, prev_sell, prev_buy = 0, -prices[0], 0, 0
for price in prices:
prev_buy = buy
buy = max(prev_sell - price, prev_buy)
prev_sell = sell
sell = max(prev_buy + price, prev_sell)
return sell
# 其实有更好的想法
def maxProfitBad(self, prices):
"""
降到最低就买,升到最高就卖
:type prices: List[int]
:rtype: int
"""
p_len = len(prices)
dp = [0] * p_len + 1
buy_point = -1
# 添加哨兵
prices.append(float('inf'))
for i in range(0, p_len):
# 还没有找到买入点
if buy_point < 0 :
if prices[i] < prices[i+1]:
if i == 0 or dp[i-1]>0:
buy_point = i
continue
# 找到买入点,但是降价或者股票价格不变直接卖出股票
if prices[i] >= prices[i+1]:
dp[i+1] = prices[i] - prices[buy_point] + dp[buy_point]
buy_point = -1
# 其他情况继续
return dp[p_len]
|
dc74bf4ad3eeacfbccded9f2a210940ca67a0911 | vishalikannan96/python-solution | /problemset3/proset3_8.py | 814 | 3.984375 | 4 | #Write a function called is_abecedarian that returns True if the letters in a word appear in alphabetical
# order (double letters are ok). How many abecedarian words are there? (i.e) "Abhor" or "Aux" or "Aadil"
# should return "True" Banana should return "False"
'''def is_abecedarian(word):
word=list(word)
if word==sorted(word):
return True
else:
return False'''
def is_abecedarian_fun(word):
count=0
print(word)
list1=list(word)
for i in range(len(list1)-1):
if list1[i]<=list1[i+1]:
count+=1
if len(list1)==(count+1):
return True
else:
return False
word=[]
for i in (1,4):
x=input('Enter word:')
word.append(x)
print(word)
for words in word:
print(is_abecedarian_fun(words))
#print(is_abecedarian(word))
|
719b2648bc2848890cf516de7983b163c2847829 | ShenTonyM/LeetCode-Learn | /Q410SplitArrayLargestSum.py | 915 | 3.578125 | 4 | class Solution1(object):
def isValid(self, nums, m, max_sum):
"""
:rtype: bool
"""
count = 0
accumu = 0
for i in range(len(nums)):
accumu += nums[i]
if accumu > max_sum:
count += 1
if count >= m:
return False
accumu = nums[i]
return True
def splitArray(self, nums, m):
"""
:type nums: List[int]
:type m: int
:rtype: int
"""
result_max, result_min = sum(nums), max(nums)
left, right = result_min, result_max
while left < right:
mid = (left + right) // 2
if self.isValid(nums, m, mid):
right = mid
else:
left = mid + 1
return left
if __name__ == '__main__':
print(Solution1().splitArray([7,2,5,10,8], 2)) |
1a47efcb48e7ffa277ad6b572d6dfc345091037c | juda/scheme | /mutual_with_text.py | 2,811 | 3.53125 | 4 | '''mutual with text'''
import numbers
from pair import *
import sys
def parentheseBalance(statement):
res=0
for i in statement:
if i=='(':
res+=1
elif i==')':
res-=1
if res<0:
raise SyntaxError('Unmatched parentheses')
return res==0
def isnumber(number):
if isinstance(number,numbers.Number):
return True
try:
int(number)
except:
try:
float(number)
except:
return False
return True
return True
def isQuoted(exp):
return isinstance(exp,str) and exp.find("'")==0
def isObject(exp,env):
try:
return isinstance(exp,str) and env.findObject(exp)!=None
except:
return False
def isstring(exp):
return isinstance(exp,str) and len(exp)>1 and exp[0]=='"' and exp[-1]=='"'
def transQuoted(exp):
if isQuoted(exp):
return exp[1:]
return exp
def transnumber(number):
if isinstance(number,numbers.Number):
return number
else:
try:
return int(number)
except:
return float(number)
def tostring(exp):
if isinstance(exp,list):
return '('+' '.join(map(tostring,exp))+')'
else:
return str(exp)
def showPair(exp):
if exp==Nil:
return ''
if isnumber(exp):
return transnumber(exp)
if isQuoted(exp):
return transQuoted(exp)
if isstring(exp):
return exp[1:-1]
if isinstance(exp,list):
return tostring(exp)
if isinstance(exp,tuple):
return exp
if isinstance(exp,str):
return exp
if isinstance(exp.car(),Pair):
res='(%s)'%(showPair(exp.car()),)
else:
res='%s'%(showPair(exp.car()),)
temp=showPair(exp.cdr())
if temp!='':
res+=' %s'%(temp,)
return res
def display(val):
if val is not None:
if isinstance(val,Pair):
sys.stdout.write('(%s)'%(showPair(val),))
elif isinstance(val,bool):
if val==True:
sys.stdout.write('#t')
elif val==False:
sys.stdout.write('#f')
elif isstring(val):
sys.stdout.write(val[1:-1])
elif isQuoted(val):
sys.stdout.write(val[1:])
else:
sys.stdout.write(tostring(val))
def transValue(i,env):
if isinstance(i,numbers.Number):
return i
elif isObject(i,env):
temp=env.findObject(i)
if isinstance(temp,list):
return temp
elif isnumber(temp):
return transnumber(temp)
else:
return temp
elif isnumber(i):
return transnumber(i)
elif isQuoted(i):
return i
elif isstring(i):
return i
else:
return i |
e4a6f924056974ed1d4eff0bd7bd6e976e284486 | spgeise/Restaurant-Selector | /Main.py | 4,964 | 3.53125 | 4 | from Files.GetRestaurants import RestaurantList
import time, sys, os
from random import randint
rest_dict = {}
final_options = []
def select_restaurants():
x = list(map(int, input("Make your selections: ").split()))
print('\n')
for i in x:
print(rest_dict[i])
final_options.append(rest_dict[i])
print('\n')
def display_list_onscreen():
RestaurantList.results.sort() # Alphabetize lists for display
all_restaurants_even = RestaurantList.results[0:][::2]
all_restaurants_odd = RestaurantList.results[1:][::2]
if len(RestaurantList.results) % 2 == 0:
a = 0
while a < len(all_restaurants_even):
for r_item in all_restaurants_even:
item_index = all_restaurants_even.index(r_item)
right_column = item_index + len(all_restaurants_even) + 1
line = '{:<3}{:<35} {:>35} {:>3}'.format(str(item_index + 1), r_item,
right_column, all_restaurants_odd[item_index])
try:
print(line)
rest_dict.update({item_index + 1: r_item})
rest_dict.update({right_column: all_restaurants_odd[item_index]})
a += 1
except IndexError:
pass
else:
a = 0
last = len(all_restaurants_even) - 1
while a < len(all_restaurants_even) - 1:
for r_item in all_restaurants_even:
item_index = all_restaurants_even.index(r_item)
right_column = item_index + len(all_restaurants_even) + 1
line = '{:<3}{:<35} {:>35} {:>3}'.format(item_index + 1, r_item,
right_column, all_restaurants_odd[item_index])
try:
print(line)
rest_dict.update({item_index + 1: r_item})
rest_dict.update({right_column: all_restaurants_odd[item_index]})
a += 1
except IndexError:
pass
print(str(last + 1), all_restaurants_even[last])
rest_dict.update({last: all_restaurants_even[last]})
print('\n')
def main_program_flow():
# Begin building the list using calls to the RestaurantList class.
# This section sends API requests and assembles the list.
# It then removes duplicates and sets the list as global for use in the next section.
print("Starting 5-2-1...", "\n")
time.sleep(1.25)
getzip = input("Enter your zip code: ") # Take zip code from user
try:
r_list = RestaurantList(getzip) # Create instance of RestaurantList
print("\n", "Getting list of nearby restaurants...", "\n")
r_list.get_request(r_list.query) # Send GET request for json data
r_list.build_list(r_list.y) # Begin assembling restaurant list
w = 0
if len(RestaurantList.results) > 0: # Check for multiple pages (20 per. 3 total)
while w < 2:
if len(RestaurantList.results) > 39:
r_list.next_page(r_list.n)
time.sleep(1)
r_list.get_request(r_list.next)
r_list.build_list(r_list.y)
w = 2
elif len(RestaurantList.results) == 20:
r_list.next_page(r_list.n)
time.sleep(1)
r_list.get_request(r_list.next)
r_list.build_list(r_list.y)
w += 1
else:
w = 2
else:
print('No restaurants found...')
main_program_flow()
except ValueError:
print("\n", "Not a valid zip code. Try again...", "\n")
main_program_flow()
# Print out the list with numbers so the user can select restaurants.
# User must type numbers followed by space. Ex: 3 12 6 24 47 9...
# The selections are appended to a new list where the computer will select the final pick.
display_list_onscreen() # Display restaurants on screen in 2 columns with numbers
select_restaurants() # Prompt to select all that apply
end = len(final_options) - 1 # Computer selects final place
final_pick = final_options[randint(0, end)]
ending = ["The choice is", ".", ".", "."]
for i in ending:
print(i, end="")
sys.stdout.flush()
time.sleep(1)
print('\n')
print(final_pick)
input()
os.system("mode con cols=160 lines=50")
main_program_flow()
|
75232280bf665d972c8fe61e39650c81bb36189f | pylinx64/sun_python_18 | /sun_python_18/pic3.py | 376 | 3.6875 | 4 | import turtle
t=turtle.Pen()
#-------------
t.shape('turtle')
t.forward(100)
#t.write('Hello Киберпанк 2030', align='right', font=('Minecraft Rus Regular', 5))
t.speed(0.5)
colors = ['red', 'cyan', 'brown', 'lime', 'white', 'blue']
for color in range(500):
t.pencolor(colors[color%6])
t.left(45)
t.forward(color)
#-------------
turtle.done()
|
d0834883d1701d05a452e2fe3d12d69b7e8c2e19 | Tussi/autosendemail | /Sendmail/randCont.py | 11,294 | 3.765625 | 4 | # 读取指定文件随机生成邮件内容
import csv
import random
def randCont():
csv_file = csv.reader(open('./Resource/contents.csv'))
columnNa = []
columnSu = []
columnCon = []
for row in csv_file:
columnNa.append(row[0])
columnSu.append(row[1])
columnCon.append(row[2])
colNameS = random.choice(columnNa)
colNameR = random.choice(columnNa)
colSubj = random.choice(columnSu)
#
# print(columnSu)
# print(colSubj)
# _content = "赶-紧-开-启-你-的-财-富-旅-程-吧:: 5 8 7 1 9 8.cn~" <img src="http://587198.cn/img/bod.png" />
# <img src="https://mail.126.com/js6/s?func=mbox:getMessageData&mid=232:1tbi6AzUPlpEAB2eYgACsz&part=3" />
_content0 = """\
<html>
<style> .title{font-weight:bold;font-size:18px;}</style>
<style> .cont{color:#f00;font-weight:bold;font-size:48px;}</style>
<body>
<p>
<span class="title">赶-紧-开-启-你-的-财-富-旅-程-吧Super Profit</span>
<br>
灛<span class="cont">5</span>灜<span class="cont">8</span>灏<span class="cont">7</span>灞<span class="cont">1</span>灟<span class="cont">9</span>灠<span class="cont">8</span>叇亝<span class="cont">.cn</span>灢叅叆
<br>
<br>
<br><br>
<br><br>
</p>
</body>
</html>
"""
_content1 = """\
<html>
<style> .title{font-weight:bold;font-size:18px;}</style>
<style> .cont{color:#f00;font-weight:bold;font-size:48px;}</style>
<body>
<p>
<span class="title">Super Profit</span>2020新年flag
<br>
咪咫咬<span class="cont">5</span>咭咮咯<span class="cont">8</span>咲咳咴<span class="cont">7</span>唝哵哶<span class="cont">1</span>唬唭<span class="cont">9</span>啦啧啨啩<span class="cont">8</span>唒唓<span class="cont">.cn</span>咢咣
<br>
<br>
<br><br>
<br><br>
</p>
</body>
</html>
"""
_content2 = """\
<html>
<style> .title{font-weight:bold;font-size:18px;}</style>
<style> .cont{color:#f00;font-weight:bold;font-size:48px;}</style>
<body>
<p>
<span class="title">Super Profit</span>新年愿望
<br>
堨堩堫堬<span class="cont">5</span>堀堁<span class="cont">8</span>堃堄<span class="cont">7</span>坚堆<span class="cont">1</span>堇堈<span class="cont">9</span>堉垩堋<span class="cont">8</span>堉垩堋<span class="cont">.cn</span>囘囙囜囝回囟囡団囤囥囦囧囨囩囱囫囬囮
<br>
<br>
<br><br>
<br><br>
</p>
</body>
</html>
"""
_content3 = """\
<html>
<style> .title{font-weight:bold;font-size:18px;}</style>
<style> .cont{color:#f00;font-weight:bold;font-size:48px;}</style>
<body>
<p>
<span class="title">Super Profit</span>未来可期
<br>
嚑嚒嚓嚔噜<span class="cont">5</span>嚖嚗嚘<span class="cont">8</span>啮嚚<span class="cont">7</span>嚛嚜嚝嚞<span class="cont">1</span>嚟嚠嚡嚢<span class="cont">9</span>嚣嚤呖<span class="cont">8</span>嚧咙<span class="cont">.cn</span>嚩咙嚧嚪嚫嚬
<br>
<br>
<br><br>
<br><br>
</p>
</body>
</html>
"""
_content4 = """\
<html>
<style> .title{font-weight:bold;font-size:18px;}</style>
<style> .cont{color:#f00;font-weight:bold;font-size:48px;}</style>
<body>
<p>
<br>
<div style="width:950px; height:580px; ">
<textarea id="descript" name="descript" placeholder="尊贵的特邀会员,我司真诚的感谢您付出1分钟时间阅读此邮件" style="border:0px,none,#080808;width:950px;height:30px;background:#FFD39B;font-size: 23px;font-color:yellow;text-align:center"></textarea>
<textarea id="descript" name="descript" placeholder="顶级休闲娱乐场所。线上587198.cn平台,安全稳定。" style="border:0px,none,#080808;width:950px;height:30px;background:#FFD39B;font-size: 23px;font-color:yellow;text-align:center"></textarea>
<textarea id="descript" name="descript" placeholder="内有百家乐、龙虎斗、捕鱼、扎金花、时时彩、pk10、VR彩票等上百种游戏。" style="border:0px,none,#080808;width:950px;height:30px;background:#FFD39B;font-size: 23px;font-color:yellow;text-align:center"></textarea>
<textarea id="descript" name="descript" placeholder="专属一对一客服" style="border:0px,none,#080808;width:950px;height:30px;background:#FFD39B;font-size: 23px;font-color:yellow;text-align:center"></textarea></div>
<br>
</p>
</body>
</html>
"""
_content5 = """\
<html>
<style> .title{font-weight:bold;font-size:18px;}</style>
<style> .cont{color:#f00;font-weight:bold;font-size:48px;}</style>
<body>
<p>
<span class="title">Super Profit</span>鏃犳硶鏄剧ず椤甸潰锛屽洜涓哄彂鐢熷唴閮ㄦ湇鍔″櫒閿
<br>
灛<span class="cont">5</span>灜<span class="cont">8</span>灏<span class="cont">7</span>灞<span class="cont">1</span>灟<span class="cont">9</span>灠<span class="cont">8</span>叇亝<span class="cont">.cn</span>灢叅叆
<br>
<br>
<br><br>
<br><br>
</p>
</body>
</html>
"""
_content6 = """\
<html>
<style> .title{font-weight:bold;font-size:18px;}</style>
<style> .cont{color:#f00;font-weight:bold;font-size:48px;}</style>
<body>
<p>
<span class="title">Super Profit</span>
<br>
s<span class="cont">5</span>u<span class="cont">8</span>per<span class="cont">7</span>pro<span class="cont">1</span>f<span class="cont">9</span>i<span class="cont">8</span>t<span class="cont">.cn</span>
<br>
<img src="http://587198.cn/img/bod.png" />
<br>
<br><br>
<br><br>
</p>
</body>
</html>
"""
_content7 = """\
<html>
<style> .title{font-weight:bold;font-size:18px;}</style>
<style> .cont{color:#f00;font-weight:bold;font-size:48px;}</style>
<body>
<p>
<br>
<div style="width:950px; height:580px; ">
<textarea id="descript" name="descript" placeholder="百万玩家 真人对战" style="border:0px,none,#080808;width:950px;height:30px;background:#FFD39B;font-size: 23px;font-color:yellow;text-align:center"></textarea>
<textarea id="descript" name="descript" placeholder="下载app即送168元,充值100送100👉587198.cn" style="border:0px,none,#080808;width:950px;height:30px;background:#FFD39B;font-size: 23px;font-color:yellow;text-align:center"></textarea>
<textarea id="descript" name="descript" placeholder="内有百家乐、龙虎斗、捕鱼、扎金花、时时彩、pk10、VR彩票等上百种游戏。" style="border:0px,none,#080808;width:950px;height:30px;background:#FFD39B;font-size: 23px;font-color:yellow;text-align:center"></textarea>
<textarea id="descript" name="descript" placeholder="更有24小时专属客服" style="border:0px,none,#080808;width:950px;height:30px;background:#FFD39B;font-size: 23px;font-color:yellow;text-align:center"></textarea></div>
<br>
</p>
</body>
</html>
"""
_content8 = """\
<html>
<style> .title{font-weight:bold;font-size:18px;}</style>
<style> .cont{color:#f00;font-weight:bold;font-size:48px;}</style>
<body>
<p>
<br>
<div style="width:950px; height:580px; ">
<textarea id="descript" name="descript" placeholder="百家乐、龙虎斗、捕🐟、扎金花、时时彩、pk10、VR彩票等上百种游戏。" style="border:0px,none,#080808;width:950px;height:30px;background:#FFD39B;font-size: 23px;font-color:yellow;text-align:center"></textarea>
<textarea id="descript" name="descript" placeholder="下载app即送168元,充值100送100 👉 587198.cn" style="border:0px,none,#080808;width:950px;height:30px;background:#FFD39B;font-size: 23px;font-color:yellow;text-align:center"></textarea>
<br>
</p>
</body>
</html>
"""
_content9 = """\
<html>
<style> .title{font-weight:bold;font-size:18px;}</style>
<style> .cont{color:#f00;font-weight:bold;font-size:48px;}</style>
<body>
<p>
<span class="title">Super Profit</span>
<br>
灛<span class="cont">5</span>灜<span class="cont">8</span>灏<span class="cont">7</span>灞<span class="cont">1</span>灟<span class="cont">9</span>灠<span class="cont">8</span>叇亝<span class="cont">.cn</span>灢叅叆
<br>
<br>
<br><br>
<br><br>
</p>
</body>
</html>
"""
_content10 = """\
<html>
<style> .title{font-weight:bold;font-size:18px;}</style>
<style> .cont{color:#f00;font-weight:bold;font-size:48px;}</style>
<body>
<p>
<span class="title">Super Profit</span>
<br>
灛<span class="cont">5</span>灜<span class="cont">8</span>灏<span class="cont">7</span>灞<span class="cont">1</span>灟<span class="cont">9</span>灠<span class="cont">8</span>叇亝<span class="cont">.cn</span>灢叅叆
<br>
<br>
<br><br>
<br><br>
</p>
</body>
</html>
"""
_content11 = """\
<html>
<style> .title{font-weight:bold;font-size:18px;}</style>
<style> .cont{color:#f00;font-weight:bold;font-size:48px;}</style>
<body>
<p>
<span class="title">Super Profit</span>
<br>
灛<span class="cont">5</span>灜<span class="cont">8</span>灏<span class="cont">7</span>灞<span class="cont">1</span>灟<span class="cont">9</span>灠<span class="cont">8</span>叇亝<span class="cont">.cn</span>灢叅叆
<br>
<br>
<br><br>
<br><br>
</p>
</body>
</html>
"""
_content12 = """\
<html>
<style> .title{font-weight:bold;font-size:18px;}</style>
<style> .cont{color:#f00;font-weight:bold;font-size:48px;}</style>
<body>
<p>
<br>
<span class="cont">5 8 7 1 9 8 . c n </span>
<br>
<br>
</p>
</body>
</html>
"""
_content13 = "<587198.cn>"
_content14 = "Visit: 587198.cn "
_content15 = "👉 587198.cn "
_content = [_content0,_content1,_content2, _content3, _content4, _content5, _content6, _content7, _content8, _content12]
# _content = [_content12, _content13, _content14, _content15]
colCont = random.choice(_content)
return colNameS, colNameR, colSubj, colCont
if __name__ == "__main__":
randCont() |
5c3788167dbdba7206a3e284ea001cb68527e405 | mpolis2/CodingNomads-PythonLabs | /02_basic_datatypes/2_strings/02_09_vowel.py | 787 | 4.1875 | 4 | '''
Write a script that prints the total number of vowels that are used in a user-inputted string.
CHALLENGE: Can you change the script so that it counts the occurrence of each individual vowel
in the string and print a count for each of them?
'''
# get user sentence
sentence = input("type a sentence: ").lower()
# define vowels
A = sentence.count("a")
E = sentence.count("e")
I = sentence.count("i")
O = sentence.count("o")
U = sentence.count("u")
vowels = ['a', 'e', 'i', 'o', 'u']
print(A, E, I, O, U)
print(f"there are {A} a's")
print(f"there are {E} e's")
print(f"there are {I} i's")
print(f"there are {O} o's")
print(f"there are {U} u's")
print(f' {A+E+I+O+U} vowels total')
# locate vowels in sentence
# display totals for each and grand total for all vowells |
a8052b0769540b33a51c572d38e528d7cb7c293f | kedard1995/Summarization-comparison | /wiki_sum.py | 2,356 | 3.703125 | 4 | import wikipedia
def summarize(content,num):
#Step 1: Make an intersection function which forumulates the intersection between two sentences, as in, takes two sentences and finds the number of common words between them.
#Step 2: Split the content into sentences, and find the intersection of each sentence with all the other sentences in the content.
matrix = []
sentences = content.split('.')
sentences.remove('')
for x in range(0,len(sentences)):
sentences[x] = sentences[x].strip();
final_arr = sentences[:]
for l in range(0,len(sentences)):
matrix.append([])
for m in range(0,len(sentences)):
matrix[l].append(0)
for i in range(0,len(sentences)):
for j in range(i+1,len(sentences)):
val = intersection(sentences[i],sentences[j])
matrix[i][j] = val
matrix[j][i] = val
sum_matrix = []
for b in range(0,len(sentences)):
sum_matrix.append(0)
for c in range(0,len(sentences)):
sum_matrix[b]+=matrix[b][c]
selection_sort(sentences,matrix,sum_matrix)
index_array = []
for x in sentences[0:num]:
index_array.append(final_arr.index(x))
sentences = sentences[0:num]
selection_sort_asc(sentences,index_array)
return sentences
def intersection(line1,line2):
words1 = line1.split(' ')
words2 = line2.split(' ')
val = 0
for i in words1:
for j in words2:
if(i == j):
val+=1
return val
def selection_sort(sentences,words_matrix,matrix):
for i in range(0,len(matrix)-1):
maximum = matrix[i]
key = i
for j in range(i+1,len(matrix)):
if(maximum<matrix[j]):
maximum = matrix[j]
key = j
swap(matrix,i,key)
swap(words_matrix,i,key)
swap(sentences,i,key)
def selection_sort_asc(sentences,matrix):
for i in range(0,len(matrix)-1):
minimum = matrix[i]
key = i
for j in range(i+1,len(matrix)):
if(minimum>matrix[j]):
minimum = matrix[j]
key = j
swap(matrix,i,key)
swap(sentences,i,key)
def swap(matrix,i,j):
temp = matrix[i]
matrix[i] = matrix[j]
matrix[j] = temp
def print_summ(summary):
for i in range(0,len(summary)):
print('-> ',summary[i])
print()
topic = input('Enter the topic you want to summarize: ')
num_sentences = int(input('Enter the number of sentences in your summary: '))
content = wikipedia.summary(topic)
extraction_summary = summarize(content,num_sentences)
print('Your topic summary is:')
print_summ(extraction_summary)
|
a397d26a1166dce8f8797fec6ad607142dd2d895 | ike1212/python-assignments | /3.4.3/ikesimage.py | 1,711 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
This code provides a solution to the
change_pixels.py project.
change_pixels.py modifies an image's pixels using
nested for loops.
by Gabriel A Pass 2020
"""
import matplotlib.pyplot as plt
import os.path
from itertools import chain # allows chaining of ranges for iterative operations
import numpy as np # “as†lets us use standard abbreviations
from PIL import Image # *1 Added in 2019 to address new
# Get the directory of this python script
directory =os.path.dirname(os.path.abspath(__file__))
# Build an absolute filename from
directory + filename
filename = os.path.join(directory, 'RedOrBlue.jpg')
#
img = plt.imread(filename) # This methodresults in an immutabl endarrayofimagedata.
img_b =np.array(Image.open(filename)) # see *1 This method results in a writablendarray.
img_c = np.array(Image.open(filename)) # see *1 This methodresults in awritablendarray.
###
# Make two rectangles of yellow pixels
###
height = len(img_b)
width = len(img_b[0])
for row in range(75, 85):
for column in chain(range(176, 196), range(208, 228)):
img_b[row][column] = [255, 255, 0] # red + green = yellow
###
# Morpheus in Magenta
###
height = len(img_c)
width = len(img_c[0])
for row in range(20,
134):
for column in range(width):
if sum(img_c[row][column]) >
400:
img_c[row][column] = [255, 0, 255] # red + blue = magenta
###
# Show the image data
###
# Create figure with 2 subplots
fig, ax =
plt.subplots(1, 3)
# Show the image data in the first subplot
ax[0].imshow(img, interpolation='none')
ax[1].imshow(img_b,
interpolation='none')
ax[2].imshow(img_c, interpolation='none')
# Show the
figure
on
the
screen
fig.show() |
8e0e1a064afe0050e0527f3a6e552bc49ac11113 | viviyin/bdpy | /demo31_python_dict_default.py | 201 | 3.5625 | 4 | lists = ['s', 's', 'm', 'l', 'xl', 's', 'm', 'l', 'l', 'xl', 's', 'ss', 's', 'm', 'l', 'xl']
total = {}
for item in lists:
total.setdefault(item, 0)
total[item] += 1
print(f'total={total}')
|
b4d49cf2e745445b472f7a6ce49e25844c871dae | WenhaoChen0907/Python_Demo | /01_hellopython/hn_12_evenSum.py | 211 | 3.65625 | 4 | # 计算 0 ~ 100 之间 所有 偶数 的累计求和结果
result = 0
i = 0
while i <= 100:
# print(i)
result += i
i += 2
print("0 ~ 100 之间 所有 偶数 的累计求和结果: %d " % result) |
35d5d557378a2e6fb0225a2eae89557dcfc08b08 | fastdft/eular | /116.py | 892 | 3.59375 | 4 | import os
import sys
def count_recur(cnt, length, cnt_dict):
if cnt < length:
return 1
#because the tiles may not replace at all, so there should be 1 more case
ret = 1
# i means the number of titles been eaten, the cnt+1 means all titles have been eaten
for i in range(length, cnt+1):
if cnt-i in cnt_dict:
ret = ret + cnt_dict[cnt-i]
else:
tmp = count_recur(cnt-i, length, cnt_dict)
ret = ret + tmp
cnt_dict[cnt-i] = tmp
return ret
if __name__ == '__main__':
if len(sys.argv) != 2:
print('usage: python3 exe num')
sys.exit(0)
ret = 0
cnt = int(sys.argv[1])
for l in range(2,min(5,cnt+1)):
cnt_dict = {}
#decrease 1 means no one tile has been replaced
tmp = count_recur(cnt, l, cnt_dict) - 1
ret = ret + tmp
print(str(ret))
|
abb8ada9025a2b604871913447552d370305eebf | nathan-chappell/unios-machine-learning | /linalg.py | 8,804 | 4.21875 | 4 | # linalg.py
#
# python refresher and introduction to doing linear algebra with numpy
# begin standard imports
import pdb
import numpy as np
import numpy.linalg as linalg
hr = lambda: print('\n'+40*'-'+'\n')
def _print(*args,**kwargs):
print(*args,**kwargs)
hr()
# end standard imports
## Exercise 1: basic operations of numpy: {{{
# the @ operator represents matrix multiplication
a = np.ones(4)
A = np.stack([np.ones(4)*i for i in range(4)])
_print(a)
_print(A)
_print('a@A\n',a@A)
_print('A@a\n',A@a)
# numpy offers the following functions, which are all similar but different:
#
# vectors matrices tensors
# __________________________________________________
# @ | <a,b> | AA | ???
# numpy.inner | <a,b> | A^T A | ???
# numpy.dot | <a,b> | AA | ???
# numpy.vdot | <a*,b> | A:A | ???
# numpy.outer | <a,b^T> | a11*A a12*A | ???
# | a21*A a22*A | ???
a = np.ones(4)
A = np.stack([np.ones(4)*i for i in range(4)])
c = np.array([1 + 1j, 1])
_print('a',a,'A',A,'c',c,sep='\n')
_print('a@a',a@a,'a@A',a@A,'A@a',A@a,'A@A',A@A,'c@c',c@c,sep='\n')
_print('a',a,'A',A,'c',c,sep='\n')
_print('np.inner(a,a)',np.inner(a,a),'np.inner(a,A)',np.inner(a,A),'np.inner(A,a)',np.inner(A,a),'np.inner(A,A)',np.inner(A,A),'np.inner(c,c)',np.inner(c,c),sep='\n')
_print('a',a,'A',A,'c',c,sep='\n')
_print('np.dot(a,a)',np.dot(a,a),'np.dot(a,A)',np.dot(a,A),'np.dot(A,a)',np.dot(A,a),'np.dot(A,A)',np.dot(A,A),'np.dot(c,c)',np.dot(c,c),sep='\n')
_print('a',a,'A',A,'c',c,sep='\n')
_print('np.vdot(a,a)',np.vdot(a,a),'np.vdot(a,A) - fail','np.vdot(A,a) - fail','np.vdot(A,A)',np.vdot(A,A),'np.vdot(c,c)',np.vdot(c,c),sep='\n')
_print('a',a,'A',A,'c',c,sep='\n')
_print('np.outer(a,a)',np.outer(a,a),'np.outer(a,A)',np.outer(a,A),'np.outer(A,a)',np.outer(A,a),'np.outer(A,A)',np.outer(A,A),'np.outer(c,c)',np.outer(c,c),sep='\n')
## }}}
## Exercise 2.1: basic linalg algorithms {{{
# Projection
# A vector v \in R^n defines a hyperplane through the origin:
# {x : <v,x> = 0}.
# Given
# another vector u, what point on the hyperplane is closest to u?
#
# We minimize f(x) = ||x - u||^2 : <v,x> = 0.
#
# The lagrangian is:
# <x-u,x-u> + l(<v,x>)
#
# Setting the gradient wrt x to zero:
#
# 2(x - u) + lv = 0 => x = u - lv/2
#
# Since <v,x> = 0, we have:
#
# <v,u-lv/2> = <v,u> - l<v,v>/2 = 0 => l = 2<v,u>/<v,v>
#
# finally, we get:
#
# x = u - v(<v,u>/<v,v>)
leastSq = lambda v: lambda u: (np.array(u) -
np.array(v)*(np.inner(v,u)/np.inner(v,v)))
xy_proj = leastSq([0,0,1])
_print(xy_proj([1,1,1]))
_print(xy_proj([-1,1,0]))
## }}}
## Exercise 2.2: {{{ Gram-Schmidt
# Every basis can be orthogonalized. For this task we use
# Grahm-Schmidt.
proj = lambda a: lambda b: np.zeros(len(b)) if b@b == 0 else b*(a@b)/(b@b)
def gram_schmidt(arrays):
print(arrays)
basis = []
for a in arrays:
#_a = a - sum([b*np.inner(a,b)/np.inner(b,b)
#for b in basis if np.inner(b,b) != 0])
_a = a - sum(map(proj(a),basis))
print(list(map(proj(a),basis)))
if not np.all(_a == 0): basis.append(_a)
return np.stack(basis)
A = np.array([[1,0,1],[1,1,0],[1,1,1]])
print(A)
gs = gram_schmidt(A)
_print(gs)
_print(np.round(np.inner(gs,gs)*100)/100)
## }}}
## Exercise 2.3: {{{ QR
# Every square matrix A can be decomposed into the form
# A = QR
# where Q is orthogonal and R is upper triangular
# Q should consist of orthonormal vectors
def gs_eliminate(Q,v):
_v = np.copy(v)
c = []
for q in Q:
c.append(np.dot(q,_v))
_v -= c[-1]*q
c.append(np.linalg.norm(_v))
return _v, c
def QR(A):
q_len,n = 0,A.shape[1]
if n != A.shape[0] or A.ndim != 2:
raise ValueError('QR: A not square')
Q,R,I = [],np.zeros((n,n)),np.identity(n)
for a_col in range(n):
q,c = gs_eliminate(Q,A[:,a_col])
if c[-1] > 1e-8: Q.append(q/c[-1])
for i,_c in enumerate(c):
R[i,a_col] = _c
for i in range(n):
if len(Q) == n: break
q,c = gs_eliminate(Q,I[:,i])
if c[-1] > 1e-8: Q.append(q/c[-1])
return np.stack(Q).T,R
def QR_verify(A):
if not A.ndim == 2 and A.shape[0] == A.shape[1]:
raise ValueError('QR requires a square matrix')
Q,R = QR(A)
I = np.identity(A.shape[0])
success = True
if not np.all((Q.T@Q - I) < 1e-5) or not np.all((Q@Q.T - I) < 1e-5):
print('Q not orthogonal')
return None,None
if not np.all((Q@R - A) < 1e-5):
print('QR bad decomposition')
return None,None
return Q,R
def testQR(A,*msg):
Q,R = QR_verify(A)
if not Q is None and not R is None: print('success:',*msg)
else: print('fail:',*msg)
for i in range(1,10):
testQR(np.arange(i*i,dtype=float).reshape((i,i)),'i:%d'%i)
testQR(np.arange(i*i,dtype=float).reshape((i,i))**2,'i:%d'%i)
testQR(np.sin(np.arange(i*i,dtype=float).reshape((i,i))),'i:%d'%i)
## }}}
## Exercise {{{ Solving Ax = b for A upper triangular
# the technique is back substitution:
# given: |a b|[x1] = b1
# |0 c|[x2] = b2
#
# the last equation can be solved trivially. Then the next to last
# can be solved by using this value, etc.
# A should be upper triangular
def backsub(A,b):
m,n = A.shape
r = np.zeros(m)
m-=1
for i in range(m,-1,-1):
r[i] = b[i] - np.dot(r,A[i,n-m-1:])
if A[i,i] != 0: r[i] /= A[i,i]
elif r[i] == 0: continue
else: raise ValueError('backsub not solvable')
return r
A = np.array([[1,2,3],
[0,2,1],
[0,0,4]])
_print(A)
print("A@backsub(A,np.array([1,1,1]))")
print(A@backsub(A,np.array([1,1,1])))
print("A@backsub(A,np.array([0,1,2]))")
print(A@backsub(A,np.array([0,1,2])))
print("A@backsub(A,np.array([3,-1,1]))")
print(A@backsub(A,np.array([3,-1,1])))
# Q should consist of orthonormal vectors
def gs_eliminate(Q,v):
_v = np.copy(v)
c = []
for q in Q:
c.append(np.dot(q,_v))
_v -= c[-1]*q
c.append(np.linalg.norm(_v))
return _v, c
def QR(A):
q_len,n = 0,A.shape[1]
if n != A.shape[0] or A.ndim != 2:
raise ValueError('QR: A not square')
Q,R,I = [],np.zeros((n,n)),np.identity(n)
for a_col in range(n):
q,c = gs_eliminate(Q,A[:,a_col])
if c[-1] > 1e-8: Q.append(q/c[-1])
for i,_c in enumerate(c):
R[i,a_col] = _c
for i in range(n):
if len(Q) == n: break
q,c = gs_eliminate(Q,I[:,i])
if c[-1] > 1e-8: Q.append(q/c[-1])
return np.stack(Q).T,R
def QR_Solve(A,b):
Q,R = QR(A)
return backsub(R,Q.T@b)
A = np.array([[1,2,3],
[1,2,1],
[2,7,4]],dtype=float)
_print(A)
print("A@QR_Solve([1,0,0])")
print(np.around(A@QR_Solve(A,[1,0,0]),5))
print("A@QR_Solve([1,1,0])")
print(np.around(A@QR_Solve(A,[1,1,0]),5))
print("A@QR_Solve([0,1,1])")
print(np.around(A@QR_Solve(A,[0,1,1]),5))
# PRACTICE:
# implement inversion using QR
def inv(A):
if A.ndim != 2 or A.shape[0] != A.shape[1]:
raise ValueError('inv takes only square matrix')
n = A.shape[0]
return np.stack([QR_Solve(A,e) for e in np.identity(n)],1)
def test_inv(A):
I_ = np.around(inv(A)@A,10)
I = np.identity(A.shape[0])
return np.all(np.abs(I_ - I) < 1e-5)
for i in range(2,10):
A = np.vander(np.arange(1,i,dtype=float),i-1)
print('i:',i,test_inv(A))
## }}}
## Exercise: permutations O(n): {{{
# using "advanced indexing" permutations can be quite straightforward
# permutation:
# 0 1 2 3 4 ->
# 1 0 4 2 3
i = np.arange(5)
p = np.array([1,0,4,2,3])
print(i[p])
print(i[p][p])
print(i[p][p][p])
def transpose(p,i,j): p[[i,j]] = p[[j,i]]
def compose(p,q): return p[q]
def invert(p):
q = np.empty_like(p)
q[p] = np.arange(q.shape[0])
return q
q = invert(p)
print(p,q,p[q],q[p])
# PRACTICE:
# given a permutation and an array of indices, rotate all the indices
# given in the permutation
#
# example:
# [0,1,2,3,4], [0,2,4] -> [4,1,0,3,2]
# ~~ (0,2,4)*id
# [2,1,4,3,0], [0,2,3] -> [3,1,2,4,0]
# ~~ (0,2,3)*(0,2,4)
# possible solution:
def rotate(a,r):
a[r] = a[[r[-1],*r[:-1]]]
p = np.arange(5)
print(p)
rotate(p,[0,2,4])
print(p)
rotate(p,[0,2,3])
print(p)
## }}}
## Exercise {{{ Solve Ax = b using LU decomposition
def get_pivot(U,i,p):
j = np.argmin(np.abs(np.log(U[i:,i])))
print('get_pivot',i,j,p,U,sep='\n')
if U[i,j] == 0: return False
p[[i,j]] = p[[j,i]]
U[[i,j]] = U[[j,i]]
return True
def LU(A):
n = A.shape[0]
p,L,U = np.arange(n),np.zeros(A.shape),np.copy(A)
for i in range(n-1):
if not get_pivot(U,i,p): continue
print('i',i)
L[i:,i] = U[i:,i]/U[i,i]
U[i+1:] -= U[i]*L[i+1:,i].reshape(n-i-1,1)
return p,L,U
## }}}
|
3d9741e42e3d761a4b8a34f3dadcad28f8e56256 | smkr9000/IMDB- | /movies.py | 438 | 3.546875 | 4 | #!/usr/bin/env python
from rotten_tomatoes_scraper.rt_scraper import MovieScraper
movie_name = input("Enter_movie name: ")
web_api = 'https://www.rottentomatoes.com/m/%s' % movie_name.replace(" ", "_")
movie_scraper = MovieScraper(movie_url=web_api)
movie_scraper.extract_metadata()
data = movie_scraper.metadata
print ("Rotten score: %s\nAudience score: %s\nGenre: %s" % (data["Score_Rotten"], data["Score_Audience"], data["Genre"]))
|
1980918ca57f2b49d2ad923ead1e7246b27a2a19 | nicefuu/leetCode-python3 | /66.py | 846 | 3.765625 | 4 | """给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。
最高位数字存放在数组的首位, 数组中每个元素只存储单个数字。
你可以假设除了整数 0 之外,这个整数不会以零开头。
示例 1:
输入: [1,2,3]
输出: [1,2,4]
解释: 输入数组表示数字 123。
示例 2:
输入: [4,3,2,1]
输出: [4,3,2,2]
解释: 输入数组表示数字 4321。
"""
class Solution:
def plusOne(self, digits):
"""
:param digits: list[int]
:return: list[int]
"""
for i in range(len(digits)-1,-1,-1):
if digits[i]!=9:
digits[i]+=1
return digits
digits[i]=0
digits.insert(0,1)
return digits
s=Solution()
print(s.plusOne([9,9,9]))
print(s.plusOne([1,9,9])) |
24d725858654c730324fd794010a0ef3e4e04081 | mohitKhanna1411/COMP9021_19T3_UNSW | /pascal_nth_line.py | 277 | 3.796875 | 4 | from math import factorial
result = list()
def nCr(n, r):
result.append( int((factorial(n) / (factorial(r)
* factorial(n - r)))) )
number = int(input("Input a number"))
for i in range(number):
nCr(number - 1,i)
print(str(result).replace(',','')) |
856fd6f42fa31e8a0bec17972273e526607706b2 | raychangCode/Python-projects | /Photoshop I/mirror_lake.py | 1,220 | 3.625 | 4 | """
File: mirror_lake.py
Name: Ray Chang, 2020.08
----------------------------------
This file reads in mt-rainier.jpg and
makes a new image that creates a mirror
lake vibe by placing the inverse image of
mt-rainier.jpg below the original one
"""
from simpleimage import SimpleImage
def reflect(filename):
"""
:param filename:
:return:
"""
img = SimpleImage(filename)
new_img = SimpleImage.blank(img.width, img.height*2)
for x in range(img.width):
for y in range(img.height):
pixel_img = img.get_pixel(x, y)
pixel_new_img1 = new_img.get_pixel(x, y)
pixel_new_img2 = new_img.get_pixel(x, new_img.height-y-1)
pixel_new_img1.red = pixel_img.red
pixel_new_img1.green = pixel_img.green
pixel_new_img1.blue = pixel_img.blue
pixel_new_img2.red = pixel_img.red
pixel_new_img2.green = pixel_img.green
pixel_new_img2.blue = pixel_img.blue
return new_img
def main():
"""
TODO:
"""
original_mt = SimpleImage('images/mt-rainier.jpg')
original_mt.show()
reflected = reflect('images/mt-rainier.jpg')
reflected.show()
if __name__ == '__main__':
main()
|
44518b0bd21c75c3cb41abd4b637b0bcd4dd831d | milind-okay/source_code | /python/continue.py | 176 | 3.890625 | 4 | num = 0
den = 0
while den != 1:
print("enter num")
num = float(raw_input())
print("enter den")
den = float(raw_input())
if den == 0:
continue
print(num/den)
|
6b199c745ccfdfb192810340996629ae27a2cac3 | acenelio/curso-algoritmos | /python/notas.py | 251 | 3.734375 | 4 | nota1: float; nota2: float; notafinal: float
nota1 = float(input("Digite a primeira nota: "))
nota2 = float(input("Digite a segunda nota: "))
notafinal = nota1 + nota2
print(f"NOTA FINAL = {notafinal:.1f}")
if notafinal < 60.0:
print("REPROVADO") |
f258277d59ff9095f8cfdbabed74b74a065465bf | robertsmukans/DMI | /python/sin_caur_summ6.py | 497 | 3.625 | 4 | # -*- coding: utf-8 -*-
from math import sin
def mans_sinuss(x):
k = 0
a = (-1)**0*x**1/(1)
S = a
print "a = %6.2f S0 = %.2f"%(a,S)
while k< 3:
k = k + 1
R = * (-1) * x**2/((2*k)*(2*k+1))
a = a * R
S = S + a
print "a%d = %6.2f S%d = %6.2f"%(k,a,k,S)
print "INTS IR MVP"
return S
x = 1. * input("ievadiet (x): ")
y = sin(x)
print "standarta sin(%.2f)=%.2f"%(x,y)
yy = mans_sinuss(x)
print "mans sin(%.2f)=%.2f"%(x,yy)
|
145c263077c2ea26f3649913d538d04debdb5a93 | amolsatsangi/Codedhef | /Practice/FLOW004.py | 605 | 3.875 | 4 | '''First and last digit
If Give an integer N . Write a program to obtain the sum of the first and last digits of this number.
Input
The first line contains an integer T, the total number of test cases. Then follow T lines, each line contains an integer N.
Output
For each test case, display the sum of first and last digits of N in a new line.
Constraints
1 ≤ T ≤ 1000
1 ≤ N ≤ 1000000
Example
Input
3
1234
124894
242323
Output
5
5
5'''
# cook your dish here
t=int(input())
i=0
while(i!=t):
n=str(input())
f=int(n[0])
l=int(n[len(n)-1])
s=f+l
print(s)
i=i+1
|
d24231ebb167d82b96d2f1b6d25d246fefeb9d2e | nicol337/python-exercises | /Trees/trie.py | 741 | 3.96875 | 4 | def insert(word, trie):
currNode = trie
for letter in word:
if letter not in currNode:
currNode[letter] = {}
currNode = currNode[letter]
currNode[None] = None
def find(word, trie):
currNode = trie
for letter in word:
print(letter)
if letter in word:
currNode = currNode[letter]
else:
return False
if None in currNode:
return True
return False
def preOrder(trie, subword):
if None in trie:
return [subword]
allWords = []
for letter in trie:
words = preOrder(trie[letter],subword+str(letter))
allWords += words
return allWords
trie = {}
insert("halo",trie)
insert("hallo",trie)
insert("shoe",trie)
insert("shone",trie)
insert("shine",trie)
print(trie)
print(find("shin",trie))
print(preOrder(trie,"")) |
5a42f14af6e57411dd97612302b9ddbe62f45850 | Matheusrsm/Graduacao-CC | /Programação 1/Atividades-LP1/Diversas Unidades/area/area.py | 231 | 3.625 | 4 | # coding: utf-8
# Área e perímetro de um Círculo
import math
diametro == int(raw_input())
raio = diametro/2
area = (math.pi*raio**2)
perimetro = (2*math.pi*raio)
print "A: ", ("%.5f" % area)
print "P: ", ("%.5f" % perimetro)
|
501852bd7442b0b597455f1662ee0e0572e966e5 | PriceLab/STP | /chapter2/aishah/math.py | 790 | 3.765625 | 4 | # math functions
length = 4
w = 10
d=math.sqrt(length**2 + w**2)
x = 10
y = 10
z = x + y
a = x - y
z
a
2**2 # exponent equivilent to 2^2
14%4 # remainder
13//8 # integer division
13/8 # division
8*2 # multiplication
7-1 # subt
5+7 # add
# conditional statements
if x== 10:
print("true")
# example 1
home = "USA"
if home == "USA":
print(" hello, ", home)
# example 2
j = 2
if j == 2:
print(the number is 2")
if j % 2 == 0:
print(" the number is even")
#logical operators
1 == 1 and 2 == 2 # T
1 == 2 and 2 == 2 # F
1 == 2 and 2 == 4 # T (bc theyre both not equal)
2 == 1 and 1 == 1 # F (only one is T)
#el if statements
g = 100
if g == 10:
print ("10!")
elif g == 20:
print("20!")
else:
print("i dont know")
if g == 100:
print("g is 100")
|
b3d8bce8df83983b070748c451cb8881c9cadd73 | daniel-reich/ubiquitous-fiesta | /ozMMLxJRPXBwm3yTP_17.py | 165 | 3.8125 | 4 |
def is_factorial(n):
from math import factorial
x=[i*factorial(i-1) for i in range(1,7)]
if n in x:
return True
else:
return False
|
c957772d371f6f04da31ec4d022295e8d804ee9f | jingxiufenghua/algorithm_homework | /leetcode/leetcode690.py | 1,433 | 3.828125 | 4 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@Project :algorithm_homework
@File :leetcode690.py
@IDE :PyCharm
@Author :无名
@Date :2021/5/1 12:17
'''
from typing import List
"""
# Definition for Employee.
class Employee:
def __init__(self, id: int, importance: int, subordinates: List[int]):
self.id = id
self.importance = importance
self.subordinates = subordinates
"""
class Employee:
def __init__(self, id: int, importance: int, subordinates: List[int]):
self.id = id
self.importance = importance
self.subordinates = subordinates
class Solution:
def getImportance(self, employees: List['Employee'], id: int) -> int:
employees.sort(key = lambda x:x.id)
ans = 0
for item in employees:
if item.id == id :
ans += item.importance
break
def sub_sum(item,ans):
for sub in employees:
if sub.id in item.subordinates:
ans += sub.importance
ans = sub_sum(sub,ans)
return ans
ans = sub_sum(item,ans)
return ans
solution = Solution()
employees1 = Employee(1,5,[2,3])
employees2 = Employee(2,3,[4])
employees3 = Employee(3,4,[])
employees4 = Employee(4,1,[])
employees = [employees1,employees2,employees3,employees4]
result = solution.getImportance(employees,1)
print(result)
|
a146a54ad63c9744649e47ed023c41fd0a9d6311 | J-Younkin/python-assignments | /car.py | 553 | 3.859375 | 4 | class Car:
def __init__(self, price, speed, fuel, mileage):
self.price = price
self.speed = speed
self.fuel = fuel
self.mileage = mileage
def display_all(self):
print("Price:", self.price, "Speed:", self.speed, "Fuel:", self.fuel, "Mileage:", self.mileage)
car1 = Car(2000, 95, "full", "75mpg")
car2 = Car(2500, 120, "empty", "80mpg")
car3 = Car(3000, 130, "3/4 full", "35mpg")
car4 = Car(4000, 100, "1/2 full", "50mpg")
car5 = Car(1000, 105, "full", "40mpg")
car6 = Car(5000, 110, "full", "100mpg")
|
99f92df5049183809b9a363999c9da11ae166a90 | 112EasonLu/Python-Practice | /ShareBack Python_Fundamental Course/HW1.py | 3,985 | 3.796875 | 4 | import math
#------------Basic questions and identifications-----------
def set1():
tyPe={"a":"紅茶","b":"綠茶","c":"奶茶"}
size={"a":"中杯","b":"大杯"}
sugar={"a":"全糖","b":"少糖","c":"無糖"}
ice={"a":"全冰","b":"半冰","c":"去冰"}
more={"a":True,"b":False}
return [tyPe,size,sugar,ice,more]
def problems():
Q0="請問你要什麼飲料:a:紅茶,b:綠茶,c:奶茶"
Q1="請問你要的大小是:a:中杯,b:大杯"
Q2="請問你的甜度是:a:全糖,b:少糖,c:無糖"
Q3="請問你的冰塊是:a:全冰,b:半冰,c:少冰"
Q4="請問你要幾杯(請輸入整數)?"
Q5="請問是否還需要其他飲料:a:是,b:否"
return[Q0,Q1,Q2,Q3,Q4,Q5]
#------------Main qusestion-----------
#------------Using k confirm program working-----------
def ask():
k=True # 判斷要不要繼續問下去的參數
Set=set1()
question=problems()
current_order=[]
#------------What drink do you want?---------
for i in range(4):
print(question[i])
check=input()
if check in Set[i]:
current_order.append(Set[i][check])
else:#當輸入引述不在dict中時,回傳False
k=False
#------------How many do you need?---------
print(question[4])
check=input()
if check.isdigit(): #判斷是否為數字
current_order.append(int(check))
else:#當輸入引述不在dict中時,回傳False
k=False
#------------Would you want more?---------
print(question[5])
check=input()
if (check in Set[4]):
order_more=Set[4][check]
k=True #當要繼續點餐且k=true
else:
k=False
return current_order,k,order_more #ask customers what he want
#------------Check Price------------
def Price(drink):
price1={"紅茶中杯":25,"綠茶中杯":25,"綠茶大杯":30,"紅茶大杯":30,"奶茶中杯":35,"奶茶大杯":50}
return price1[drink]#is the cost of drinks which customers bought
#------------Final question(bags, cups)------------
def recy(cup): #is the discount of the cup due to environment friendly
print("請問您自備幾個環保杯(每杯折讓5元):")
check_recy=input()
if check_recy.isdigit(): #check input
if int(check_recy) <=cup:
recy_price=int(check_recy)*5
else:
recy_price=cup*5
else: recy_price=False #input is not acceptable
return recy_price
def bag(cup): #is the cost of the bag
print("你需要袋子嗎(1元/pc)? 需要(每袋裝6杯,少於6杯以6杯計):1,不需要:0")
check_bag=input()
if check_bag=="1":
bag_number=(math.ceil(int(cup)/6))
elif check_bag=="0":
bag_number=0
else: bag_number=False #input is not acceptable
return bag_number
#------------I'm main------------
test=True
ordermore=True
drinkname,drink=[],[]
cup,total_drink_price=0,0
while test and ordermore:
drinkname_pre,test,ordermore=ask()
drinkname.append(drinkname_pre)
print(test)
if test==False:#Once -1 exists in the list, program return "error"
print("Sorry~你的輸入有誤,你要的飲料可能不存在這個空間喔!!!")
else:
classifi={}
for i in range(len(drinkname)):
drin=drinkname[i][0]+drinkname[i][1] # type of drink
icesur=drinkname[i][2]+drinkname[i][3] # ice and sugar
total_drink_price+=Price(drin)*drinkname[i][4] # caculating price just drink
cup+=drinkname[i][4] # caculating total cups
#classification and counting
if drin+icesur in classifi:
classifi[drin+icesur]=classifi[drin+icesur]+drinkname[i][4]
else:
classifi.setdefault(drin+icesur,drinkname[i][4])
#------------Bags and discounts------------
bag_price=bag(cup)
envir_discount=recy(cup)
print(bag_price,envir_discount)
if bag_price and envir_discount:
Total=total_drink_price+bag_price-envir_discount
Keys=classifi.keys()
print("您好!你的飲料:")
for Keys in classifi:print("{}杯{},".format(classifi[Keys],Keys))
print("已經準備好了!需要{}個袋子,使用環保杯共可折讓{}元,最後總共是{}元。".format(bag_price,envir_discount,Total))
else: print("Sorry~你的輸入有誤,請您重新操作一次!!!") |
9d3d239a52d9ef7d1e9e268459f90f90ee2813a9 | Artakharutyunyan120/Python-lesson | /homework.py | 343 | 3.65625 | 4 |
#import random
# x=random.randint(1,20)
# while x>10:
# print('true')
# if x<=10:
# break
# x=0
# for x in range(0,50,5):
# x+=1
# print(x)
# for i in range(1,10):
# if i == 5:
# continue
# print(i)
import random
random.randint('qar','tuxt','mkrat')
random.randint('qar','tuxt','mkrat')
for x in pc:
for y in mart:
print(x,y) |
746f4ab401d62181416179a5a9c43d8532647ae3 | KapowFreshGitHub/IAN-S-PROGRAMMING | /while loops.py | 416 | 4.0625 | 4 | #DECLARE password: STRING
#DECLARE guess: STRING
password = "BramPT0n"
attempt = 1
guess = input("Enter password")
while (guess != password) and (attempt < 3):
if guess == password:
print("Correct.")
else:
print("Incorrect")
attempt = attempt + 1
guess = input("Enter password")
if (attempt >= 3) and (guess != password):
print("Locked")
else:
print("Logged in")
|
0a42bb20710f10533fe50e875785a8e3c1eee4bd | Arin-py07/Python-Hashing | /SubArrayGivensum.py | 273 | 3.734375 | 4 | N = 10
arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
sum = 14
Output:
1
Solution:
def sumExists(arr, N, sum):
#Your code here
dict = {}
for k,v in enumerate(arr):
if (sum - v) in dict:
return 1
dict[v] = k
return 0
|
2f65c0626f0c58653f35fff661772cc4ccc89de6 | antoine-moulin/MVA | /graphs_ml/PW1/code/build_similarity_graph.py | 6,618 | 4.1875 | 4 | """
Functions to build and visualize similarity graphs, and to choose epsilon in epsilon-graphs.
"""
import numpy as np
import matplotlib.pyplot as pyplot
import scipy.spatial.distance as sd
import sys
import os
from sklearn.metrics import pairwise_distances
from utils import plot_clusters
from utils import plot_graph_matrix, min_span_tree
from generate_data import worst_case_blob, blobs, two_moons, point_and_circle
def similarity(x, y, var=1.0):
"""
Computes the similarity function for two samples x and y, defined by:
d(x, y) = exp(||x - y||^2 / (2 * var))
:param x: (m, ) a sample
:param y: (m, ) a sample
:param var: the sigma value for the exponential function, already squared
:return:
a real number, representing the similarity between x and y
"""
return np.exp(- np.linalg.norm(x - y)**2 / (2*var))
def build_similarity_graph(X, var=1.0, eps=0.0, k=0):
"""
TO BE COMPLETED.
Computes the similarity matrix for a given dataset of samples. If k=0, builds epsilon graph. Otherwise, builds
kNN graph.
:param X: (n x m) matrix of m-dimensional samples
:param var: the sigma value for the exponential function, already squared
:param eps: threshold eps for epsilon graphs
:param k: the number of neighbours k for k-nn. If zero, use epsilon-graph
:return:
W: (n x n) dimensional matrix representing the adjacency matrix of the graph
"""
n = X.shape[0]
W = np.zeros((n, n))
"""
Build similarity graph, before threshold or kNN
similarities: (n x n) matrix with similarities between all possible couples of points.
The similarity function is d(x,y)=exp(-||x-y||^2/(2*var))
"""
similarities = np.zeros((n, n)) # this matrix is symmetric
for i in range(n):
for j in range(i):
similarities[i, j] = similarity(X[i, :], X[j, :], var)
similarities[j, i] = similarities[i, j]
# If epsilon graph
if k == 0:
"""
compute an epsilon graph from the similarities
for each node x_i, an epsilon graph has weights
w_ij = d(x_i,x_j) when w_ij >= eps, and 0 otherwise
"""
for i in range(n):
for j in range(i):
sim_ij = similarities[i, j]
if sim_ij >= eps:
W[i, j] = sim_ij
W[j, i] = sim_ij
# If kNN graph
if k != 0:
"""
compute a k-nn graph from the similarities
for each node x_i, a k-nn graph has weights
w_ij = d(x_i,x_j) for the k closest nodes to x_i, and 0
for all the k-n remaining nodes
Remember to remove self similarity and
make the graph undirected
"""
similarities -= np.diag(np.diag(similarities))
for i in range(n):
neighbours = np.argsort(similarities[i, :])
for NN in neighbours[-k:][::-1]:
W[i, NN] = similarities[i, NN]
W = np.maximum(W, W.T) # to make W symmetric
return W
def plot_similarity_graph(X, Y, var=1.0, eps=0.0, k=5):
"""
Function to plot the similarity graph, given data and parameters.
:param X: (n x m) matrix of m-dimensional samples
:param Y: (n, ) vector with cluster assignments
:param var: the sigma value for the exponential function, already squared
:param eps: threshold eps for epsilon graphs
:param k: the number of neighbours k for k-nn
:return:
"""
# use the build_similarity_graph function to build the graph W
# W: (n x n) dimensional matrix representing the adjacency matrix of the graph
W = build_similarity_graph(X, var, eps, k)
# Use auxiliary function to plot
plot_graph_matrix(X, Y, W)
def how_to_choose_epsilon():
"""
TO BE COMPLETED.
Consider the distance matrix with entries dist(x_i, x_j) (the euclidean distance between x_i and x_j)
representing a fully connected graph.
One way to choose the parameter epsilon to build a graph is to choose the maximum value of dist(x_i, x_j) where
(i,j) is an edge that is present in the minimal spanning tree of the fully connected graph. Then, the threshold
epsilon can be chosen as exp(-dist(x_i, x_j)**2.0/(2*sigma^2)).
"""
# the number of samples to generate
num_samples = 100
# the option necessary for worst_case_blob, try different values
gen_pam = 2.0 # to understand the meaning of the parameter, read worst_case_blob in generate_data.py
# get blob data
X, Y = worst_case_blob(num_samples, gen_pam)
# get two moons data
# X, Y = two_moons(num_samples)
n = X.shape[0]
"""
use the distance function and the min_span_tree function to build the minimal spanning tree min_tree
- var: the exponential_euclidean's sigma2 parameter
- dists: (n x n) matrix with euclidean distance between all possible couples of points
- min_tree: (n x n) indicator matrix for the edges in the minimal spanning tree
"""
var = 1.0
dists = pairwise_distances(X).reshape((n, n)) # dists[i, j] = euclidean distance between x_i and x_j
min_tree = min_span_tree(dists)
"""
set threshold epsilon to the max weight in min_tree
"""
distance_threshold = np.max(dists[min_tree])
eps = np.exp(- distance_threshold**2 / (2*var))
"""
use the build_similarity_graph function to build the graph W
W: (n x n) dimensional matrix representing
the adjacency matrix of the graph
use plot_graph_matrix to plot the graph
"""
W = build_similarity_graph(X, var=var, eps=eps, k=0)
plot_graph_matrix(X, Y, W)
if __name__ == '__main__':
n = 300
blobs_data, blobs_clusters = blobs(n)
moons_data, moons_clusters = two_moons(n)
point_circle_data, point_circle_clusters = point_and_circle(n)
worst_blobs_data, worst_blobs_clusters = worst_case_blob(n, 1.0)
var = 1
X, Y = moons_data, moons_clusters
n_samples = X.shape[0]
dists = pairwise_distances(X).reshape((n_samples, n_samples))
min_tree = min_span_tree(dists)
eps = np.exp(- np.max(dists[min_tree])**2 / (2*var))
W_eps = build_similarity_graph(X, var=var, eps=0.6)
W_knn = build_similarity_graph(X, k=15)
plot_graph_matrix(X, Y, W_eps)
plot_graph_matrix(X, Y, W_knn) |
c2fda1f0cd577414996a4fd8550e86a152a0653f | tariqdaouda/pyGeno | /pyGeno/tools/io.py | 757 | 3.515625 | 4 | import sys
def printf(*s) :
'print + sys.stdout.flush()'
for e in s[:-1] :
print e,
print s[-1]
sys.stdout.flush()
def enterConfirm_prompt(enterMsg) :
stopi = False
while not stopi :
print "====\n At any time you can quit by entering 'quit'\n===="
vali = raw_input(enterMsg)
if vali.lower() == 'quit' :
vali = None
stopi = True
else :
print "You've entered:\n\t%s" % vali
valj = confirm_prompt("")
if valj == 'yes' :
stopi = True
if valj == 'quit' :
vali = None
stopi = True
return vali
def confirm_prompt(preMsg) :
while True :
val = raw_input('%splease confirm ("yes", "no", "quit"): ' % preMsg)
if val.lower() == 'yes' or val.lower() == 'no' or val.lower() == 'quit':
return val.lower()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.