blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
4e08f866c6b750c0523aaa96833ed67c4e606e3d | jordan78906/CSCI-161_projects | /HernandezAlmache_Jordan_9.py | 6,417 | 3.875 | 4 |
#Jordan Hernandez-Alamche
#CSci 161 L03
#Assignment 9
'''
Extend the shopping cart class
'''
class ShoppingCart:
count = 0
def __init__(self,customer_name,current_date):
self.customer_name = customer_name
self.current_date = current_date
self.cart_items = []
def add_item(self,ItemToPurchase):
self.cart_items.append(ItemToPurchase)
ShoppingCart.count += 1
def get_cost_of_cart(self):
amount_count = 0
item_count = 0
for list_a in self.cart_items:
for items in list_a:
for qty in items:
amount = float(items[qty][0] * items[qty][1])
quantity = int(items[qty][0])
price = float(items[qty][1])
amount_count += amount
item_count += quantity
print('{}, {} @ ${:.2f} = ${:.2f}'.format(qty,quantity,price,amount))
print('\nQuantity of Items: {}'.format(item_count))
print('Total: ${:.2f}'.format(amount_count))
if amount_count == 0:
print('Shopping Cart is Empty')
def print_descriptions(self):
for list_a in self.cart_items:
for items in list_a:
for description in items:
print(description,': ',items[description][2])
print('Number of Items:{}'.format(order.count))
def remove_item(self, item_name):
###Removing item by key
count_b = 0
for list_a in self.cart_items:
for items in list_a:
if item_name in items:
count_b += 1
items.pop(item_name, 0)
print(items)
if count_b == 0:
print('Item not found in the cart')
def modify_item(self,ItemToPurchase):
###Dealing with input to find key
for names in ItemToPurchase:
for x in names:
name = x
###Modifing dict with key and new_qty
count_c = 0
for list_a in self.cart_items:
for items in list_a:
for names in items:
if names == name:
print(names)
count_c += 1
print(self.cart_items[0][0][name][0])
new_qty = ItemToPurchase[0][item][0]
self.cart_items[0][0][name][0] = new_qty
print(self.cart_items)
if count_c == 0:
print('Item not found in the cart')
class LessThanZerroError(Exception):
def __init__(self, value):
self.value = value
#menu
def print_menu():
print('\nMENU\n\
a - Add item to cart\n\
r - Remove item from the cart\n\
c - Change item quantity\n\
i - output item\'s description\n\
o - output shopping cart\n\
q - quit\n')
commands = str(input('Enter a menu option: '))
commands = commands.lower()
return commands
####main####
customer_name = str(input('Enter the customer\'s name: '))
current_date = str(input('Enter today\'s date(MMM DD, YYYY):'))
print('\nCustomer name: {}'.format(customer_name))
print('Today\'s date: {}'.format(current_date))
order = ShoppingCart(customer_name,current_date)
command = print_menu()
while command != 'q':
try:
if command == 'a':
try:
print('ADD ITEM TO CART')
item = str(input('Enter the item name:'))
description = str(input('Enter the item description:'))
try:
price = float(input('Enter the item price:'))
quantity = int(input('Enter the item quantity:'))
print(price)
print(quantity)
if quantity <= 0:
raise LessThanZerroError('Invalid: entry less than 0.')
elif price <= 0:
raise LessThanZerroError('Invalid: entry less than 0.')
elif price == chr:
raise TypeError('Invalid: character instead of integer/float.')
elif quantity == chr:
raise TypeError('Invalid: character instead of integer/float.')
elif quantity == float:
raise TypeError('Invalid amount: float instead of integer.')
except ValueError as excpt:
print(excpt)
print('Invalid Entry')
except TypeError as excpt:
print(excpt)
print('Invalid Entry')
ItemToPurchase = [{item:[quantity,price,description]}]
order.add_item(ItemToPurchase)
#except LessThanZerroError as excpt:
# print(excpt)
# print('Invalid Entry')
#except ValueError as excpt:
# print(excpt)
# print('Invalid Entry')
#except TypeError as excpt:
# print(excpt)
# print('Invalid Entry')
except Exception as e:
print(e)
# except TypeError:
# print('Invalid: character instead of integer/float.'')
elif command == 'r':
item_name = str(input('Enter the name of the item to remove:'))
order.remove_item(item_name)
elif command == 'c':
item = str(input('Enter the name of the item to be changed:'))
print('MODIFY ITEM TO CART')
description = '0'
price = 0.00
quantity = int(input('Enter the item quantity:'))
ItemToPurchase = [{item:[quantity,price,description]}]
order.modify_item(ItemToPurchase)
elif command == 'i':
print('OUTPUT ITMES\' DESCRIPTIONS')
print('{}\'s Shopping Cart - {}'.format(customer_name,current_date))
print('Items Descriptions')
order.print_descriptions()
elif command == 'o':
print('OUTPUT SHOPPING CART')
print('{}\'s Shopping Cart - {}'.format(customer_name,current_date))
order.get_cost_of_cart()
except Exception as e:
#print('Could not calculate info(a).\n')
print(e)
command = print_menu()
|
5063a1d8744b0bec91ed57b4af7c6ee5b91bb82f | Chaitalykundu/100daysofCoding | /filter_func.py | 354 | 3.625 | 4 | #filter function
def even(a):
return a%2==0
number=list(range(1,11))
print(number) #o/p:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
n=filter(even,number)
print(n) #o/p:<filter object at 0x030EB8D0>
evens=tuple(filter(even,number))
print(evens) #o/p:(2, 4, 6, 8, 10)
even_no=list(filter(lambda i:i%2==0,number))
print(even_no) #o/p:[2, 4, 6, 8, 10]
|
c020627c3ebd8a0dfe54bb2b179137dfade2e80a | wayne-pham/pci-xpress | /databaseCreation.py | 9,141 | 3.65625 | 4 | import sqlite3
database = sqlite3.connect("pythonsqlite.db")
cursor = database.cursor()
############ TABLES #############
# Store
cursor.execute("DROP TABLE IF EXISTS STORE")
store = """
CREATE TABLE STORE
(
Store_Name VARCHAR(100) NOT NULL,
Address_line_1 VARCHAR(100) NOT NULL,
City VARCHAR(100) NOT NULL,
State VARCHAR(100) NOT NULL,
Zip INT NOT NULL,
Phone_Number INT NOT NULL,
PRIMARY KEY (Store_Name),
UNIQUE (Phone_Number)
); """
cursor.execute(store)
# Employee
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
employee = """
CREATE TABLE EMPLOYEE
(
ID INT NOT NULL,
Name VARCHAR(100) NOT NULL,
Wage FLOAT NOT NULL,
Address_line_1 VARCHAR(100) NOT NULL,
City VARCHAR(100) NOT NULL,
State VARCHAR(100) NOT NULL,
Zip INT NOT NULL,
DOB VARCHAR(100) NOT NULL,
Store_Name VARCHAR(100) NOT NULL,
PRIMARY KEY (ID),
FOREIGN KEY (Store_Name) REFERENCES STORE(Store_Name)
); """
cursor.execute(employee)
# Customer Account
cursor.execute("DROP TABLE IF EXISTS CUSTOMER_ACCOUNT")
customer_account = """
CREATE TABLE CUSTOMER_ACCOUNT
(
Account_ID INT NOT NULL,
Email VARCHAR(100) NOT NULL,
Phone_Number INT NOT NULL,
Address_line_1 VARCHAR(100) NOT NULL,
City VARCHAR(100) NOT NULL,
State VARCHAR(100) NOT NULL,
Zip INT NOT NULL,
Name VARCHAR(100) NOT NULL,
DOB VARCHAR(100) NOT NULL,
PRIMARY KEY (Account_ID)
); """
cursor.execute(customer_account)
# Aftermarket Inventory
cursor.execute("DROP TABLE IF EXISTS AFTERMARKET_INVENTORY")
aftermarket_inventory = """
CREATE TABLE AFTERMARKET_INVENTORY
(
GPU_Name VARCHAR(100) NOT NULL,
GPU_Quantity INT NOT NULL,
Store_Name VARCHAR(100) NOT NULL,
PRIMARY KEY (GPU_Name),
FOREIGN KEY (Store_Name) REFERENCES STORE(Store_Name)
); """
cursor.execute(aftermarket_inventory)
# Manufacturer
cursor.execute("DROP TABLE IF EXISTS MANUFACTURER")
manufacturer = """
CREATE TABLE MANUFACTURER
(
Name VARCHAR(100) NOT NULL,
Contact_Number INT NOT NULL,
Address_line_1 VARCHAR(100) NOT NULL,
City VARCHAR(100) NOT NULL,
State VARCHAR(100) NOT NULL,
Zip INT NOT NULL,
Store_Name VARCHAR(100) NOT NULL,
PRIMARY KEY (Name),
FOREIGN KEY (Store_Name) REFERENCES STORE(Store_Name),
UNIQUE (Contact_Number)
); """
cursor.execute(manufacturer)
# Stock Inventory
cursor.execute("DROP TABLE IF EXISTS STOCK_INVENTORY")
stock_inventory = """
CREATE TABLE STOCK_INVENTORY
(
GPU_Name VARCHAR(100) NOT NULL,
GPU_Quantity INT NOT NULL,
Store_Name VARCHAR(100) NOT NULL,
PRIMARY KEY (GPU_Name),
FOREIGN KEY (Store_Name) REFERENCES STORE(Store_Name)
); """
cursor.execute(stock_inventory)
# Customer
cursor.execute("DROP TABLE IF EXISTS CUSTOMER")
customer = """
CREATE TABLE CUSTOMER
(
ID INT NOT NULL,
Payment_Method VARCHAR(100) NOT NULL,
Payment_Amount FLOAT NOT NULL,
Items_Purchased INT NOT NULL,
Card_Number INT NULL,
Store_Name VARCHAR(100),
PRIMARY KEY (ID),
FOREIGN KEY (Store_Name) REFERENCES STORE(Store_Name),
FOREIGN KEY (ID) REFERENCES CUSTOMER_ACCOUNT(Account_ID)
); """
cursor.execute(customer)
# GPU
cursor.execute("DROP TABLE IF EXISTS GPU")
gpu = """
CREATE TABLE GPU
(
GPU_Name VARCHAR(100) NOT NULL,
GPU_Retail_Price FLOAT NOT NULL,
GPU_Wholesale_Price FLOAT NOT NULL,
Architecture VARCHAR(100) NOT NULL,
Power_Requirement INT NOT NULL,
VRAM INT NOT NULL,
Clock_Speed INT NOT NULL,
Manufacturer VARCHAR(100) NOT NULL,
PRIMARY KEY (GPU_Name),
FOREIGN KEY (GPU_Name) REFERENCES STOCK_INVENTORY(GPU_Name),
FOREIGN KEY (GPU_Name) REFERENCES AFTERMARKET_INVENTORY(GPU_Name)
); """
cursor.execute(gpu)
############ INSERT DATA #############
# Store
cursor.execute("INSERT INTO STORE VALUES(?, ?, ?, ?, ?, ?);", ('PCIXpress','1234 Capacitor Rd','Indianapolis','IN', 12345, 1234567890))
# Stock Inventory
cursor.execute("INSERT INTO STOCK_INVENTORY VALUES(?,?,?);", ('RTX 3090 Founders Edition', 10, 'PCIXpress'))
cursor.execute("INSERT INTO STOCK_INVENTORY VALUES(?,?,?);", ('RTX 3080 Founders Edition', 9, 'PCIXpress'))
cursor.execute("INSERT INTO STOCK_INVENTORY VALUES(?,?,?);", ('RTX 3070 Founders Edition', 8, 'PCIXpress'))
cursor.execute("INSERT INTO STOCK_INVENTORY VALUES(?,?,?);", ('RTX 3060 Founders Edition', 7, 'PCIXpress'))
cursor.execute("INSERT INTO STOCK_INVENTORY VALUES(?,?,?);", ('RTX 3060 Ti Founders Edition', 6, 'PCIXpress'))
cursor.execute("INSERT INTO STOCK_INVENTORY VALUES(?,?,?);", ('Radeon RX 6700XT', 5, 'PCIXpress'))
# Aftermarket Inventory
cursor.execute("INSERT INTO AFTERMARKET_INVENTORY VALUES(?,?,?);", ('ASUS ROG STRIX NVIDIA GeForce RTX 3090 Gaming', 10, 'PCIXpress'))
cursor.execute("INSERT INTO AFTERMARKET_INVENTORY VALUES(?,?,?);", ('EVGA GeForce RTX 3080 XC3 ULTRA HYBRID GAMING', 9, 'PCIXpress'))
cursor.execute("INSERT INTO AFTERMARKET_INVENTORY VALUES(?,?,?);", ('MSI GeForce RTX 3070 GAMING X TRIO', 8, 'PCIXpress'))
cursor.execute("INSERT INTO AFTERMARKET_INVENTORY VALUES(?,?,?);", ('GIGABYTE AORUS GeForce RTX 3060 ELITE', 7, 'PCIXpress'))
cursor.execute("INSERT INTO AFTERMARKET_INVENTORY VALUES(?,?,?);", ('ZOTAC GAMING GeForce RTX 3060 Ti Twin Edge OC', 6, 'PCIXpress'))
cursor.execute("INSERT INTO AFTERMARKET_INVENTORY VALUES(?,?,?);", ('Sapphire Pulse AMD Radeon RX 6700XT', 5, 'PCIXpress'))
# GPU
cursor.execute("INSERT INTO GPU VALUES(?,?,?,?,?,?,?,?);", ('RTX 3090 Founders Edition', 1500.0, 600.0, 'Ampere', 1000, 24, 1395, 'Nvidia'))
cursor.execute("INSERT INTO GPU VALUES(?,?,?,?,?,?,?,?);", ('RTX 3080 Founders Edition', 700.0, 280.0, 'Ampere', 750, 10, 1440, 'Nvidia'))
cursor.execute("INSERT INTO GPU VALUES(?,?,?,?,?,?,?,?);", ('RTX 3070 Founders Edition', 500.0, 200.0, 'Ampere', 650, 8, 1500, 'Nvidia'))
cursor.execute("INSERT INTO GPU VALUES(?,?,?,?,?,?,?,?);", ('RTX 3060 Founders Edition', 330.0, 132.0, 'Ampere', 550, 12, 1320, 'Nvidia'))
cursor.execute("INSERT INTO GPU VALUES(?,?,?,?,?,?,?,?);", ('RTX 3060 Ti Founders Edition', 400.0, 160.0, 'Ampere', 600, 8, 1410, 'Nvidia'))
cursor.execute("INSERT INTO GPU VALUES(?,?,?,?,?,?,?,?);", ('Radeon RX 6700XT', 479.0, 287.0, 'Big Navi', 600, 12, 2321, 'AMD'))
cursor.execute("INSERT INTO GPU VALUES(?,?,?,?,?,?,?,?);", ('ASUS ROG STRIX NVIDIA GeForce RTX 3090 Gaming', 1800.0, 600.0, 'Ampere', 1000, 24, 1395, 'Nvidia'))
cursor.execute("INSERT INTO GPU VALUES(?,?,?,?,?,?,?,?);", ('EVGA GeForce RTX 3080 XC3 ULTRA HYBRID GAMING', 900.0, 280.0, 'Ampere', 750, 10, 1440, 'Nvidia'))
cursor.execute("INSERT INTO GPU VALUES(?,?,?,?,?,?,?,?);", ('MSI GeForce RTX 3070 GAMING X TRIO', 700.0, 200.0, 'Ampere', 650, 8, 1500, 'Nvidia'))
cursor.execute("INSERT INTO GPU VALUES(?,?,?,?,?,?,?,?);", ('GIGABYTE AORUS GeForce RTX 3060 ELITE', 530.0, 132.0, 'Ampere', 550, 12, 1320, 'Nvidia'))
cursor.execute("INSERT INTO GPU VALUES(?,?,?,?,?,?,?,?);", ('ZOTAC GAMING GeForce RTX 3060 Ti Twin Edge OC', 400.0, 160.0, 'Ampere', 600, 8, 1410, 'Nvidia'))
cursor.execute("INSERT INTO GPU VALUES(?,?,?,?,?,?,?,?);", ('Sapphire Pulse AMD Radeon RX 6700XT', 579.0, 287.0, 'Big Navi', 600, 12, 2321, 'AMD'))
# Customer
cursor.execute("INSERT INTO CUSTOMER VALUES(?,?,?,?,?,?);", (1, 'CREDIT', 899.00, 1, 5161889457891231, 'PCIXpress'))
cursor.execute("INSERT INTO CUSTOMER VALUES(?,?,?,?,?,?);", (2, 'DEBIT', 1800.00, 2, 9875458612258549, 'PCIXpress'))
cursor.execute("INSERT INTO CUSTOMER VALUES(?,?,?,?,?,?);", (3, 'CREDIT', 3000.00, 3, 5421649879865465, 'PCIXpress'))
cursor.execute("INSERT INTO CUSTOMER VALUES(?,?,?,?,?,?);", (4, 'CREDIT', 4000.00, 4, 8916854489491213, 'PCIXpress'))
cursor.execute("INSERT INTO CUSTOMER VALUES(?,?,?,?,?,?);", (5, 'DEBIT', 500.00, 1, 5454897425689864, 'PCIXpress'))
# Customer Account
cursor.execute("INSERT INTO CUSTOMER_ACCOUNT VALUES(?,?,?,?,?,?,?,?,?);", (1, 'Blub@pcixpress.com', 1234567, '1234 Nulaxy Ave', 'Indianapolis', 'IN', 46589, 'Blub', '12/11/2000'))
cursor.execute("INSERT INTO CUSTOMER_ACCOUNT VALUES(?,?,?,?,?,?,?,?,?);", (2, 'Klee@pcixpress.com', 7654321, '6456 Jumpty dumpty Rd', 'Mondstadt', 'MD', 97897, 'Klee', '12/11/2010'))
cursor.execute("INSERT INTO CUSTOMER_ACCOUNT VALUES(?,?,?,?,?,?,?,?,?);", (3, 'Nora@pcixpress.com', 6762655, '4564 Imaginary ln', 'Mondstadt', 'MD', 56486, 'Nora', '12/11/2010'))
cursor.execute("INSERT INTO CUSTOMER_ACCOUNT VALUES(?,?,?,?,?,?,?,?,?);", (4, 'Fatooey@pcixpress.com', 1666666, '4898 Tsarista Ct', 'Zapolyarny Palace', 'SN', 79786, 'Fatooey', '12/11/1990'))
cursor.execute("INSERT INTO CUSTOMER_ACCOUNT VALUES(?,?,?,?,?,?,?,?,?);", (5, 'Lapis@pcixpress.com', 1564897, '6878 Jade ln', 'Minlin', 'LY', 45644, 'Lapis', '12/11/1000'))
# Employee
cursor.execute("INSERT INTO EMPLOYEE VALUES(?,?,?,?,?,?,?,?,?);", (1, 'Wayne Pham', 200.00, '3432 West Haven Dr.', 'Indianapolis', 'IN', 47899, '10/12/1999', 'PCIXpress'))
cursor.execute("INSERT INTO EMPLOYEE VALUES(?,?,?,?,?,?,?,?,?);", (2, 'Samip Vaidh', 200.00,'4654 Sugar Weight Dr.', 'Indianapolis', 'IN', 56481, '05/28/1994', 'PCIXpress'))
# Manufacturer
cursor.execute("INSERT INTO MANUFACTURER VALUES(?,?,?,?,?,?,?);", ('Nvidia', 18007976530, '2788 San Tomas Expressway', 'Santa Clara', 'CA', 95050, 'PCIXpress'))
cursor.execute("INSERT INTO MANUFACTURER VALUES(?,?,?,?,?,?,?);", ('AMD', 18772841566, '2485 Augustine Road', 'Santa Clara', 'CA', 95054, 'PCIXpress'))
database.commit()
|
deb27cc24b0de5884ec92c38f479ef3f1df3a766 | soom1017/ITE1014 | /2020_ITE1014/5-1/2.py | 308 | 3.984375 | 4 | import random
numbers = []
for i in range(0,100):
a= random.randint(1, 1000)
numbers.append(a)
for j in numbers:
print(j, end = ' ')
print('\n')
max_number = 1
for k in numbers:
if k > max_number:
max_number = k
print("max value: " + str(max_number))
|
36e14e604f52315bc26630b23b757d4fd6b4fee0 | 41xu/SwordToProblem | /04重建二叉树.py | 952 | 3.53125 | 4 | # -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回构造的TreeNode根节点
def reConstructBinaryTree(self, pre, tin):
# write code here
root=pre[0]
rootindex=tin.index(root)
leftnum=rootindex
rightnum=len(tin)-leftnum-1
left_pre=pre[1:leftnum+1]
right_pre=pre[leftnum+1:]
left_tin=tin[:rootindex]
right_tin=tin[rootindex+1:]
curroot=TreeNode(root)
#if left_pre!=[]:
#curroot.left=TreeNode(left_pre[0])
#if right_pre!=[]:
#curroot.right=TreeNode(right_pre[0])
if left_pre!=[]:
curroot.left=self.reConstructBinaryTree(left_pre,left_tin)
if right_pre!=[]:
curroot.right=self.reConstructBinaryTree(right_pre,right_tin)
return curroot
|
bbf42b09e9fa78bca48430d9269e90c9cb9cf549 | markgreene74/bitesofpy | /bytes/40/exercise_40.py | 812 | 4.03125 | 4 | # https://codechalleng.es/bites/40/
def binary_search(sequence, target):
# define the uppper/lower limits
low = 0
high = len(sequence) - 1
# start the search
while low <= high:
# pick the middle
middle = (low + high) // 2
# now start the search
if sequence[middle] == target:
# found it
return middle
elif sequence[middle] > target:
# it's in the lower half, discard the upper half
high = middle - 1
else:
# it must be in the upper half, discard the lower half
low = middle + 1
# if we made it to this point the target is not in the sequence
return None
"""
Resolution time: ~50 min. (avg. submissions of 5-240 min.) - awesome, you solved it in 12 min. 💪
"""
|
4ad9dddfb4d22162ba91be7ee16df6b535069079 | NiuNiu-jupiter/Leetcode | /Premuim/1102. Path With Maximum Minimum Value.py | 1,492 | 3.828125 | 4 | """
Given a matrix of integers A with R rows and C columns, find the maximum score of a path starting at [0,0] and ending at [R-1,C-1].
The score of a path is the minimum value in that path. For example, the value of the path 8 → 4 → 5 → 9 is 4.
A path moves some number of times from one visited cell to any neighbouring unvisited cell in one of the 4 cardinal directions (north, east, west, south).
Example 1:
Input: [[5,4,5],[1,2,6],[7,4,6]]
Output: 4
Explanation:
The path with the maximum score is highlighted in yellow.
Example 2:
Input: [[2,2,1,2,2,2],[1,2,2,2,1,2]]
Output: 2
Example 3:
Input: [[3,4,6,3,4],[0,2,1,1,7],[8,8,3,2,7],[3,2,4,9,8],[4,1,2,0,0],[4,6,5,4,3]]
Output: 3
Note:
1 <= R, C <= 100
0 <= A[i][j] <= 10^9
"""
class Solution:
def maximumMinimumPath(self, A: List[List[int]]) -> int:
if not A: return -1
visited = set()
start = (0,0)
Q = [(-A[0][0], 0, 0)]
directions = [(0,1),(1,0),(-1,0),(0,-1)]
while Q:
val ,r, c = heapq.heappop(Q)
if r == len(A) - 1 and c == len(A[0]) - 1:
return -val
for dir in directions:
nr , nc = r + dir[0] , c + dir[1]
if 0 <= nr < len(A) and 0 <= nc < len(A[0]) and A[nr][nc]!= -1:
heapq.heappush(Q,(max(val,-A[nr][nc]),nr,nc))
A[nr][nc] = -1
return -1
|
d496e3554c6145e451a5b61a70df2d53e3454fca | WillPowerCraft/my-first-repository | /str_lines_slices.py | 1,548 | 4.1875 | 4 | # Python поддерживает emoji
# Индексация символов в строке - указать конкретный символ внутри []
# s = 'Hello'
# print(s[0])
# # Python индексирует символы в строке по возрастающей и по убывающей '-1' - последний символ строки
# print(s[-1])
# # Пример сканирования каждого символа в строке
# # Такой способ удобен, если нужно узнать не только символ, но и индекс символа (i)
# for i in range(len(s)):
# print(s[i])
# # Тот же результат без индекса - короче
# for c in s:
# print(c)
#
# s = '01234567891011121314151617'
# for i in range(0, len(s), 5):
# print(s[i], end='')
# Slice - срез для работы с целыми частями строки в диапазоне
# s = 'abcdefghij'
# print(s)
# print(s[2:5])
# print(s[0:6])
# print(s[2:7])
# Slice from digit to end or from start to digit
# print(s[2:])
# print(s[:2])
# print(s[:])
# Slice with '-digits'
# print(s[-9:-4])
# print(s[-3:])
# print(s[:-3])
# Slice step - 3d not mandatory param in Slice what mean slice digit every X
# print()
# print(s)
# print(s[::-1]) # turn last to start digit
# print(s[::-2])
# print(s[1:7:2])
# print(s[3::2])
# print(s[:7:3])
# print(s[::2])
# Changing string digits
# if i need change digit in string i do this code
# s = s[:4] + 'XXX' + s[5:]
# print(s) |
593b395ec358252d6ef7a4afb6839d0131e887f0 | GiovanniScattolin/stock_market | /stock_package/scripts/csv_reader.py | 1,141 | 3.953125 | 4 | import pandas as pd
def read_currency_data(path):
"""Read the file containing data about currencies, store it in a DataFrame
:param path: The path to the .csv file containing currencies info
:type path: string
:return: the Dataframe containing infos about the currencies
:rtype: Pandas.Dataframe
"""
if path.split('.')[-1] != 'csv':
return False
df = pd.DataFrame()
try:
df = pd.read_csv(path, sep=";")
df.columns = ['currency', 'curr_to_dollar', 'symbol']
df.set_index('currency', inplace=True)
except Exception:
return False
return df
def read_available_companies(path):
"""Read the file containing data about companies, store it in a DataFrame
:param path: The path to the .csv file containing companies info
:type path: string
:return: the Dataframe containing infos about the companies
:rtype: Pandas.Dataframe
"""
if path.split('.')[-1] != 'csv':
return False
df = pd.DataFrame
try:
df = pd.read_csv(path, sep=";")
except Exception:
return False
return set(list(df['ticker']))
|
d95d9688d393bc9df6ad00d41e544cfcaa044a2f | projjal1/PCAP_Programming_Series | /classes_part1.py | 484 | 4.34375 | 4 | #Program to demonstrate the simple implementation of OOP concept
#using classes in Python
class A:
'''This class is for simple demo of constructors and methods'''
def __init__(self):
'''Default-constructor'''
print("Inside the constructor")
def hello(self):
'''Prints hello'''
print("Hello")
v=A()
v.hello()
#Help to print the docstring
print(help(A))
#Help to print the particular docstring of a method in method
print(help(A.hello)) |
abb561c2081b9a56dc4e1f156de92a9678a916d0 | sunilkum84/golang-practice-2 | /revisiting_ctci/chapter1/ZeroMatrix_1_8.py | 1,098 | 3.65625 | 4 | """
take an m x n matrix and if there is a zero in the matrix then change the entire
row and column it is in to 0s
"""
import unittest
def ZeroMatrix(mat):
""" take a list of lists where cells are integers,
if there is a zero cell then change all values in the row and
column to zero """
z_rows = []
z_cols = []
for r, row in enumerate(mat):
for c, val in enumerate(row):
if val == 0:
z_rows.append(r)
z_cols.append(c)
for r in set(z_rows):
for i in range(0, len(mat[0])):
mat[r][i] = 0
for c in set(z_cols):
for i in range(0,len(mat)):
mat[i][c] = 0
return mat
class TestZeroMat(unittest.TestCase):
def test_ZeroMatrix(self):
self.t1 = [[0,1,1,],
[1,1,1,],
[1,0,1,],
[1,1,1,],]
self.o1 = [[0,0,0,],
[0,0,1,],
[0,0,0,],
[0,0,1,],]
self.t2 = [[1,1,1,1,],
[1,1,1,1,],
[1,1,1,0,],
[1,1,1,1,],]
self.o2 = [[1,1,1,0,],
[1,1,1,0,],
[0,0,0,0,],
[1,1,1,0,],]
self.assertEqual(ZeroMatrix(self.t1),self.o1)
self.assertEqual(ZeroMatrix(self.t2),self.o2)
if __name__ == "__main__":
unittest.main() |
70fd0ed87f2cc53e9b3c5aaa6d860d372a2070e7 | donggyuu/algorithm | /algorithm-python/chp2_check_palindrome_string.py | 1,342 | 3.734375 | 4 | '''
N개의 문자열을 입력받아 회문이면 YES, 아니면 NO를 출력하는 프로그램을 작성한다.
(대소문자 구분은 안함, 각 단어 길이는 100을 넘지 않는다)
**input
5
level
moon
abcba
soon
gooG
**output
# 1 YES
# 2 NO
# 3 YES
# 4 NO
# 5 YES
'''
# ---------------------------------
# 여러 방법
# 1. for문으로 역순 구하기
# 2. [::-1] // 이거 문자열에서만 쓰임. list는 해보니까 안되더라...
# 3. method활용 -> reverse, reversed
# 개선된 풀이 - [::-1]
n = int(input())
for i in range(n):
s = input()
s = s.upper()
if s == s[::-1]:
print("#%d YES" %(i+1))
else:
print("#%d NO" %(i+1))
# ---------------------------------
# 나의 초기 풀이 - for문 사용
def isPalindrome(inputString):
lowerString = inputString.lower()
fromStart = ""
fromEnd = ""
# get fromStart & fromEnd
for i in range(len(lowerString)):
fromStart += lowerString[i]
fromEnd += lowerString[-i-1]
# print
if fromStart == fromEnd:
return 'YES'
else:
return 'NO'
# get result
nString = int(input())
nResultList = []
for i in range(nString):
inputString = input()
nResultList.append(isPalindrome(inputString))
# print result
for i in range(nString):
print('#', i+1, nResultList[i]) |
a14538fbc19b998f44d3ed1634b5faef4091e76e | nosoccus/Applied-Programming | /LAB3/lab1-4.py | 231 | 3.8125 | 4 | arr = ['a', ['c', 1, 3], ['f', 7, [4, '4']], [{'lalala': 111}]]
lst = []
def func(arr):
for i in arr:
if type(i) == list:
func(i)
else:
lst.append(i)
return lst
print(func(arr))
|
194e478fd23c2078973bd2aa8d3f76fcf2fc7735 | ljia2/leetcode.py | /solutions/hashtable/750.Number.Of.Corner.Rectangles.py | 2,341 | 3.796875 | 4 | import collections
import math
class Solution(object):
def countCornerRectangles(self, grid):
"""
Given a grid where each entry is only 0 or 1, find the number of corner rectangles.
A corner rectangle is 4 distinct 1s on the grid that form an axis-aligned rectangle.
Note that only the corners need to have the value 1. Also, all four 1s used must be distinct.
Example 1:
Input: grid =
[[1, 0, 0, 1, 0],
[0, 0, 1, 0, 1],
[0, 0, 0, 1, 0],
[1, 0, 1, 0, 1]]
Output: 1
Explanation: There is only one corner rectangle, with corners grid[1][2], grid[1][4], grid[3][2], grid[3][4].
Example 2:
Input: grid =
[[1, 1, 1],
[1, 1, 1],
[1, 1, 1]]
Output: 9
Explanation: There are four 2x2 rectangles, four 2x3 and 3x2 rectangles, and one 3x3 rectangle.
Example 3:
Input: grid =
[[1, 1, 1, 1]]
Output: 0
Explanation: Rectangles must have four distinct corners.
Note:
The number of rows and columns of grid will each be in the range [1, 200].
Each grid[i][j] will be either 0 or 1.
The number of 1s in the grid will be at most 6000.
:type grid: List[List[int]]
:rtype: int
"""
if not grid or not len(grid[0]):
return 0
if len(grid) == 1 or len(grid[0]) == 1:
return 0
r, c = len(grid), len(grid[0])
col_dict = collections.defaultdict(set)
for j in range(c):
for i in range(r):
if grid[i][j] == 1:
col_dict[j].add(i)
ans = 0
cols = list(col_dict.keys())
for c1 in range(len(cols)):
for c2 in range(0, c1):
s1, s2 = col_dict[cols[c1]], col_dict[cols[c2]]
ans += self.combination(len(s1.intersection(s2)), 2)
return ans
def combination(self, n, m):
if n < m:
return 0
if n == m:
return 1
return math.factorial(n) / (math.factorial(n-m) * math.factorial(m))
s = Solution()
print(s.countCornerRectangles([[0,0,1,1],
[1,0,0,0],
[0,0,1,0],
[1,0,1,1]])) |
08d320cdb159c3c38a1e08fe533a26d8348a74a5 | omergundogdu75/python-egitim | /OOP/specials.py | 669 | 3.796875 | 4 | mylist = [1,2,3]
# myString = "My String"
#
# print(len(mylist))
# print(len(myString))
#
# print(type(mylist))
# print(type(myString)print(type(myString)
class Movie:
def __init__(self,title,director,duration):
self.title = title
self.director = director
self.duration = duration
print(f"Movie oluşturuldu")
def __str__(self):
return f" {self.title} by {self.director}"
def __len__(self):
return self.duration # len
def __del__(self):
print("Film Silindi")
m = Movie("Film Adı","Yönetmen",120)
# print(mylist)
# print(str(m))
print(len(mylist))
print(len(m))
del m
# m objesi silindi
|
ed70b2da7484a8a9e94170113f446c39140569f5 | iamchiranjeeb/Python-Task | /task/passwords.py | 1,123 | 3.703125 | 4 | import re
class Capital(object):
def __init__(self,str):
self.string = str
def capitalCheck(self):
if re.search("[A-Z]",self.string):
return True
else:
return False
class Small(Capital):
def __init__(self,str):
super().__init__(str)
def smallCheck(self):
if re.search("[a-z]",self.string):
return True
else:
return False
class Number(Small):
def __init__(self,str):
super().__init__(str)
def numCheck(self):
if re.search("[0-9]",self.string):
return True
else:
return False
class Special(Number):
def __init__(self,str):
super().__init__(str)
def checkSpecial(self):
if re.search("[_@$/|?#]",self.string):
return True
else:
return False
if __name__ == '__main__':
sp = Special("chirH98")
sp2 = Special("CHIRU")
sp3 = Special("goldy#98")
print(sp.capitalCheck())
print(sp2.smallCheck())
print(sp2.numCheck())
print(sp3.checkSpecial())
print(sp2.checkSpecial()) |
48400e8bb1e0f42c0cdca5a10187d4587875021d | zyxdSTU/Ner_Method | /util.py | 379 | 3.734375 | 4 | #获取词典
def acquireWordDict(inputPathArr, wordDict):
for inputPath in inputPathArr:
input = open(inputPath, 'r', encoding='utf-8', errors='ignore')
for line in input.readlines():
if len(line) == 0: continue
word = line.split(' ')[0]
if word not in wordDict:
wordDict.append(word)
input.close() |
1e0f3685bea6d6b428404b65e69b73cc530ec915 | jadewu/Practices | /Python/Reverse_String_II.py | 526 | 3.71875 | 4 | # 把string分成多个片段放进list里,每个片段长度为k
# 把每两个片段中的第一个reverse,第二个不动
# 把所有片段join一下
class Solution:
def reverseStr(self, s: str, k: int) -> str:
# Divide s into an array of substrings length k
s = [s[i:i+k] for i in range(0,len(s),k)]
# Reverse every other substring, beginning with s[0]
for i in range(0,len(s),2):
s[i] = s[i][::-1]
# Join array of substrings into one string and return
return ''.join(s)
|
e82ffd1539d515872bbf777cf424d28e0e075181 | satusuuronen/pythai | /gp/command.py | 3,683 | 3.78125 | 4 | """
@project: Pythai - Artificial Intellegence Project with Python
@package: Genetic Programming
@author: Timo Ruokonen (timoruokonen)
"""
import random
from literal import literal
from global_variable import global_variable
class command:
'''
Represents a command (function call) in the generated code. Commands can take parameters
and have a return value.
'''
registered_commands = list()
@staticmethod
def register(name, return_type, typeof, parameters, state_only):
'''
Static method for registering a new command type.
Parameters:
name - Name of the command. Must be the actual method/function name.
return_type - The return type of the command, can be None.
typeof - Type of the class that has this command. For example str. Type can be
also None which means that command is executed in global namespace.
parameters - Array of parameters that the command requires. Can be empty list.
state_only - Is the command only about the state. If true, this command will no be
used in the blocks where the actual commands are executed. It will only be used
in the equations. If false, this command can ne used in both places.
'''
command.registered_commands.append([name, return_type, typeof, parameters, state_only])
print "Registered command: " + name
@staticmethod
def generate():
'''
Static method for generating a command instance. Generated command instance
will be randomly selected from the all registered commands. Returns the generated
command.
'''
new_command = command()
#Find a command that is not a status command
while (True):
new_command.command = command.registered_commands[random.randrange(len(command.registered_commands))]
if (new_command.command[4] == False):
break
#create parameters to command if needed
new_command.parameters = []
if (len(new_command.command[3]) > 0):
for param in new_command.command[3]:
new_command.parameters.append(literal.generate(param))
return new_command
@staticmethod
def generate_with_type(typeof):
'''
Static method for generating a command with specific return type. The new generated
command is randomly selected from all registered commands that have the given return
type.
'''
new_command = command()
while True:
cmd = command.registered_commands[random.randrange(len(command.registered_commands))]
if (cmd[1] == typeof):
break
new_command.command = cmd
#create parameters to command if needed
new_command.parameters = []
if (len(new_command.command[3]) > 0):
for param in new_command.command[3]:
new_command.parameters.append(literal.generate(param))
return new_command
def to_s(self):
'''Returns the command as string (code). '''
retval = ""
#if object was given, add that to the call
if (self.command[2] != None):
variable = global_variable.generate(self.command[2])
retval += variable.to_s() + "."
retval += self.command[0] + '('
#add parameters to the call
first = True
for param in self.parameters:
if (first == False):
retval += ', '
else:
first = False
retval += param.to_s()
retval += ')'
return retval
|
1d7a6d523975ef4245a1ea0a348f52b262d67f7e | buyi823/learn_python | /Python_100/python_79_string_order.py | 825 | 4.28125 | 4 | #!/usr/bin/python3
# -*- coding: UTF-8 -*-
# By Blaine 2021-08-04 16:43
# string order
if __name__ == '__main__':
str1 = input('input string:\n')
str2 = input('input string:\n')
str3 = input('input string:\n')
print(str1, str2, str3)
if str1 > str2:
str1, str2 = str2, str1
if str1 > str3:
str1, str3 = str3, str1
if str2 > str3:
str2, str3 = str3, str2
print('after being sorted.')
print(str1, str2, str3)
'''
在python中,默认是按照ascii的大小比较的; 字符串按位比较,
两个字符串第一位字符的ascii码谁大,字符串就大,不再比较后面的;
第一个字符相同就比第二个字符串,以此类推。
注意:空格的ascii码是32,空(null)的ascii码是0,大写字母和小写字母的ascii不同
''' |
5055a423d4f7ac3e4df64d06ba63f704bb2d3103 | gistable/gistable | /all-gists/32d1a0d97e391392dec10a83070336f8/snippet.py | 5,816 | 3.671875 | 4 | def move_to_dir(old, new):
"""Converts using e.g. old position (1,1) and new position (2, 1) to a direction (RIGHT)"""
if old[0] < new[0]:
return "RIGHT"
if old[1] < new[1]:
return "DOWN"
if old[0] > new[0]:
return "LEFT"
return "UP"
def get_score(starts):
"""
Function for calculating the score given current starting positions for all bots
"""
# create a nested dict called graph to store which bot (o) contains which
# spot (n) at which iteration (it)
graphs = {i: {} for i in range(n_players)}
# graphset just contains a copy that is being updated from the current `occupied` places
# once no changes for any bot, indicates it stops
graphset = set(x for x in occupied)
# the order in which bots are playing this turn, e.g. if our bot is player 2: (2, 3, 1, 0)
order = list(range(my_id, n_players)) + list(range(0, my_id))
it = 1
# loop until no changes
while True:
# full gets falsified when any new move is possible by any bot in a round
full = True
# keeps track of who will end up owning the spots from this turn
moves = {}
for o in order:
# on a single turn, for each bot, `starts` contains the possible starting positions
# in case of starting round, logically there is only 1 possibility
# so: for each possibility `x` of starting for bot `o`
for x in starts[o]:
# consider all the neighbouring tiles
for n in NEIGHBOURS[x]:
# if n not visitable by other bots earlier
if n not in graphset or (n in moves and it == 1):
# make sure we will continue for at least 1 more round as we found new
full = False
# add to occupied for this `get_score`
graphset.add(n)
# register `neighbour` to belong to bot `o`
moves[n] = o
# update the graph with who owns in this round
for k, v in moves.items():
graphs[v][k] = it
if full:
# break since no changes were in the last round (no new possible moves)
break
# update the new possible starting positions for each bot
starts = [[k for k, v in moves.items() if v == i] for i in range(n_players)]
it += 1
# number of tiles we are closest to (higher=better)
num_my_tiles = len(graphs[my_id])
# number of tiles enemies are closest to (lower=better)
num_enemy_tiles = sum([len(graphs[i]) for i in range(n_players) if i != my_id])
# summed distance for reaching each tile for all enemies (higher=better)
enemies_dist = sum([sum(graphs[i].values()) for i in range(n_players) if i != my_id])
# simple weighting, importance: num_my_tiles > num_enemy_tiles > enemies_dist
return sum([num_my_tiles * 10000000, num_enemy_tiles * -100000, enemies_dist])
# NEIGHBOURS is a constant structure that gives the neighbouring tiles (e.g. 4 neighbours for a centered square)
# NEIGHBOURS[(2,2)] would give [(1,2), (2,1), (3, 2), (2, 3)]
NEIGHBOURS = {}
for i in range(30):
for j in range(20):
neighbours = []
if i < 29:
neighbours.append((i + 1, j))
if i > 0:
neighbours.append((i - 1, j))
if j < 19:
neighbours.append((i, j + 1))
if j > 0:
neighbours.append((i, j - 1))
NEIGHBOURS[(i, j)] = neighbours
# `occupied` contains all the previously visited spots by bots
occupied = {}
# loop as long as the game lasts
while True:
# each turn we receive the number of players (n_players) and our id
# (my_id) from the codingame engine
n_players, my_id = [int(i) for i in input().split()]
# curr_moves will consist of the previously played move for each bot
curr_moves = []
for i in range(n_players):
# for each player, obtain the old and new coordinates
x0, y0, x1, y1 = [int(j) for j in input().split()]
occupied[(x0, y0)] = i
occupied[(x1, y1)] = i
curr_moves.append((x1, y1))
for i, cm in enumerate(curr_moves):
# (-1, -1) indicates bot is dead
if cm == (-1, -1):
occupied = {k: v for k, v in occupied.items() if v != i}
for p in range(n_players):
x1, y1 = curr_moves[p]
# currently only calculate from "our" perspective
if p == my_id:
# our current location
me = (x1, y1)
scores = []
# loop over our neighbouring tiles
for neighbour in NEIGHBOURS[me]:
# if a neighbour is not in occupied, it means it is still availbable and
# should be considered a starting position to calculate from how good of a
# move it is
if neighbour not in occupied:
# copy to prevent overwriting
player_starts = [[x] for x in curr_moves.copy()]
# fix our starting position to a candidate move
player_starts[my_id] = [neighbour]
# each player that is dead does not play (since no starting moves)
for i, cm in enumerate(curr_moves):
if cm == (-1, -1):
player_starts[i] = []
# gather score for board given starting positions
score = get_score(player_starts)
scores.append((score, neighbour))
# return the best move given the posible candidate moves
best_score_move = sorted(scores, key=lambda x: x[0], reverse=True)[0]
# print the direction we want to go to
print(move_to_dir(me, best_score_move[-1]))
|
06668bb6ab52aeb5b5eb2468576b4c7e6cc8502a | Bram-Hub/Proof-Generator | /src/main.py | 2,319 | 3.546875 | 4 | import os
import sys
import argument_parser as arg_p
from lxml import etree
def main():
print("Prove or disprove an argument defined in a .bram file. All premises should be defined in assumption tags "
"and all goals should be defined in goal tags within the proof with an id of 0.\n")
location = os.path.dirname(sys.argv[0])
directory = ""
invalid_dir = True
while invalid_dir:
directory = input(f"Directory of argument file (default is {location}/arguments): ")
if directory.strip() == "":
directory = location + "/arguments"
if os.path.isdir(directory):
invalid_dir = False
else:
print("Directory not found.")
invalid_name = True
file_name = ""
while invalid_name:
file_name = input("Name of argument file (leave out .bram): ").strip()
if os.path.isfile(f"{directory}/{file_name}.bram"):
invalid_name = False
else:
print("File not found.")
file_loc = f"{directory}/{file_name}.bram"
try:
ap = arg_p.ArgumentParser(file_loc)
except ValueError:
print("A statement was improperly formatted and could not be read in or no goals were given.")
input("Please press enter to close the program.")
return
if len(ap.goals) == 1:
xml_doc = ap.solve(0)
with open(f"{directory}/{file_name}_proof.bram", 'w') as f:
f.write(etree.tostring(xml_doc, pretty_print=True, xml_declaration=True, encoding="utf-8").decode('utf-8'))
print(f"{file_name}_proof.bram has been generated in {directory}.")
input("Please press enter to close the program.")
return
else:
print(f"{len(ap.goals)} goals detected in the file. Proving or disproving each of them in separate files.")
for i in range(len(ap.goals)):
xml_doc = ap.solve(i)
with open(f"{directory}/{file_name}_proof_{i}.bram", 'w') as f:
f.write(
etree.tostring(xml_doc, pretty_print=True, xml_declaration=True, encoding="utf-8").decode('utf-8'))
print(f"{file_name}_proof_{i}.bram has been generated in {directory}.")
input("Please press enter to close the program.")
return
if __name__ == '__main__':
main()
|
f195b163b4ac2aec77a6e17e8e1cfada43691f1f | ADebut/Leetcode | /844. Backspace String Compare.py | 485 | 3.625 | 4 | class Solution:
def backspaceCompare(self, S: str, T: str) -> bool:
s = []
for i in range(len(S)):
if S[i] == '#' and s:
s.pop()
elif S[i] != '#':
s.append(S[i])
t = []
for i in range(len(T)):
if T[i] == '#' and t:
t.pop()
elif T[i] != '#':
t.append(T[i])
if t == s:
return True
else:
return False |
4f8cc15d24a17974a31a54e773f958ae58f939dc | kunalkhadalia04/python_sample | /Documents/Python_Projects/numbers1.py | 123 | 3.640625 | 4 | var1 = 10
var2 = 5
var3 = 2
var4 = 3
print(var4**var3)
var5 = var3*(var1+var2)
print(var5)
var6 = 0.5
print(var1*var6)
|
27ca4d76856476cb7276131aa0e70840a15f37fb | vishalpmittal/practice-fun | /funNLearn/src/main/java/dsAlgo/leetcode/P9xx/P925_LongPressedName.py | 1,898 | 3.8125 | 4 | """
Tag: string
Your friend is typing his name into a keyboard.
Sometimes, when typing a character c, the key might get
long pressed, and the character will be typed 1 or more times.
You examine the typed characters of the keyboard.
Return True if it is possible that it was your friends name,
with some characters (possibly none) being long pressed.
Example 1: Input: name = "alex", typed = "aaleex" Output: true
Explanation: 'a' and 'e' in 'alex' were long pressed.
Example 2: Input: name = "saeed", typed = "ssaaedd" Output: false
Explanation: 'e' must have been pressed twice, but it wasn't in the typed output.
Example 3: Input: name = "leelee", typed = "lleeelee" Output: true
Example 4: Input: name = "laiden", typed = "laiden" Output: true
Explanation: It's not necessary to long press any character.
Note:
- name.length <= 1000
- typed.length <= 1000
- The characters of name and typed are lowercase letters.
"""
from typing import List
class Solution:
def isLongPressedName(self, name: str, typed: str) -> bool:
n, t = 0, 0
while n < len(name) and t < len(typed):
if typed[t] == name[n]:
t += 1
n += 1
elif n > 0 and typed[t] == name[n-1]:
t += 1
else:
return False
if t < len(typed):
return all(name[n-1] == x for x in typed[t:])
return n == len(name) and t == len(typed)
assert Solution().isLongPressedName("alex", "aaleex")
assert not Solution().isLongPressedName("saeed", "ssaaedd")
assert Solution().isLongPressedName("leelee", "lleeelee")
assert Solution().isLongPressedName("laiden", "laiden")
assert not Solution().isLongPressedName("pyplrz", "ppyypllr")
assert Solution().isLongPressedName("vtkgn", "vttkgnn")
print('Tests Passed!!')
|
b34dabc1bc8cf7474cf000a2ad0578c23ce4d540 | ryzvonusef/ryzvonusef.github.io | /PYTHON/empy.py | 1,270 | 3.703125 | 4 | import csv
import pandas as pd
eFileName = './employee_file.csv'
class Employee:
def __init__(self,eFirstName,eLastName,eID,eCNIC,ePhoneNumber):
self.empFName = eFirstName
self.empLName = eLastName
self.empID = eID
self.empCNIC = eCNIC
self.empPhone = ePhoneNumber
def eWriter(a,b,c,d,e):
with open(eFileName, mode='a', newline='') as csv_file:
fieldnames = ['FirstName','LastName','Emp_ID','CNIC','Phone']
writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
if csv_file.tell() == 0:
writer.writeheader()
writer.writerow({'FirstName':a,'LastName':b,'Emp_ID':c,'CNIC':d,'Phone':e})
def eReader():
df = pd.read_csv(eFileName)
print (df)
def eInput():
empFName = str(input("Enter First Name of Employee:\n"))
empLName = str(input("Enter Last Name of Employee:\n"))
empID = str(input("Enter Employee ID:\n"))
empCNIC = str(input("Enter Employee CNIC:\n"))
empPhone = str(input("Enter Employee Phone Number:\n"))
Employee.eWriter(empFName,empLName,empID,empCNIC,empPhone)
#Employee.eInput()
Employee.eReader()
|
db4540ee7d0adc40bc3692bd45d9b0fc4c4bc5eb | pybokeh/python | /code_snippets/SortedDictionary.py | 144 | 3.53125 | 4 | myhash = {1:'John', 4:'Dick', 3:'Bill', 2:'Alex'}
for score in sorted(myhash.keys(), reverse=True):
print myhash[score] + ' ' + str(score)
|
91f1601d2f69ff64d93ad5c0b912d73eb7da801a | Derek-Y-Wang/Octagon-Health-Data-Science-Competition | /question_2.py | 4,164 | 3.609375 | 4 | # Name: Question 2
# Date: 07/11/2020
# Authors: Robert Ciborowski, Derek Wang
# Description: Answers question 2 of the competition: What might predict
# successful therapy? We use a patient recovering before 9 months
# as a success.
# The code starts running in main() (at the bottom of this file).
from Constants import *
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OrdinalEncoder
from SelectKBest import selectKBestAndGetBestValues
def getNumberOfSuccesses(data, row):
"""
Returns the number of successful treatments for a given row.
"""
sum = 0
for i in range(MONTHS_COLUMN_START + 1, MONTHS_COLUMN_START + NUM_MONTHS, 1):
sum += data.iloc[row + 1, i]
return sum
def addSuccessfulTherapyColumn(data):
"""
Returns a DataFrame showing the % of therapies that were successful.
"""
values = []
for i in range(0, len(data.index), 3):
row = [data["Prov"].iloc[i], data["Con_ACT"].iloc[i],
data["Sex"].iloc[i], data["Age"].iloc[i]]
# We are not interested in aggregated data.
if "ALL" in row or "UNKWN" in row or "Null" in row:
continue
successes = getNumberOfSuccesses(data, i)
row.append(successes / data.iloc[i, MONTHS_COLUMN_START])
values.append(row)
columns = ["Prov", "Con_ACT", "Sex", "Age", "Success_Rate"]
successData = pd.DataFrame(values, columns=columns)
return successData
def findMostCorrelatedColumns(data: pd.DataFrame):
X = data.iloc[:, :-1]
y = data.iloc[:, -1]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33,
random_state=1)
# Encoding our data to numbers:
oe = OrdinalEncoder()
oe.fit(X_train)
X_train_enc = pd.DataFrame(oe.transform(X_train), columns=X_train.columns)
X_test_enc = pd.DataFrame(oe.transform(X_test), columns=X_test.columns)
le = LabelEncoder()
le.fit(y_train)
y_train_enc = pd.DataFrame(le.transform(y_train))
# y_test_enc = pd.DataFrame(le.transform(y_test))
# This finds the columns that are the most correlated with success. It also
# finds their values that are the most correlated with dropout.
best_1, best_1_combos = selectKBestAndGetBestValues(data, X_train, X_train_enc, y_train_enc, k=1)
best_2, best_2_combos = selectKBestAndGetBestValues(data, X_train, X_train_enc, y_train_enc, k=2)
best_3, best_3_combos = selectKBestAndGetBestValues(data, X_train, X_train_enc, y_train_enc, k=3)
print("Please note that we are skipping rows with the \"ALL\", \"UNKWN\" or \"Null\" values.")
print("* Most correlated column to success:")
print(best_1)
print("* Top 5 values for this column that get the highest success:")
print(best_1_combos)
print("* 2 most correlated columns to success:")
print(best_2)
print("* Top 5 values for these 2 columns that get the highest success:")
print(best_2_combos)
print("* 3 most correlated columns to success:")
print(best_3)
print("* Top 5 values for these 3 columns that get the highest success:")
print(best_3_combos)
def main():
# This reads the data and sets up a dataframe.
data = pd.read_excel('Octagon_data_set_TKI_2020.xlsx',
sheet_name="Data_Table")
data = data[9:]
del data['Unnamed: 0']
cols = 'Prov Con_ACT Sex Age Measure M0 M1 M2 M3 M4 M5 M6 M7 M8 M9 M10 M11 M12 M13 M14 M15 M16 M17 M18 M19 M20 M21 M22 M23 M24 M25 M26 M27 M28 M29 M30 M31 M32 M33 M34 M35 M36 M37 M38 M39'
data.columns = cols.split('\t')
data.reset_index(inplace=True)
data = data.fillna(0)
# Question 3
print("====== Question 2 ======")
# This adds the "% that were successful therapies" to each row.
data_successful_therapy = addSuccessfulTherapyColumn(data)
# This finds the columns and values most correlated with a successful
# therapy.
findMostCorrelatedColumns(data_successful_therapy)
if __name__ == '__main__':
main()
|
d492da35c2d2191dbbf72b0e7ec7457c50f4da29 | rohitbhatghare/python | /Dec-21-2020/DuckTyping.py | 292 | 3.65625 | 4 | class Duck:
def talk(self):
print('quack..quack..')
class dog:
def talk(self):
print('bow bow')
class goat:
def talk(self):
print('Myah myah')
def f1(self):
obj.talk()
l = [Duck(), dog(), goat()]
for obj in l:
f1(obj)
|
0cd98a4d0d40e0f7b730e8ef07b18a374a52baa0 | LBouck/ProjectEulerSolutions | /PythonSolutions/ProjectEuler001.py | 265 | 3.609375 | 4 | #project euler 001
import numpy as np
import time
t0 = time.time()
# create array of values up to 1000
arr = np.arange(1,1000)
sum = np.sum(arr[np.logical_or(arr%3==0, arr%5==0)])
t1 = time.time()
print("Sum is: "+str(sum))
print("Time elapsed is: "+str(t1-t0))
|
5f52970b26c5443bb53114b7551cc804157140e6 | junweinehc/Python | /Practice/jusPractice.py | 558 | 3.9375 | 4 |
#just practice
#don’t waste time reading pls
name = "Loha hahaha"
print(name.title())
print("python \nC \nJava")
print(name.rstrip())
print(name.lstrip())
print(name.strip())
fName="eric"
lname="dak"
fullName=f"{fName} {lName}"
print("Hello " + fullName + ", " + "would you like to learn some Python today?")
import this
fp = 0.0
while fp <= 1.0:
fp = fp + 0.1
print(fp)
bicyles = ['trek','cannondale','redline','specialized']
print(bicyles[-1])
bicyles = ['trek','cannondale','redline','specialized']
bicyles.insert(0, 'Ducati')
print(bicyles)
|
e260558548e8b6c1c7114f1405c9659deda05295 | Blade6/PythonDiary | /文件读写/IO编程/picking.py | 1,865 | 3.796875 | 4 | # -*- coding:utf-8 -*-
# 我们把变量从内存中变成可存储或传输的过程称之为序列化,在Python中叫pickling,在其他语言中也被称之为serialization,marshalling,flattening等等,都是一个意思。
# 序列化之后,就可以把序列化后的内容写入磁盘,或者通过网络传输到别的机器上。
# 反过来,把变量内容从序列化的对象重新读到内存里称之为反序列化,即unpickling
# Python提供两个模块来实现序列化:cPickle和pickle。这两个模块功能是一样的,
# 区别在于cPickle是C语言写的,速度快,pickle是纯Python写的,速度慢,跟cStringIO和StringIO一个道理。
# 用的时候,先尝试导入cPickle,如果失败,再导入pickle
try:
import cPickle as pickle
except ImportError:
import pickle
d = dict(name='Bob', age=20, score=88)
print pickle.dumps(d)
# pickle.dumps()方法把任意对象序列化成一个str,然后,就可以把这个str写入文件。或者用另一个方法pickle.dump()直接把对象序列化后写入一个file-like Object:
# >>> f = open('dump.txt', 'wb')
# >>> pickle.dump(d, f)
# >>> f.close()
# 看看写入的dump.txt文件,一堆乱七八糟的内容,这些都是Python保存的对象内部信息
# 当我们要把对象从磁盘读到内存时,可以先把内容读到一个str,然后用pickle.loads()方法反序列化出对象,也可以直接用pickle.load()方法从一个file-like Object中直接反序列化出对象。我们打开另一个Python命令行来反序列化刚才保存的对象:
# >>> f = open('dump.txt', 'rb')
# >>> d = pickle.load(f)
# >>> f.close()
# >>> d
# {'age': 20, 'score': 88, 'name': 'Bob'}
# 变量的内容又回来了!
# 当然,这个变量和原来的变量是完全不相干的对象,它们只是内容相同而已。 |
c533aa17ae6829bfdd347a4402334c43cb7342f1 | acvanw79/pyglet-starter | /game.py | 609 | 3.765625 | 4 | import pyglet # import the library
window = pyglet.window.Window() # create the window
# Create some text
label = pyglet.text.Label('Hello erabody', x = 200, y = 200)
# inside the loop:
def on_draw():
text.draw()
# label = pyglet.text.Label('Hello, world', x = 200, y = 200)
# Create a sprite
ball_image = pyglet.image.load('assets/hero/Old hero.png')
ball = pyglet.sprite.Sprite(ball_image, x=50, y=50)
def update(dt):
ball.x += 0.5
ball.y += 0.5
# Start the event loop
@window.event
def on_draw():
window.clear()
ball.draw()
pyglet.clock.schedule(update)
pyglet.app.run() |
2e02aaddff53488797e06d00e6d2b1e6e2c7ae4f | FlimothyCrow/Python | /battleship.py | 2,654 | 3.84375 | 4 | import copy
def updateGame(game, move, player):
[row, col] = move
newGame = game
newGame[row][col] = player
return newGame
# updateGame(beginBoard, [0,0], 1)
def printGame(game):
for row in game:
print(row)
def moveValid(game, move):
x, y = move
if game[x][y] == 9 :
return False
elif game[x][y] == 8 :
return False
else :
return True
# moveValid(shipsBoard, [0,0])
def hitMiss(game, move): # remember (move) == player-entered coordinates
x, y = move
if game[x][y] == 2:
return True
def playerMove(name):
print("Player", name, "pick a move using row/col coordinates, e.g. 1,1"
"\nRemember, 8 = miss, and 9 = hit")
return list(map(int, input().split(",")))
# remember that playerMove doesn't need to update the game
# its only purpose is to extract the move data from the user
# that data can be returned to another function
def gameOver(game):
newGroup = [y for x in game for y in x]
if newGroup.count(9) == 4 :
return True
else :
return False
def run(currentPlayer, playerBoard, shipsBoard):
move = playerMove(currentPlayer)
if moveValid(playerBoard, move):
if hitMiss(shipsBoard, move):
print("Hit!")
playerBoard = updateGame(playerBoard, move, 9)
printGame(playerBoard)
if gameOver(playerBoard):
print(currentPlayer, "is the winner!")
else:
print("Miss")
playerBoard = updateGame(playerBoard, move, 8)
printGame(playerBoard)
else:
print("That space was already attempted")
def playGame():
playerBoard1 = [[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]
shipsBoard1 = [[2, 0, 0, 0],
[2, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 2, 2]]
playerBoard2 = [[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]
shipsBoard2 = [[0, 0, 0, 0],
[0, 2, 2, 0],
[0, 0, 0, 0],
[0, 2, 2, 0]]
while True:
run(1, playerBoard1, shipsBoard1)
run(2, playerBoard2, shipsBoard2)
# can we build it so that an attempted invalid move restarts that turn?
# the victory conditional from gameOver only prints after a "failed" move
# right now gameOver is based on having 4 hits, shouldn't that vary?
# can we put meat in moveValid so the game doesn't crash with string inputs?
playGame()
|
b0325df7b58ec4e68cc80bf2feedd0572a4bf8f7 | aadityadabli97/Python-Practice | /17.py | 795 | 3.890625 | 4 | # concept of radiobutton
from tkinter import *
import tkinter.messagebox as tmsg
main=Tk()
def order():
tmsg.showinfo("order received",f"we have received your order for {var.get()} thanks for ordering")
main.geometry("500x500")
main.title("concept of radiobutton")
#var=IntVar()
var=StringVar()
var.set("no")
Label(main,text="what would you like to have eat?",justify=LEFT,padx=14).pack()
radio=Radiobutton(main,text="dosa",padx=14,variable=var,value='dosa').pack()
radio2=Radiobutton(main,text="idli",padx=14,variable=var,value='idli').pack()
radio3=Radiobutton(main,text="chaumin",padx=14,variable=var,value='chaumin').pack()
radio4=Radiobutton(main,text="thali",padx=14,variable=var,value='thali').pack()
Button(main,text="order now",command=order).pack()
main.mainloop() |
b69ec24f0d3678e76099963aabb690cd41b704f4 | Degelzhao/python | /advanced_features/slice.py | 220 | 3.984375 | 4 | #使用切片来完成trim操作
def trim(s):
if s[:1] != ' ' and s[-1:] != ' ': #判断首尾是否为空
return s
elif s[:1] == ' ':
return trim(s[1:])
elif s[-1:] == ' ':
return trim(s[:-1])
|
23f8276a07d57898876f15a6dd6544d63b3fcb9e | ammartawil/AdventOfCode2017 | /day3/spiral_memory.py | 1,673 | 4.03125 | 4 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import math
# import pdb; pdb.set_trace()
x = 361527
# Start by finding which square x is in.
sq_root_x = math.sqrt(x)
int_sq_root_x = int(sq_root_x)
# Squares sizes are 1, 3, 5, 7, etc.
# If sqrt of x is even, then adding one to it gives us the correct square.
# if sqrt of x is odd and not int then we need to add 2 to get the correct square.
# else sqrt of x is odd int. This is the actual square size.
if int_sq_root_x % 2 == 0:
square = int_sq_root_x + 1
elif sq_root_x > int_sq_root_x:
square = int_sq_root_x + 2
else:
square = int_sq_root_x
# The square starts with ((square-2)^2)+1
square_begins = ((square-2)**2)+1
# The square ends with (square^2)
square_ends = square**2
# find the side x belongs to
if x < (square_begins-1+square-1): # Right hand side.
midpoint = square_begins - 1 + int(square/2)
horizontal_distance = int(square/2)
vertical_distance = abs(x-midpoint)
elif x < (square_begins-1+(2*(square-1))): # Top side.
midpoint = square_begins -1 + (square - 1) + int(square / 2)
vertical_distance = int(square/2)
horizontal_distance = abs(x-midpoint)
elif x < (square_begins-1+(3*(square-1))): # Left side.
midpoint = square_begins - 1 + (2*(square-1)) + int(square / 2)
horizontal_distance = int(square/2)
vertical_distance = abs(x-midpoint)
else: # Bottom side
midpoint = square_begins - 1 + (3*(square-1)) + int(square / 2)
vertical_distance = int(square / 2)
horizontal_distance = abs(x - midpoint)
distance = vertical_distance + horizontal_distance
print(distance)
|
c4c4c6f14a6edf8bfbefd3fd1b578a8e6c3cf4e5 | emiliacg/Python-Class | /Estructuras de datos 1.py | 736 | 3.921875 | 4 | print("esto es un texto")
Emilia=13
print(Emilia+6)
Miguel=Emilia+6+8
print(Miguel)
# se compara Emilia con el numero 14
if Emilia==14:
print("hola")
# Estructuras de datos 1
Compras=["carne","leche","arroz","huevos","carne","leche","arroz","huevos","carne","leche","arroz","huevos","carne","leche","arroz","huevos"]
print(Compras)
print(Compras[0])
print(Compras[1])
print(Compras[2])
print(Compras[3])
print()
for compra in Compras:
if True:
print("pepe")
if False:
print("lindo")
print("hey")
print(compra)
print(len(Compras))
for i in range(100):
print("Emilia es dura")
print(i)
# para saber si la variable i es par
if i%2==0:
print("Miguel tambien es bacano")
|
17cbd0b5b66bc985ce87a72c15f90358c034c731 | tomaszbobrucki/numeric_matrix | /Problems/Markdown heading/task.py | 225 | 3.734375 | 4 | def heading(phrase, quant=1):
if quant <= 1:
return "#" + " " + phrase
elif 6 > quant > 1:
return "#" * quant + " " + phrase
else:
return "#" * 6 + " " + phrase
# print(heading("A", 10))
|
db55950185325b7ddcff85bb27f01a7246521ee6 | alfitec/ProjectEulerChallenge | /project7/project7_10001stPrime.py | 571 | 3.90625 | 4 | """
10001st prime
Problem 7
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13,
we can see that the 6th prime is 13.
What is the 10 001st prime number?
"""
import math
def prime(number):
primes=[]
for i in range (2,number+1):
i_is_prime=True
sqroot=math.sqrt(i)
for j in primes:
if i%j==0:
i_is_prime=False
break
if j>sqroot: break
if i_is_prime:
primes.append(i)
return primes
def foo():
return prime(1000000)
print(foo()[10000]) |
18d2f39bb5116554528ee1cc769d9342ac88eb32 | yiming1012/MyLeetCode | /LeetCode/字符串/20. Valid Parentheses.py | 1,122 | 3.765625 | 4 | class Solution:
def isValid(self, s: str) -> bool:
'''
执行用时 :36 ms, 在所有 Python3 提交中击败了62.46%的用户
内存消耗 :13.5 MB, 在所有 Python3 提交中击败了23.89%的用户
:param s:
:return:
'''
left = ['(', '{', '[']
total = ['()', '{}', '[]']
res = []
for i in s:
if i in left:
res.append(i)
else:
if len(res) > 0 and res[-1] + i in total:
res.pop()
else:
return False
return res == []
def isValid2(self, s: str) -> bool:
'''
执行用时 :56 ms, 在所有 Python3 提交中击败了13.77%的用户
内存消耗 :13.4 MB, 在所有 Python3 提交中击败了23.89%的用户
:param s:
:return:
'''
while '()' in s or '{}' in s or '[]' in s:
s = s.replace('()', '')
s = s.replace('{}', '')
s = s.replace('[]', '')
return s == ''
arr = "(){}"
s = Solution()
print(s.isValid2(arr))
|
8abef3688739666c0b04c18ca0c336798094d992 | sochic2/kis | /머신러닝 이론 및 실습/Day_01_02_numpy.py | 2,167 | 3.65625 | 4 | # Day_01_02_numpy.py
import numpy as np
# 문제
# 0~9까지의 리스트를 만들어서 거꾸로 출력하세요.
a = list(range(10))
print(a)
print([i for i in reversed(a)])
print(a[3:4])
print(a[3:3])
print(a[-1])
print(a[:])
print(a[::])
print(a[::2])
print(a[9:0:-1])
print(a[9:-1:-1])
print(a[-1:-1:-1])
print(a[::-1])
print('-------------------------------------------------------')
# broadcast 연산과 벡터연산이 numpy를 쓰는 가장 기본중의 기본 이유
b = np.arange(10)
print(b)
print(type(b))
print(b.shape, b.dtype, b.size)
print(b[0], b[-1])
print(b[:5])
print()
print(b + 3) #broadcast
print(b + b)
print(b > 3)
print(b[b > 3]) # boolean 배열
# for i in b:
# print(i + 3 , end=' ')
print()
d = b.reshape(2, 5)
print(d)
c = b.reshape(2, -1)
print(c)
e = b.reshape(-1, 5)
print(e)
print(np.sin(b))
print(np.sin(c))
print()
print(b)
print(c)
print()
g = b.copy() #deep copy
b[0] = 123
print(b)
print(c)
print(g)
a1 = np.arange(3)
a2 = np.arange(6)
a3 = np.arange(3).reshape(1, 3)
a4 = np.arange(6).reshape(2, 3)
# print(a1+a2) #error
print(a1+a3) #vector
print(a1+a4) #broadcast + vector
print()
print(np.arange(12).reshape(3, 4))
print(np.arange(12).reshape(2, -1))
print()
d = np.arange(12)
print(d)
print(np.reshape(d, (3, 4))) # 추천방식
print(d.reshape(3, 4))
print(np.zeros(5, dtype=np.int32))
print(np.ones(5))
print(np.full(5, 2))
print(np.full(5, -1.0))
print(np.full(5, -1.0).dtype)
#문제
#테두리는1로, 속은 0으로 채워진 5행 5열 크기의 배열
f = np.zeros([5, 5], dtype=np.int32)
print(f)
# f[0], f[-1] = 1, 1 # 이거랑 밑에꺼 같은 의미
# f[0, :], f[-1, :] = 1, 1
f[[0, -1], :] = 1
f[:, 0], f[:, -1] = 1, 1
print(f)
print('---------------')
print()
g = np.ones([5, 5], dtype=np.int16)
g[1:-1, 1:-1] = 0
print(g)
print('----------')
print()
e = np.zeros([5, 5], dtype=np.int32)
# for i in range(5):
# e[i, i] = 1
# print(e)
# print(np.eye(5))
# print(np.identity(5))
# e[[0, 1, -1], 0] = 1 #index array
# e[[0, 1, 2, 3, 4], [0, 1, 2, 3, 4]] = 1
e[range(5), range(5)] = 1
print(e)
print('---------')
print()
|
82670b27e8b382cb33c2a15af6be4ecd70ea2606 | ender8848/the_fluent_python | /chapter_14/demo_14_17.py | 1,465 | 3.96875 | 4 | import itertools
'''
示例 14-17 演示用于合并的生成器函数
'''
# 调用 chain 函数时通常传入两个或更多个可迭代对象
print(list(itertools.chain('ABC', range(2))))
'''['A', 'B', 'C', 0, 1]'''
# 如果只传入一个可迭代的对象,那么 chain 函数没什么用
print(list(itertools.chain(enumerate('ABC'))))
'''[(0, 'A'), (1, 'B'), (2, 'C')]'''
# 但是 chain.from_iterable 函数从可迭代的对象中获取每个元素,然后按顺序把元素连接起来,前提是各个元素本身也是可迭代的对象
print(list(itertools.chain.from_iterable(enumerate('ABC'))))
'''[0, 'A', 1, 'B', 2, 'C']'''
# zip 常用于把两个可迭代的对象合并成一系列由两个元素组成的元组
print(list(zip('ABC', range(5))))
'''[('A', 0), ('B', 1), ('C', 2)]'''
# zip 可以并行处理任意数量个可迭代的对象,不过只要有一个可迭代的对象到头了,生成器就停止
print(list(zip('ABC', range(5), [10, 20, 30, 40])))
'''[('A', 0, 10), ('B', 1, 20), ('C', 2, 30)]'''
# itertools.zip_longest 函数的作用与 zip 类似,不过输入的所有可迭代对象都会处理到头,如果需要会填充 None
print(list(itertools.zip_longest('ABC', range(5))))
'''[('A', 0), ('B', 1), ('C', 2), (None, 3), (None, 4)]'''
# fillvalue 关键字参数用于指定填充的值
print(list(itertools.zip_longest('ABC', range(5), fillvalue='?')))
'''[('A', 0), ('B', 1), ('C', 2), ('?', 3), ('?', 4)]'''
|
60728a6b6812ffc9c46430ae805e3dfea6e0c20d | anupjungkarki/IWAcademy-Assignment | /Assignment 1/DataTypes/answer42.py | 164 | 3.953125 | 4 | # Write a Python program to convert a list to a tuple.
list_data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(list_data)
tuple_data = tuple(list_data)
print(tuple_data)
|
7eef6098a977199f80456d28eb39a6116a62044a | spenserca/aoc-python | /src/_2020/day_nine/utils.py | 1,368 | 3.953125 | 4 | def is_sum_of_two_preamble_values(preamble: [int], number: int):
for i in range(len(preamble)):
first_number = preamble[i]
other_numbers = preamble[i + 1:]
sums = [first_number + on for on in other_numbers]
if number in sums:
return True
return False
def get_first_value_not_sum_of_two_preamble_values(port_output: [str], preamble_length: int):
port_output_ints = [int(po) for po in port_output]
i = 0
while i < len(port_output) - preamble_length:
preamble = port_output_ints[i:preamble_length + i]
number = port_output_ints[preamble_length + i]
if not is_sum_of_two_preamble_values(preamble, number):
return number
i += 1
return -1
def get_sum_of_range_min_max(port_output: [str], preamble_length: int):
port_output_ints = [int(po) for po in port_output]
value = get_first_value_not_sum_of_two_preamble_values(port_output_ints, preamble_length)
for i in range(len(port_output)):
sum_of_range = -value
count = 1
while sum_of_range <= value:
num_range = port_output_ints[i:i + count]
sum_of_range = sum(num_range)
if sum_of_range == value:
return min(num_range) + max(num_range)
count += 1
return -1
|
45b80cff8d0098026bfb1c50ee123bfb5bdbe729 | bitores/python-life | /demo_re2.py | 364 | 3.953125 | 4 | import re
pattern = re.compile(r'hello')
match = pattern.match('hello world!')
if match:
print match.group()
p=re.match(r'hello','hello world!')
print p.group()
# a <==> b
a = re.compile(r"""\d + # the integral part
\. # the decimal point
\d * # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
|
4d3fc5380a824cceb962c3116540d1bd914d92b0 | ee491f/python-demo-2021 | /branching.py | 127 | 4.03125 | 4 | number = 3.3
if number > 3:
print("greater than 3")
print("greater than 3 again")
else:
print("less than or equal to 3") |
7eaa2eb20ae9e569a9d7719a519de9faee25c9a1 | Ramlanka7/PythonSample | /ListExamples.py | 303 | 3.703125 | 4 | q = [1, "Plum", 3.14, 2, "One", 3]
print(q[1])
print(q[0:2])
print(q[1:])
print(q[-1])
print(q[:3])
a = [1, 2, 3]
b = [4, 5, 6]
print(a * 2)
c = a + b
print(c)
del c[1:3]
print(c)
d = [1, 2, 3, 4, 5, 6]
d[1] = 'a'
print(d)
d[2:4] = ['b', 'c']
print(d)
d[2:4] = ["A", "B", "C", "D"]
print(d)
|
30628ff1849cc1fa494b709add2b218e8ddc86d4 | cosmos512/PyDevoir | /StartingOutWithPy/Chapter 07/ProgrammingExercises/08_random_number_file_reader.py | 308 | 3.671875 | 4 | # This exercise assumes you have completed Programming Exercise 7, Random
# Number File Writer. Write another program that reads the random numbers from
# the file, display the numbers, and then display the following data:
# • The total of the numbers
# • The number of random numbers read from the file
|
ee44d53d1d2a643710b5dbf8a44e55200765346b | UnsableMin/guess-number | /main.py | 719 | 3.96875 | 4 | import random
print ("welcome to number Guesser")
comp_num = random.randint (0, 10)
tries = 3
won = False
play = True
while play == True:
while tries > 0:
print()
player_num = input ("enter a number between 0-10:")
player_num = float(player_num)
if player_num < 0 or player_num > 10:
print ("Bad Number")
break
else:
if player_num == comp_num:
print("correct")
won = True
print ("god level?")
break
elif player_num < comp_num:
print("to small")
tries -= 1
print ("you have " + str(tries) + "tries left")
else:
print("to big")
tries -= 1
print ("you have " + str(tries) + ("left"))
|
143b49c369565b2f1c15323f141ab471510e9cde | atuanpham/HMM | /hmm/forward_algorithm.py | 2,564 | 3.6875 | 4 | import numpy as np
def compute_alpha(t, x_t, A, B, alpha_matrix):
"""
Compute the joint probability of each state and observation x_t at time t.
x_t is a index of 'observations' list.
Arguments:
t -- Time t.
x_t -- The observation at time t.
A -- State Transition Matrix.
B -- Emission Matrix.
alpha_matrix -- Alpha Matrix
Return:
alphas -- A list of alpha values corresponding to each state y_t
"""
n_states = A.shape[0]
alphas = np.zeros((1, n_states))
for y_t in range(n_states):
s = 0
for previous_y_t in range(n_states):
s += A[previous_y_t, y_t] * alpha_matrix[t - 1, previous_y_t]
alphas[0, y_t] = B[y_t, x_t] * s
# alphas is a matrix with size (1, n_states)
return alphas
def compute_alpha_vec(t, x_t, A, B, alpha_matrix):
"""
This is vectorized version of function 'compute_alpha'. It requires the same
arguments and generates the same output also.
Arguments:
t -- Time t.
x_t -- The observation at time t.
A -- State Transition Matrix.
B -- Emission Matrix.
alpha_matrix -- Alpha Matrix
Return:
alphas -- A list of alpha values corresponding to each state y_t
"""
# alphas is a matrix with size (1, n_states)
alphas = B[:, x_t].T * np.dot(alpha_matrix[t - 1, :], A)
return alphas
def compute_forward_prob(x, A, B, init_prob):
"""
An implementation of Forward algorithm that computes the forward probability
of the observation sequence.
Arguments:
x -- A sequence of observations.
A -- State Transition Matrix.
B -- Emission Matrix.
init_prob -- The initial probability of Forward trellis matrix.
Return:
forward_output -- A tuple that contains the computed forward trellis matrix
and the probability of the observation sequence.
"""
# alpha_matrix[i, j] is the probability of the state_j at time t_i, given by x_0,.. x_t
alpha_matrix = np.ndarray((len(x), A.shape[0]))
alpha_matrix[0, :] = init_prob
for t, x_t in enumerate(x):
# We don't compute alpha for t = 0
if t == 0:
continue
# Build Alpha trellis matrix.
alphas = compute_alpha_vec(t, x_t, A, B, alpha_matrix).round(6)
alpha_matrix[t, :] = alphas
sequence_prob = np.sum(alpha_matrix[-1, :])
return (alpha_matrix, sequence_prob)
|
17c55236c9038564112321bfd96301d1f2bcb551 | dhtcwd/learnpython | /EX18.py | 793 | 4.28125 | 4 | # -*- coding:utf-8 -*-
# this one is like your scripts with argv
def print_two(*args):
arg1, arg2 = args
print "arg1: %r, arg2: %r" % (arg1, arg2)
# ok, that *args is actually pointless, we can just do this
def print_two_again(arg1, arg2):
print "arg1: %r, arg2: %r" % (arg1, arg2)
# this just takes one argument
def print_one(arg1):
print "arg1: %r" % arg1
# this one takes no arguments
def print_none():
print "I got nothin'."
def print_hello():
print "def is nice"
#不确定参数个数的时候使用*args
def fun_var_args(farg, *args):
print "arg:", farg
for value in args:
print "another arg:", value
print_two("Zed","Shaw")
print_two_again("Zed","Shaw")
print_one("First!")
print_none()
print_hello()
fun_var_args("1","2","3","4")
|
62cd2d31f76f87fbf6c581b5109da8a2c3247079 | ImranAvenger/uri-python | /1180.py | 214 | 3.6875 | 4 | x = input()
y = (raw_input()).split(' ')
m = 0
p = 0
for i in range(x):
y[i] = int(y[i])
if y[i] < m:
m = y[i]
p = i
print "Menor valor: " + str(m)
print "Posicao: " + str(p)
|
9a0539fab47ef4162437bc2d31969b24b090bebf | BenTsai7/Machine-Learning-Practical-Codes | /Logistic_Regression/two-classification.py | 2,162 | 3.890625 | 4 | # 多特征梯度下降算法
# 用于二分类的逻辑回归
import numpy as np
import matplotlib.pyplot as plt
# 学习率 非常关键的参数,调得不好容易导致无法收敛,甚至不断震荡至溢出
learning_rate = 0.001
# 迭代次数
iterations = 1000
def sigmoid(z):
return 1 / (1 + np.exp(-z))
def gradient_descent(x_data,y_data):
weightslen = x_data.shape[1]
weights = np.ones(weightslen)
weights = np.mat(weights)
for i in range(iterations):
cost = sigmoid(x_data * weights.T)
print(weights)
weights = weights + learning_rate * (x_data.T * (y_data.T-cost)).T
print(learning_rate * (x_data.T * (y_data.T-cost)).T)
return weights
def printGraph(weights, x_data, y_data):
class1x = []
class1y = []
class2x = []
class2y = []
minx = x_data[0][0]
maxx = x_data[0][0]
for i in range(0, x_data.shape[0]):
if x_data[i][0]>maxx:
maxx = x_data[i][0]
if x_data[i][0]<minx:
minx = x_data[i][0]
if y_data[i] == 1:
class1x.append(x_data[i][0])
class1y.append(x_data[i][1])
elif y_data[i] == 0:
class2x.append(x_data[i][0])
class2y.append(x_data[i][1])
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(class1x, class1y, s=30, c='red', marker='s')
ax.scatter(class2x, class2y, s=30, c='green')
pointx = np.arange(minx, maxx) # 用来画决策边界
weights = np.array(weights)
pointy = (-weights[0][2]-weights[0][0]*pointx)/weights[0][1]
ax.plot(pointx, pointy)
plt.xlabel('x1')
plt.ylabel('x2')
plt.show()
def run():
data_matrix = np.loadtxt('./data/data1.csv', skiprows=0)
print("Input Matrix:")
print(data_matrix)
x_data = data_matrix[:, 0:-1]
y_data = data_matrix[:, -1]
# column 是0维的,增加一个常量
scalar = np.ones(x_data.shape[0])
x_data = np.column_stack((x_data, scalar))
weights = gradient_descent(np.mat(x_data), np.mat(y_data))
print("Weights:")
print(weights)
printGraph(weights, x_data, y_data)
if __name__ == '__main__':
run()
|
576d73bad9e36fef2506a9689f63eb608c18df2f | gulamd/python | /fromkeys_get_copy.py | 383 | 3.734375 | 4 | #fromkeys-use to create dictionary
#d = {'name' : 'unknown', 'age': 'unknown'}
#d = dict.fromkeys(['name','age','height'],'unkown')
#print(d)
# get method
d = {'name' : 'gulam', 'age': 'unknown'}
#print(d.get('name'))
#if d.get('name'):
# print('present')
#else:
# print('not present')
# if none --->false , else ---------->true
#clear() and copy()
d.clear()
print(d)
|
4cca03034fca913727ba8f97c449141a2b85f5c1 | assassint2017/leetcode-algorithm | /House Robber III/House_Robber_III.py | 1,422 | 3.609375 | 4 | # Runtime: 72 ms, faster than 39.39% of Python3 online submissions for House Robber III.
# Memory Usage: 15.8 MB, less than 5.09% of Python3 online submissions for House Robber III.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def rob(self, root: TreeNode) -> int:
hashmap = dict()
return self.helper(root, hashmap)
def helper(self, root, hashmap):
if root is None:
return 0
if root not in hashmap:
notrobfirst = self.helper(root.left, hashmap) + self.helper(root.right, hashmap)
robfirst = root.val
if root.left and root.right:
robfirst += (self.helper(root.left.left, hashmap) +
self.helper(root.left.right, hashmap) +
self.helper(root.right.left, hashmap) +
self.helper(root.right.right, hashmap))
elif root.left:
robfirst += self.helper(root.left.left, hashmap) + self.helper(root.left.right, hashmap)
elif root.right:
robfirst += self.helper(root.right.left, hashmap) + self.helper(root.right.right, hashmap)
hashmap[root] = max(robfirst, notrobfirst)
return hashmap[root]
|
a266386c7a9c68a16ccacd87bbd8db11dd411322 | fatmazgucc/python-neuralNetworkStart | /mainSetListTuple.py | 1,624 | 3.9375 | 4 | # This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint.
def listAndTuple(): #Tuple can not be changed later. It is immutable
#List can be changed. Allows to duplication
lst = ['a', 'b', 'c', 'd', 'e'] # This is how to initialize list
tpl = ('x', 'y', 'z', 'w', 't') # This is how to initialize tuple
print('Lst values 1 are : ')
print(lst)
print('Tpl values 2 are:')
print(tpl)
print()
lst[1] = 'bb'
print('Lst values 3 are : ')
print(lst)
lst.append('x')
print('Lst values 4 are : ')
print(lst)
lst.insert(2, 'ff')
print('Lst values 5 are : ')
print(lst)
lst.remove('a')
print('Lst values 6 are : ')
print(lst)
del lst[0]
print('Lst values 7 are : ')
print(lst)
def forSet():
#Set is unordered, mutable(can be changed), no duplication
st = set()
st = {'a', 'b', 'c', 'd', 'e'}
print('Values of set is ')
print(st)
#or
st=set(['a', 'b', 'c'])
print('Values of set 1 is ')
print(st)
st.add('f')
print('Values of set 2 is ')
print(st)
# Press the green button in the gutter to run the script.
print_hi('We are starting :) Hello :)')
listAndTuple()
forSet()
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
|
cce699583232f74950feafc91d64e9cd0d48f940 | dagongji10/LeCode | /scripts/9.py | 525 | 3.6875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Aug 15 14:17:42 2019
@author: Administrator
"""
def isPalindrome(x: int) -> bool:
if x<0:
return False # 不能用'false'代替
else:
s = '#' + '#'.join(str(x)) + '#' # 也可以直接用字符串倒序然后判断是否相等
center = int(len(s)/2)
p = 1
while(center-p>=0):
if s[center-p]==s[center+p]:
p += 1
else:
return False
return True |
cbb88d6182d96b1a4f095ebc274320ffd086aba2 | Mariamapa/Formulario- | /formulario.py | 2,418 | 3.515625 | 4 | from tkinter import *
def send_data():
#Definición de las variables
usuario_info = usuario.get()
contraseña_info = contraseña.get()
nombre_info = nombre.get()
edad_info = str(edad.get())
#Abriremos la sección de llenado
print(usuario_info,"\t", contraseña_info,"\t", nombre_info,"\t", edad_info)
#Crearemos nuestra base de datos
file = open("registro.txt", "a")
file.write(usuario_info)
file.write("\t")
file.write(contraseña_info)
file.write("\t")
file.write(nombre_info)
file.write("\t")
file.write(edad_info)
file.write("\t\n")
file.close()
print(" Nuevo usuario. Usuario: {} | Nombre completo: {} ".format(usuario_info, nombre_info))
usuario_entry.delete(0, END)
contraseña_entry.delete(0, END)
nombre_entry.delete(0, END)
edad_entry.delete(0, END)
mywindow = Tk()
mywindow.geometry("650x550")
mywindow.title("REGISTRO OMIND SEX ")
mywindow.resizable(False,False)
mywindow.config(background = "#fa8bf1")
main_title = Label(text = "REGISTRO | OMIND SEX", font = ("calibri", 16), bg = "#fa8bf1", fg = "white", width = "500", height = "2")
main_title.pack()
usuario_label = Label(text = "Usuario", bg = "#fa8bf1", fg = "white", font = ("calibri", 14))
usuario_label.place(x = 200, y = 100)
contraseña_label = Label(text = "Contraseña", bg = "#fa8bf1", fg = "white", font = ("calibri", 14))
contraseña_label.place(x = 200, y = 160)
nombre_label = Label(text = "Nombre completo", bg = "#fa8bf1", fg = "white",font = ("calibri", 14))
nombre_label.place(x = 200, y = 220)
edad_label = Label(text = "Edad", bg = "#fa8bf1", fg = "white", font = ("calibri", 14))
edad_label.place(x = 200, y = 280)
usuario= StringVar()
contraseña = StringVar()
nombre= StringVar()
edad= StringVar()
usuario_entry = Entry(textvariable = usuario, width = "40")
contraseña_entry = Entry(textvariable = contraseña, width = "40", show = "*")
nombre_entry = Entry(textvariable = nombre, width = "40")
edad_entry = Entry(textvariable = edad, width = "40")
usuario_entry.place(x = 200, y = 130)
contraseña_entry.place(x = 200, y = 190)
nombre_entry.place(x = 200, y = 250)
edad_entry.place(x = 200, y = 310)
submit_btn = Button(mywindow,text = "Registrarse", width = "30", height = "2", command = send_data, bg = "#fc6998", font = ("calibri", 12))
submit_btn.place(x = 210, y = 350)
mywindow.mainloop() |
6fb555e4774deb8ea038269ce1b4a9fd04f75c01 | varshinireddyt/Python | /GoldManSachs/StringCompression.py | 2,036 | 3.703125 | 4 | """
Leetcode 443: StringCompression
Given an array of characters chars, compress it using the following algorithm:
Begin with an empty string s. For each group of consecutive repeating characters in chars:
If the group's length is 1, append the character to s.
Otherwise, append the character followed by the group's length.
The compressed string s should not be returned separately, but instead be stored in the input character array chars.
Note that group lengths that are 10 or longer will be split into multiple characters in chars.
After you are done modifying the input array, return the new length of the array.
"""
class Solution:
def compress(self, chars):
N = len(chars)
if N > 1:
temp = chars[0]
else: return len(chars)
count = 1 #count of characters
compres = "" #appending charracter and their count
i = 1
while i < N:
if chars[i] == temp: # if temp is equal to its next character then increment count
count += 1
if chars[i] != temp: # concatenting the character and their count to the compres
compres = compres + chars[i-1]
if 1 < count : # if count greater than one appending the count as string to the compress
compres = compres + str(count)
temp = chars[i] # updating temp with new character
count = 1 # updating the count or restarting the count
i += 1
if i == N : # appending the last character and its count to the compress
compres = compres + chars[i - 1]
if 1 < count:
compres = compres + str(count)
chars[:] = list(compres) # updating the char with the new compres string
print(chars)
return len(chars)
obj = Solution()
chars = ["a","a","b","b","c","c","c"]
#chars = ["a","a","a","b","b","a","a"]
#chars = ["a","b","b","b","b","b","b","b","b","b","b","b","b"]
#chars = ["a","b","c"]
print(obj.compress(chars))
|
ad168ea3cc67035dcb1bee60c7ff2b4b20f88f7e | hnzhang/python | /SierphinskiTriangle.py | 1,577 | 4.09375 | 4 |
import turtle #draw graphics
def draw_triangle(points, color, turtle_instance):
'''
draw triangle
'''
#print("Color", color)
turtle_instance.fillcolor(color)
turtle_instance.up()
turtle_instance.goto(points[0][0], points[0][1])
turtle_instance.down()
turtle_instance.begin_fill()
turtle_instance.goto(points[1][0], points[1][1])
turtle_instance.goto(points[2][0], points[2][1])
turtle_instance.goto(points[0][0], points[0][1])
turtle_instance.end_fill()
def draw_sierphinski_triangle(points, colors, level, turtle_instance):
draw_triangle(points, colors[level], turtle_instance)
if level >=0:
mid_points = [((points[0][0] + points[1][0])/2, (points[0][1] + points[1][1])/2 ), ( (points[1][0] + points[2][0])/2, (points[1][1] + points[2][1])/2 ), ( (points[0][0] + points[2][0])/2, (points[0][1] + points[2][1])/2 ) ]
draw_sierphinski_triangle([points[0], mid_points[0], mid_points[2]], colors, level-1, turtle_instance)
draw_sierphinski_triangle([ mid_points[0], points[1], mid_points[1]], colors, level-1, turtle_instance)
draw_sierphinski_triangle([ mid_points[2], mid_points[1], points[2]], colors, level-1, turtle_instance)
def main():
'''
main function
'''
my_turtle = turtle.Turtle()
my_win = turtle.Screen()
points = [(-100, 50), (0, 200), (100, -50)]
#draw_triangle(points, "green", my_turtle)
colors = ["green", "black", "blue", "orange"]
draw_sierphinski_triangle(points, colors, 3, my_turtle)
my_win.exitonclick()
main()
|
8f4bc53e79d249a93e780eb71841fa183423bd7e | MilenaTupiza/programacion | /funmultiply.py | 302 | 4 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 30 11:59:27 2020
@author: User
"""
def multiply(a,b):
print("El resultado en print de la multiplicacion es: ",a,"y ",b,"es ", a*b)
print("\n")
return (a*b)
print("\n")
multiply(4,5)
print("El resultado es: ",multiply(5,4))
|
a9f5b4e37f3b3abd184d0637dec914a38cc32ceb | gratsgravelsins/DMI | /PYTHON/sinmape/bezj1.py | 701 | 3.515625 | 4 | # -*- coding: utf-8 -*-
#from math import j1
#import numpy as np
#import matplotlib.pyplot as plt
#Jasarēķina savs kods tieši šajā veidā
#viena argumenta funk
#def mans_sinuss(x):
#def j1(x,n):
k = 0
a = (-1)**0*x**1/(1)
s = a
# while k<0:
while k<n:
k = k + 1
R = (-1) * x**2/(k*(4*k+4))
a = a * R
s = s + a
#return s
#x = np.arange(0.,6.28,0.01)
#y = sin(x)
#y = np.sin(x)
#f1 = mans_sinuss(x,0)
#f2 = mans_sinuss(x,1)
#f3 = mans_sinuss(x,2)
#f4 = mans_sinuss(x,3)
#f5 = mans_sinuss(x,4)
#plt.plot un show grafikus uzzīmēs
#plt.plot(x,y,'r')
#plt.plot(x,f1,'g')
#plt.plot(x,f2,'b')
#plt.plot(x,f3,'c')
#plt.plot(x,f4,'y')
#plt.plot(x,f5,'k')
#plt.grid()
#plt.show()
|
ea93b55582e94eb8efb731e235207f1b5f725f97 | Navdeep656/python_file_handling | /main.py | 1,271 | 3.609375 | 4 | import requests
def fetch_rest_api():
print("Rest API call")
response = requests.get("https://reqres.in/api/users?page=1")
user_data = response.json()
print(user_data)
total = user_data["total"]
print(total)
data = user_data['data']
for record in data:
print(record["id"], record["email"], record["first_name"], record["last_name"])
if __name__ == '__main__':
fetch_rest_api()
try:
f1 = open("student.txt","r")
except:
print("fie not Found")
else:
print(f1.read(10))
print(f1.readline())
f1.close()
finally:
print("Always going to execute")
# Read data from user console
first_name = input("Enter your first name:")
print(first_name)
last_name = input("Enter your last name:")
print(last_name)
city = input("Enter your city name:")
print(city)
# write dta to file
f1 = open("student.txt", "w")
f1.write("First_name last_name city \n")
f1.close()
# appned data
f1 = open("student.txt", "a")
f1.write(first_name + ", " + last_name + ", " + city)
f1.close()
f1 = open("student.txt","r")
for row in f1:
print(row)
print(row.split(","))
f1.close()
|
02cbbeafe4d2d86effbb855a2267023920e89fd2 | gopularam/developer | /Python/Generator_Fibonacci.py | 271 | 3.65625 | 4 |
def fibinocci():
a,b = 1,1
while 1:
yield a
a,b = b, a+b
def main():
counter =0
for i in fibinocci():
print(i)
counter+=1
if counter == 5:
break
print('Done')
if __name__ == '__main__':
main() |
3cdd09b92243b04a334e16cecc648eca82770419 | masilvasql/curso_python3_basico_avancado | /fundamentos_projetos/area_circunferencia_v4.py | 213 | 3.96875 | 4 | # import math
from math import pi
raio = input("Informe o raio : ")
areaCircunferencia = pi * float(raio) ** 2
print(f'A área da circunferência é {areaCircunferencia}')
print('Nomde do módulo', __name__)
|
7fafc497a71882ca12696ceadd6a204baa363484 | JESmith804/python-challenge | /PyPoll/main.py | 2,746 | 3.65625 | 4 | import os
import csv
# input file path
csvpath = os.path.join ('..', 'PyPoll', 'election_data.csv')
# Lists to store data
voterIDs = []
candidates = []
voteCounts = []
# set initial values
i = 0
j = 0
k = 0
win = 0
# opens input file, removes header row and loops through the remaining rows
with open(csvpath, newline= "") as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
header = next(csvreader)
for row in csvreader:
# add each vorer ID to list 'voterIDs'; it's length is the total number of votes
voterIDs.append(row[0])
# add the candidate for each vote to a list
candidates.append(row[2])
# remove duplicates from candidate list
candidates = list( dict.fromkeys(candidates))
#loops through candidates list
while i < (len(candidates)):
# opens input file, removes header row and loops through the remaining rows
with open(csvpath, newline= "") as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
header = next(csvreader)
voteCnt = 0
for row in csvreader:
# counts the number of votes for each candidate
if candidates[i] == row[2]:
voteCnt = voteCnt + 1
# adds vote count for each cadidate to list
voteCounts.append(voteCnt)
i = i + 1
# print output in terminal
print("Election Results")
print("-------------------------")
print("Total Votes: " + str(f"{(len(voterIDs)):,d}"))
print("-------------------------")
# loops and prints results for each canditates and stores the index of the highest vote count
while j < (len(candidates)):
if voteCounts[j] > win:
win = voteCounts[j]
winCand = j
pct = ((voteCounts[j])/(sum(voteCounts)))*100
pct = round(pct, 2)
print(candidates[j] + ": " + str(pct) + "% (" + str(f"{(voteCounts[j]):,d}") + ")")
j = j + 1
print("-------------------------")
# uses the index of the highest vote count to return the name of the winning candidate
print("Winner: " + candidates[winCand])
print("-------------------------")
# create output text file and write output into the file
output_file = os.path.join("output.txt")
writer = open(output_file, 'w+')
writer.write("Election Results\n")
writer.write("-------------------------\n")
writer.write("Total Votes: " + str(f"{(len(voterIDs)):,d}") + "\n")
writer.write("-------------------------\n")
while k < (len(candidates)):
pct = ((voteCounts[k])/(sum(voteCounts)))*100
pct = round(pct, 2)
writer.write(candidates[k] + ": " + str(pct) + "% (" + str(f"{(voteCounts[k]):,d}") + ")\n")
k = k + 1
writer.write("-------------------------\n")
writer.write("Winner: " + candidates[winCand] + "\n")
writer.write("-------------------------\n") |
05c126ebf480bd19ad7fea07aa3f674f875566f2 | quento/encrypting-with-python | /ca-server.py | 5,179 | 3.609375 | 4 | import socket
import helper
from helper import simpleCipher
class CertServer:
"""
This class creates a simple certificate server that verifies a server belongs to a certain certificate
"""
def __init__( self, host = '127.0.2.1', port = 9000 ):
self._host = host
self._port = port
def create_socket(self):
try:
return socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error as err:
print("socket creation failed with error: \n {0}".format(err))
def start_server( self ):
display_helper("CA Server")
# Create socket
sock = self.create_socket()
print("Socket created...")
try:
with sock:
# bind to port
sock.bind( (self._host, self._port) )
print("Socket bound to ", self._host)
while True:
sock.listen(5)
print("Server is listening on port ", self._port)
conn, addr = sock.accept()
#Establish client connection
print("Got connection from ", addr)
with conn:
while True:
data = conn.recv( 1024 )
msg_recieved = data.decode()
cert_valid = False
# If msg is a certificate, check if it's valid.
if msg_recieved.find("CA:") > -1 or msg_recieved.find("DB:") > -1:
print("Certificate received. Checking validity ...")
if msg_recieved.find("DB:") > -1: # encrypted msg
# Decrypt returns decrypted array
decrypt_cert_and_key = simpleCipher( msg_recieved,1,'d' )
decrypt_cert_and_key_array = self.readCert(decrypt_cert_and_key)
server_cert = decrypt_cert_and_key_array[0]
server_public_key = decrypt_cert_and_key_array[1]
# TODO: Extract Cert and Public Key
cert_valid = self.checkCertValidity(server_cert)
if cert_valid == True:
print( "Server received a VALID certificate '{0}'".format(data.decode()) )
print( "Server sending back - Server's Public Key...." )
# TODO: Send public key of Certificate.
conn.sendall(server_public_key.encode())
else:
print( "Server received INVALID '{0}'".format(data.decode()) )
print( "Server sending back - 'False' response" )
print()
conn.sendall(b'INVALID')
break
elif data == b'':
print("No data ...")
break
else:
print( "CA Server received '{0}'".format(data.decode()) )
print( "CA Server sending back - 'Goodbye' response" )
print()
conn.sendall(b'Goodbye')
break
print("Connection closed ..")
conn.close()
except socket.error as err:
print("Socket use error: \n {0}".format(err))
print("Server shutting down ...")
sock.close()
def checkCertValidity(self, cert):
""" Check if mock certificate is valid """
cert_validity = False
if cert == 'CA: I am Simple Server Certificate':
cert_validity = True
return cert_validity
def decrypt_cert(self,encrypted_cert):
return simpleCipher( encrypted_cert,1,'d')
def readCert(self,cert):
""" Read certificate and seperate public key from certificate.
@return = Returns an array with cert and public key.
"""
return cert.split("~")
def shutdown_server( self ):
exit_input = input("Do you want to exit/shutdown the server (y/n): ")
decision = False
if exit_input == 'y':
decision = True
return decision
def display_helper(msg):
print("\n****************** ", msg, "******************\n")
if __name__ == "__main__":
# Create simple server
host = '127.0.2.1'
port = 9000
cert_server = CertServer( host, port )
# Open connection
cert_server.start_server() |
eaa9255d75cb57217d5bfc13e4444108fd2690aa | ARUNDHATHI1234/Python | /co1/program11.py | 226 | 4.03125 | 4 | a=int(input("enter first number"))
b=int(input("enter second number"))
c=int(input("enter third number"))
if a>b:
if a>c:
print(a,"is big")
else:
print(c," is big")
elif b>c:
print(b,"is big")
else:
print(c," is big")
|
2d5d59705197ca008c0354752f088b3920706155 | xuziyan001/lc_daily | /25-reverse-kgroup.py | 1,540 | 3.5625 | 4 | from tool import ListNode,concat_node
class Solution:
def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
if k < 2:
return head
if not head:
return head
start = head
end = head
for i in range(k-1):
end = end.next
if not end:
return head
new_head = end
tail = end.next
# reverse fist
self.reverse(start, end)
start.next = tail
# reverse tails
prev = start
start = tail
end = start
while end:
for i in range(k-1):
end = end.next
if not end:
return new_head
tail = end.next
self.reverse(start, end)
start.next = tail
prev.next = end
#
prev = start
start = tail
end = start
return new_head
def reverse(self, start, end: ListNode):
pre = start
cur = start.next
nex = cur.next
tail = end.next
start.next = None
# swap first
cur.next = pre
while nex != tail:
pre = cur
cur = nex
nex = cur.next
cur.next = pre
if __name__ == '__main__':
l = concat_node([1,2,3,4,5])
print(Solution().reverseKGroup(l, 1))
l = concat_node([1,2,3,4,5])
print(Solution().reverseKGroup(l, 2))
l = concat_node([1,2,3,4,5])
print(Solution().reverseKGroup(l, 3))
|
52147d6f868ae549874a7092ae35bc92c931ebb9 | gonzeD/CS1-Python | /LoadSaveGame/src/CorrLoadSave.py | 622 | 3.515625 | 4 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
def save_data(filename, life, mana, position_x, position_y):
with open(filename, 'w') as f:
f.write(str(life)+'\n')
f.write(str(mana)+'\n')
f.write(str(position_x)+'\n')
f.write(str(position_y)+'\n')
def load_data(filename):
try:
f = open(filename, 'r')
life = int(f.readline())
mana = int(f.readline())
position_x = int(f.readline())
position_y = int(f.readline())
return life, mana, position_x, position_y
except FileNotFoundError:
raise FileNotFoundError("file not found")
|
27f668cca9053c7ea130091c03df8a36eee6771a | aaron0215/Projects | /Python/HW11/temps_ex.py | 1,899 | 3.515625 | 4 | import tkinter
class TempCoverterGUI:
def __init__(self):
self.main_window = tkinter.Tk()
self.top_frame = tkinter.Frame(self.main_window)
self.bottom_frame = tkinter.Frame(self.main_window)
self.prompt1_label = tkinter.Label(self.top_frame,\
text='Enter the Celsius temperature')
self.prompt2_label = tkinter.Label(self.top_frame,\
text='Fahrenheit temperature')
self.calc_button = tkinter.Button(self.top_frame,\
text='Convert to Fahrenheit',\
command = self.convert)
self.prompt1_label.pack(side='left')
self.prompt2_label.pack(side='left')
self.calc_button.pack(side='left')
self.cels_entry = tkinter.Entry(self.bottom_frame,\
width = 10)
self.value = tkinter.StringVar()
self.faher_label=tkinter.Label(self.bottom_frame,\
textvariable = self.value)
self.quit_button = tkinter.Button(self.bottom_frame,\
text = 'Quit',\
command = self.main_window.destroy)
self.cels_entry.pack(side='left')
self.faher_label.pack(side='left')
self.quit_button.pack(side='left')
self.top_frame.pack()
self.bottom_frame.pack()
tkinter.mainloop()
def convert(self):
num1 = 9/5
num2 = 32
try:
celsius_temp = float(self.cels_entry.get())
fahre_temp = num1*celsius_temp+num2
result = format(fahre_temp,'.1f')
except:
self.value.set('Invalid input')
else:
self.value.set(result)
Temp_conv = TempCoverterGUI()
|
9f17c7e06b7755bf62fc710e6fd51519b73d26e4 | udaykodeboina/Test | /import_decimal.py | 351 | 3.75 | 4 |
from decimal import Decimal
a = 22 #total number of days
"""
This is a mothly payable calculation
"""
b = 600 # daily allowance
c = a * b
d =Decimal(c * 0.27)
e = c - d
print ("No of days in a month are:", a)
print ("Daily allowance per day is:", b)
print("Monthly Expected: ", c)
print("tax Payable", round(d,2))
print("Remaining monthly is:", e)
|
0ce7036e6b737dd291b6e1054ec5c090a76d3cfd | bmiraski/tlacs | /ch9.py | 2,475 | 4.09375 | 4 | import turtle
import sys
import string
def test(did_pass):
""" Print the result of a test. """
linenum = sys._getframe(1).f_lineno # Get the caller's line number.
if did_pass:
msg = "Test at line {0} ok.".format(linenum)
else:
msg = ("Test at line {0} FAILED.".format(linenum))
print(msg)
# Your friend will complete this function
def play_once(human_plays_first):
"""
Must play one round of the game. If the parameter
is True, the human gets to play first, else the
computer gets to play first. When the round ends,
the return value of the function is one of
-1 (human wins), 0 (game drawn), 1 (computer wins).
"""
# This is all dummy scaffolding code right at the moment...
import random # See Modules chapter ...
rng = random.Random()
# Pick a random result between -1 and 1.
result = rng.randrange(-1,2)
print("Human plays first={0}, winner={1} "
.format(human_plays_first, result))
return result
def win_perc(a,b,c):
"""
Returns the winning percentage for a in a 3-outcome game
"""
perc = str(round(100*(a/(a+b+c)),2))
return perc
def ttt():
"""
Plays 1 to many rounds of tic-tac-toe
"""
x=""
comp_score=0
human_score=0
draws=0
turn = True
while x != "n":
result = play_once(turn)
if result == -1:
human_score += 1
print("You win!","\n")
elif result == 0:
draws += 1
print("Game drawn!","\n")
elif result == 1:
comp_score += 1
print("I win!","\n")
print("Current Score: Human","\t",human_score,"\t","Computer","\t",comp_score,"\t","Draws","\t",draws)
print("The Human has won ",win_perc(human_score, comp_score, draws)," percent of the games.")
turn = not turn
x = input("Do you want to play again? ")
print("Goodbye")
b = ("Ben","Miraski",40)
def is_old(tup):
(first,last,age)=tup
result = ""
if age>=40:
result = "Yes, you are old"
else:
result = "Nope, not old yet"
return result
print(is_old(b))
def test_suite():
"""
Run the suite of tests for code in this module (this file).
"""
test(count_letters("banana", "a")== 3)
#test_suite()
|
cd01ffa2ae8c08a0d7e22ede49a0008f3bd9d228 | sandipan898/agent-selection-program | /agent_selector.py | 2,930 | 3.671875 | 4 | import random
def create_agent_list():
""" Used to make a agent data list if needed """
while True:
agent_list = []
agent_id = input("Enter an unique agent id: ")
is_available = input("Is the agent available?(0/1) ")
available_since = input("Available Since: ")
roles = input("Enter the role of the agent: ")
agent_list.append({
'agent_id': agent_id, 'is_available': is_available, 'available_since': available_since, 'roles': roles
})
op = input("Want to add more agent?(y/n)").lower()
if op == 'n':
break
print(agent_list)
print("\nAgent-data:")
for item in agent_list:
print("\n")
for k, v in item.items():
print("{}: {}".format(k, v))
return agent_list
def select_agent(agent_list, selection_mode, issue_role):
""" check the conditions based on selection mode and returns the agent id of selected agents """
selected_agents = None
selection_mode = selection_mode.lower()
for item in agent_list:
if item['is_available']:
available_time_list = [i['available_since'] for i in agent_list]
if selection_mode == 'all available':
selected_agents = [i['agent_id'] for i in agent_list if i['roles'] == issue_role]
if selection_mode == 'least busy':
max_time = max(available_time_list)
selected_agents = [i['agent_id'] for i in agent_list if i['available_since'] == max_time and i['roles'] == issue_role]
if selection_mode == 'random':
s = random.choice(agent_list)
selected_agents = [s['agent_id'] if s['roles'] == issue_role else None]
return selected_agents
# selection_mode_list = ['all available', 'least busy', 'random']
# agent_list = create_agent_list()
"""
Statically creating a agent list
we can create a list by user input by using the create_agent_list() function
"""
agent_list = [
{'agent_id': 1, 'is_available': 1, 'available_since': 2, 'roles': 'sales'},
{'agent_id': 2, 'is_available': 1, 'available_since': 3, 'roles': 'spanish speaker'},
{'agent_id': 3, 'is_available': 0, 'available_since': 2, 'roles': 'sales'},
{'agent_id': 4, 'is_available': 1, 'available_since': 1, 'roles': 'support'},
{'agent_id': 5, 'is_available': 1, 'available_since': 3, 'roles': 'sales'},
]
issue_role = ['sales', 'support']
mode = input("Enter agent selection mode (all available, least busy or random): ")
for role in issue_role:
selected_agents = select_agent(agent_list, mode, role)
print("\n*********Selected agents for issue role {} with their data*********\n".format(role))
for a_id in selected_agents:
for i in agent_list:
if i['agent_id'] == a_id:
print("Agent-{} Available_since: {} Role: {}".format(a_id, i['available_since'], i['roles']))
|
3388970ba4d218a06e06e6444c6c5511c54ea002 | ghaed/Fun-With-Algorithms | /Heap-Median/median.py | 1,247 | 3.765625 | 4 | """ Calculates the median using heap"""
import heapq
f = open('test_case_large.txt')
lines = f.readlines()
x_list = [int(numeric_string) for numeric_string in lines]
# x_list = [1, 2, 3, 4, 5]
heap_high = [] # Min- heap
heap_low = [] # Also min-heap, stored as negative numbers
medians_sum = 0
x0 = x_list[0:3]
larger = max(x_list[0:3])
smaller = min(x_list[0:3])
x0.remove(larger)
x0.remove(smaller)
median = x0[0]
medians_sum += x_list[0] + min(x_list[0:2]) + median
heapq.heappush(heap_high, larger)
heapq.heappush(heap_low, -smaller)
for x in x_list[3:]:
smaller = min(x, median)
larger = max(x, median)
if len(heap_low) == len(heap_high):
heapq.heappush(heap_high, larger)
if smaller < -heap_low[0]:
median = -heapq.heappop(heap_low)
heapq.heappush(heap_low, -smaller)
else:
median = smaller
else:
heapq.heappush(heap_low, -smaller)
if larger > heap_high[0]:
median = heapq.heappop(heap_high)
heapq.heappush(heap_high, larger)
else:
median = larger
medians_sum = (medians_sum + median)%10000
print 'median=', median, ', medians_sum=', medians_sum
|
28b211f3e937b75aa4f05e8d2d4f2ac373e2ba72 | maciejdomagala/thegreatUpsolving | /various/FindComplement.py | 389 | 3.875 | 4 | """
Given a positive integer num, output its complement number. The complement strategy is to flip the bits of its binary representation.
"""
class Solution(object):
def findComplement(self, num):
"""
:type num: int
:rtype: int
"""
num_b = bin(num)[2:]
ans = ''.join(['0' if a == '1' else '1' for a in num_b])
return int(ans, 2) |
19e516773399fd7f591936c172389b4bd9115c34 | KidSpace/GretaPy | /Question3.py | 984 | 4.03125 | 4 | # Greta's Quiz Game
from matplotlib.pyplot import imshow
import numpy as np
from PIL import Image
number = 3
#--Cool Image to show if they answer the question Right
pil_im = Image.open('door3.png', 'r')
imshow(np.asarray(pil_im))
imshow(pil_im)
#--The Question and Answer Pairs
print('Congenital hearing loss is...?\n\n')
print('a. Slight hearing loss\n')
print('b. Caused by genetic factors ALL the time\n')
print('c. Present at birth\n')
print('d. Hearing loss old people get\n')
#--Correct Answer
answer = 'c'
#--Link to learn more
url2 = "http://www.asha.org/public/hearing/Congenital-Hearing-Loss/"
#--Boolean
understand_deafness=False
#--While loop
while not understand_deafness:
guess = input('a, b, c, or d?\n\n\n')
if guess == answer:
print('Correct! Great Job! You Just Passed Through Door # {}!'.format(number))
understand_deafness=True
else:
print('\nSorry, Try Again! Go Here For a Clue: {}'.format(url2))
|
78d4436cd3059da058ef2f5f059502aba9aac4c0 | WUJIAWIN/Data-Structure-Algo-P3 | /P7.py | 5,061 | 3.515625 | 4 | # Problem 7
# Request Routing in a Web Server with a Trie
# A RouteTrie will store our routes and their associated handlers
class RouteTrie:
def __init__(self, handler = None, description = None):
# Initialize the trie with an root node and a handler, this is the root path or home page node
self.root = RouteTrieNode(handler, description)
def insert(self, path, description):
# Similar to our previous example you will want to recursively add nodes
# Make sure you assign the handler to only the leaf (deepest) node of this path
current_node = self.root
for i in path:
current_node.insert(i)
current_node = current_node.children[i]
current_node.is_handler = True
current_node.description = description
def find(self, match_path):
# Starting at the root, navigate the Trie to find a match for this path
# Return the handler for a match, or None for no match
current_node = self.root
for i in match_path:
if i in current_node.children:
current_node = current_node.children[i]
else:
return None
return current_node
# A RouteTrieNode will be similar to our autocomplete TrieNode... with one additional element, a handler.
class RouteTrieNode:
def __init__(self, handler = None, description = None):
# Initialize the node with children as before, plus a handler
self.children = {}
self.is_handler = False
self.handler = handler
self. description = description
def insert(self, handler):
# Insert the node as before
for i in handler.split('/'):
if i not in self.children:
self.children[i] = RouteTrieNode()
# The Router class will wrap the Trie and handle
class Router:
def __init__(self, handler, description):
self.trie = RouteTrie(handler, description)
def add_handler(self, handler, description):
if isinstance(handler, str) is False:
print('Please input a handler again.')
return
elif '/' not in [x for x in handler]:
print('Please input a handler again.')
return
path_parts = self.split_path(handler)
self.trie.insert(path_parts, description)
def lookup(self, path):
try:
ans = self.trie.find(self.split_path(path)).description
except:
ans = None
if path == '/':
ans = self.trie.root.handler
return ans
def split_path(self, path):
if not isinstance(path, str):
return None
return path.split('/')
# Test cases:
# Router and route 1:
router = Router("root handler","not found handler")
# add a router
router.add_handler("/home/about", "about handler")
# add a route
print(router.lookup("/"))
# should print 'root handler'
print(router.lookup("/home"))
# should print None
print(router.lookup("/home/about"))
# should print 'about handler'
print(router.lookup("/home/about/"))
# should print None
print(router.lookup("/home/about/me"))
# should print None
# Router and route 2:
router = Router("root handler", 'not found handler')
# add a router
router.add_handler("/home", "No handler")
# add a route
router.add_handler("/home/about/", "No handler")
# add a route
router.add_handler(None, "No handler")
# add an edge case route here. Attempting to add None as a router, should return
# a print "Please input a handler again"
router.add_handler("hello", "No handler")
# add an edge case route here. Attempting to add None as a router, should return
# a print "Please input a handler again"
print(router.lookup("/"))
# should print 'root handler'
print(router.lookup("/home"))
# should print "No handler"
# Test case 3:
router = Router("root handler", "not found handler")
# add a router
router.add_handler("/main/contact", "contact handler")
# add a route
router.add_handler("/main/about", "about handler")
# add a route
router.add_handler("/main/past clients", "past clients handler")
# add a route
router.add_handler("/main/past clients/1", "past clients: 1 handler")
# add a route
router.add_handler("/main/past clients/1/a", "past clients: 1a handler")
# add a route
# some lookups with the expected output
print(router.lookup("/"))
# should print 'root handler'
print(router.lookup("/main"))
# should print None
print(router.lookup("/main/contact"))
# should print 'contact handler'
print(router.lookup("/main/about"))
# should print 'about handler'
print(router.lookup("/main/past clients"))
# should print 'past clients handler'
print(router.lookup("/main/past clients/1"))
# should print 'past clients: 1 handler'
print(router.lookup("/main/past clients/1/a"))
# should print 'past clients: 1a handler'
# Handling unavailable links
print(router.lookup("/main/contact/"))
# should print None
print(router.lookup("/main/contact/me"))
# should print None
print(router.lookup("/main/past clients/1/a/"))
# should print None
|
eea24fad422d5317c2f9e7884a62548b03bd7837 | Yashika1305/PythonPrograms | /prog10.py | 258 | 3.90625 | 4 | m=int(input("Enter marks in maths"))
p=int(input("Enter marks in physics"))
c=int(input("Enter marks in chemistry"))
if (m>=65 and p>=55 and c>=50 and m+p+c>=180 and m+p>=140 and m+c>=140):
print("Eligible for course")
else:
print("not eligible")
|
39ed4ebd96d241d32a998df12507205b27b431fd | ewatso11/ew_bootcamp | /seq_features_and_tests.py | 935 | 3.921875 | 4 | def number_negatives(seq):
"""Number of negative residues a protein sequence"""
# Convert sequence to upper case
seq = seq.upper()
# Count E's and D's, since these are the negative residues
return seq.count('E') + seq.count('D')
def test_number_negatives_for_single_AA():
"""Perform unit tests on number_negative for single AA"""
assert number_negatives('E') == 1
assert number_negatives('D') == 1
def test_number_negatives_for_empty():
"""Perform unit tests on number_negative for empty entry"""
assert number_negatives('') == 0
def test_number_negatives_for_short_sequence():
"""Perform unit tests on number_negative for short sequence"""
assert number_negatives('ACKLWTTAE') == 1
assert number_negatives('DDDDEEEE') == 8
def test_number_negatives_for_lowercase():
"""Perform unit tests on number_negative for lowercase"""
assert number_negatives('acklwttae') == 1 |
9e783df208e273dfd1689fdc4497685016351507 | ijoshi90/Python | /Python/sum_of_odd_evens_in_list.py | 1,128 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 4 19:40:50 2019
@author: akjoshi
"""
# Count sum of off and even numbers in list
from random import *
odd = 0
even = 0
odd_total=0
even_total=0
odd_list=[]
even_list=[]
def odd_even(numbers):
for i in numbers:
if i % 2 == 0:
even_list.append(i)
globals()['even'] += i
globals()['even_total'] += 1
else:
odd_list.append(i)
globals()['odd'] += i
globals()['odd_total'] += 1
numbers = []
iteration=0
while True:
iteration += 1
for i in range (100):
numbers=[]
numbers.append(randrange(0,100,1))
odd_even(numbers)
# print ("Even : {}\nOdd : {}".format(even_total, odd_total))
if (even_total or odd_total) == 50:
break
else:
continue
print ("Iteration : " + str(iteration))
print ("\nOdd List : " + str(odd_list))
print ("\nOdd Sum : " + str (odd))
print ("\nOdd Total : " + str (odd_total))
print ("\nEven List : " + str(even_list))
print ("\nEven Sum : " + str (even))
print ("\nEven Total : " + str (even_total)) |
4629d65f5a4b6a15091aede2e8813d100d3f89d1 | JonnyCheong/machineLearning | /learning2.py | 1,749 | 3.625 | 4 | #The code do the machine learning. Finally export .pkl file.
import numpy as np
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.svm import SVC
from sklearn.neighbors import KNeighborsClassifier
from sklearn.externals import joblib
"""
The program using the data of dimensionality reduction to machine learning.
"""
data=np.loadtxt('bvh.csv',delimiter=',')#Load the bvh.csv file(data).
X=data[:,1:]#set the data at X.
y=data[:,0]#set the category(Label) of data.
print 'Start PCA...'
pca=PCA(n_components=2)#Define the multidimensional data to two-dimensional.
pca.fit(X)#Reducing the multi dimensional to two-dimensional
print pca.transform(X)
joblib.dump(pca.transform(X),'save/PCA.pkl')#Export the .pkl file.
print 'Export pkl done...'
X_train,X_test,y_train,y_test=train_test_split(pca.transform(X),y,test_size=0.3,random_state=42)
print 'Start Linear SVC...'
lsvc=SVC(kernel='linear')#Define choose using model(Linear SVC).
lsvc.fit(X_train,y_train)#Machine learning.
joblib.dump(lsvc,'save/linearSVC_PCA.pkl')#Export the .pkl file.
print 'Export pkl done...'
print 'Start SVC'
svc=SVC()#Define choose using model(SVC).
svc.fit(X_train,y_train)#Machine learning.
print 'Accuracy of SVC is ',svc.score(X_test,y_test)
joblib.dump(svc,'save/SVC_PCA.pkl')#Export the .pkl file.
print 'Export pkl done...'
print 'Start KNeighbors Classifier'
knn = KNeighborsClassifier()#Define choose using model(KNeighbors Classifier).
knn.fit(X_train,y_train)#Machine learning.
print 'Accuracy of KNeighbors Classifier is ',knn.score(X_test,y_test)
joblib.dump(knn,'save/knn_PCA.pkl')#Export the .pkl file.
print 'Export pkl done...'
|
75df4bd86deab4163f51103dec6648c60ccdc838 | cristianA06/ProgCompEAFIT.github.io | /20171/presentaciones/Ordenamiento/sol2.py | 503 | 3.59375 | 4 | import random
def insertionSort():
tam = 10000
lista = random.sample(range(0,tam+1),tam)
#print lista
for index in range(1,len(lista)):
actual = lista[index]
pos = index
while pos>0 and lista[pos-1]>actual:
lista[pos]=lista[pos-1]
pos = pos-1
lista[pos]=actual
#print lista
if __name__ == '__main__':
import timeit
print(timeit.timeit("insertionSort()", setup="from __main__ import insertionSort", number=1000))
|
dd74a8a74e4781c733dd3afbe3ba8abbfbec39d1 | joaquinloustau/cmsi386 | /homework1/lines.py | 241 | 3.78125 | 4 | import sys
num_lines = 0
for line in open(sys.argv[1]):
line = line.strip()
if line and not line.startswith("#"):
num_lines += 1
print num_lines
#http://stackoverflow.com/questions/7896495/python-how-to-check-if-a-line-is-an-empty-line
|
aae475e1e3e8056f060a3e13614788d8a15ba507 | yeshixuan/Python | /02-高级语法系列/07-多线程/04.py | 944 | 4.03125 | 4 | #利用time延时函数,生成两个函数
# 利用多线程调用
# 计算总运行时间
# 练习带参数的多线程启动方法
import time
# 导入多线程处理包
import threading
def loop1(in1):
# ctime得到当前时间
print("Start loop 1 at:", time.ctime())
# 睡眠多长时间,单位是秒
print("我是参数:", in1)
time.sleep(4)
print("End loop 1 at:", time.ctime())
def loop2(in1, in2):
print("Start loop 2 at:", time.ctime())
print("我是参数:", in1, "和参数:", in2)
time.sleep(2)
print("End loop 2 at:", time.ctime())
def main():
print("Starting at:", time.ctime())
# 生成thread.Thread实例
t = threading.Thread(target=loop1, args=("王老大",))
t1 = threading.Thread(target=loop2, args=("王大鹏", "王晓鹏"))
t.start()
t1.start()
print("Ending at:", time.ctime())
if __name__ == '__main__':
main()
# 不需要while |
77e53b10be0fd480bc40a6fbac933196086c7838 | Kandiotti/Setiembre2021 | /PensamientoComputacional/scope.py | 294 | 3.546875 | 4 | def funcion1 (arg, func):
def funcion2(arg):
return arg * 2
valor = funcion2(arg)
return func(valor)
def funcion_random(arg):
return arg * 5
def main():
argumento = 2
print(funcion1 (argumento, funcion_random))
if __name__ == '__main__':
main() |
3b0fa50159622197f8e4617fbdcfd5339701b737 | NuAyeSan/python-class1 | /variable.py | 805 | 3.671875 | 4 | + - * /
%
**
>>>2 + 2
4
>>>50 - 5 * 6
20
>>>(50 - 5 * 6 ) / 4
5.0
>>>round(5.0)
5
>>>5.123456
5.123456
round(5.12345,2)
5.12
>>>17 / 3
5.666666667
>>>17 // 3
5
>>>18 // 4
4
>>>20 // 5
4
>>>17 % 3
2
>>>17 * 4 % 3
2
a = 1
a (variable) = (assign) 1 (value)
weight = 50
height = 5 * 9
vol = weight * height
vol
sale = 300000
tax = 5/100
total_tax = sale * tax
total_tax
total_price = sale + total_tax
total_price
sale = 300000
tax = 5/100
total_tax = sale * tax
total_tax
total_price = sale + total_tax
total_price
print('spam eggs')
print('don\'t')
print("doesn't")
print('"yes"')
print("\'Yes, \" They said.")
print('"Isn\'t, "They said')
s= 'first Line\n Second Line.'
print(s)
print("""\
Usage: thingy
-a
-b
-c
""" )
"""...""" or """..."""
3 * 'A'
2 * 'BC' + 'DE'
10 * 'GH' + 3
>>>List
|
0fd8e4df976c34732be82e16ef76b829188f7473 | kiminh/offer_code | /06_PrintListFromTailToHead.py | 982 | 3.96875 | 4 | # -*- coding:utf-8 -*-
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# 返回从尾部到头部的列表值序列,例如[1,2,3]
# 循环
def printListFromTailToHead(self, listNode):
# write code here
value = []
while listNode:
value.insert(0, listNode.val)
listNode = listNode.next
return value
# 递归,链表过长时,导致函数调用层级很深,函数调用栈溢出
def printListFromTailToHead2(self, listNode):
self.value = []
if not listNode:
return []
self.printListFromTailToHead2(listNode.next) # 先递归尾部节点,再输出头节点
self.value.append(listNode.val)
return self.value
s = Solution()
listNode = ListNode(1)
listNode.next = ListNode(2)
listNode.next = ListNode(3)
print(s.printListFromTailToHead(listNode))
print(s.printListFromTailToHead2(listNode))
|
da3969e6ad90a6a77a395965f8ff7ae7e8ba16da | tchirktema-zz/python-cme | /bianne.py | 407 | 3.953125 | 4 | #ce programme permet de voir si une annee est bisexitile
annee = input("Entrer l'annee : ")
#conversion de l'annee en entier
annee = int(annee)
if annee%400 == 0:
print(str(annee)+ " est bisexitile")
elif annee%4 == 0:
if annee%100 != 0:
print( str(annee)+ " est bisexitile")
else :
print( str(annee)+ " n'est bisexitile")
else:
print( str(annee)+ " n' est bisexitile")
|
7af826fd1a14c3901c37b55a8167f6cec345b681 | SoliDeoGloria31/study | /AID12 day01-16/day02/code/if.py | 246 | 3.796875 | 4 | # if.py
# 写一个程序,输入一个整数,判断这个整数是奇数还是偶数
# 分析: 奇数对2求余一定等于1
x = int(input('请输入一个整数: '))
if x % 2 == 1:
print(x, '是奇数')
else:
print(x, '是偶数')
|
7047bb9d45bafcefb774e03ca14c4a45c166387b | mspspeak/problems | /python/euler_seven.py | 588 | 3.90625 | 4 |
# By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
# What is the 10 001st prime number?
def divisible_by(a,b):
if (a != 0) and (b != 0):
return (a % b) == 0
else:
return False
def is_prime(n):
i = 2
upperbound = n
return_value = True
while i < upperbound and return_value:
if divisible_by(n, i):
return_value = False
i += 1
return return_value
count = 1
current_candidate = 2
while count < 10002:
if is_prime(current_candidate):
print count, ":", current_candidate
count += 1
current_candidate += 1
|
ce7ed7fe2cdb8557440e85f57a1e6c8ff62cbca9 | DanielMevs/Babylonian-Algorithm | /hw7.py | 547 | 4.15625 | 4 | import math
def bab(x):
x0 = 0.1
x1 = x/2
if(x<0):
raise Exception("x should not be less than 0. The value of x was: ", x)
while .01 <= abs(x1-x0)/x0:
x0 = x1
r = x/x0
x1 = (x0+r)/2
print(x1)
return x1
x = 0
x = float(input("Please input the value of x: "))
bab_sqrt = bab(x)
print("The the square root of ", x," as approximated by by the Babylonian algorithm is: ", bab_sqrt)
print("The the square root of ", x," as approximated by by the math module is: ", math.sqrt(x))
|
822d51bcb839bad0bbe3a2fb51323f6b83ed33f1 | Ramsey0179/Ramboilk-CWEU | /Assig8_Leapyear.py | 271 | 3.765625 | 4 | year = int(input("Sene kaç, girin lütfen :"))
leap_year = year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
result = (leap_year == True)*'artık yıldır.' + (leap_year == False)*'artık yıl değildir.'
print(f"Girdiğiniz *{year:^10}* senesi {result:^20}!")
|
0c0eb1a6f46c3d8f9521e4b622bd8c3f3b081349 | RaviTejaKomma/learn-python | /unit5_assignment_05.py | 2,844 | 4.21875 | 4 | __author__ = 'Kalyan'
notes = '''
1. Read instructions for the function carefully and constraints carefully.
2. Try to generate all possible combinations of tests which exhaustively test the given constraints.
3. If behavior in certain cases is unclear, you can ask on the forums
'''
from placeholders import *
# Convert a sentence which has either or to only the first choice.
# e.g we could either go to a movie or a hotel -> we could go to a movie.
# note: do not use intermediate lists (string.split), only use string functions
# assume words are separated by a single space. you can use control flow statements
# So sentence is of form <blah> either <something> or <somethingelse> and gets converted to <blah> <something>
# if it is not of the correct form, you just return the original sentence.
def prune_either_or(sentence):
if sentence==None:
return None
blah,something="",""
index1 = sentence.find("either")
index2 = sentence.find("or")
if "either" in sentence and "or" in sentence and index1 < index2 and index1!=0 and index2!=len(sentence)-2 :
flag1= sentence[sentence.find("either")+6]==' ' and sentence[sentence.find("either")-1]==' '
flag2 = sentence[sentence.find("or") + 2] == ' ' and sentence[sentence.find("or") - 1] == ' '
if flag1 and flag2:
blah = sentence[:sentence.find("either")]
something = sentence[sentence.find("either")+6:sentence.find("or")]
blah= blah.strip()
something=something.strip()
sentence=blah+" "+something
return sentence
else:
return sentence
else:
return sentence
def test_prune_either_or_student():
assert "we could go to a movie"==prune_either_or("we could either go to a movie or a hotel")
assert "we could either go to a movie a hotel" == prune_either_or("we could either go to a movie a hotel")
assert "we could go to a movie or a hotel" == prune_either_or("we could go to a movie or a hotel")
assert "we could go to a movie a hotel " == prune_either_or("we could go to a movie a hotel ")
assert "either i accompany you to your room or i wait here" == prune_either_or("either i accompany you to your room or i wait here")
assert "either or"==prune_either_or("either or")
assert "neither this or that"==prune_either_or("neither this or that")
assert " either or" == prune_either_or(" either or")
assert "Two mythical cities eitheron and oregon" == prune_either_or("Two mythical cities eitheron and oregon")
# these tests run only on our runs and will be skipped on your computers.
# DO NOT EDIT.
import pytest
def test_prune_either_or_server():
servertests = pytest.importorskip("unit5_server_tests")
servertests.test_prune_either_or(prune_either_or)
|
473a9d56a78bde3f3573a74a2b33ddd7dce50275 | weilin-zhang/MyProject_siat | /Python/data_structure/LeetCode/FlippingAnImage.py | 1,162 | 3.59375 | 4 | '''
给定一个二进制矩阵 A,我们想先水平翻转图像,然后反转图像并返回结果。
水平翻转图片就是将图片的每一行都进行翻转,即逆序。例如,水平翻转 [1, 1, 0] 的结果是 [0, 1, 1]。
反转图片的意思是图片中的 0 全部被 1 替换, 1 全部被 0 替换。例如,反转 [0, 1, 1] 的结果是 [1, 0, 0]
输入: [[1,1,0],[1,0,1],[0,0,0]]
输出: [[1,0,0],[0,1,0],[1,1,1]]
解释: 首先翻转每一行: [[0,1,1],[1,0,1],[0,0,0]];
然后反转图片: [[1,0,0],[0,1,0],[1,1,1]]
输入: [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]
输出: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
解释: 首先翻转每一行: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]];
然后反转图片: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
'''
class Solution:
def flipAndInvertImage(self, A):
"""
:type A: List[List[int]]
:rtype: List[List[int]]
"""
for i in range(len(A)):
A[i].reverse()
for j in range(len(A[i])):
A[i][j] = (A[i][j]+1)%2
return A
obj = Solution()
print(obj.flipAndInvertImage([[1,1,0],[1,0,1],[0,0,0]])) |
79b584580f750c160d49e781d4dab6bf6435dcf8 | jankeromnes/Python-Calc | /phys/main.py | 1,126 | 4.0625 | 4 | #! /usr/bin/python3.7
import os
print("Welcome to the physics calculator available calculators include: distance speed time calculator (dstc), gravity formula(gf), lorentz factor(lf), mass energy(mee),line displacement(ld), velocity (velocity) acceleration(acceleration), range(range)")
while True:
keywords1 = ["dst", "dtc"]
keywords2 = ['grav', 'gf']
def chooseCalc():
userInt = input("Which calculator do you want?: ").lower()
if userInt in keywords1:
import phys.distspeed
elif userInt in keywords2:
import phys.gravforce
elif userInt == 'lf':
import phys.lorenfact
elif userInt == 'me':
import phys.massEner
elif userInt == 'ld':
import phys.lineDisplace
elif userInt in "velocity":
import phys.velocity
elif userInt in "acceleration":
import phys.accelerate
elif userInt in "range":
import phys.range
elif userInt == 'exit':
exit()
else:
print("An error has occurred")
chooseCalc()
chooseCalc()
|
4e86c437cd9843fad1e21820a7088cc4f7a6cd4f | Johngitonga/Python-advance-tracks | /python_classes/enemy.py | 404 | 3.5625 | 4 | class Enemy:
def __init__(self, ranks, strength):
self.ranks = ranks
self.strength = strength
def get_rank(self):
return self.ranks
def get_strength(self):
return self.strength
def get_hurt(self):
self.strength-=5
enemy1 = Enemy('corporal', 8)
enemy2 = Enemy('Lieutenant', 16)
print enemy1.strength
|
01bda1414e0001d9f6d44b6ad81dce5db4147715 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2730/60623/284735.py | 269 | 3.71875 | 4 | a=int(input())
t=[]
tL=[]
for i in range(a):
b=input()
l=input().split()
t.append(b)
tL.append(l)
if tL==[['40', '50', '60'], ['4', '5']]:
print(1)
print(1)
elif tL==[['40', '50', '70'], ['2', '5']]:
print(0)
print(0)
else:
print(tL) |
8f4cc09a63db8b94990bc92d5b73211c575ae6f8 | jtyurkovich/python-tutorial | /Lesson Two: Strings/exercises2.py | 5,362 | 4.125 | 4 | # jtyurkovich, 2014
# coding: utf-8
# In[1]:
# Write a function that takes a string as input and outputs the reverse
# of the string (e.g., input 'James is awesome' and output 'emosewa si
# semaJ').
def reverse(string):
newstr = ''
for letter in reversed(string):
newstr += letter
print string
print newstr
reverse('James is awesome')
# In[2]:
# Write a function that takes as input two DNA sequences of arbitrary
# but equal length and returns the positions of any SNPs that exist. Test
# with 'ACTCTATCGGCTACG' and 'ACTCTATCGACTACG' where a SNP has occurred
# at position 9 (zero-based indexing). Also report the SNP that occurred
# (i.e., which base was mutated to which base). Make sure your function
# can handle multiple SNPs.
def snp_finder(seq1,seq2):
snp = []
bases = []
count = 0
for index in range(0,len(seq1)):
if seq1[index] != seq2[index]:
snp.append(index)
bases.append([seq1[index],seq2[index]])
count += 1
if len(snp) > 0:
for index in range(0,len(snp)):
print 'SNP at position %(snp)s (%(bases1)s is replaced with %(bases2)s)' %{"snp":snp[index],"bases1":bases[index][0],"bases2":bases[index][1]}
else:
print 'No SNPs present'
seq1 = 'ACTCTATCGGCTACA'
seq2 = 'ACTCTATCGACTACG'
snp_finder(seq1,seq2)
# In[7]:
# Write a function that determines whether an input phrase is a pangram (a
# sentence that contains all the letters in the alphabet). Test it with
# 'The quick brown fox jumps over the lazy dog' which is a pangram. If the
# input is not a pangram, report which letter(s) is/are missing.
def ispangram(sentence):
sentence.replace(' ','')
abc = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
#flag = True
missingletters = ''
for letter in abc:
if letter not in sentence:
#flag = False
missingletters += letter
#break
if missingletters == '':
print '"' + sentence + '" is a pangram'
elif len(missingletters) == 1:
print '"' + sentence + '" is not a pangram; "%s" is missing.' %missingletters
else:
print '"' + sentence + '" is not a pangram; "%s" are missing.' %missingletters
sentence = 'The quick brown fox jumps over the lazy dog'
output = ispangram(sentence)
sentence = 'This is not a pangram'
output = ispangram(sentence)
# In[32]:
# Determine if the two strings are equal: 'AATAGATCGCTAGCT' and
# 'AATAGATCGCTAGCT'.
str1 = 'AATAGATCGCTAGCT'
str2 = 'AATAGATCGCTAGCT'
if str1 == str2:
print 'Strings equal'
else:
print 'Strings not equal'
# In[15]:
# Determine if the substrings 'AATA' and 'TTT' are present in the larger
# string 'AATAGATCGCTAGCT'.
def issubstringpresent(str1,str2):
index = str1.find(str2)
if index >= 0:
print str2 + ' found in ' + str1 + ' at index %s' %index
else:
print str2 + ' not found in ' + str1
issubstringpresent('AATAGATCGCTAGCT','CGC')
issubstringpresent('AATAGATCGCTAGCT','TTT')
# In[19]:
# Now try the same problem again, but look for a substring that appears
# multiple times, such as 'TAG'. Report the position within the string
# (zero-based indexing) at which the substring appears.
str1 = 'AATAGATCGCTAGCT'
str2 = 'TAG'
flag = False
for index in range(0,len(str1)-2):
if str1[index:(index+2)] == str2:
flag = True
print str2 + ' found in ' + str1 + ' at index %s' %index
if not flag:
print str2 + ' not found in ' + str1
# In[29]:
# That can be fairly inefficient, especially for large strings. We can
# instead use something called a regular expression to quickly and
# efficiently do the same search.
# You will need to install Python's regular expression module to run this
# block of code.
import re
str1 = 'AATAGATCGCTAGCT'
str2 = 'TAG'
indices = [m.start() for m in re.finditer(str2,str1)]
for index in indices:
print str2 + ' found in ' + str1 + ' at index %s' %index
if len(indices) == 0:
print str2 + ' not found in ' + str1
# In[94]:
# Importing a package may not be preferable, especially if you don't have
# that particular package already. In that case, we can implement more
# complex solutions.
def locations_of_substring(string,substring):
substring_length = len(substring)
def recurse(locations_found,start):
location = string.find(substring,start)
if location != -1:
return recurse(locations_found + [location],location + substring_length)
else:
return locations_found
return recurse([], 0)
indices = locations_of_substring('AATAGATCGCTAGCT','TAG')
for index in indices:
print str2 + ' found in ' + str1 + ' at index %s' %index
if len(indices) == 0:
print str2 + ' not found in ' + str1
# In[103]:
# Or, we could use a built-in method for strings in Python to find the
# number of occurrences. Ultimately, we see that although this may be the
# easiest, we would need to use additional methods to find the location of
# these occurrences. Experiment with the different string methods to find
# similarly easy implementations for various problems.
str1 = 'AATAGATCGCTAGCT'
str2 = 'TAG'
print str2 + ' occurs ' + str(str1.count(str2)) + ' times in ' + str1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.